@onekeyfe/hd-transport-react-native 1.2.8-alpha.10 → 1.2.8-alpha.101

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.
@@ -1 +1 @@
1
- {"version":3,"file":"subscribeBleOn.d.ts","sourceRoot":"","sources":["../src/subscribeBleOn.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,eAAO,MAAM,cAAc,eAAgB,aAAa,kBAAc,QAAQ,IAAI,CAmB9E,CAAC"}
1
+ {"version":3,"file":"subscribeBleOn.d.ts","sourceRoot":"","sources":["../src/subscribeBleOn.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,eAAO,MAAM,cAAc,eAAgB,aAAa,kBAAc,QAAQ,IAAI,CAsC9E,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/hd-transport-react-native",
3
- "version": "1.2.8-alpha.10",
3
+ "version": "1.2.8-alpha.101",
4
4
  "homepage": "https://github.com/OneKeyHQ/hardware-js-sdk#readme",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
@@ -20,11 +20,11 @@
20
20
  "lint:fix": "eslint . --fix"
21
21
  },
22
22
  "dependencies": {
23
- "@onekeyfe/hd-core": "1.2.8-alpha.10",
24
- "@onekeyfe/hd-shared": "1.2.8-alpha.10",
25
- "@onekeyfe/hd-transport": "1.2.8-alpha.10",
23
+ "@onekeyfe/hd-core": "1.2.8-alpha.101",
24
+ "@onekeyfe/hd-shared": "1.2.8-alpha.101",
25
+ "@onekeyfe/hd-transport": "1.2.8-alpha.101",
26
26
  "@onekeyfe/react-native-ble-utils": "0.1.9",
27
27
  "react-native-ble-plx": "3.5.1"
28
28
  },
29
- "gitHead": "47d2f63acb8e5fa9ee623c060af7c9f83ad6f939"
29
+ "gitHead": "5670876ee082bbdf07bc1dcb17e0a93cda390085"
30
30
  }
package/src/BleManager.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import BleUtils from '@onekeyfe/react-native-ble-utils';
2
2
  import { ERRORS, HardwareErrorCode } from '@onekeyfe/hd-shared';
3
3
 
4
- import { onBleKeyMissing, startBleKeyMissingTracking } from './bleKeyMissing';
5
4
  import { bleLogger } from './logger';
6
5
 
7
6
  import type { Peripheral } from '@onekeyfe/react-native-ble-utils';
@@ -33,20 +32,7 @@ export const getBondedDevices = () => BleUtils.getBondedPeripherals();
33
32
 
34
33
  export const pairDevice = (macAddress: string) => BleUtils.pairDevice(macAddress);
35
34
 
36
- /**
37
- * Android replaces a bond as BONDING -> NONE, then NONE -> BONDING within milliseconds.
38
- * The window covers slow broadcast delivery before the first half counts as a failure.
39
- */
40
- export const SYSTEM_BONDING_RESTART_WINDOW_MS = 1500;
41
-
42
- export type DeviceBondStateOptions = {
43
- /**
44
- * The system, not this transport, started the bonding in progress. Android 16+ re-pairs
45
- * by itself after it detects a lost bond, and a successful re-pair replaces the old bond
46
- * instead of going straight to BONDED.
47
- */
48
- systemInitiated?: boolean;
49
- };
35
+ const SYSTEM_BONDING_RESTART_WINDOW_MS = 1500;
50
36
 
51
37
  const createBondFailureError = (bondState: Peripheral['bondState']) => {
52
38
  const nativeReason =
@@ -83,7 +69,7 @@ const createBondFailureError = (bondState: Peripheral['bondState']) => {
83
69
  export const onDeviceBondState = (
84
70
  bleMacAddress: string,
85
71
  signal?: AbortSignal,
86
- options?: DeviceBondStateOptions
72
+ options?: { systemInitiated?: boolean }
87
73
  ): Promise<Peripheral | undefined> =>
88
74
  new Promise((resolve, reject) => {
89
75
  if (signal?.aborted) {
@@ -97,7 +83,6 @@ export const onDeviceBondState = (
97
83
  }
98
84
  if (pendingFailure) clearTimeout(pendingFailure);
99
85
  if (cleanupListener) cleanupListener();
100
- cleanupKeyMissing?.();
101
86
  signal?.removeEventListener('abort', onAbort);
102
87
  };
103
88
  const onAbort = () => {
@@ -117,20 +102,6 @@ export const onDeviceBondState = (
117
102
  );
118
103
  }, 60 * 1000);
119
104
 
120
- // A failed system re-pair restores the old bond, so it also ends in BONDED. Key
121
- // missing is what tells it apart from a bond that now works.
122
- const cleanupKeyMissing = startBleKeyMissingTracking()
123
- ? onBleKeyMissing(bleMacAddress, () => {
124
- cleanup();
125
- reject(
126
- ERRORS.TypedError(HardwareErrorCode.BleBondInvalid, undefined, {
127
- phase: 'bond',
128
- reason: 'key_missing',
129
- })
130
- );
131
- })
132
- : undefined;
133
-
134
105
  const cleanupListener = BleUtils.onDeviceBondState(peripheral => {
135
106
  if (peripheral.id?.toLowerCase() !== bleMacAddress.toLowerCase()) {
136
107
  return;
@@ -148,6 +119,8 @@ export const onDeviceBondState = (
148
119
  clearTimeout(pendingFailure);
149
120
  pendingFailure = undefined;
150
121
  } else if (hasFailed && options?.systemInitiated) {
122
+ // Android can briefly remove the old bond before continuing an
123
+ // already-running system pairing. The original overall deadline stays.
151
124
  if (pendingFailure) clearTimeout(pendingFailure);
152
125
  pendingFailure = setTimeout(() => {
153
126
  cleanup();
@@ -14,7 +14,7 @@ describe('native BLE disconnect mapping', () => {
14
14
  });
15
15
  });
16
16
 
17
- test('does not treat a stale-bond iOS code as a disconnect', () => {
17
+ test('does not treat an unrelated iOS code as a disconnect', () => {
18
18
  expect(
19
19
  isNativeBleDisconnectError({
20
20
  iosErrorCode: 14,
@@ -30,4 +30,25 @@ 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
+ });
33
54
  });
@@ -129,6 +129,102 @@ 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
+
132
228
  test('aborts the bond wait and removes its listener and deadline', async () => {
133
229
  const controller = new AbortController();
134
230
  const result = onDeviceBondState(UUID, controller.signal);
@@ -623,6 +719,20 @@ describe('BLE connect timeout', () => {
623
719
  expect(bleManager.cancelDeviceConnection).toHaveBeenCalledWith(UUID);
624
720
  });
625
721
 
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
+
626
736
  test('a successful GATT retry clears the timeout budget before an abandoned call settles', async () => {
627
737
  const { transport, device, bleManager } = createHarness(() => Promise.resolve());
628
738
  let resolveAbandonedDiscovery: (() => void) | undefined;
@@ -1,12 +1,22 @@
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';
2
5
 
3
6
  import { getConnectedDeviceIds } from '../BleManager';
4
7
  import ReactNativeBleTransport from '../index';
8
+ import { subscribeBleOn } from '../subscribeBleOn';
5
9
 
6
10
  jest.mock(
7
11
  'react-native',
8
12
  () => ({
9
- PermissionsAndroid: {},
13
+ PermissionsAndroid: {
14
+ PERMISSIONS: {
15
+ BLUETOOTH_CONNECT: 'android.permission.BLUETOOTH_CONNECT',
16
+ BLUETOOTH_SCAN: 'android.permission.BLUETOOTH_SCAN',
17
+ },
18
+ requestMultiple: jest.fn(),
19
+ },
10
20
  Platform: { OS: 'ios' },
11
21
  }),
12
22
  { virtual: true }
@@ -14,7 +24,14 @@ jest.mock(
14
24
 
15
25
  jest.mock('react-native-ble-plx', () => ({
16
26
  BleError: class BleError extends Error {},
17
- BleErrorCode: {},
27
+ BleErrorCode: {
28
+ BluetoothUnsupported: 100,
29
+ BluetoothUnauthorized: 101,
30
+ BluetoothPoweredOff: 102,
31
+ BluetoothInUnknownState: 103,
32
+ ScanStartFailed: 600,
33
+ LocationServicesDisabled: 601,
34
+ },
18
35
  BleManager: jest.fn(),
19
36
  ScanMode: { LowLatency: 2 },
20
37
  }));
@@ -25,27 +42,61 @@ jest.mock('../BleManager', () => ({
25
42
  pairDevice: jest.fn(),
26
43
  }));
27
44
 
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
-
43
45
  jest.mock('../subscribeBleOn', () => ({
44
46
  subscribeBleOn: jest.fn(() => Promise.resolve()),
45
47
  }));
46
48
 
47
49
  const ONEKEY_SERVICE_UUID = '00000001-0000-1000-8000-00805f9b34fb';
48
50
 
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
+
49
100
  describe('ReactNativeBleTransport iOS discovery', () => {
50
101
  test('keeps a bonded Pro2 communication peripheral after Find My changes its name', async () => {
51
102
  jest.mocked(getConnectedDeviceIds).mockResolvedValueOnce([