@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.
@@ -0,0 +1,318 @@
1
+ import EventEmitter from 'events';
2
+ import { ERRORS, HardwareErrorCode } from '@onekeyfe/hd-shared';
3
+
4
+ import ReactNativeBleTransport from '../index';
5
+ import {
6
+ IOS_PEER_TERMINATION_LINK_WINDOW_MS,
7
+ IOS_PEER_TERMINATION_REPEAT_WINDOW_MS,
8
+ IosPeerTerminationTracker,
9
+ } from '../bleIosStaleBond';
10
+ import protocolV1Schema from './protocolV1SchemaFixture';
11
+
12
+ jest.mock(
13
+ 'react-native',
14
+ () => ({
15
+ Platform: { OS: 'ios', select: (spec: Record<string, unknown>) => spec.ios },
16
+ PermissionsAndroid: {
17
+ PERMISSIONS: {},
18
+ RESULTS: {},
19
+ request: jest.fn(),
20
+ requestMultiple: jest.fn(),
21
+ },
22
+ }),
23
+ { virtual: true }
24
+ );
25
+
26
+ jest.mock('react-native-ble-plx', () => ({
27
+ BleATTErrorCode: { InvalidHandle: 1, UnlikelyError: 14 },
28
+ BleError: Error,
29
+ BleErrorCode: {
30
+ DeviceDisconnected: 201,
31
+ OperationStartFailed: 601,
32
+ DeviceMTUChangeFailed: 401,
33
+ OperationCancelled: 2,
34
+ OperationTimedOut: 3,
35
+ DeviceAlreadyConnected: 203,
36
+ },
37
+ BleManager: jest.fn(),
38
+ ScanMode: { LowLatency: 2 },
39
+ }));
40
+
41
+ jest.mock('@onekeyfe/react-native-ble-utils', () => ({
42
+ __esModule: true,
43
+ default: {
44
+ getConnectedPeripherals: jest.fn(() => Promise.resolve([])),
45
+ getBondedPeripherals: jest.fn(() => Promise.resolve([])),
46
+ pairDevice: jest.fn(() => Promise.resolve({ bonded: true, bonding: false })),
47
+ onDeviceBondState: jest.fn(),
48
+ },
49
+ }));
50
+
51
+ const UUID = '2146E74A-21CC-2EA6-2CE3-B4258520FD0F';
52
+
53
+ // What ble-plx rejects the in-flight operation with when the device ends the link. An iPhone 17
54
+ // reports a wiped device this way instead of CBErrorPeerRemovedPairingInformation.
55
+ const nativeDisconnect = (iosErrorCode: number, reason: string) =>
56
+ Object.assign(new Error(`Device ${UUID} was disconnected`), {
57
+ errorCode: 201,
58
+ iosErrorCode,
59
+ reason,
60
+ });
61
+ const peerEndedLink = () => nativeDisconnect(7, 'The specified device has disconnected from us.');
62
+ const linkTimedOut = () => nativeDisconnect(6, 'The connection has timed out unexpectedly.');
63
+
64
+ function createHarness() {
65
+ const writeCharacteristic = {
66
+ uuid: '00000002-0000-1000-8000-00805f9b34fb',
67
+ isWritableWithResponse: true,
68
+ writeWithResponse: jest.fn(() => Promise.resolve()),
69
+ };
70
+ const notifyCharacteristic = {
71
+ uuid: '00000003-0000-1000-8000-00805f9b34fb',
72
+ isNotifiable: true,
73
+ monitor: jest.fn(() => ({ remove: jest.fn() })),
74
+ };
75
+ const device = {
76
+ id: UUID,
77
+ name: 'Pro 2 48E9',
78
+ localName: 'Pro 2 48E9',
79
+ mtu: 247,
80
+ serviceUUIDs: ['00000001-0000-1000-8000-00805f9b34fb'],
81
+ isConnected: jest.fn(() => Promise.resolve(false)),
82
+ cancelConnection: jest.fn(() => Promise.resolve()),
83
+ connect: jest.fn(),
84
+ discoverAllServicesAndCharacteristics: jest.fn(() => Promise.resolve()),
85
+ characteristicsForService: jest.fn(() =>
86
+ Promise.resolve([writeCharacteristic, notifyCharacteristic])
87
+ ),
88
+ services: jest.fn(() => Promise.resolve([])),
89
+ onDisconnected: jest.fn(() => ({ remove: jest.fn() })),
90
+ };
91
+ device.connect.mockImplementation(() => Promise.resolve(device));
92
+ const transport = new ReactNativeBleTransport({});
93
+ (transport as any).blePlxManager = {
94
+ devices: jest.fn(() => Promise.resolve([device])),
95
+ connectedDevices: jest.fn(() => Promise.resolve([])),
96
+ connectToDevice: jest.fn(() => Promise.resolve(device)),
97
+ cancelTransaction: jest.fn(() => Promise.resolve()),
98
+ cancelDeviceConnection: jest.fn(() => Promise.resolve()),
99
+ onStateChange: jest.fn((listener: (state: string) => void) => {
100
+ setImmediate(() => listener('PoweredOn'));
101
+ return { remove: jest.fn() };
102
+ }),
103
+ state: jest.fn(() => Promise.resolve('PoweredOn')),
104
+ };
105
+ const logger = { debug: jest.fn(), error: jest.fn(), warn: jest.fn() };
106
+ transport.init(logger as any, new EventEmitter());
107
+ transport.configure(protocolV1Schema);
108
+ return { transport, device, writeCharacteristic, notifyCharacteristic, logger };
109
+ }
110
+
111
+ type Outcome = { code?: unknown; params?: unknown; native?: unknown };
112
+
113
+ const flush = () =>
114
+ new Promise(resolve => {
115
+ setImmediate(resolve);
116
+ });
117
+
118
+ /** Runs one acquire to its end, moving the fake clock past the transport's own waits. */
119
+ async function acquire(
120
+ transport: ReactNativeBleTransport,
121
+ input: Record<string, unknown> = {}
122
+ ): Promise<Outcome> {
123
+ let outcome: Outcome | undefined;
124
+ transport.acquire({ uuid: UUID, ...input } as never).then(
125
+ () => {
126
+ outcome = {};
127
+ },
128
+ error => {
129
+ const { code, params } = ERRORS.serializeError({ error });
130
+ outcome = { code, params, native: (error as { iosErrorCode?: unknown }).iosErrorCode };
131
+ }
132
+ );
133
+ for (let i = 0; i < 400 && !outcome; i += 1) {
134
+ // eslint-disable-next-line no-await-in-loop
135
+ await flush();
136
+ if (!outcome) jest.advanceTimersByTime(100);
137
+ }
138
+ if (!outcome) throw new Error('acquire did not settle');
139
+ return outcome;
140
+ }
141
+
142
+ describe('iOS link ended by the device right after connecting', () => {
143
+ beforeEach(() => {
144
+ jest.useFakeTimers({ doNotFake: ['setImmediate', 'performance', 'nextTick'] });
145
+ });
146
+
147
+ afterEach(() => {
148
+ jest.clearAllTimers();
149
+ jest.useRealTimers();
150
+ });
151
+
152
+ test('keeps the first error so Core retries, then reports an invalid bond', async () => {
153
+ const { transport, device } = createHarness();
154
+ device.discoverAllServicesAndCharacteristics.mockImplementation(() =>
155
+ Promise.reject(peerEndedLink())
156
+ );
157
+
158
+ // Core retries an error it cannot classify, which is what makes the second attempt.
159
+ await expect(acquire(transport)).resolves.toEqual({ native: 7 });
160
+ await expect(acquire(transport)).resolves.toEqual({
161
+ code: HardwareErrorCode.BleBondInvalid,
162
+ params: { phase: 'connect', reason: 'peer_disconnected' },
163
+ });
164
+ // The verdict consumes the evidence, so the next one needs two attempts again.
165
+ await expect(acquire(transport)).resolves.toEqual({ native: 7 });
166
+ });
167
+
168
+ test('counts a drop that interrupts the first write the same way', async () => {
169
+ const { transport, writeCharacteristic } = createHarness();
170
+ writeCharacteristic.writeWithResponse.mockImplementation(() => Promise.reject(peerEndedLink()));
171
+
172
+ await expect(acquire(transport)).resolves.toMatchObject({
173
+ code: HardwareErrorCode.BleDeviceNotBonded,
174
+ });
175
+ await expect(acquire(transport)).resolves.toMatchObject({
176
+ code: HardwareErrorCode.BleBondInvalid,
177
+ });
178
+ });
179
+
180
+ test('counts a drop that only the notification stream reports', async () => {
181
+ const { transport, notifyCharacteristic } = createHarness();
182
+ // The request went out before the link ended, so no write is there to fail.
183
+ notifyCharacteristic.monitor.mockImplementation(((
184
+ listener: (error: unknown, characteristic: unknown) => void
185
+ ) => {
186
+ setTimeout(() => listener(peerEndedLink(), null), 50);
187
+ return { remove: jest.fn() };
188
+ }) as never);
189
+
190
+ await expect(acquire(transport)).resolves.not.toMatchObject({
191
+ code: HardwareErrorCode.BleBondInvalid,
192
+ });
193
+ await expect(acquire(transport)).resolves.toMatchObject({
194
+ code: HardwareErrorCode.BleBondInvalid,
195
+ });
196
+ });
197
+
198
+ test('needs the second drop soon after the first', async () => {
199
+ const { transport, device } = createHarness();
200
+ device.discoverAllServicesAndCharacteristics.mockImplementation(() =>
201
+ Promise.reject(peerEndedLink())
202
+ );
203
+
204
+ await acquire(transport);
205
+ jest.setSystemTime(Date.now() + IOS_PEER_TERMINATION_REPEAT_WINDOW_MS + 1);
206
+
207
+ await expect(acquire(transport)).resolves.toEqual({ native: 7 });
208
+ });
209
+
210
+ test('starts over after an attempt that failed for another reason', async () => {
211
+ const { transport, device } = createHarness();
212
+ device.discoverAllServicesAndCharacteristics
213
+ .mockImplementationOnce(() => Promise.reject(peerEndedLink()))
214
+ .mockImplementationOnce(() => Promise.reject(linkTimedOut()))
215
+ .mockImplementation(() => Promise.reject(peerEndedLink()));
216
+
217
+ await acquire(transport);
218
+ await expect(acquire(transport)).resolves.toEqual({ native: 6 });
219
+ await expect(acquire(transport)).resolves.toEqual({ native: 7 });
220
+ });
221
+
222
+ test('starts over once the device has answered', async () => {
223
+ const { transport, device } = createHarness();
224
+ (transport as any).detectProtocol = jest.fn(() => Promise.resolve('V1'));
225
+ device.discoverAllServicesAndCharacteristics
226
+ .mockImplementationOnce(() => Promise.reject(peerEndedLink()))
227
+ .mockImplementationOnce(() => Promise.resolve())
228
+ .mockImplementation(() => Promise.reject(peerEndedLink()));
229
+
230
+ await acquire(transport);
231
+ await expect(acquire(transport)).resolves.toEqual({});
232
+
233
+ await expect(acquire(transport)).resolves.toEqual({ native: 7 });
234
+ });
235
+
236
+ test('never classifies a firmware-install reconnect', async () => {
237
+ const { transport, device } = createHarness();
238
+ device.discoverAllServicesAndCharacteristics.mockImplementation(() =>
239
+ Promise.reject(peerEndedLink())
240
+ );
241
+ const reconnect = { expectedProtocol: 'V2', skipProtocolProbe: true };
242
+
243
+ await expect(acquire(transport, reconnect)).resolves.toEqual({ native: 7 });
244
+ await expect(acquire(transport, reconnect)).resolves.toEqual({ native: 7 });
245
+ // The device was rebooting, so those drops are not evidence for a later attempt either.
246
+ await expect(acquire(transport)).resolves.toEqual({ native: 7 });
247
+ });
248
+
249
+ test('logs the native codes of the failed operation, which iOS reports nowhere else', async () => {
250
+ const { transport, device, logger } = createHarness();
251
+ device.discoverAllServicesAndCharacteristics.mockImplementation(() =>
252
+ Promise.reject(peerEndedLink())
253
+ );
254
+
255
+ await acquire(transport);
256
+
257
+ expect(logger.debug).toHaveBeenCalledWith('[ReactNativeBleTransport] iOS operation failed', {
258
+ connectIdSuffix: UUID.slice(-8),
259
+ stage: 'gatt-setup',
260
+ errorCode: 201,
261
+ iosErrorCode: 7,
262
+ attErrorCode: undefined,
263
+ });
264
+ });
265
+
266
+ test('reports a lost bond that iOS names during GATT setup', async () => {
267
+ const { transport, device } = createHarness();
268
+ device.discoverAllServicesAndCharacteristics.mockImplementation(() =>
269
+ Promise.reject(nativeDisconnect(14, 'Peer removed pairing information'))
270
+ );
271
+
272
+ await expect(acquire(transport)).resolves.toMatchObject({
273
+ code: HardwareErrorCode.BlePeerRemovedPairingInformation,
274
+ });
275
+ });
276
+ });
277
+
278
+ describe('IosPeerTerminationTracker', () => {
279
+ beforeEach(() => {
280
+ jest.useFakeTimers({ doNotFake: ['performance'] });
281
+ });
282
+
283
+ afterEach(() => {
284
+ jest.useRealTimers();
285
+ });
286
+
287
+ const dropLink = (tracker: IosPeerTerminationTracker, linkAgeMs = 0) => {
288
+ tracker.attemptStarted(UUID);
289
+ tracker.linkStarted(UUID);
290
+ jest.setSystemTime(Date.now() + linkAgeMs);
291
+ tracker.note(UUID, peerEndedLink());
292
+ return tracker.attemptFailed(UUID);
293
+ };
294
+
295
+ test('ignores a drop on a link that was reused or had been up for a while', () => {
296
+ const tracker = new IosPeerTerminationTracker();
297
+ expect(dropLink(tracker)).toBe(false);
298
+
299
+ tracker.attemptStarted(UUID);
300
+ tracker.note(UUID, peerEndedLink());
301
+ expect(tracker.attemptFailed(UUID)).toBe(false);
302
+
303
+ expect(dropLink(tracker)).toBe(false);
304
+ expect(dropLink(tracker, IOS_PEER_TERMINATION_LINK_WINDOW_MS + 1)).toBe(false);
305
+ });
306
+
307
+ test('ignores errors that do not say the peer ended the link', () => {
308
+ const tracker = new IosPeerTerminationTracker();
309
+ expect(dropLink(tracker)).toBe(false);
310
+
311
+ tracker.attemptStarted(UUID);
312
+ tracker.linkStarted(UUID);
313
+ tracker.note(UUID, linkTimedOut());
314
+ tracker.note(UUID, { errorCode: 201 });
315
+ tracker.note(UUID, undefined);
316
+ expect(tracker.attemptFailed(UUID)).toBe(false);
317
+ });
318
+ });
@@ -45,6 +45,21 @@ jest.mock('../BleManager', () => ({
45
45
  pairDevice: jest.fn(() => Promise.resolve({ bonded: true, bonding: false })),
46
46
  }));
