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

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,307 @@
1
+ import EventEmitter from 'events';
2
+
3
+ import { ERRORS, HardwareErrorCode } from '@onekeyfe/hd-shared';
4
+
5
+ import ReactNativeBleTransport, {
6
+ ANDROID_KEY_MISSING_GRACE_MS,
7
+ ANDROID_KEY_MISSING_LINK_WINDOW_MS,
8
+ } from '../index';
9
+ import { SYSTEM_BONDING_RESTART_WINDOW_MS, onDeviceBondState } from '../BleManager';
10
+ import { stopBleKeyMissingTracking } from '../bleKeyMissing';
11
+ import protocolV1Schema from './protocolV1SchemaFixture';
12
+
13
+ let mockKeyMissingSupported = true;
14
+ let mockEmitKeyMissing: ((event: { id?: string }) => void) | undefined;
15
+ let mockEmitBondState: ((peripheral: unknown) => void) | undefined;
16
+
17
+ jest.mock(
18
+ 'react-native',
19
+ () => ({
20
+ Platform: { OS: 'android', select: (spec: Record<string, unknown>) => spec.android },
21
+ PermissionsAndroid: {
22
+ PERMISSIONS: {},
23
+ RESULTS: {},
24
+ request: jest.fn(),
25
+ requestMultiple: jest.fn(),
26
+ },
27
+ }),
28
+ { virtual: true }
29
+ );
30
+
31
+ jest.mock('react-native-ble-plx', () => ({
32
+ BleATTErrorCode: { InvalidHandle: 1 },
33
+ BleError: Error,
34
+ BleErrorCode: { DeviceDisconnected: 201, OperationStartFailed: 601 },
35
+ BleManager: jest.fn(),
36
+ ScanMode: { LowLatency: 2 },
37
+ }));
38
+
39
+ jest.mock('@onekeyfe/react-native-ble-utils', () => ({
40
+ __esModule: true,
41
+ default: {
42
+ getConnectedPeripherals: jest.fn(() => Promise.resolve([])),
43
+ getBondedPeripherals: jest.fn(() => Promise.resolve([])),
44
+ pairDevice: jest.fn(() => Promise.resolve({ bonded: true, bonding: false })),
45
+ supportsDeviceKeyMissing: jest.fn(() => mockKeyMissingSupported),
46
+ onDeviceKeyMissing: jest.fn((callback: (event: { id?: string }) => void) => {
47
+ mockEmitKeyMissing = callback;
48
+ return () => {
49
+ mockEmitKeyMissing = undefined;
50
+ };
51
+ }),
52
+ onDeviceBondState: jest.fn((callback: (peripheral: unknown) => void) => {
53
+ mockEmitBondState = callback;
54
+ return () => {
55
+ mockEmitBondState = undefined;
56
+ };
57
+ }),
58
+ },
59
+ }));
60
+
61
+ const UUID = 'CC:06:1C:FD:48:E9';
62
+
63
+ const flush = () =>
64
+ new Promise(resolve => {
65
+ setImmediate(resolve);
66
+ });
67
+
68
+ const advance = async (ms: number) => {
69
+ jest.advanceTimersByTime(ms);
70
+ await flush();
71
+ };
72
+
73
+ // What ble-plx reports when the device drops the link while the first write is queued.
74
+ const peerTerminated = () =>
75
+ Promise.reject(
76
+ Object.assign(new Error(`Device ${UUID} was disconnected`), {
77
+ errorCode: 201,
78
+ attErrorCode: 19,
79
+ reason: 'Disconnected with status 19 (GATT_CONN_TERMINATE_PEER_USER)',
80
+ })
81
+ );
82
+
83
+ function createConnectedTransport(linkAgeMs = 0) {
84
+ const t = new ReactNativeBleTransport({});
85
+ t.configure(protocolV1Schema);
86
+ (t as any).deviceProtocol.set(UUID, 'V1');
87
+ (t as any).getCachedTransport = () => ({
88
+ writeCharacteristic: { writeWithoutResponse: jest.fn(peerTerminated) },
89
+ });
90
+ (t as any).androidLinkStartedAt.set(UUID, Date.now() - linkAgeMs);
91
+ return t;
92
+ }
93
+
94
+ const settle = (promise: Promise<unknown>) => {
95
+ const outcome: { error?: { errorCode?: unknown }; done: boolean } = { done: false };
96
+ promise.then(
97
+ () => {
98
+ outcome.done = true;
99
+ },
100
+ error => {
101
+ outcome.error = error;
102
+ outcome.done = true;
103
+ }
104
+ );
105
+ return outcome;
106
+ };
107
+
108
+ describe('Android key missing', () => {
109
+ beforeEach(() => {
110
+ jest.useFakeTimers({ doNotFake: ['setImmediate', 'performance'] });
111
+ mockKeyMissingSupported = true;
112
+ });
113
+
114
+ afterEach(() => {
115
+ stopBleKeyMissingTracking();
116
+ jest.clearAllTimers();
117
+ jest.useRealTimers();
118
+ });
119
+
120
+ describe('link dropped right after connect', () => {
121
+ test('reports an invalid bond when the system says the keys are missing', async () => {
122
+ const outcome = settle(createConnectedTransport().call(UUID, 'GetFeatures', {}));
123
+ await flush();
124
+ // The broadcast is delivered separately and can trail the GATT disconnect.
125
+ mockEmitKeyMissing?.({ id: UUID.toLowerCase() });
126
+ await flush();
127
+
128
+ expect(outcome.error?.errorCode).toBe(HardwareErrorCode.BleBondInvalid);
129
+ });
130
+
131
+ test('keeps the original error when no key missing follows', async () => {
132
+ const outcome = settle(createConnectedTransport().call(UUID, 'GetFeatures', {}));
133
+ await flush();
134
+ expect(outcome.done).toBe(false);
135
+
136
+ await advance(ANDROID_KEY_MISSING_GRACE_MS);
137
+
138
+ expect(outcome.error?.errorCode).toBe(HardwareErrorCode.BleDeviceNotBonded);
139
+ });
140
+
141
+ test('ignores key missing reported for an earlier link', async () => {
142
+ const transport = createConnectedTransport();
143
+ const earlier = settle(transport.call(UUID, 'GetFeatures', {}));
144
+ await flush();
145
+ mockEmitKeyMissing?.({ id: UUID });
146
+ await flush();
147
+ expect(earlier.error?.errorCode).toBe(HardwareErrorCode.BleBondInvalid);
148
+
149
+ // The user re-paired; a later link that drops is an ordinary disconnect.
150
+ await advance(1000);
151
+ (transport as any).androidLinkStartedAt.set(UUID, Date.now());
152
+ const later = settle(transport.call(UUID, 'GetFeatures', {}));
153
+ await flush();
154
+ await advance(ANDROID_KEY_MISSING_GRACE_MS);
155
+
156
+ expect(later.error?.errorCode).toBe(HardwareErrorCode.BleDeviceNotBonded);
157
+ });
158
+
159
+ test('ignores key missing for another device', async () => {
160
+ const outcome = settle(createConnectedTransport().call(UUID, 'GetFeatures', {}));
161
+ await flush();
162
+ mockEmitKeyMissing?.({ id: 'E9:B9:F4:DD:DE:CD' });
163
+ await advance(ANDROID_KEY_MISSING_GRACE_MS);
164
+
165
+ expect(outcome.error?.errorCode).toBe(HardwareErrorCode.BleDeviceNotBonded);
166
+ });
167
+
168
+ test('does not wait on a link that has been up for a while', async () => {
169
+ const transport = createConnectedTransport(ANDROID_KEY_MISSING_LINK_WINDOW_MS + 1);
170
+ const outcome = settle(transport.call(UUID, 'GetFeatures', {}));
171
+ await flush();
172
+
173
+ expect(outcome.error?.errorCode).toBe(HardwareErrorCode.BleDeviceNotBonded);
174
+ });
175
+
176
+ test('does not wait when the OS or native build never reports key missing', async () => {
177
+ mockKeyMissingSupported = false;
178
+ const outcome = settle(createConnectedTransport().call(UUID, 'GetFeatures', {}));
179
+ await flush();
180
+
181
+ expect(outcome.error?.errorCode).toBe(HardwareErrorCode.BleDeviceNotBonded);
182
+ });
183
+ });
184
+
185
+ describe('acquire over a bond the device no longer holds', () => {
186
+ // Android still reports BONDED, so connect, MTU and GATT setup all succeed and the
187
+ // protocol probe is the first operation to meet the dropped link.
188
+ function createStaleBondHarness() {
189
+ const writeCharacteristic = {
190
+ uuid: '00000002-0000-1000-8000-00805f9b34fb',
191
+ isWritableWithoutResponse: true,
192
+ writeWithoutResponse: jest.fn(peerTerminated),
193
+ };
194
+ const notifyCharacteristic = {
195
+ uuid: '00000003-0000-1000-8000-00805f9b34fb',
196
+ isNotifiable: true,
197
+ monitor: jest.fn(() => ({ remove: jest.fn() })),
198
+ };
199
+ const device = {
200
+ id: UUID,
201
+ name: 'Pro 2 48E9',
202
+ localName: 'Pro 2 48E9',
203
+ mtu: 247,
204
+ serviceUUIDs: ['00000001-0000-1000-8000-00805f9b34fb'],
205
+ isConnected: jest.fn(() => Promise.resolve(true)),
206
+ cancelConnection: jest.fn(() => Promise.resolve()),
207
+ discoverAllServicesAndCharacteristics: jest.fn(() => Promise.resolve()),
208
+ characteristicsForService: jest.fn(() =>
209
+ Promise.resolve([writeCharacteristic, notifyCharacteristic])
210
+ ),
211
+ services: jest.fn(() => Promise.resolve([])),
212
+ onDisconnected: jest.fn(() => ({ remove: jest.fn() })),
213
+ };
214
+ const transport = new ReactNativeBleTransport({});
215
+ (transport as any).blePlxManager = {
216
+ devices: jest.fn(() => Promise.resolve([device])),
217
+ connectedDevices: jest.fn(() => Promise.resolve([])),
218
+ cancelTransaction: jest.fn(() => Promise.resolve()),
219
+ cancelDeviceConnection: jest.fn(() => Promise.resolve()),
220
+ onStateChange: jest.fn((listener: (state: string) => void) => {
221
+ setImmediate(() => listener('PoweredOn'));
222
+ return { remove: jest.fn() };
223
+ }),
224
+ state: jest.fn(() => Promise.resolve('PoweredOn')),
225
+ };
226
+ transport.init(
227
+ { debug: jest.fn(), error: jest.fn(), warn: jest.fn() } as any,
228
+ new EventEmitter()
229
+ );
230
+ transport.configure(protocolV1Schema);
231
+ return { transport, write: writeCharacteristic.writeWithoutResponse };
232
+ }
233
+
234
+ async function acquireUntilSettled(keyMissing: boolean) {
235
+ const { transport, write } = createStaleBondHarness();
236
+ const outcome = settle(transport.acquire({ uuid: UUID }));
237
+ for (let i = 0; i < 100 && !outcome.done; i += 1) {
238
+ // eslint-disable-next-line no-await-in-loop
239
+ await advance(100);
240
+ // The broadcast follows the dropped link, which the probe write is first to meet.
241
+ if (keyMissing && write.mock.calls.length > 0) mockEmitKeyMissing?.({ id: UUID });
242
+ }
243
+ expect(write).toHaveBeenCalled();
244
+ return JSON.parse(JSON.stringify(ERRORS.serializeError({ error: outcome.error })));
245
+ }
246
+
247
+ test('ends as an invalid bond that survives the Core response path', async () => {
248
+ await expect(acquireUntilSettled(true)).resolves.toEqual({
249
+ code: HardwareErrorCode.BleBondInvalid,
250
+ error: expect.stringContaining('Forget the device'),
251
+ params: { phase: 'connect', reason: 'key_missing' },
252
+ });
253
+ });
254
+
255
+ test('keeps the legacy error when the system reports nothing', async () => {
256
+ await expect(acquireUntilSettled(false)).resolves.toMatchObject({
257
+ code: HardwareErrorCode.BleDeviceNotBonded,
258
+ });
259
+ });
260
+ });
261
+
262
+ describe('waiting for bonding', () => {
263
+ const bondState = (preState: string, state: string) =>
264
+ mockEmitBondState?.({ id: UUID, bondState: { preState, state } });
265
+
266
+ test('fails as an invalid bond when the system re-pair ends in key missing', async () => {
267
+ const outcome = settle(onDeviceBondState(UUID, undefined, { systemInitiated: true }));
268
+ mockEmitKeyMissing?.({ id: UUID });
269
+ await flush();
270
+
271
+ expect(outcome.error?.errorCode).toBe(HardwareErrorCode.BleBondInvalid);
272
+ });
273
+
274
+ test('follows a system re-pair that replaces the bond', async () => {
275
+ const outcome = settle(onDeviceBondState(UUID, undefined, { systemInitiated: true }));
276
+ bondState('BOND_BONDING', 'BOND_NONE');
277
+ bondState('BOND_NONE', 'BOND_BONDING');
278
+ await advance(SYSTEM_BONDING_RESTART_WINDOW_MS);
279
+ expect(outcome.done).toBe(false);
280
+
281
+ bondState('BOND_BONDING', 'BOND_BONDED');
282
+ await flush();
283
+
284
+ expect(outcome.done).toBe(true);
285
+ expect(outcome.error).toBeUndefined();
286
+ });
287
+
288
+ test('fails a system re-pair that ends without a bond', async () => {
289
+ const outcome = settle(onDeviceBondState(UUID, undefined, { systemInitiated: true }));
290
+ bondState('BOND_BONDING', 'BOND_NONE');
291
+ await flush();
292
+ expect(outcome.done).toBe(false);
293
+
294
+ await advance(SYSTEM_BONDING_RESTART_WINDOW_MS);
295
+
296
+ expect(outcome.error?.errorCode).toBe(HardwareErrorCode.BleDeviceNotBonded);
297
+ });
298
+
299
+ test('fails a bonding this transport started as soon as it ends without a bond', async () => {
300
+ const outcome = settle(onDeviceBondState(UUID));
301
+ bondState('BOND_BONDING', 'BOND_NONE');
302
+ await flush();
303
+
304
+ expect(outcome.error?.errorCode).toBe(HardwareErrorCode.BleDeviceNotBonded);
305
+ });
306
+ });
307
+ });
@@ -14,7 +14,7 @@ describe('native BLE disconnect mapping', () => {
14
14
  });
