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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  }));
@@ -432,42 +447,6 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
432
447
  expect(pairDeviceMock).toHaveBeenCalledTimes(1);
433
448
  });
434
449
 
435
- test.each([
436
- ['ios', 'V1'],
437
- ['ios', 'V2'],
438
- ['android', 'V1'],
439
- ['android', 'V2'],
440
- ] as const)(
441
- 'uses connection or disconnect errors instead of a legacy bond error for ATT 22 on %s %s',
442
- async (platform, expectedProtocol) => {
443
- setPlatformOS(platform);
444
- const BleErrorMock = jest.requireMock('react-native-ble-plx').BleError as new (
445
- message: string
446
- ) => Error;
447
-
448
- for (const [nativeCode, expectedCode] of [
449
- [205, HardwareErrorCode.BleConnectedError],
450
- [201, HardwareErrorCode.BleDeviceDisconnected],
451
- ]) {
452
- const { transport, uuid, device } = createHarness();
453
- const nativeError = Object.assign(new BleErrorMock('GATT connect failed'), {
454
- errorCode: nativeCode,
455
- attErrorCode: 22,
456
- reason: 'GATT connect failed',
457
- });
458
- device.isConnected.mockResolvedValueOnce(false);
459
- device.connect.mockRejectedValueOnce(nativeError);
460
-
461
- await expect(transport.acquire({ uuid, expectedProtocol })).rejects.toMatchObject({
462
- errorCode: expectedCode,
463
- message: expect.stringContaining('GATT connect failed'),
464
- });
465
- expect(device.connect).toHaveBeenCalledTimes(1);
466
- expect(transport.getProtocolType(uuid)).toBeUndefined();
467
- }
468
- }
469
- );
470
-
471
450
  test('does not connect Android GATT when the system cannot start bonding', async () => {
472
451
  setPlatformOS('android');
473
452
  const { transport, uuid, device, bleManager } = createHarness();
@@ -499,11 +478,27 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
499
478
  });
500
479
 
501
480
  test.each([
502
- ['ios', 'OneKey Neo', { iosErrorCode: 14, reason: 'Native connection failed' }],
503
- ['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
+ ],
504
499
  ] as const)(
505
- 'keeps a %s %s native connect failure generic before protocol detection',
506
- async (platform, deviceName, nativeError) => {
500
+ 'maps a %s %s stale bond during connect before protocol detection',
501
+ async (platform, deviceName, nativeError, errorCode) => {
507
502
  setPlatformOS(platform);
508
503
  const { transport, uuid, device } = createHarness({ deviceName });
509
504
  const BleErrorMock = jest.requireMock('react-native-ble-plx').BleError as new (
@@ -517,9 +512,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
517
512
  .fn()
518
513
  .mockRejectedValue(Object.assign(new BleErrorMock(nativeError.reason), nativeError));
519
514
 
520
- await expect(transport.acquire({ uuid })).rejects.toMatchObject({
521
- errorCode: HardwareErrorCode.BleConnectedError,
522
- });
515
+ await expect(transport.acquire({ uuid })).rejects.toMatchObject({ errorCode });
523
516
  expect(pairDeviceMock).toHaveBeenCalledTimes(platform === 'android' ? 1 : 0);
524
517
  expect(transport.getProtocolType(uuid)).toBeUndefined();
525
518
  }
@@ -615,7 +608,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
615
608
  await transport.release(uuid, true);
616
609
  });
617
610
 
618
- 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 () => {
619
612
  const { transport, uuid, writeCharacteristic } = createV1Harness();
620
613
  const nativeError = Object.assign(new Error('Encryption is insufficient'), {
621
614
  attErrorCode: 15,
@@ -838,6 +831,35 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
838
831
  }
839
832
  );
840
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
+
841
863
  test.each(['ios', 'android'] as const)(
842
864
  'disconnects after a confirmed Protocol V2 probe miss on %s without reporting a bond error',
843
865
  async platform => {
@@ -1007,6 +1029,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
1007
1029
  for (const errorCode of [
1008
1030
  HardwareErrorCode.BleDeviceNotBonded,
1009
1031
  HardwareErrorCode.BleDeviceBondedCanceled,
1032
+ HardwareErrorCode.BlePeerRemovedPairingInformation,
1010
1033
  HardwareErrorCode.BleDeviceDisconnected,
1011
1034
  HardwareErrorCode.BleCharacteristicNotifyError,
1012
1035
  HardwareErrorCode.BleCharacteristicNotifyChangeFailure,
@@ -1187,20 +1210,20 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
1187
1210
  await transport.release(uuid, true);
1188
1211
  }, 10_000);
1189
1212
 
1190
- test('keeps an iOS MTU-timeout reconnect failure generic', async () => {
1213
+ test('maps a stale bond from the iOS MTU-timeout reconnect', async () => {
1191
1214
  const { BleError: BleErrorMock } = jest.requireMock('react-native-ble-plx');
1192
1215
  const { transport, uuid, device } = createHarness();
1193
1216
  device.mtu = 23;
1194
1217
  device.requestMTU.mockImplementationOnce(() => new Promise(() => {}));
1195
1218
  device.connect.mockRejectedValueOnce(
1196
- Object.assign(new BleErrorMock('Native connection failed'), {
1219
+ Object.assign(new BleErrorMock('Peer removed pairing information'), {
1197
1220
  errorCode: 200,
1198
1221
  iosErrorCode: 14,
1199
1222
  })
1200
1223
  );
1201
1224
 
1202
1225
  await expect(transport.acquire({ uuid })).rejects.toMatchObject({
1203
- errorCode: HardwareErrorCode.BleConnectedError,
1226
+ errorCode: HardwareErrorCode.BlePeerRemovedPairingInformation,
1204
1227
  });
1205
1228
  await transport.release(uuid, true).catch(() => undefined);
1206
1229
  }, 10_000);