47
47
 
48
+ // The native facade is replaced wholesale above; key missing and link encryption are covered
49
+ // by their own suites.
50
+ jest.mock('../bleKeyMissing', () => ({
51
+ isBleKeyMissingSupported: jest.fn(() => false),
52
+ startBleKeyMissingTracking: jest.fn(() => false),
53
+ stopBleKeyMissingTracking: jest.fn(),
54
+ waitForBleKeyMissing: jest.fn(() => Promise.resolve(false)),
55
+ }));
56
+ jest.mock('../bleEncryption', () => ({
57
+ markBleLinkEncrypted: jest.fn(),
58
+ startBleEncryptionTracking: jest.fn(() => false),
59
+ stopBleEncryptionTracking: jest.fn(),
60
+ waitForAndroidLinkEncryption: jest.fn(() => Promise.resolve('unresolved')),
61
+ }));
62
+
48
63
  jest.mock('../subscribeBleOn', () => ({
49
64
  subscribeBleOn: jest.fn(() => Promise.resolve()),
50
65
  }));
@@ -303,45 +318,6 @@ const createV1Harness = ({
303
318
  };
304
319
 
305
320
  describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
306
- test.each(['ios', 'android'] as const)(
307
- 'identifies MTU logs for concurrent devices and reconnects on %s',
308
- async platform => {
309
- setPlatformOS(platform);
310
- const { transport, uuid, device, bleManager, logger } = createHarness();
311
- const otherUuid = 'rn-pro2-other-id';
312
- const otherDevice = { ...device, id: otherUuid };
313
-
314
- try {
315
- await transport.acquire({ uuid, expectedProtocol: 'V2' });
316
- await transport.acquire({ uuid, expectedProtocol: 'V2' });
317
- bleManager.devices.mockResolvedValue([otherDevice]);
318
- await transport.acquire({ uuid: otherUuid, expectedProtocol: 'V2' });
319
- await transport.release(uuid, true);
320
- bleManager.devices.mockResolvedValue([device]);
321
- await transport.acquire({ uuid, expectedProtocol: 'V2' });
322
-
323
- const mtuLogs = logger.debug.mock.calls
324
- .filter(([message]) => message === '[ReactNativeBleTransport] BLE MTU ready')
325
- .map(([, params]) => params as { connectionId: number; actual: number });
326
- expect(mtuLogs).toHaveLength(3);
327
- expect(new Set(mtuLogs.map(({ connectionId }) => connectionId)).size).toBe(3);
328
- for (const params of mtuLogs) {
329
- expect(params).toEqual({
330
- platform,
331
- requested: expect.any(Number),
332
- actual: device.mtu,
333
- connectionId: expect.any(Number),
334
- });
335
- expect(Number.isSafeInteger(params.connectionId)).toBe(true);
336
- expect(params.connectionId).toBeGreaterThan(0);
337
- }
338
- } finally {
339
- await transport.release(uuid, true);
340
- await transport.release(otherUuid, true);
341
- }
342
- }
343
- );
344
-
345
321
  test('does not classify disconnects as retryable firmware writes', () => {
346
322
  expect(
347
323
  getFirmwareUploadWriteRetryType({
@@ -402,16 +378,9 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
402
378
  expect(new ReactNativeBleTransport({}).scanTimeout).toBe(3000);
403
379
  });
404
380
 
405
- test.each([
406
- { protocol: 'V1', initiated: true },
407
- { protocol: 'V1', initiated: false },
408
- { protocol: 'V1', initiated: undefined },
409
- { protocol: 'V2', initiated: true },
410
- { protocol: 'V2', initiated: false },
411
- { protocol: 'V2', initiated: undefined },
412
- ] as const)(
413
- 'waits for Android bonding before connecting $protocol GATT, initiated=$initiated',
414
- async ({ protocol, initiated }) => {
381
+ test.each(['V1', 'V2'] as const)(
382
+ 'waits for Android bonding before connecting the %s GATT link',
383
+ async protocol => {
415
384
  setPlatformOS('android');
416
385
  const { transport, uuid, device } = protocol === 'V1' ? createV1Harness() : createHarness();
417
386
  const operationOrder: string[] = [];
@@ -426,7 +395,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
426
395
  });
427
396
  pairDeviceMock.mockImplementationOnce(() => {
428
397
  operationOrder.push('bond');
429
- return Promise.resolve({ bonded: false, bonding: true, initiated });
398
+ return Promise.resolve({ bonded: false, bonding: true });
430
399
  });
431
400
  bondStateMock.mockImplementationOnce(() => bonding.promise);
432
401
 
@@ -436,9 +405,6 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
436
405
  });
437
406
  expect(operationOrder).toEqual(['bond']);
438
407
  expect(device.connect).not.toHaveBeenCalled();
439
- expect(bondStateMock).toHaveBeenLastCalledWith(uuid, expect.any(AbortSignal), {
440
- systemInitiated: initiated === false,
441
- });
442
408
 
443
409
  bonding.resolve();
444
410
  await expect(acquiring).resolves.toEqual({
@@ -481,42 +447,6 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
481
447
  expect(pairDeviceMock).toHaveBeenCalledTimes(1);
482
448
  });
483
449
 
484
- test.each([
485
- ['ios', 'V1'],
486
- ['ios', 'V2'],
487
- ['android', 'V1'],
488
- ['android', 'V2'],
489
- ] as const)(
490
- 'uses connection or disconnect errors instead of a legacy bond error for ATT 22 on %s %s',
491
- async (platform, expectedProtocol) => {
492
- setPlatformOS(platform);
493
- const BleErrorMock = jest.requireMock('react-native-ble-plx').BleError as new (
494
- message: string
495
- ) => Error;
496
-
497
- for (const [nativeCode, expectedCode] of [
498
- [205, HardwareErrorCode.BleConnectedError],
499
- [201, HardwareErrorCode.BleDeviceDisconnected],
500
- ]) {
501
- const { transport, uuid, device } = createHarness();
502
- const nativeError = Object.assign(new BleErrorMock('GATT connect failed'), {
503
- errorCode: nativeCode,
504
- attErrorCode: 22,
505
- reason: 'GATT connect failed',
506
- });
507
- device.isConnected.mockResolvedValueOnce(false);
508
- device.connect.mockRejectedValueOnce(nativeError);
509
-
510
- await expect(transport.acquire({ uuid, expectedProtocol })).rejects.toMatchObject({
511
- errorCode: expectedCode,
512
- message: expect.stringContaining('GATT connect failed'),
513
- });
514
- expect(device.connect).toHaveBeenCalledTimes(1);
515
- expect(transport.getProtocolType(uuid)).toBeUndefined();
516
- }
517
- }
518
- );
519
-
520
450
  test('does not connect Android GATT when the system cannot start bonding', async () => {
521
451
  setPlatformOS('android');
522
452
  const { transport, uuid, device, bleManager } = createHarness();
@@ -548,11 +478,27 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
548
478
  });
549
479
 
550
480
  test.each([
551
- ['ios', 'OneKey Neo', { iosErrorCode: 14, reason: 'Native connection failed' }],
552
- ['android', 'OneKey Pro 2', { androidErrorCode: 5, reason: 'Native connection failed' }],
481
+ [
482
+ 'ios',
483
+ 'OneKey Neo',
484
+ {
485
+ iosErrorCode: 14,
486
+ reason: 'Peer removed pairing information',
487
+ },
488
+ HardwareErrorCode.BlePeerRemovedPairingInformation,
489
+ ],
490
+ [
491
+ 'android',
492
+ 'OneKey Pro 2',
493
+ {
494
+ androidErrorCode: 5,
495
+ reason: 'Connection state changed with status 5',
496
+ },
497
+ HardwareErrorCode.BleDeviceBondError,
498
+ ],
553
499
  ] as const)(
554
- 'keeps a %s %s native connect failure generic before protocol detection',
555
- async (platform, deviceName, nativeError) => {
500
+ 'maps a %s %s stale bond during connect before protocol detection',
501
+ async (platform, deviceName, nativeError, errorCode) => {
556
502
  setPlatformOS(platform);
557
503
  const { transport, uuid, device } = createHarness({ deviceName });
558
504
  const BleErrorMock = jest.requireMock('react-native-ble-plx').BleError as new (
@@ -566,9 +512,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
566
512
  .fn()
567
513
  .mockRejectedValue(Object.assign(new BleErrorMock(nativeError.reason), nativeError));
568
514
 
569
- await expect(transport.acquire({ uuid })).rejects.toMatchObject({
570
- errorCode: HardwareErrorCode.BleConnectedError,
571
- });
515
+ await expect(transport.acquire({ uuid })).rejects.toMatchObject({ errorCode });
572
516
  expect(pairDeviceMock).toHaveBeenCalledTimes(platform === 'android' ? 1 : 0);
573
517
  expect(transport.getProtocolType(uuid)).toBeUndefined();
574
518
  }
@@ -664,7 +608,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
664
608
  await transport.release(uuid, true);
665
609
  });
666
610
 
667
- test('maps native Protocol V1 write failures to the generic write error', async () => {
611
+ test('keeps native stale-bond write mapping out of Protocol V1 calls', async () => {
668
612
  const { transport, uuid, writeCharacteristic } = createV1Harness();
669
613
  const nativeError = Object.assign(new Error('Encryption is insufficient'), {
670
614
  attErrorCode: 15,
@@ -887,6 +831,35 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
887
831
  }
888
832
  );
889
833
 
834
+ test.each([
835
+ [
836
+ 'Encryption is insufficient',
837
+ { reason: 'Encryption is insufficient', attErrorCode: 15 },
838
+ HardwareErrorCode.BleDeviceBondError,
839
+ ],
840
+ [
841
+ 'Peer removed pairing information',
842
+ { reason: 'Peer removed pairing information', iosErrorCode: 14 },
843
+ HardwareErrorCode.BlePeerRemovedPairingInformation,
844
+ ],
845
+ ] as const)(
846
+ 'fails Protocol V2 acquire immediately on %s instead of waiting for Ping',
847
+ async (_label, nativeError, errorCode) => {
848
+ const { transport, uuid, device } = createHarness({
849
+ monitorError: Object.assign(new Error(nativeError.reason), nativeError),
850
+ });
851
+ const probe = jest.spyOn(transport as any, 'probeProtocolV2');
852
+
853
+ await expect(transport.acquire({ uuid, expectedProtocol: 'V2' })).rejects.toMatchObject({
854
+ errorCode,
855
+ });
856
+
857
+ expect(probe).not.toHaveBeenCalled();
858
+ expect(device.cancelConnection).toHaveBeenCalled();
859
+ expect(transport.getProtocolType(uuid)).toBeUndefined();
860
+ }
861
+ );
862
+
890
863
  test.each(['ios', 'android'] as const)(
891
864
  'disconnects after a confirmed Protocol V2 probe miss on %s without reporting a bond error',
892
865
  async platform => {
@@ -1056,6 +1029,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
1056
1029
  for (const errorCode of [
1057
1030
  HardwareErrorCode.BleDeviceNotBonded,
1058
1031
  HardwareErrorCode.BleDeviceBondedCanceled,
1032
+ HardwareErrorCode.BlePeerRemovedPairingInformation,
1059
1033
  HardwareErrorCode.BleDeviceDisconnected,
1060
1034
  HardwareErrorCode.BleCharacteristicNotifyError,
1061
1035
  HardwareErrorCode.BleCharacteristicNotifyChangeFailure,
@@ -1236,20 +1210,20 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
1236
1210
  await transport.release(uuid, true);
1237
1211
  }, 10_000);
1238
1212
 
1239
- test('keeps an iOS MTU-timeout reconnect failure generic', async () => {
1213
+ test('maps a stale bond from the iOS MTU-timeout reconnect', async () => {
1240
1214
  const { BleError: BleErrorMock } = jest.requireMock('react-native-ble-plx');
1241
1215
  const { transport, uuid, device } = createHarness();
1242
1216
  device.mtu = 23;
1243
1217
  device.requestMTU.mockImplementationOnce(() => new Promise(() => {}));
1244
1218
  device.connect.mockRejectedValueOnce(
1245
- Object.assign(new BleErrorMock('Native connection failed'), {
1219
+ Object.assign(new BleErrorMock('Peer removed pairing information'), {
1246
1220
  errorCode: 200,
1247
1221
  iosErrorCode: 14,
1248
1222
  })
1249
1223
  );
1250
1224
 
1251
1225
  await expect(transport.acquire({ uuid })).rejects.toMatchObject({
1252
- errorCode: HardwareErrorCode.BleConnectedError,
1226
+ errorCode: HardwareErrorCode.BlePeerRemovedPairingInformation,
1253
1227
  });
1254
1228
  await transport.release(uuid, true).catch(() => undefined);
1255
1229
  }, 10_000);