@onekeyfe/hd-transport-electron 1.2.2-alpha.9 → 1.2.3-alpha.2
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/dist/{index-00297050.js → index-985e2bf3.js} +33 -1
- package/dist/index.d.ts +24 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/{noble-ble-handler-95c5cf0d.js → noble-ble-handler-263d4736.js} +374 -88
- package/dist/noble-ble-handler.d.ts +11 -1
- package/dist/noble-ble-handler.d.ts.map +1 -1
- package/dist/noble-ble-timeouts.d.ts +1 -1
- package/dist/noble-ble-timeouts.d.ts.map +1 -1
- package/dist/types/desktop-api.d.ts +13 -0
- package/dist/types/desktop-api.d.ts.map +1 -1
- package/dist/types/noble-extended.d.ts +2 -0
- package/dist/types/noble-extended.d.ts.map +1 -1
- package/package.json +5 -5
- package/src/__tests__/noble-ble-handler.test.ts +653 -18
- package/src/index.ts +14 -1
- package/src/noble-ble-handler.ts +438 -109
- package/src/noble-ble-timeouts.ts +1 -1
- package/src/types/desktop-api.ts +44 -0
- package/src/types/noble-extended.ts +2 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { EventEmitter } from 'events';
|
|
2
|
-
import { EOneKeyBleMessageKeys } from '@onekeyfe/hd-shared';
|
|
2
|
+
import { EOneKeyBleMessageKeys, HardwareErrorCode } from '@onekeyfe/hd-shared';
|
|
3
3
|
|
|
4
4
|
import {
|
|
5
|
-
|
|
5
|
+
NOBLE_BLE_SUBSCRIBE_TIMEOUT_MS,
|
|
6
6
|
NOBLE_BLE_TARGETED_SCAN_TIMEOUT_MS,
|
|
7
7
|
} from '../noble-ble-timeouts';
|
|
8
8
|
|
|
@@ -26,9 +26,126 @@ describe('Electron Noble BLE device discovery', () => {
|
|
|
26
26
|
jest.clearAllMocks();
|
|
27
27
|
});
|
|
28
28
|
|
|
29
|
-
test('
|
|
29
|
+
test('bounds targeted scans and subscription callbacks independently', () => {
|
|
30
30
|
expect(NOBLE_BLE_TARGETED_SCAN_TIMEOUT_MS).toBe(5_000);
|
|
31
|
-
expect(
|
|
31
|
+
expect(NOBLE_BLE_SUBSCRIBE_TIMEOUT_MS).toBe(10_000);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test('maps structured macOS stale pairing failures without parsing localized text', async () => {
|
|
35
|
+
const { createNobleBleConnectionError } = await import('../noble-ble-handler');
|
|
36
|
+
|
|
37
|
+
const staleBondError = createNobleBleConnectionError(
|
|
38
|
+
Object.assign(new Error('Peer removed pairing information on the device side'), {
|
|
39
|
+
nativeErrorCode: 14,
|
|
40
|
+
nativeErrorDomain: 'CBErrorDomain',
|
|
41
|
+
})
|
|
42
|
+
);
|
|
43
|
+
expect(staleBondError).toMatchObject({
|
|
44
|
+
errorCode: HardwareErrorCode.BleBondInvalid,
|
|
45
|
+
params: {
|
|
46
|
+
nativeErrorMessage: 'Peer removed pairing information on the device side',
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
expect(staleBondError.message).toContain('Peer removed pairing information on the device side');
|
|
50
|
+
expect(createNobleBleConnectionError(new Error('Encryption is insufficient'))).toMatchObject({
|
|
51
|
+
errorCode: HardwareErrorCode.BleConnectedError,
|
|
52
|
+
});
|
|
53
|
+
expect(
|
|
54
|
+
createNobleBleConnectionError(
|
|
55
|
+
Object.assign(new Error('localized native message'), {
|
|
56
|
+
nativeErrorCode: 14,
|
|
57
|
+
nativeErrorDomain: 'CBATTErrorDomain',
|
|
58
|
+
})
|
|
59
|
+
)
|
|
60
|
+
).toMatchObject({
|
|
61
|
+
errorCode: HardwareErrorCode.BleConnectedError,
|
|
62
|
+
});
|
|
63
|
+
expect(
|
|
64
|
+
createNobleBleConnectionError(
|
|
65
|
+
Object.assign(new Error('Encryption is insufficient'), {
|
|
66
|
+
nativeErrorCode: 15,
|
|
67
|
+
nativeErrorDomain: 'CBATTErrorDomain',
|
|
68
|
+
})
|
|
69
|
+
)
|
|
70
|
+
).toMatchObject({
|
|
71
|
+
errorCode: HardwareErrorCode.BleBondInvalid,
|
|
72
|
+
});
|
|
73
|
+
expect(createNobleBleConnectionError(new Error('connection failed'))).toMatchObject({
|
|
74
|
+
errorCode: HardwareErrorCode.BleConnectedError,
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('serializes HardwareError fields for the Noble IPC boundary', async () => {
|
|
79
|
+
const { createNobleBleIpcErrorResponse } = await import('../noble-ble-handler');
|
|
80
|
+
|
|
81
|
+
expect(
|
|
82
|
+
createNobleBleIpcErrorResponse({
|
|
83
|
+
name: 'HardwareError',
|
|
84
|
+
message: 'Bluetooth pairing information is no longer valid',
|
|
85
|
+
errorCode: HardwareErrorCode.BleBondInvalid,
|
|
86
|
+
params: { nativeErrorMessage: 'native message' },
|
|
87
|
+
})
|
|
88
|
+
).toEqual({
|
|
89
|
+
type: 'NobleBleIpcError',
|
|
90
|
+
success: false,
|
|
91
|
+
error: {
|
|
92
|
+
name: 'HardwareError',
|
|
93
|
+
message: 'Bluetooth pairing information is no longer valid',
|
|
94
|
+
errorCode: HardwareErrorCode.BleBondInvalid,
|
|
95
|
+
params: { nativeErrorMessage: 'native message' },
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
expect(createNobleBleIpcErrorResponse(new Error('untyped failure'))).toEqual({
|
|
100
|
+
type: 'NobleBleIpcError',
|
|
101
|
+
success: false,
|
|
102
|
+
error: {
|
|
103
|
+
name: 'Error',
|
|
104
|
+
message: 'untyped failure',
|
|
105
|
+
errorCode: HardwareErrorCode.UnknownError,
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
const circularParams: { self?: unknown } = {};
|
|
110
|
+
circularParams.self = circularParams;
|
|
111
|
+
expect(
|
|
112
|
+
createNobleBleIpcErrorResponse({
|
|
113
|
+
message: 'failure with unsafe params',
|
|
114
|
+
errorCode: HardwareErrorCode.BleConnectedError,
|
|
115
|
+
params: circularParams,
|
|
116
|
+
})
|
|
117
|
+
).toEqual({
|
|
118
|
+
type: 'NobleBleIpcError',
|
|
119
|
+
success: false,
|
|
120
|
+
error: {
|
|
121
|
+
name: 'Error',
|
|
122
|
+
message: 'failure with unsafe params',
|
|
123
|
+
errorCode: HardwareErrorCode.BleConnectedError,
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test('rejects a structured Noble IPC failure at the preload boundary', async () => {
|
|
129
|
+
const { invokeNobleBleIpc } = await import('../types/desktop-api');
|
|
130
|
+
|
|
131
|
+
await expect(
|
|
132
|
+
invokeNobleBleIpc(
|
|
133
|
+
Promise.resolve({
|
|
134
|
+
type: 'NobleBleIpcError' as const,
|
|
135
|
+
success: false as const,
|
|
136
|
+
error: {
|
|
137
|
+
name: 'HardwareError',
|
|
138
|
+
message: 'Bluetooth pairing information is no longer valid',
|
|
139
|
+
errorCode: HardwareErrorCode.BleBondInvalid,
|
|
140
|
+
},
|
|
141
|
+
})
|
|
142
|
+
)
|
|
143
|
+
).rejects.toMatchObject({
|
|
144
|
+
name: 'HardwareError',
|
|
145
|
+
errorCode: HardwareErrorCode.BleBondInvalid,
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
await expect(invokeNobleBleIpc(Promise.resolve('connected'))).resolves.toBe('connected');
|
|
32
149
|
});
|
|
33
150
|
|
|
34
151
|
test('keeps safe pacing by default and allows an explicit high-throughput bypass', async () => {
|
|
@@ -176,13 +293,19 @@ describe('Electron Noble BLE device discovery', () => {
|
|
|
176
293
|
expect(peripheral.connect).not.toHaveBeenCalled();
|
|
177
294
|
|
|
178
295
|
stopScanningCallback?.();
|
|
179
|
-
await expect(connectPromise).
|
|
296
|
+
await expect(connectPromise).resolves.toEqual({
|
|
297
|
+
type: 'NobleBleIpcError',
|
|
298
|
+
success: false,
|
|
299
|
+
error: {
|
|
300
|
+
name: 'HardwareError',
|
|
301
|
+
message: 'expected test connection failure',
|
|
302
|
+
errorCode: HardwareErrorCode.BleConnectedError,
|
|
303
|
+
},
|
|
304
|
+
});
|
|
180
305
|
expect(peripheral.connect).toHaveBeenCalledTimes(1);
|
|
181
306
|
});
|
|
182
307
|
|
|
183
|
-
test('disconnects a
|
|
184
|
-
jest.useFakeTimers({ doNotFake: ['performance'] });
|
|
185
|
-
|
|
308
|
+
test('disconnects and settles a pending Noble connect before a late callback arrives', async () => {
|
|
186
309
|
const handlers = new Map<string, IpcHandler>();
|
|
187
310
|
const ipcMain = {
|
|
188
311
|
handle: jest.fn((channel: string, handler: IpcHandler) => {
|
|
@@ -197,6 +320,7 @@ describe('Electron Noble BLE device discovery', () => {
|
|
|
197
320
|
startScanning: jest.Mock;
|
|
198
321
|
stopScanning: jest.Mock;
|
|
199
322
|
};
|
|
323
|
+
let stopScanningCallback: (() => void) | undefined;
|
|
200
324
|
let connectCallback: ((error?: Error) => void) | undefined;
|
|
201
325
|
let resolveConnectStarted = () => undefined;
|
|
202
326
|
const connectStarted = new Promise<void>(resolve => {
|
|
@@ -204,13 +328,17 @@ describe('Electron Noble BLE device discovery', () => {
|
|
|
204
328
|
});
|
|
205
329
|
const peripheral = Object.assign(
|
|
206
330
|
new EventEmitter(),
|
|
207
|
-
createPeripheral('
|
|
331
|
+
createPeripheral('pending-device', 'Pro2 C3D4'),
|
|
208
332
|
{
|
|
209
333
|
connect: jest.fn((callback: (error?: Error) => void) => {
|
|
210
334
|
connectCallback = callback;
|
|
211
335
|
resolveConnectStarted();
|
|
212
336
|
}),
|
|
213
|
-
disconnect: jest.fn((callback: () => void) =>
|
|
337
|
+
disconnect: jest.fn((callback: () => void) => {
|
|
338
|
+
peripheral.state = 'disconnected';
|
|
339
|
+
callback();
|
|
340
|
+
}),
|
|
341
|
+
discoverServices: jest.fn(),
|
|
214
342
|
}
|
|
215
343
|
);
|
|
216
344
|
noble.state = 'poweredOn';
|
|
@@ -218,7 +346,9 @@ describe('Electron Noble BLE device discovery', () => {
|
|
|
218
346
|
callback?.();
|
|
219
347
|
noble.emit('discover', peripheral);
|
|
220
348
|
});
|
|
221
|
-
noble.stopScanning = jest.fn(callback =>
|
|
349
|
+
noble.stopScanning = jest.fn(callback => {
|
|
350
|
+
stopScanningCallback = callback;
|
|
351
|
+
});
|
|
222
352
|
|
|
223
353
|
jest.doMock('@stoprocent/noble', () => noble);
|
|
224
354
|
jest.doMock('electron', () => ({ ipcMain }));
|
|
@@ -235,20 +365,257 @@ describe('Electron Noble BLE device discovery', () => {
|
|
|
235
365
|
} as unknown as WebContents);
|
|
236
366
|
|
|
237
367
|
const connect = handlers.get(EOneKeyBleMessageKeys.NOBLE_BLE_CONNECT);
|
|
238
|
-
|
|
239
|
-
|
|
368
|
+
const disconnect = handlers.get(EOneKeyBleMessageKeys.NOBLE_BLE_DISCONNECT);
|
|
369
|
+
if (!connect || !disconnect) {
|
|
370
|
+
throw new Error('Electron Noble BLE handlers were not registered');
|
|
240
371
|
}
|
|
241
372
|
|
|
242
|
-
const connectPromise = Promise.resolve(connect(undefined,
|
|
373
|
+
const connectPromise = Promise.resolve(connect(undefined, peripheral.id));
|
|
374
|
+
await Promise.resolve();
|
|
375
|
+
stopScanningCallback?.();
|
|
243
376
|
await connectStarted;
|
|
244
|
-
expect(peripheral.connect).toHaveBeenCalledTimes(1);
|
|
245
377
|
|
|
246
|
-
|
|
247
|
-
await expect(connectPromise).
|
|
378
|
+
await expect(Promise.resolve(disconnect(undefined, peripheral.id))).resolves.toBeUndefined();
|
|
379
|
+
await expect(connectPromise).resolves.toMatchObject({
|
|
380
|
+
type: 'NobleBleIpcError',
|
|
381
|
+
success: false,
|
|
382
|
+
error: {
|
|
383
|
+
errorCode: HardwareErrorCode.BleDeviceDisconnected,
|
|
384
|
+
},
|
|
385
|
+
});
|
|
386
|
+
expect(peripheral.disconnect).toHaveBeenCalledTimes(1);
|
|
248
387
|
|
|
388
|
+
peripheral.state = 'connected';
|
|
249
389
|
connectCallback?.();
|
|
250
390
|
await Promise.resolve();
|
|
251
|
-
|
|
391
|
+
|
|
392
|
+
expect(peripheral.discoverServices).not.toHaveBeenCalled();
|
|
393
|
+
expect(peripheral.disconnect).toHaveBeenCalledTimes(2);
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
test('disconnects and settles a pending forced reconnect before a late callback arrives', async () => {
|
|
397
|
+
const handlers = new Map<string, IpcHandler>();
|
|
398
|
+
const ipcMain = {
|
|
399
|
+
handle: jest.fn((channel: string, handler: IpcHandler) => {
|
|
400
|
+
handlers.set(channel, handler);
|
|
401
|
+
}),
|
|
402
|
+
removeHandler: jest.fn((channel: string) => {
|
|
403
|
+
handlers.delete(channel);
|
|
404
|
+
}),
|
|
405
|
+
};
|
|
406
|
+
const noble = new EventEmitter() as EventEmitter & {
|
|
407
|
+
state: string;
|
|
408
|
+
startScanning: jest.Mock;
|
|
409
|
+
stopScanning: jest.Mock;
|
|
410
|
+
};
|
|
411
|
+
let stopScanningCallback: (() => void) | undefined;
|
|
412
|
+
const connectCallbacks: Array<(error?: Error) => void> = [];
|
|
413
|
+
let resolveInitialConnectStarted = () => undefined;
|
|
414
|
+
const initialConnectStarted = new Promise<void>(resolve => {
|
|
415
|
+
resolveInitialConnectStarted = resolve;
|
|
416
|
+
});
|
|
417
|
+
let resolveForcedReconnectStarted = () => undefined;
|
|
418
|
+
const forcedReconnectStarted = new Promise<void>(resolve => {
|
|
419
|
+
resolveForcedReconnectStarted = resolve;
|
|
420
|
+
});
|
|
421
|
+
const peripheral = Object.assign(
|
|
422
|
+
new EventEmitter(),
|
|
423
|
+
createPeripheral('forced-reconnect-device', 'Pro2 C3D4'),
|
|
424
|
+
{
|
|
425
|
+
connect: jest.fn((callback: (error?: Error) => void) => {
|
|
426
|
+
connectCallbacks.push(callback);
|
|
427
|
+
if (connectCallbacks.length === 1) {
|
|
428
|
+
resolveInitialConnectStarted();
|
|
429
|
+
} else if (connectCallbacks.length === 2) {
|
|
430
|
+
resolveForcedReconnectStarted();
|
|
431
|
+
}
|
|
432
|
+
}),
|
|
433
|
+
disconnect: jest.fn((callback: () => void) => {
|
|
434
|
+
peripheral.state = 'disconnected';
|
|
435
|
+
callback();
|
|
436
|
+
}),
|
|
437
|
+
discoverServices: jest.fn(),
|
|
438
|
+
}
|
|
439
|
+
);
|
|
440
|
+
noble.state = 'poweredOn';
|
|
441
|
+
noble.startScanning = jest.fn((_services, _duplicates, callback) => {
|
|
442
|
+
callback?.();
|
|
443
|
+
noble.emit('discover', peripheral);
|
|
444
|
+
});
|
|
445
|
+
noble.stopScanning = jest.fn(callback => {
|
|
446
|
+
stopScanningCallback = callback;
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
jest.doMock('@stoprocent/noble', () => noble);
|
|
450
|
+
jest.doMock('electron', () => ({ ipcMain }));
|
|
451
|
+
jest.doMock('electron-log', () => ({
|
|
452
|
+
info: jest.fn(),
|
|
453
|
+
debug: jest.fn(),
|
|
454
|
+
error: jest.fn(),
|
|
455
|
+
}));
|
|
456
|
+
|
|
457
|
+
const { setupNobleBleHandlers } = await import('../noble-ble-handler');
|
|
458
|
+
setupNobleBleHandlers({
|
|
459
|
+
on: jest.fn(),
|
|
460
|
+
send: jest.fn(),
|
|
461
|
+
} as unknown as WebContents);
|
|
462
|
+
|
|
463
|
+
const connect = handlers.get(EOneKeyBleMessageKeys.NOBLE_BLE_CONNECT);
|
|
464
|
+
const disconnect = handlers.get(EOneKeyBleMessageKeys.NOBLE_BLE_DISCONNECT);
|
|
465
|
+
if (!connect || !disconnect) {
|
|
466
|
+
throw new Error('Electron Noble BLE handlers were not registered');
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const connectPromise = Promise.resolve(connect(undefined, peripheral.id));
|
|
470
|
+
await Promise.resolve();
|
|
471
|
+
stopScanningCallback?.();
|
|
472
|
+
await initialConnectStarted;
|
|
473
|
+
|
|
474
|
+
peripheral.state = 'connected';
|
|
475
|
+
connectCallbacks[0]?.();
|
|
476
|
+
await forcedReconnectStarted;
|
|
477
|
+
|
|
478
|
+
await expect(Promise.resolve(disconnect(undefined, peripheral.id))).resolves.toBeUndefined();
|
|
479
|
+
await expect(connectPromise).resolves.toMatchObject({
|
|
480
|
+
type: 'NobleBleIpcError',
|
|
481
|
+
success: false,
|
|
482
|
+
error: {
|
|
483
|
+
errorCode: HardwareErrorCode.BleDeviceDisconnected,
|
|
484
|
+
},
|
|
485
|
+
});
|
|
486
|
+
expect(peripheral.disconnect).toHaveBeenCalledTimes(2);
|
|
487
|
+
|
|
488
|
+
peripheral.state = 'connected';
|
|
489
|
+
connectCallbacks[1]?.();
|
|
490
|
+
await Promise.resolve();
|
|
491
|
+
|
|
492
|
+
expect(peripheral.discoverServices).not.toHaveBeenCalled();
|
|
493
|
+
expect(peripheral.disconnect).toHaveBeenCalledTimes(3);
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
test('maps a structured native subscription failure before returning it over IPC', async () => {
|
|
497
|
+
const handlers = new Map<string, IpcHandler>();
|
|
498
|
+
const ipcMain = {
|
|
499
|
+
handle: jest.fn((channel: string, handler: IpcHandler) => {
|
|
500
|
+
handlers.set(channel, handler);
|
|
501
|
+
}),
|
|
502
|
+
removeHandler: jest.fn((channel: string) => {
|
|
503
|
+
handlers.delete(channel);
|
|
504
|
+
}),
|
|
505
|
+
};
|
|
506
|
+
const nativeError = Object.assign(new Error('Encryption is insufficient'), {
|
|
507
|
+
nativeErrorCode: 15,
|
|
508
|
+
nativeErrorDomain: 'CBATTErrorDomain',
|
|
509
|
+
});
|
|
510
|
+
const notifyCharacteristic = Object.assign(new EventEmitter(), {
|
|
511
|
+
uuid: '0003',
|
|
512
|
+
unsubscribe: jest.fn((callback: (error?: Error) => void) => callback()),
|
|
513
|
+
subscribe: jest.fn((callback: (error?: Error) => void) => callback(nativeError)),
|
|
514
|
+
});
|
|
515
|
+
const writeCharacteristic = Object.assign(new EventEmitter(), {
|
|
516
|
+
uuid: '0002',
|
|
517
|
+
});
|
|
518
|
+
const service = {
|
|
519
|
+
uuid: '0001',
|
|
520
|
+
discoverCharacteristics: jest.fn(
|
|
521
|
+
(
|
|
522
|
+
_characteristicUuids: string[],
|
|
523
|
+
callback: (error: Error | null, value: unknown[]) => void
|
|
524
|
+
) => callback(null, [writeCharacteristic, notifyCharacteristic])
|
|
525
|
+
),
|
|
526
|
+
};
|
|
527
|
+
const peripheral = Object.assign(
|
|
528
|
+
new EventEmitter(),
|
|
529
|
+
createPeripheral('subscription-device', 'Pro2 E5F6'),
|
|
530
|
+
{
|
|
531
|
+
connect: jest.fn((callback: (error?: Error) => void) => {
|
|
532
|
+
peripheral.state = 'connected';
|
|
533
|
+
callback();
|
|
534
|
+
}),
|
|
535
|
+
disconnect: jest.fn((callback: () => void) => {
|
|
536
|
+
peripheral.state = 'disconnected';
|
|
537
|
+
callback();
|
|
538
|
+
}),
|
|
539
|
+
discoverServices: jest.fn(
|
|
540
|
+
(_serviceUuids: string[], callback: (error: Error | null, value: unknown[]) => void) =>
|
|
541
|
+
callback(null, [service])
|
|
542
|
+
),
|
|
543
|
+
}
|
|
544
|
+
);
|
|
545
|
+
const noble = Object.assign(new EventEmitter(), {
|
|
546
|
+
state: 'poweredOn',
|
|
547
|
+
startScanning: jest.fn((_services, _duplicates, callback) => {
|
|
548
|
+
callback?.();
|
|
549
|
+
noble.emit('discover', peripheral);
|
|
550
|
+
}),
|
|
551
|
+
stopScanning: jest.fn(callback => callback?.()),
|
|
552
|
+
});
|
|
553
|
+
|
|
554
|
+
jest.doMock('@stoprocent/noble', () => noble);
|
|
555
|
+
jest.doMock('electron', () => ({ ipcMain }));
|
|
556
|
+
jest.doMock('electron-log', () => ({
|
|
557
|
+
info: jest.fn(),
|
|
558
|
+
debug: jest.fn(),
|
|
559
|
+
error: jest.fn(),
|
|
560
|
+
}));
|
|
561
|
+
|
|
562
|
+
const { setupNobleBleHandlers } = await import('../noble-ble-handler');
|
|
563
|
+
setupNobleBleHandlers({
|
|
564
|
+
on: jest.fn(),
|
|
565
|
+
send: jest.fn(),
|
|
566
|
+
} as unknown as WebContents);
|
|
567
|
+
|
|
568
|
+
const connect = handlers.get(EOneKeyBleMessageKeys.NOBLE_BLE_CONNECT);
|
|
569
|
+
const subscribe = handlers.get(EOneKeyBleMessageKeys.NOBLE_BLE_SUBSCRIBE);
|
|
570
|
+
const disconnect = handlers.get(EOneKeyBleMessageKeys.NOBLE_BLE_DISCONNECT);
|
|
571
|
+
if (!connect || !subscribe || !disconnect) {
|
|
572
|
+
throw new Error('Electron Noble BLE handlers were not registered');
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
await expect(Promise.resolve(connect(undefined, peripheral.id))).resolves.toBeUndefined();
|
|
576
|
+
try {
|
|
577
|
+
await expect(Promise.resolve(subscribe(undefined, peripheral.id))).resolves.toMatchObject({
|
|
578
|
+
type: 'NobleBleIpcError',
|
|
579
|
+
success: false,
|
|
580
|
+
error: {
|
|
581
|
+
errorCode: HardwareErrorCode.BleBondInvalid,
|
|
582
|
+
params: {
|
|
583
|
+
nativeErrorMessage: 'Notification subscription failed: Encryption is insufficient',
|
|
584
|
+
},
|
|
585
|
+
},
|
|
586
|
+
});
|
|
587
|
+
} finally {
|
|
588
|
+
await disconnect(undefined, peripheral.id);
|
|
589
|
+
}
|
|
590
|
+
});
|
|
591
|
+
|
|
592
|
+
test('settles a pending Noble connect with the native disconnect error', () => {
|
|
593
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires, global-require
|
|
594
|
+
const Noble = require('@stoprocent/noble/lib/noble');
|
|
595
|
+
const bindings = Object.assign(new EventEmitter(), {
|
|
596
|
+
connect: jest.fn(),
|
|
597
|
+
});
|
|
598
|
+
const noble = new Noble(bindings);
|
|
599
|
+
noble._registerListeners();
|
|
600
|
+
const peripheral = noble._createPeripheral(
|
|
601
|
+
'aabbccdd',
|
|
602
|
+
'',
|
|
603
|
+
'unknown',
|
|
604
|
+
true,
|
|
605
|
+
{ localName: 'Pro2 A1B2', serviceUuids: ['0001'] },
|
|
606
|
+
-50,
|
|
607
|
+
false
|
|
608
|
+
);
|
|
609
|
+
const connectCallback = jest.fn();
|
|
610
|
+
|
|
611
|
+
peripheral.connect(connectCallback);
|
|
612
|
+
const nativeError = new Error(
|
|
613
|
+
'CBErrorDomain:14 Peer removed pairing information on the device side'
|
|
614
|
+
);
|
|
615
|
+
bindings.emit('disconnect', 'aabbccdd', nativeError);
|
|
616
|
+
|
|
617
|
+
expect(connectCallback).toHaveBeenCalledWith(nativeError);
|
|
618
|
+
expect(peripheral.state).toBe('disconnected');
|
|
252
619
|
});
|
|
253
620
|
|
|
254
621
|
test('enumerates a Pro2 communication advertisement after Find My changes its name', async () => {
|
|
@@ -381,3 +748,271 @@ describe('Electron Noble BLE device discovery', () => {
|
|
|
381
748
|
]);
|
|
382
749
|
});
|
|
383
750
|
});
|
|
751
|
+
|
|
752
|
+
describe('Noble BLE process shutdown', () => {
|
|
753
|
+
const flushCallbacks = () =>
|
|
754
|
+
new Promise<void>(resolve => {
|
|
755
|
+
setImmediate(resolve);
|
|
756
|
+
});
|
|
757
|
+
afterEach(() => {
|
|
758
|
+
jest.useRealTimers();
|
|
759
|
+
jest.resetModules();
|
|
760
|
+
jest.clearAllMocks();
|
|
761
|
+
});
|
|
762
|
+
|
|
763
|
+
const setup = async (state = 'poweredOn') => {
|
|
764
|
+
const handlers = new Map<string, IpcHandler>();
|
|
765
|
+
const native = Object.assign(new EventEmitter(), {
|
|
766
|
+
state,
|
|
767
|
+
startScanning: jest.fn((_uuids, _duplicates, callback) => callback?.()),
|
|
768
|
+
stopScanning: jest.fn(callback => callback?.()),
|
|
769
|
+
stop: jest.fn(),
|
|
770
|
+
});
|
|
771
|
+
jest.doMock('@stoprocent/noble', () => native);
|
|
772
|
+
jest.doMock('electron', () => ({
|
|
773
|
+
ipcMain: {
|
|
774
|
+
handle: (channel: string, listener: IpcHandler) => handlers.set(channel, listener),
|
|
775
|
+
removeHandler: (channel: string) => handlers.delete(channel),
|
|
776
|
+
},
|
|
777
|
+
}));
|
|
778
|
+
jest.doMock(
|
|
779
|
+
'electron-log',
|
|
780
|
+
() => ({
|
|
781
|
+
info: jest.fn(),
|
|
782
|
+
debug: jest.fn(),
|
|
783
|
+
warn: jest.fn(),
|
|
784
|
+
error: jest.fn(),
|
|
785
|
+
}),
|
|
786
|
+
{ virtual: true }
|
|
787
|
+
);
|
|
788
|
+
const sdk = await import('../noble-ble-handler');
|
|
789
|
+
const window = new EventEmitter();
|
|
790
|
+
sdk.setupNobleBleHandlers(window as unknown as WebContents);
|
|
791
|
+
return { sdk, native, window, handlers };
|
|
792
|
+
};
|
|
793
|
+
|
|
794
|
+
test('does not initialize native BLE when quitting before first use', async () => {
|
|
795
|
+
const { sdk, native, handlers } = await setup();
|
|
796
|
+
await sdk.disposeNobleBleSupport();
|
|
797
|
+
expect(native.stop).not.toHaveBeenCalled();
|
|
798
|
+
expect(handlers.size).toBe(0);
|
|
799
|
+
});
|
|
800
|
+
|
|
801
|
+
test('cancels an active scan, ignores its late callback and releases native once', async () => {
|
|
802
|
+
jest.useFakeTimers({ doNotFake: ['performance'] });
|
|
803
|
+
const { sdk, native, handlers } = await setup();
|
|
804
|
+
let completeScan: (() => void) | undefined;
|
|
805
|
+
native.startScanning.mockImplementation((_uuids, _duplicates, callback) => {
|
|
806
|
+
completeScan = callback;
|
|
807
|
+
});
|
|
808
|
+
const scan = handlers.get(EOneKeyBleMessageKeys.NOBLE_BLE_ENUMERATE)?.({});
|
|
809
|
+
await Promise.resolve();
|
|
810
|
+
await Promise.resolve();
|
|
811
|
+
await sdk.disposeNobleBleSupport();
|
|
812
|
+
await sdk.disposeNobleBleSupport();
|
|
813
|
+
await scan;
|
|
814
|
+
completeScan?.();
|
|
815
|
+
expect(native.stop).toHaveBeenCalledTimes(1);
|
|
816
|
+
expect(native.listenerCount('discover')).toBe(0);
|
|
817
|
+
expect(native.listenerCount('stateChange')).toBe(0);
|
|
818
|
+
expect(jest.getTimerCount()).toBe(0);
|
|
819
|
+
});
|
|
820
|
+
|
|
821
|
+
test('cancels power-on waits before releasing native', async () => {
|
|
822
|
+
jest.useFakeTimers({ doNotFake: ['performance'] });
|
|
823
|
+
const { sdk, native, handlers } = await setup('unknown');
|
|
824
|
+
const availability = handlers.get(EOneKeyBleMessageKeys.BLE_AVAILABILITY_CHECK)?.({});
|
|
825
|
+
await sdk.disposeNobleBleSupport();
|
|
826
|
+
await availability;
|
|
827
|
+
expect(native.stop).toHaveBeenCalledTimes(1);
|
|
828
|
+
expect(native.listenerCount('stateChange')).toBe(0);
|
|
829
|
+
expect(jest.getTimerCount()).toBe(0);
|
|
830
|
+
});
|
|
831
|
+
|
|
832
|
+
test('cancels native connects and waits for disconnect before release', async () => {
|
|
833
|
+
const { sdk, native, handlers } = await setup();
|
|
834
|
+
await handlers.get(EOneKeyBleMessageKeys.BLE_AVAILABILITY_CHECK)?.({});
|
|
835
|
+
let connectCallback: ((error?: Error) => void) | undefined;
|
|
836
|
+
let disconnectCallback: (() => void) | undefined;
|
|
837
|
+
const peripheral = Object.assign(new EventEmitter(), {
|
|
838
|
+
...createPeripheral('pending-device', 'OneKey Pro'),
|
|
839
|
+
connect: jest.fn(callback => {
|
|
840
|
+
connectCallback = callback;
|
|
841
|
+
}),
|
|
842
|
+
cancelConnect: jest.fn(() => connectCallback?.(new Error('connection canceled'))),
|
|
843
|
+
disconnect: jest.fn(callback => {
|
|
844
|
+
disconnectCallback = callback;
|
|
845
|
+
}),
|
|
846
|
+
discoverServices: jest.fn(),
|
|
847
|
+
});
|
|
848
|
+
native.emit('discover', peripheral);
|
|
849
|
+
const connecting = handlers.get(EOneKeyBleMessageKeys.NOBLE_BLE_CONNECT)?.({}, peripheral.id);
|
|
850
|
+
await Promise.resolve();
|
|
851
|
+
await Promise.resolve();
|
|
852
|
+
expect(peripheral.connect).toHaveBeenCalledTimes(1);
|
|
853
|
+
const disposing = sdk.disposeNobleBleSupport();
|
|
854
|
+
await flushCallbacks();
|
|
855
|
+
expect(peripheral.cancelConnect).toHaveBeenCalledTimes(1);
|
|
856
|
+
expect(peripheral.disconnect).toHaveBeenCalled();
|
|
857
|
+
expect(native.stop).not.toHaveBeenCalled();
|
|
858
|
+
disconnectCallback?.();
|
|
859
|
+
await disposing;
|
|
860
|
+
expect(native.stop).toHaveBeenCalledTimes(1);
|
|
861
|
+
expect(await connecting).toMatchObject({ success: false });
|
|
862
|
+
expect(peripheral.discoverServices).not.toHaveBeenCalled();
|
|
863
|
+
});
|
|
864
|
+
|
|
865
|
+
test.each(['peripheral', 'direct'])(
|
|
866
|
+
'keeps late %s connects inert after the disposal timeout',
|
|
867
|
+
async route => {
|
|
868
|
+
jest.useFakeTimers({ doNotFake: ['performance', 'setImmediate'] });
|
|
869
|
+
const { sdk, native, handlers } = await setup();
|
|
870
|
+
await handlers.get(EOneKeyBleMessageKeys.BLE_AVAILABILITY_CHECK)?.({});
|
|
871
|
+
let finishConnect: () => void = () => undefined;
|
|
872
|
+
const peripheral = Object.assign(new EventEmitter(), {
|
|
873
|
+
...createPeripheral('late-device', 'OneKey Pro'),
|
|
874
|
+
connect: jest.fn(callback => {
|
|
875
|
+
finishConnect = () => callback();
|
|
876
|
+
}),
|
|
877
|
+
cancelConnect: jest.fn(),
|
|
878
|
+
disconnect: jest.fn(callback => callback?.()),
|
|
879
|
+
discoverServices: jest.fn(),
|
|
880
|
+
});
|
|
881
|
+
const connectAsync = jest.fn(
|
|
882
|
+
() =>
|
|
883
|
+
new Promise(resolve => {
|
|
884
|
+
finishConnect = () => resolve(peripheral);
|
|
885
|
+
})
|
|
886
|
+
);
|
|
887
|
+
const cancelConnect = jest.fn();
|
|
888
|
+
if (route === 'direct') Object.assign(native, { connectAsync, cancelConnect });
|
|
889
|
+
else native.emit('discover', peripheral);
|
|
890
|
+
const connecting = handlers.get(EOneKeyBleMessageKeys.NOBLE_BLE_CONNECT)?.({}, peripheral.id);
|
|
891
|
+
await flushCallbacks();
|
|
892
|
+
if (route === 'direct') {
|
|
893
|
+
jest.advanceTimersByTime(1500);
|
|
894
|
+
await flushCallbacks();
|
|
895
|
+
}
|
|
896
|
+
expect(route === 'direct' ? connectAsync : peripheral.connect).toHaveBeenCalledTimes(1);
|
|
897
|
+
const disposing = sdk.disposeNobleBleSupport();
|
|
898
|
+
await flushCallbacks();
|
|
899
|
+
expect(route === 'direct' ? cancelConnect : peripheral.cancelConnect).toHaveBeenCalledTimes(
|
|
900
|
+
1
|
|
901
|
+
);
|
|
902
|
+
expect(native.stop).not.toHaveBeenCalled();
|
|
903
|
+
jest.advanceTimersByTime(3500);
|
|
904
|
+
await disposing;
|
|
905
|
+
const disconnects = peripheral.disconnect.mock.calls.length;
|
|
906
|
+
peripheral.state = 'connected';
|
|
907
|
+
finishConnect();
|
|
908
|
+
await flushCallbacks();
|
|
909
|
+
expect(peripheral.disconnect).toHaveBeenCalledTimes(disconnects);
|
|
910
|
+
expect(peripheral.discoverServices).not.toHaveBeenCalled();
|
|
911
|
+
expect(native.stop).toHaveBeenCalledTimes(1);
|
|
912
|
+
expect(await connecting).toMatchObject({ success: false });
|
|
913
|
+
expect(jest.getTimerCount()).toBe(0);
|
|
914
|
+
}
|
|
915
|
+
);
|
|
916
|
+
|
|
917
|
+
test('allows a host to defer shared native release until both transports are idle', async () => {
|
|
918
|
+
const { sdk, native, handlers } = await setup();
|
|
919
|
+
await handlers.get(EOneKeyBleMessageKeys.BLE_AVAILABILITY_CHECK)?.({});
|
|
920
|
+
const releaseNoble = jest.fn();
|
|
921
|
+
await sdk.disposeNobleBleSupport(releaseNoble);
|
|
922
|
+
expect(releaseNoble).toHaveBeenCalledWith(native);
|
|
923
|
+
expect(native.stop).not.toHaveBeenCalled();
|
|
924
|
+
});
|
|
925
|
+
|
|
926
|
+
test('replacement window scanning waits for old cleanup and preserves native', async () => {
|
|
927
|
+
jest.useFakeTimers({ doNotFake: ['performance', 'setImmediate'] });
|
|
928
|
+
const { sdk, native, handlers, window } = await setup();
|
|
929
|
+
await handlers.get(EOneKeyBleMessageKeys.BLE_AVAILABILITY_CHECK)?.({});
|
|
930
|
+
let finishOldCleanup: (() => void) | undefined;
|
|
931
|
+
native.stopScanning.mockImplementationOnce(callback => {
|
|
932
|
+
finishOldCleanup = callback;
|
|
933
|
+
});
|
|
934
|
+
window.emit('destroyed');
|
|
935
|
+
sdk.setupNobleBleHandlers(new EventEmitter() as unknown as WebContents);
|
|
936
|
+
const scan = handlers.get(EOneKeyBleMessageKeys.NOBLE_BLE_ENUMERATE)?.({});
|
|
937
|
+
await flushCallbacks();
|
|
938
|
+
expect(native.startScanning).not.toHaveBeenCalled();
|
|
939
|
+
finishOldCleanup?.();
|
|
940
|
+
await flushCallbacks();
|
|
941
|
+
expect(native.startScanning).toHaveBeenCalledTimes(1);
|
|
942
|
+
expect(native.listenerCount('discover')).toBe(1);
|
|
943
|
+
native.emit('discover', createPeripheral('replacement-device', 'OneKey Pro'));
|
|
944
|
+
jest.advanceTimersByTime(5000);
|
|
945
|
+
expect(await scan).toEqual([expect.objectContaining({ id: 'replacement-device' })]);
|
|
946
|
+
expect(native.stop).not.toHaveBeenCalled();
|
|
947
|
+
await sdk.disposeNobleBleSupport();
|
|
948
|
+
expect(native.stop).toHaveBeenCalledTimes(1);
|
|
949
|
+
});
|
|
950
|
+
|
|
951
|
+
test.each(['started', 'late-start-callback'])(
|
|
952
|
+
'retires an old enumeration before a shared native scan resumes: %s',
|
|
953
|
+
async scanState => {
|
|
954
|
+
jest.useFakeTimers({ doNotFake: ['performance', 'setImmediate'] });
|
|
955
|
+
const { sdk, native, handlers, window } = await setup();
|
|
956
|
+
let lateStart: (() => void) | undefined;
|
|
957
|
+
if (scanState === 'late-start-callback') {
|
|
958
|
+
native.startScanning.mockImplementationOnce((_uuids, _duplicates, callback) => {
|
|
959
|
+
lateStart = callback;
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
let oldScanSettled = false;
|
|
963
|
+
const oldScan = Promise.resolve(
|
|
964
|
+
handlers.get(EOneKeyBleMessageKeys.NOBLE_BLE_ENUMERATE)?.({})
|
|
965
|
+
).then(result => {
|
|
966
|
+
oldScanSettled = true;
|
|
967
|
+
return result;
|
|
968
|
+
});
|
|
969
|
+
await flushCallbacks();
|
|
970
|
+
jest.advanceTimersByTime(1000);
|
|
971
|
+
|
|
972
|
+
let finishOldScan: (() => void) | undefined;
|
|
973
|
+
native.stopScanning.mockImplementationOnce(callback => {
|
|
974
|
+
finishOldScan = callback;
|
|
975
|
+
});
|
|
976
|
+
window.emit('destroyed');
|
|
977
|
+
sdk.setupNobleBleHandlers(new EventEmitter() as unknown as WebContents);
|
|
978
|
+
const replacementReady = handlers.get(EOneKeyBleMessageKeys.BLE_AVAILABILITY_CHECK)?.({});
|
|
979
|
+
let replacementSettled = false;
|
|
980
|
+
Promise.resolve(replacementReady).then(() => {
|
|
981
|
+
replacementSettled = true;
|
|
982
|
+
});
|
|
983
|
+
await flushCallbacks();
|
|
984
|
+
expect(replacementSettled).toBe(false);
|
|
985
|
+
finishOldScan?.();
|
|
986
|
+
await replacementReady;
|
|
987
|
+
await flushCallbacks();
|
|
988
|
+
expect(oldScanSettled).toBe(true);
|
|
989
|
+
expect(await oldScan).toEqual([]);
|
|
990
|
+
|
|
991
|
+
// Another transport can now scan on the same process-wide Noble instance.
|
|
992
|
+
native.startScanning([], true, () => undefined);
|
|
993
|
+
const stopCount = native.stopScanning.mock.calls.length;
|
|
994
|
+
lateStart?.();
|
|
995
|
+
jest.advanceTimersByTime(5000);
|
|
996
|
+
await flushCallbacks();
|
|
997
|
+
expect(native.stopScanning).toHaveBeenCalledTimes(stopCount);
|
|
998
|
+
expect(jest.getTimerCount()).toBe(0);
|
|
999
|
+
expect(native.stop).not.toHaveBeenCalled();
|
|
1000
|
+
await sdk.disposeNobleBleSupport();
|
|
1001
|
+
}
|
|
1002
|
+
);
|
|
1003
|
+
|
|
1004
|
+
test('does not start an old window enumeration after Bluetooth becomes ready', async () => {
|
|
1005
|
+
const { sdk, native, handlers, window } = await setup('unknown');
|
|
1006
|
+
const oldScan = handlers.get(EOneKeyBleMessageKeys.NOBLE_BLE_ENUMERATE)?.({});
|
|
1007
|
+
await flushCallbacks();
|
|
1008
|
+
window.emit('destroyed');
|
|
1009
|
+
sdk.setupNobleBleHandlers(new EventEmitter() as unknown as WebContents);
|
|
1010
|
+
await handlers.get(EOneKeyBleMessageKeys.BLE_AVAILABILITY_CHECK)?.({});
|
|
1011
|
+
|
|
1012
|
+
native.state = 'poweredOn';
|
|
1013
|
+
native.emit('stateChange', 'poweredOn');
|
|
1014
|
+
expect(await oldScan).toEqual([]);
|
|
1015
|
+
expect(native.startScanning).not.toHaveBeenCalled();
|
|
1016
|
+
await sdk.disposeNobleBleSupport();
|
|
1017
|
+
});
|
|
1018
|
+
});
|