15
15
  });
16
16
 
17
- test('does not treat an unrelated iOS code as a disconnect', () => {
17
+ test('does not treat a stale-bond iOS code as a disconnect', () => {
18
18
  expect(
19
19
  isNativeBleDisconnectError({
20
20
  iosErrorCode: 14,
@@ -30,25 +30,4 @@ describe('native BLE disconnect mapping', () => {
30
30
  })
31
31
  ).toBe(false);
32
32
  });
33
-
34
- test('recognizes the unstructured ble-plx disconnect observed during GATT discovery', () => {
35
- const nativeError = {
36
- errorCode: 0,
37
- message: 'BleError: Device stalled-connect-device was disconnected',
38
- };
39
-
40
- expect(isNativeBleDisconnectError(nativeError)).toBe(true);
41
- expect(toBleDisconnectHardwareError(nativeError)).toMatchObject({
42
- errorCode: HardwareErrorCode.BleDeviceDisconnected,
43
- });
44
- });
45
-
46
- test('does not infer a disconnect from an unrelated discovery failure', () => {
47
- expect(
48
- isNativeBleDisconnectError({
49
- errorCode: 0,
50
- message: 'Known OneKey service UUID not found',
51
- })
52
- ).toBe(false);
53
- });
54
33
  });
@@ -0,0 +1,47 @@
1
+ import { HardwareErrorCode } from '@onekeyfe/hd-shared';
2
+
3
+ import { isNativeBleStaleBondError, toBleStaleBondHardwareError } from '../bleStaleBond';
4
+
5
+ describe('native BLE stale bond mapping', () => {
6
+ test.each([
7
+ [
8
+ { attErrorCode: 15, reason: 'Encryption is insufficient' },
9
+ HardwareErrorCode.BleDeviceBondError,
10
+ ],
11
+ [
12
+ { attErrorCode: 5, reason: 'GATT_INSUF_AUTHENTICATION' },
13
+ HardwareErrorCode.BleDeviceBondError,
14
+ ],
15
+ [
16
+ { androidErrorCode: 5, reason: 'Connection state changed with status 5' },
17
+ HardwareErrorCode.BleDeviceBondError,
18
+ ],
19
+ [
20
+ { androidErrorCode: 15, reason: 'Connection state changed with status 15' },
21
+ HardwareErrorCode.BleDeviceBondError,
22
+ ],
23
+ [
24
+ { iosErrorCode: 14, reason: 'Peer removed pairing information' },
25
+ HardwareErrorCode.BlePeerRemovedPairingInformation,
26
+ ],
27
+ [
28
+ { reason: 'peer removed pairing information' },
29
+ HardwareErrorCode.BlePeerRemovedPairingInformation,
30
+ ],
31
+ [
32
+ { message: 'PEER REMOVED PAIRING INFORMATION' },
33
+ HardwareErrorCode.BlePeerRemovedPairingInformation,
34
+ ],
35
+ ])('maps %j to %s', (nativeError, errorCode) => {
36
+ expect(isNativeBleStaleBondError(nativeError)).toBe(true);
37
+ expect(toBleStaleBondHardwareError(nativeError)).toMatchObject({ errorCode });
38
+ });
39
+
40
+ test('does not treat the generic ATT unlikely error as a stale bond', () => {
41
+ expect(isNativeBleStaleBondError({ attErrorCode: 14, reason: 'Unlikely error' })).toBe(false);
42
+ });
43
+
44
+ test('does not treat a generic disconnect as a stale bond', () => {
45
+ expect(isNativeBleStaleBondError({ reason: 'Device disconnected' })).toBe(false);
46
+ });
47
+ });
@@ -129,102 +129,6 @@ describe('Android bond failure reasons', () => {
129
129
  expect(cleanup).toHaveBeenCalledTimes(1);
130
130
  });
131
131
 
132
- test('lets system-initiated bonding restart before accepting the replacement bond', async () => {
133
- const result = onDeviceBondState(UUID, undefined, { systemInitiated: true });
134
- const outcome = result.catch(error => error);
135
- emitBondState({
136
- id: UUID,
137
- advertising: {},
138
- bondState: { preState: 'BOND_BONDING', state: 'BOND_NONE', reason: 9 },
139
- });
140
- jest.advanceTimersByTime(1499);
141
- expect(cleanup).not.toHaveBeenCalled();
142
-
143
- emitBondState({
144
- id: UUID,
145
- advertising: {},
146
- bondState: { preState: 'BOND_NONE', state: 'BOND_BONDING' },
147
- });
148
- jest.advanceTimersByTime(1500);
149
- expect(cleanup).not.toHaveBeenCalled();
150
- const bonded: Peripheral = {
151
- id: UUID,
152
- advertising: {},
153
- bondState: { preState: 'BOND_BONDING', state: 'BOND_BONDED' },
154
- };
155
- emitBondState(bonded);
156
-
157
- await expect(outcome).resolves.toBe(bonded);
158
- expect(cleanup).toHaveBeenCalledTimes(1);
159
- expect(jest.getTimerCount()).toBe(0);
160
- });
161
-
162
- test('rejects a genuine system bond failure when the restart window expires', async () => {
163
- const result = onDeviceBondState(UUID, undefined, { systemInitiated: true });
164
- const rejection = expect(result).rejects.toMatchObject({
165
- errorCode: HardwareErrorCode.BleDeviceNotBonded,
166
- params: { phase: 'bond', reason: 'authentication_failed', nativeReason: 1 },
167
- });
168
- emitBondState({
169
- id: UUID,
170
- advertising: {},
171
- bondState: { preState: 'BOND_BONDING', state: 'BOND_NONE', reason: 1 },
172
- });
173
- jest.advanceTimersByTime(1499);
174
- expect(cleanup).not.toHaveBeenCalled();
175
- jest.advanceTimersByTime(1);
176
-
177
- await rejection;
178
- expect(cleanup).toHaveBeenCalledTimes(1);
179
- expect(jest.getTimerCount()).toBe(0);
180
- });
181
-
182
- test('aborts a pending system restart without leaving either timer or listener', async () => {
183
- const controller = new AbortController();
184
- const result = onDeviceBondState(UUID, controller.signal, { systemInitiated: true });
185
- const outcome = result.catch(error => error);
186
- emitBondState({
187
- id: UUID,
188
- advertising: {},
189
- bondState: { preState: 'BOND_BONDING', state: 'BOND_NONE', reason: 9 },
190
- });
191
- expect(cleanup).not.toHaveBeenCalled();
192
-
193
- controller.abort();
194
- await expect(outcome).resolves.toMatchObject({
195
- errorCode: HardwareErrorCode.BleDeviceDisconnected,
196
- });
197
- expect(cleanup).toHaveBeenCalledTimes(1);
198
- expect(jest.getTimerCount()).toBe(0);
199
- });
200
-
201
- test('keeps the overall deadline when system bonding repeatedly restarts', async () => {
202
- const result = onDeviceBondState(UUID, undefined, { systemInitiated: true });
203
- const outcome = result.catch(error => error);
204
- for (let index = 0; index < 40; index += 1) {
205
- emitBondState({
206
- id: UUID,
207
- advertising: {},
208
- bondState: { preState: 'BOND_BONDING', state: 'BOND_NONE', reason: 9 },
209
- });
210
- emitBondState({
211
- id: UUID,
212
- advertising: {},
213
- bondState: { preState: 'BOND_NONE', state: 'BOND_BONDING' },
214
- });
215
- jest.advanceTimersByTime(1000);
216
- }
217
- expect(cleanup).not.toHaveBeenCalled();
218
- jest.advanceTimersByTime(20_000);
219
-
220
- await expect(outcome).resolves.toMatchObject({
221
- errorCode: HardwareErrorCode.BleDeviceNotBonded,
222
- params: { phase: 'bond', reason: 'timeout' },
223
- });
224
- expect(cleanup).toHaveBeenCalledTimes(1);
225
- expect(jest.getTimerCount()).toBe(0);
226
- });
227
-
228
132
  test('aborts the bond wait and removes its listener and deadline', async () => {
229
133
  const controller = new AbortController();
230
134
  const result = onDeviceBondState(UUID, controller.signal);
@@ -719,20 +623,6 @@ describe('BLE connect timeout', () => {
719
623
  expect(bleManager.cancelDeviceConnection).toHaveBeenCalledWith(UUID);
720
624
  });
721
625
 
722
- test('normalizes an unstructured GATT disconnect instead of leaking an unknown error', async () => {
723
- const { transport, device } = createHarness(() => Promise.resolve());
724
- const nativeError = Object.assign(new Error(`BleError: Device ${UUID} was disconnected`), {
725
- errorCode: 0,
726
- });
727
- device.discoverAllServicesAndCharacteristics.mockRejectedValueOnce(nativeError);
728
-
729
- await expect(
730
- (transport as any).resolveCharacteristicsWithTimeout(UUID, device)
731
- ).rejects.toMatchObject({
732
- errorCode: HardwareErrorCode.BleDeviceDisconnected,
733
- });
734
- });
735
-
736
626
  test('a successful GATT retry clears the timeout budget before an abandoned call settles', async () => {
737
627
  const { transport, device, bleManager } = createHarness(() => Promise.resolve());
738
628
  let resolveAbandonedDiscovery: (() => void) | undefined;
@@ -1,22 +1,12 @@
1
1
  import { EventEmitter } from 'events';
2
- import { PermissionsAndroid, Platform } from 'react-native';
3
- import { BleErrorCode } from 'react-native-ble-plx';
4
- import { HardwareErrorCode } from '@onekeyfe/hd-shared';
5
2
 
6
3
  import { getConnectedDeviceIds } from '../BleManager';
7
4
  import ReactNativeBleTransport from '../index';
8
- import { subscribeBleOn } from '../subscribeBleOn';
9
5
 
10
6
  jest.mock(
11
7
  'react-native',
12
8
  () => ({
13
- PermissionsAndroid: {
14
- PERMISSIONS: {
15
- BLUETOOTH_CONNECT: 'android.permission.BLUETOOTH_CONNECT',
16
- BLUETOOTH_SCAN: 'android.permission.BLUETOOTH_SCAN',
17
- },
18
- requestMultiple: jest.fn(),
19
- },
9
+ PermissionsAndroid: {},
20
10
  Platform: { OS: 'ios' },
21
11
  }),
22
12
  { virtual: true }
@@ -24,14 +14,7 @@ jest.mock(
24
14
 
25
15
  jest.mock('react-native-ble-plx', () => ({
26
16
  BleError: class BleError extends Error {},
27
- BleErrorCode: {
28
- BluetoothUnsupported: 100,
29
- BluetoothUnauthorized: 101,
30
- BluetoothPoweredOff: 102,
31
- BluetoothInUnknownState: 103,
32
- ScanStartFailed: 600,
33
- LocationServicesDisabled: 601,
34
- },
17
+ BleErrorCode: {},
35
18
  BleManager: jest.fn(),
36
19
  ScanMode: { LowLatency: 2 },
37
20
  }));
@@ -42,61 +25,27 @@ jest.mock('../BleManager', () => ({
42
25
  pairDevice: jest.fn(),
43
26
  }));
44
27
 
28
+ // The native facade is replaced wholesale above; key missing and link encryption are covered
29
+ // by their own suites.
30
+ jest.mock('../bleKeyMissing', () => ({
31
+ isBleKeyMissingSupported: jest.fn(() => false),
32
+ startBleKeyMissingTracking: jest.fn(() => false),
33
+ stopBleKeyMissingTracking: jest.fn(),
34
+ waitForBleKeyMissing: jest.fn(() => Promise.resolve(false)),
35
+ }));
36
+ jest.mock('../bleEncryption', () => ({
37
+ markBleLinkEncrypted: jest.fn(),
38
+ startBleEncryptionTracking: jest.fn(() => false),
39
+ stopBleEncryptionTracking: jest.fn(),
40
+ waitForAndroidLinkEncryption: jest.fn(() => Promise.resolve('unresolved')),
41
+ }));
42
+
45
43
  jest.mock('../subscribeBleOn', () => ({
46
44
  subscribeBleOn: jest.fn(() => Promise.resolve()),
47
45
  }));
48
46
 
49
47
  const ONEKEY_SERVICE_UUID = '00000001-0000-1000-8000-00805f9b34fb';
50
48
 
51
- describe('ReactNativeBleTransport scan error mapping', () => {
52
- beforeEach(() => {
53
- jest.clearAllMocks();
54
- });
55
-
56
- afterEach(() => {
57
- Object.assign(Platform, { OS: 'ios', Version: undefined });
58
- });
59
-
60
- test('checks Android Bluetooth permissions before waiting for adapter state', async () => {
61
- Object.assign(Platform, { OS: 'android', Version: 31 });
62
- jest.mocked(PermissionsAndroid).requestMultiple.mockResolvedValueOnce({
63
- [PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT]: 'denied',
64
- [PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN]: 'denied',
65
- });
66
- const transport = new ReactNativeBleTransport({});
67
- transport.blePlxManager = {} as never;
68
- transport.init({ debug: jest.fn(), error: jest.fn() }, new EventEmitter());
69
-
70
- await expect(transport.enumerate()).rejects.toMatchObject({
71
- errorCode: HardwareErrorCode.BleLocationError,
72
- });
73
- expect(subscribeBleOn).not.toHaveBeenCalled();
74
- });
75
-
76
- test.each([
77
- [BleErrorCode.BluetoothPoweredOff, HardwareErrorCode.BlePoweredOff],
78
- [BleErrorCode.BluetoothUnsupported, HardwareErrorCode.BleUnsupported],
79
- [BleErrorCode.BluetoothInUnknownState, HardwareErrorCode.BleScanError],
80
- [BleErrorCode.BluetoothUnauthorized, HardwareErrorCode.BleLocationError],
81
- ])('maps native BLE error %s to hardware error %s', async (nativeCode, errorCode) => {
82
- jest.mocked(getConnectedDeviceIds).mockResolvedValueOnce([]);
83
- const blePlxManager = {
84
- startDeviceScan: jest.fn((_serviceUUIDs, _options, listener) => {
85
- queueMicrotask(() => {
86
- listener({ errorCode: nativeCode, reason: 'native scan failure' }, null);
87
- });
88
- }),
89
- stopDeviceScan: jest.fn(() => Promise.resolve()),
90
- };
91
- const transport = new ReactNativeBleTransport({ scanTimeout: 10_000 });
92
- transport.blePlxManager = blePlxManager as never;
93
- transport.init({ debug: jest.fn(), error: jest.fn() }, new EventEmitter());
94
-
95
- await expect(transport.enumerate()).rejects.toMatchObject({ errorCode });
96
- expect(blePlxManager.stopDeviceScan).toHaveBeenCalledTimes(1);
97
- });
98
- });
99
-
100
49
  describe('ReactNativeBleTransport iOS discovery', () => {
101
50
  test('keeps a bonded Pro2 communication peripheral after Find My changes its name', async () => {
102
51
  jest.mocked(getConnectedDeviceIds).mockResolvedValueOnce([