@onekeyfe/hd-transport-web-device 1.2.11-alpha.2 → 1.2.11-alpha.21
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/__tests__/electron-ble-transport.test.ts +478 -1
- package/__tests__/webusb-protocol-cache.test.ts +31 -0
- package/dist/electron-ble-transport.d.ts +15 -2
- package/dist/electron-ble-transport.d.ts.map +1 -1
- package/dist/index.d.ts +17 -4
- package/dist/index.js +239 -48
- package/dist/webusb.d.ts +2 -2
- package/dist/webusb.d.ts.map +1 -1
- package/package.json +6 -5
- package/src/electron-ble-transport.ts +299 -37
- package/src/webusb.ts +6 -7
|
@@ -19,22 +19,28 @@ import {
|
|
|
19
19
|
HardwareErrorCodeMessage,
|
|
20
20
|
createDeferred,
|
|
21
21
|
isHeaderChunk,
|
|
22
|
+
isLegacyProtocolV1BleName,
|
|
22
23
|
} from '@onekeyfe/hd-shared';
|
|
23
24
|
|
|
24
25
|
import { resolveBlePacketCapacity } from './ble-packet-capacity';
|
|
25
26
|
|
|
26
27
|
import type { Deferred } from '@onekeyfe/hd-shared';
|
|
27
|
-
import type {
|
|
28
|
+
import type {
|
|
29
|
+
DesktopAPI,
|
|
30
|
+
NobleBleIpcErrorResponse,
|
|
31
|
+
NobleBleWriteOptions,
|
|
32
|
+
} from '@onekeyfe/hd-transport-electron';
|
|
28
33
|
import type {
|
|
29
34
|
AcquireInput,
|
|
30
35
|
OneKeyDeviceInfo,
|
|
31
36
|
ProtocolType,
|
|
32
37
|
ProtocolV2CallContext,
|
|
33
38
|
TransportCallOptions,
|
|
39
|
+
TransportReleaseOptions,
|
|
34
40
|
} from '@onekeyfe/hd-transport';
|
|
35
41
|
import type EventEmitter from 'events';
|
|
36
42
|
|
|
37
|
-
const {
|
|
43
|
+
const { parseTransportConfigure, ProtocolV1, check } = transport;
|
|
38
44
|
|
|
39
45
|
declare global {
|
|
40
46
|
interface Window {
|
|
@@ -47,6 +53,8 @@ export type BleAcquireInput = {
|
|
|
47
53
|
forceCleanRunPromise?: boolean;
|
|
48
54
|
expectedProtocol?: ProtocolType;
|
|
49
55
|
protocolHint?: ProtocolType;
|
|
56
|
+
onlyConnectBleDevice?: boolean;
|
|
57
|
+
abortSignal?: AbortSignal;
|
|
50
58
|
};
|
|
51
59
|
|
|
52
60
|
interface PacketProcessResult {
|
|
@@ -91,6 +99,43 @@ const BLE_WRITE_DELAY_MS = 5;
|
|
|
91
99
|
const PROTOCOL_PROBE_TIMEOUT_MS = 3000;
|
|
92
100
|
const PROTOCOL_V2_PROBE_TIMEOUT_MS = 5000;
|
|
93
101
|
|
|
102
|
+
const shouldRethrowElectronProtocolProbeError = (error: unknown): boolean => {
|
|
103
|
+
if (isProtocolV2LinkDisabledError(error)) {
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
const code = (error as { errorCode?: unknown })?.errorCode;
|
|
107
|
+
// Pairing rejections, disconnects, and missing GATT state are link failures rather than
|
|
108
|
+
// evidence of a protocol mismatch. Rethrow them instead of entering wake or probing V2.
|
|
109
|
+
return (
|
|
110
|
+
code === HardwareErrorCode.TransportCallInProgress ||
|
|
111
|
+
code === HardwareErrorCode.BleConnectedError ||
|
|
112
|
+
code === HardwareErrorCode.BleDeviceNotBonded ||
|
|
113
|
+
code === HardwareErrorCode.BleDeviceBondedCanceled ||
|
|
114
|
+
code === HardwareErrorCode.BleDeviceDisconnected ||
|
|
115
|
+
code === HardwareErrorCode.BleCharacteristicNotFound ||
|
|
116
|
+
code === HardwareErrorCode.BleCharacteristicNotifyError ||
|
|
117
|
+
code === HardwareErrorCode.BleCharacteristicNotifyChangeFailure ||
|
|
118
|
+
code === HardwareErrorCode.BleServiceNotFound ||
|
|
119
|
+
code === HardwareErrorCode.BlePoweredOff ||
|
|
120
|
+
code === HardwareErrorCode.BleUnsupported ||
|
|
121
|
+
code === HardwareErrorCode.BleLocationError
|
|
122
|
+
);
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
const isUnstartedElectronWakeError = (error: unknown): boolean => {
|
|
126
|
+
const candidate = error as { errorCode?: unknown; params?: { writeRejected?: unknown } };
|
|
127
|
+
const code = candidate?.errorCode;
|
|
128
|
+
// Errors returned before a GATT write is submitted or explicitly rejected by the host
|
|
129
|
+
// (e.g. Windows pairing rejection with status: 3) leave the peripheral untouched.
|
|
130
|
+
return (
|
|
131
|
+
candidate?.params?.writeRejected === true ||
|
|
132
|
+
code === HardwareErrorCode.BleCharacteristicNotFound ||
|
|
133
|
+
code === HardwareErrorCode.BlePoweredOff ||
|
|
134
|
+
code === HardwareErrorCode.BleUnsupported ||
|
|
135
|
+
code === HardwareErrorCode.BleLocationError
|
|
136
|
+
);
|
|
137
|
+
};
|
|
138
|
+
|
|
94
139
|
/**
|
|
95
140
|
* Desktop Electron BLE transport with automatic Protocol V1/V2 detection.
|
|
96
141
|
*
|
|
@@ -98,9 +143,9 @@ const PROTOCOL_V2_PROBE_TIMEOUT_MS = 5000;
|
|
|
98
143
|
* after a Protocol V1 GetFeatures timeout by probing Protocol V2 Ping.
|
|
99
144
|
*/
|
|
100
145
|
export default class ElectronBleTransport {
|
|
101
|
-
private _messages: ReturnType<typeof transport.
|
|
146
|
+
private _messages: ReturnType<typeof transport.parseTransportConfigure> | undefined;
|
|
102
147
|
|
|
103
|
-
private _messagesV2: ReturnType<typeof transport.
|
|
148
|
+
private _messagesV2: ReturnType<typeof transport.parseTransportConfigure> | undefined;
|
|
104
149
|
|
|
105
150
|
private protocolV2SchemaConfiguration: string | undefined;
|
|
106
151
|
|
|
@@ -131,10 +176,24 @@ export default class ElectronBleTransport {
|
|
|
131
176
|
*/
|
|
132
177
|
private acquiringDevices: Set<string> = new Set();
|
|
133
178
|
|
|
179
|
+
private stopped = false;
|
|
180
|
+
|
|
181
|
+
private stopPromise?: Promise<void>;
|
|
182
|
+
|
|
134
183
|
private deviceProtocol: Map<string, ProtocolType> = new Map();
|
|
135
184
|
|
|
136
185
|
private deviceProtocolHints: Map<string, ProtocolType> = new Map();
|
|
137
186
|
|
|
187
|
+
private silentDetections = new Map<string, 'silent' | 'woken'>();
|
|
188
|
+
|
|
189
|
+
private probeResponseTimeoutErrors = new WeakSet<Error>();
|
|
190
|
+
|
|
191
|
+
private lastV1ProbeFailedWithoutTimeout: Set<string> = new Set();
|
|
192
|
+
|
|
193
|
+
private acquireGenerations: Map<string, number> = new Map();
|
|
194
|
+
|
|
195
|
+
private nextAcquireGeneration = 1;
|
|
196
|
+
|
|
138
197
|
private deviceMtus: Map<string, number> = new Map();
|
|
139
198
|
|
|
140
199
|
private devicePacketCapacities: Map<string, number> = new Map();
|
|
@@ -162,7 +221,7 @@ export default class ElectronBleTransport {
|
|
|
162
221
|
this.v2Assemblers.get(uuid)?.reset();
|
|
163
222
|
this.rejectProtocolV2Frames(uuid, new Error(reason));
|
|
164
223
|
this.Log?.debug('[Electron BLE] Protocol V2 link invalidated:', uuid, reason);
|
|
165
|
-
if (reason.startsWith('Protocol V2 link-fatal error:')) {
|
|
224
|
+
if (!this.stopped && reason.startsWith('Protocol V2 link-fatal error:')) {
|
|
166
225
|
await this.releaseNative(uuid, { forceNative: true });
|
|
167
226
|
}
|
|
168
227
|
},
|
|
@@ -247,6 +306,7 @@ export default class ElectronBleTransport {
|
|
|
247
306
|
// and doesn't depend on connection state. Preserving it avoids redundant V1 probe on reconnect.
|
|
248
307
|
this.v1Buffers.delete(deviceId);
|
|
249
308
|
this.v2Assemblers.delete(deviceId);
|
|
309
|
+
this.lastV1ProbeFailedWithoutTimeout.delete(deviceId);
|
|
250
310
|
this.resetProtocolV2Frames(deviceId);
|
|
251
311
|
this.notificationTokens.delete(deviceId);
|
|
252
312
|
if (this.runPromise && this.runPromiseDeviceId === deviceId) {
|
|
@@ -269,6 +329,8 @@ export default class ElectronBleTransport {
|
|
|
269
329
|
}
|
|
270
330
|
|
|
271
331
|
init(logger: any, emitter?: EventEmitter) {
|
|
332
|
+
this.stopped = false;
|
|
333
|
+
this.stopPromise = undefined;
|
|
272
334
|
this.Log = logger;
|
|
273
335
|
this.emitter = emitter;
|
|
274
336
|
|
|
@@ -284,6 +346,46 @@ export default class ElectronBleTransport {
|
|
|
284
346
|
this.Log?.debug('[Electron BLE] Transport initialized');
|
|
285
347
|
}
|
|
286
348
|
|
|
349
|
+
private assertRunning() {
|
|
350
|
+
if (this.stopped) {
|
|
351
|
+
throw ERRORS.TypedError(HardwareErrorCode.RuntimeError, 'Electron BLE transport is stopped');
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
stop(): Promise<void> {
|
|
356
|
+
this.stopped = true;
|
|
357
|
+
this.hostDisconnectCleanup?.();
|
|
358
|
+
this.hostDisconnectCleanup = undefined;
|
|
359
|
+
|
|
360
|
+
if (!this.stopPromise) {
|
|
361
|
+
this.stopPromise = this.stopResources();
|
|
362
|
+
}
|
|
363
|
+
return this.stopPromise;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private async stopResources(): Promise<void> {
|
|
367
|
+
const trackedDeviceIds = new Set<string>([
|
|
368
|
+
...this.connectedDevices,
|
|
369
|
+
...this.retainedDevices,
|
|
370
|
+
...this.acquiringDevices,
|
|
371
|
+
...this.notificationCleanups.keys(),
|
|
372
|
+
...this.mtuCleanups.keys(),
|
|
373
|
+
...this.deviceProtocol.keys(),
|
|
374
|
+
...this.v1Buffers.keys(),
|
|
375
|
+
...this.v2Assemblers.keys(),
|
|
376
|
+
]);
|
|
377
|
+
|
|
378
|
+
await Promise.all(Array.from(trackedDeviceIds, deviceId => this.releaseNative(deviceId)));
|
|
379
|
+
this.acquiringDevices.clear();
|
|
380
|
+
this.acquireGenerations.clear();
|
|
381
|
+
this.lastV1ProbeFailedWithoutTimeout.clear();
|
|
382
|
+
this.protocolV2CallCounts.clear();
|
|
383
|
+
this.silentDetections.clear();
|
|
384
|
+
await this.protocolV2Links
|
|
385
|
+
.dispose('Electron BLE transport stopped')
|
|
386
|
+
.catch(error => this.Log?.debug('[Electron BLE] link dispose failed:', error));
|
|
387
|
+
}
|
|
388
|
+
|
|
287
389
|
/**
|
|
288
390
|
* One host subscription for the whole transport lifetime. init() can run
|
|
289
391
|
* again after an SDK reset, so drop the previous listener first rather than
|
|
@@ -322,7 +424,7 @@ export default class ElectronBleTransport {
|
|
|
322
424
|
}
|
|
323
425
|
|
|
324
426
|
configure(signedData: any) {
|
|
325
|
-
this._messages =
|
|
427
|
+
this._messages = parseTransportConfigure(signedData);
|
|
326
428
|
this.configured = true;
|
|
327
429
|
}
|
|
328
430
|
|
|
@@ -333,7 +435,7 @@ export default class ElectronBleTransport {
|
|
|
333
435
|
}
|
|
334
436
|
|
|
335
437
|
const isReconfiguration = this.protocolV2SchemaConfiguration !== undefined;
|
|
336
|
-
this._messagesV2 =
|
|
438
|
+
this._messagesV2 = parseTransportConfigure(signedData);
|
|
337
439
|
this.protocolV2SchemaConfiguration = configuration;
|
|
338
440
|
if (isReconfiguration) {
|
|
339
441
|
this.protocolV2Links
|
|
@@ -370,6 +472,20 @@ export default class ElectronBleTransport {
|
|
|
370
472
|
if (!uuid) {
|
|
371
473
|
throw ERRORS.TypedError(HardwareErrorCode.BleRequiredUUID);
|
|
372
474
|
}
|
|
475
|
+
if (input.abortSignal?.aborted) {
|
|
476
|
+
throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const acquireGeneration = this.nextAcquireGeneration;
|
|
480
|
+
this.nextAcquireGeneration += 1;
|
|
481
|
+
this.acquireGenerations.set(uuid, acquireGeneration);
|
|
482
|
+
const isCurrentAcquire = () => this.acquireGenerations.get(uuid) === acquireGeneration;
|
|
483
|
+
const assertAcquireActive = () => {
|
|
484
|
+
this.assertRunning();
|
|
485
|
+
if (input.abortSignal?.aborted || !isCurrentAcquire()) {
|
|
486
|
+
throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
|
|
487
|
+
}
|
|
488
|
+
};
|
|
373
489
|
|
|
374
490
|
const retainedToken =
|
|
375
491
|
this.retainedDevices.has(uuid) &&
|
|
@@ -383,6 +499,8 @@ export default class ElectronBleTransport {
|
|
|
383
499
|
await this.release(uuid);
|
|
384
500
|
}
|
|
385
501
|
|
|
502
|
+
assertAcquireActive();
|
|
503
|
+
|
|
386
504
|
if (forceCleanRunPromise && this.runPromise) {
|
|
387
505
|
const error = ERRORS.TypedError(HardwareErrorCode.BleForceCleanRunPromise);
|
|
388
506
|
this.runPromise.reject(error);
|
|
@@ -391,12 +509,14 @@ export default class ElectronBleTransport {
|
|
|
391
509
|
}
|
|
392
510
|
|
|
393
511
|
this.acquiringDevices.add(uuid);
|
|
512
|
+
let connectAttempted = false;
|
|
394
513
|
try {
|
|
395
514
|
if (!window.desktopApi?.nobleBle) {
|
|
396
515
|
throw new Error('Noble BLE API not available');
|
|
397
516
|
}
|
|
398
517
|
|
|
399
518
|
const device = await invokeNobleBle(window.desktopApi.nobleBle.getDevice(uuid));
|
|
519
|
+
assertAcquireActive();
|
|
400
520
|
if (!device) {
|
|
401
521
|
throw ERRORS.TypedError(HardwareErrorCode.DeviceNotFound, `Device ${uuid} not found`);
|
|
402
522
|
}
|
|
@@ -420,11 +540,14 @@ export default class ElectronBleTransport {
|
|
|
420
540
|
}
|
|
421
541
|
|
|
422
542
|
try {
|
|
543
|
+
connectAttempted = true;
|
|
423
544
|
await invokeNobleBle(window.desktopApi.nobleBle.connect(uuid));
|
|
545
|
+
assertAcquireActive();
|
|
424
546
|
this.connectedDevices.add(uuid);
|
|
425
547
|
} catch (error) {
|
|
426
548
|
this.handleBluetoothError(error);
|
|
427
549
|
}
|
|
550
|
+
assertAcquireActive();
|
|
428
551
|
|
|
429
552
|
const mtuCleanup = this.createMtuSubscription(uuid);
|
|
430
553
|
if (mtuCleanup) {
|
|
@@ -439,12 +562,20 @@ export default class ElectronBleTransport {
|
|
|
439
562
|
} catch (error) {
|
|
440
563
|
this.handleBluetoothError(error);
|
|
441
564
|
}
|
|
442
|
-
|
|
565
|
+
assertAcquireActive();
|
|
566
|
+
const connectedDevice = await this.refreshBlePacketCapacity(uuid);
|
|
567
|
+
assertAcquireActive();
|
|
568
|
+
const resolvedDeviceName = connectedDevice?.name || device.name;
|
|
443
569
|
|
|
444
570
|
const cleanup = this.createNotificationSubscription(uuid);
|
|
445
571
|
this.notificationCleanups.set(uuid, cleanup);
|
|
446
572
|
|
|
447
|
-
const protocolType = await this.detectProtocol(uuid, expectedProtocol, protocolHint
|
|
573
|
+
const protocolType = await this.detectProtocol(uuid, expectedProtocol, protocolHint, {
|
|
574
|
+
isKnownLegacyV1Device: isLegacyProtocolV1BleName(resolvedDeviceName),
|
|
575
|
+
onlyConnectBleDevice: input.onlyConnectBleDevice,
|
|
576
|
+
abortSignal: input.abortSignal,
|
|
577
|
+
});
|
|
578
|
+
assertAcquireActive();
|
|
448
579
|
if (protocolType === 'V2') {
|
|
449
580
|
this.Log?.debug('[Electron BLE] Protocol V2 write configured', {
|
|
450
581
|
writeMode: 'withoutResponse',
|
|
@@ -454,35 +585,44 @@ export default class ElectronBleTransport {
|
|
|
454
585
|
}
|
|
455
586
|
|
|
456
587
|
return {
|
|
457
|
-
...toBleDescriptor({ id: device.id, name:
|
|
588
|
+
...toBleDescriptor({ id: device.id, name: resolvedDeviceName }, protocolType),
|
|
458
589
|
uuid,
|
|
459
590
|
};
|
|
460
591
|
} catch (error) {
|
|
461
592
|
this.Log?.error('[Electron BLE] acquire failed:', error);
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
if (this.connectedDevices.has(uuid)) {
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
593
|
+
if (isCurrentAcquire()) {
|
|
594
|
+
try {
|
|
595
|
+
const nobleBle = window.desktopApi?.nobleBle;
|
|
596
|
+
if (nobleBle && !this.stopped && (connectAttempted || this.connectedDevices.has(uuid))) {
|
|
597
|
+
if (this.connectedDevices.has(uuid)) {
|
|
598
|
+
await invokeNobleBle(nobleBle.unsubscribe(uuid)).catch(cleanupError => {
|
|
599
|
+
this.Log?.debug('[Electron BLE] acquire unsubscribe failed:', cleanupError);
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
await invokeNobleBle(nobleBle.disconnect(uuid));
|
|
469
603
|
}
|
|
470
|
-
|
|
604
|
+
} catch (cleanupError) {
|
|
605
|
+
this.Log?.debug('[Electron BLE] acquire cleanup failed:', cleanupError);
|
|
471
606
|
}
|
|
472
|
-
|
|
473
|
-
this.Log?.debug('[Electron BLE] acquire cleanup failed:', cleanupError);
|
|
607
|
+
this.cleanupDeviceState(uuid);
|
|
474
608
|
}
|
|
475
|
-
this.
|
|
476
|
-
this.handleBluetoothError(error);
|
|
609
|
+
throw this.normalizeBluetoothError(error);
|
|
477
610
|
} finally {
|
|
478
|
-
|
|
611
|
+
if (isCurrentAcquire()) {
|
|
612
|
+
this.acquiringDevices.delete(uuid);
|
|
613
|
+
}
|
|
479
614
|
}
|
|
480
615
|
}
|
|
481
616
|
|
|
482
|
-
async release(
|
|
617
|
+
async release(
|
|
618
|
+
id: string,
|
|
619
|
+
onclose?: boolean,
|
|
620
|
+
keepSession?: boolean,
|
|
621
|
+
options?: TransportReleaseOptions
|
|
622
|
+
) {
|
|
483
623
|
try {
|
|
484
624
|
const retainLink =
|
|
485
|
-
keepSession === true &&
|
|
625
|
+
(keepSession === true || options?.retainLink === true) &&
|
|
486
626
|
!onclose &&
|
|
487
627
|
this.connectedDevices.has(id) &&
|
|
488
628
|
this.deviceProtocol.get(id) === 'V2' &&
|
|
@@ -583,8 +723,17 @@ export default class ElectronBleTransport {
|
|
|
583
723
|
private async detectProtocol(
|
|
584
724
|
uuid: string,
|
|
585
725
|
expectedProtocol?: ProtocolType,
|
|
586
|
-
protocolHint?: ProtocolType
|
|
726
|
+
protocolHint?: ProtocolType,
|
|
727
|
+
options: {
|
|
728
|
+
isKnownLegacyV1Device?: boolean;
|
|
729
|
+
onlyConnectBleDevice?: boolean;
|
|
730
|
+
abortSignal?: AbortSignal;
|
|
731
|
+
} = {}
|
|
587
732
|
): Promise<ProtocolType> {
|
|
733
|
+
if (options.abortSignal?.aborted) {
|
|
734
|
+
throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
|
|
735
|
+
}
|
|
736
|
+
|
|
588
737
|
// A declared V1 is taken at face value, as the React Native transport
|
|
589
738
|
// already does on iOS: the caller reads the protocol off its own device
|
|
590
739
|
// record, so probing re-asks a question that is already answered and adds a
|
|
@@ -616,25 +765,112 @@ export default class ElectronBleTransport {
|
|
|
616
765
|
protocolHint === 'V2' || this.deviceProtocol.get(uuid) === 'V2' ? ['V2', 'V1'] : ['V1', 'V2'];
|
|
617
766
|
|
|
618
767
|
for (let i = 0; i < probeOrder.length; i += 1) {
|
|
768
|
+
this.assertRunning();
|
|
619
769
|
const protocol = probeOrder[i];
|
|
620
770
|
if (i > 0) {
|
|
621
771
|
// Keep the physical BLE link while switching probes. Reconnecting here can
|
|
622
772
|
// summon a second OS pairing prompt for a device that is still onboarding.
|
|
623
773
|
await this.resetProbeStateAfterProtocolProbe(uuid, probeOrder[i - 1]);
|
|
774
|
+
this.assertRunning();
|
|
624
775
|
}
|
|
625
|
-
|
|
776
|
+
this.lastV1ProbeFailedWithoutTimeout.delete(uuid);
|
|
777
|
+
let detected =
|
|
626
778
|
protocol === 'V1' ? await this.probeProtocolV1(uuid) : await this.probeProtocolV2(uuid);
|
|
779
|
+
if (!detected && protocol === 'V1' && !this.lastV1ProbeFailedWithoutTimeout.has(uuid)) {
|
|
780
|
+
detected = await this.wakeSilentProtocolV1Device(uuid, probeOrder, options);
|
|
781
|
+
}
|
|
782
|
+
this.assertRunning();
|
|
627
783
|
if (detected) {
|
|
628
784
|
this.deviceProtocol.set(uuid, protocol);
|
|
785
|
+
this.silentDetections.delete(uuid);
|
|
629
786
|
this.Log?.debug(`[Electron BLE] detectProtocol: uuid=${uuid} -> ${protocol}`);
|
|
630
787
|
return protocol;
|
|
631
788
|
}
|
|
632
789
|
}
|
|
633
790
|
|
|
791
|
+
if (!this.silentDetections.has(uuid)) {
|
|
792
|
+
this.silentDetections.set(uuid, 'silent');
|
|
793
|
+
}
|
|
634
794
|
this.deviceProtocol.delete(uuid);
|
|
635
795
|
throw this.createProtocolDetectionError();
|
|
636
796
|
}
|
|
637
797
|
|
|
798
|
+
private async wakeSilentProtocolV1Device(
|
|
799
|
+
uuid: string,
|
|
800
|
+
probeOrder: ProtocolType[],
|
|
801
|
+
options: {
|
|
802
|
+
isKnownLegacyV1Device?: boolean;
|
|
803
|
+
onlyConnectBleDevice?: boolean;
|
|
804
|
+
abortSignal?: AbortSignal;
|
|
805
|
+
} = {}
|
|
806
|
+
): Promise<boolean> {
|
|
807
|
+
if (
|
|
808
|
+
options.onlyConnectBleDevice ||
|
|
809
|
+
probeOrder[0] !== 'V1' ||
|
|
810
|
+
this.silentDetections.get(uuid) === 'woken' ||
|
|
811
|
+
(!options.isKnownLegacyV1Device && this.silentDetections.get(uuid) !== 'silent')
|
|
812
|
+
) {
|
|
813
|
+
return false;
|
|
814
|
+
}
|
|
815
|
+
if (options.abortSignal?.aborted) {
|
|
816
|
+
throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
|
|
817
|
+
}
|
|
818
|
+
this.assertRunning();
|
|
819
|
+
|
|
820
|
+
// A timed-out GetFeatures probe retires the renderer notification listener;
|
|
821
|
+
// re-attach it on the live physical link before sending Initialize.
|
|
822
|
+
await this.resetProbeStateAfterProtocolProbe(uuid, 'V1');
|
|
823
|
+
if (options.abortSignal?.aborted) {
|
|
824
|
+
throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
|
|
825
|
+
}
|
|
826
|
+
this.assertRunning();
|
|
827
|
+
|
|
828
|
+
const previousSilentState = this.silentDetections.get(uuid);
|
|
829
|
+
this.silentDetections.set(uuid, 'woken');
|
|
830
|
+
this.Log?.debug('[Electron BLE] sending Protocol V1 Initialize wake', {
|
|
831
|
+
connectIdSuffix: uuid.slice(-8),
|
|
832
|
+
source: options.isKnownLegacyV1Device ? 'legacy-v1-name' : 'silent-retry',
|
|
833
|
+
});
|
|
834
|
+
|
|
835
|
+
let answeredV1 = false;
|
|
836
|
+
try {
|
|
837
|
+
this.deviceProtocol.set(uuid, 'V1');
|
|
838
|
+
const response = await this.callProtocolV1(
|
|
839
|
+
uuid,
|
|
840
|
+
'Initialize',
|
|
841
|
+
{},
|
|
842
|
+
{ timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS },
|
|
843
|
+
{ oneShot: true },
|
|
844
|
+
true
|
|
845
|
+
);
|
|
846
|
+
answeredV1 = typeof response?.type === 'string';
|
|
847
|
+
} catch (error) {
|
|
848
|
+
this.clearProbeProtocol(uuid, 'V1');
|
|
849
|
+
if (isUnstartedElectronWakeError(error)) {
|
|
850
|
+
if (previousSilentState) {
|
|
851
|
+
this.silentDetections.set(uuid, previousSilentState);
|
|
852
|
+
} else {
|
|
853
|
+
this.silentDetections.delete(uuid);
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
this.Log?.debug('[Electron BLE] Protocol V1 Initialize wake failed:', error);
|
|
857
|
+
if (shouldRethrowElectronProtocolProbeError(error)) {
|
|
858
|
+
throw error;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
if (answeredV1) {
|
|
863
|
+
return true;
|
|
864
|
+
}
|
|
865
|
+
if (options.abortSignal?.aborted) {
|
|
866
|
+
throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
|
|
867
|
+
}
|
|
868
|
+
this.assertRunning();
|
|
869
|
+
await this.resetProbeStateAfterProtocolProbe(uuid, 'V1');
|
|
870
|
+
this.assertRunning();
|
|
871
|
+
return this.probeProtocolV1(uuid);
|
|
872
|
+
}
|
|
873
|
+
|
|
638
874
|
private createNotificationSubscription(uuid: string) {
|
|
639
875
|
if (!window.desktopApi?.nobleBle) {
|
|
640
876
|
throw new Error('Noble BLE API not available');
|
|
@@ -683,15 +919,28 @@ export default class ElectronBleTransport {
|
|
|
683
919
|
try {
|
|
684
920
|
this.deviceProtocol.set(uuid, 'V1');
|
|
685
921
|
// GetFeatures identifies Protocol V1 without resetting an existing wallet
|
|
686
|
-
// session before Core has a chance to restore a hidden wallet.
|
|
687
|
-
|
|
922
|
+
// session before Core has a chance to restore a hidden wallet. Use a one-shot
|
|
923
|
+
// native write so a fresh Windows link does not stall 28s in the 15-attempt
|
|
924
|
+
// pairing retry loop when a sleeping Classic silently ignores GetFeatures.
|
|
925
|
+
this.lastV1ProbeFailedWithoutTimeout.delete(uuid);
|
|
926
|
+
await this.callProtocolV1(
|
|
927
|
+
uuid,
|
|
928
|
+
'GetFeatures',
|
|
929
|
+
{},
|
|
930
|
+
{ timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS },
|
|
931
|
+
{ oneShot: true },
|
|
932
|
+
true
|
|
933
|
+
);
|
|
688
934
|
return true;
|
|
689
935
|
} catch (error) {
|
|
690
936
|
this.clearProbeProtocol(uuid, 'V1');
|
|
691
937
|
this.Log?.debug('[Electron BLE] Protocol V1 GetFeatures probe failed:', error);
|
|
692
|
-
if (
|
|
938
|
+
if (shouldRethrowElectronProtocolProbeError(error)) {
|
|
693
939
|
throw error;
|
|
694
940
|
}
|
|
941
|
+
if (!(error instanceof Error && this.probeResponseTimeoutErrors.has(error))) {
|
|
942
|
+
this.lastV1ProbeFailedWithoutTimeout.add(uuid);
|
|
943
|
+
}
|
|
695
944
|
return false;
|
|
696
945
|
}
|
|
697
946
|
}
|
|
@@ -722,6 +971,7 @@ export default class ElectronBleTransport {
|
|
|
722
971
|
}
|
|
723
972
|
|
|
724
973
|
private async writeOnce(uuid: string, hexData: string): Promise<void> {
|
|
974
|
+
this.assertRunning();
|
|
725
975
|
const nobleBle = window.desktopApi?.nobleBle;
|
|
726
976
|
if (!nobleBle) {
|
|
727
977
|
throw new Error('Noble BLE API not available');
|
|
@@ -729,15 +979,17 @@ export default class ElectronBleTransport {
|
|
|
729
979
|
|
|
730
980
|
try {
|
|
731
981
|
await invokeNobleBle(nobleBle.write(uuid, hexData, { pacingDelayMs: 0 }));
|
|
982
|
+
this.assertRunning();
|
|
732
983
|
} catch (error) {
|
|
733
984
|
this.handleBluetoothError(error);
|
|
734
985
|
}
|
|
735
986
|
}
|
|
736
987
|
|
|
737
|
-
private async refreshBlePacketCapacity(uuid: string)
|
|
988
|
+
private async refreshBlePacketCapacity(uuid: string) {
|
|
738
989
|
const nobleBle = window.desktopApi?.nobleBle;
|
|
739
990
|
const device = nobleBle ? await invokeNobleBle(nobleBle.getDevice(uuid)) : undefined;
|
|
740
991
|
this.updateBlePacketCapacity(uuid, device?.mtu);
|
|
992
|
+
return device;
|
|
741
993
|
}
|
|
742
994
|
|
|
743
995
|
private updateBlePacketCapacity(uuid: string, mtu?: number): void {
|
|
@@ -961,7 +1213,9 @@ export default class ElectronBleTransport {
|
|
|
961
1213
|
uuid: string,
|
|
962
1214
|
name: string,
|
|
963
1215
|
data: Record<string, unknown>,
|
|
964
|
-
options?: TransportCallOptions
|
|
1216
|
+
options?: TransportCallOptions,
|
|
1217
|
+
writeOptions?: NobleBleWriteOptions,
|
|
1218
|
+
isProtocolProbe = false
|
|
965
1219
|
) {
|
|
966
1220
|
if (!this._messages) {
|
|
967
1221
|
throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
|
|
@@ -979,6 +1233,7 @@ export default class ElectronBleTransport {
|
|
|
979
1233
|
const messages = this._messages;
|
|
980
1234
|
const buffers = ProtocolV1.encodeTransportPackets(messages, name, data);
|
|
981
1235
|
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
1236
|
+
let responseTimedOut = false;
|
|
982
1237
|
|
|
983
1238
|
try {
|
|
984
1239
|
if (!window.desktopApi?.nobleBle) {
|
|
@@ -994,7 +1249,11 @@ export default class ElectronBleTransport {
|
|
|
994
1249
|
if (hexString.length === 0) {
|
|
995
1250
|
throw new Error(`Buffer ${i + 1} is empty`);
|
|
996
1251
|
}
|
|
997
|
-
await invokeNobleBle(
|
|
1252
|
+
await invokeNobleBle(
|
|
1253
|
+
writeOptions
|
|
1254
|
+
? window.desktopApi.nobleBle.write(uuid, hexString, writeOptions)
|
|
1255
|
+
: window.desktopApi.nobleBle.write(uuid, hexString)
|
|
1256
|
+
);
|
|
998
1257
|
}
|
|
999
1258
|
|
|
1000
1259
|
const response = await Promise.race([
|
|
@@ -1002,6 +1261,7 @@ export default class ElectronBleTransport {
|
|
|
1002
1261
|
new Promise<never>((_, reject) => {
|
|
1003
1262
|
if (options?.timeoutMs) {
|
|
1004
1263
|
timeout = setTimeout(() => {
|
|
1264
|
+
responseTimedOut = true;
|
|
1005
1265
|
const error = ERRORS.TypedError(
|
|
1006
1266
|
HardwareErrorCode.BleTimeoutError,
|
|
1007
1267
|
`BLE response timeout after ${options.timeoutMs}ms for ${name}`
|
|
@@ -1020,19 +1280,21 @@ export default class ElectronBleTransport {
|
|
|
1020
1280
|
return check.call(jsonData);
|
|
1021
1281
|
} catch (e) {
|
|
1022
1282
|
this.Log?.error('[Electron BLE] Protocol V1 call error:', e);
|
|
1023
|
-
const isProbeTimeout =
|
|
1024
|
-
name === 'GetFeatures' && options?.timeoutMs === PROTOCOL_PROBE_TIMEOUT_MS;
|
|
1025
1283
|
if ((e as { errorCode?: unknown })?.errorCode === HardwareErrorCode.BleTimeoutError) {
|
|
1026
1284
|
this.v1Buffers.set(uuid, { buffer: [], bufferLength: 0 });
|
|
1027
1285
|
const notifyCleanup = this.notificationCleanups.get(uuid);
|
|
1028
1286
|
notifyCleanup?.();
|
|
1029
1287
|
this.notificationCleanups.delete(uuid);
|
|
1030
1288
|
this.notificationTokens.delete(uuid);
|
|
1031
|
-
if (!
|
|
1289
|
+
if (!isProtocolProbe) {
|
|
1032
1290
|
await this.releaseNative(uuid, { forceNative: true });
|
|
1033
1291
|
}
|
|
1034
1292
|
}
|
|
1035
|
-
|
|
1293
|
+
const normalized = this.normalizeBluetoothError(e);
|
|
1294
|
+
if (isProtocolProbe && responseTimedOut && normalized instanceof Error) {
|
|
1295
|
+
this.probeResponseTimeoutErrors.add(normalized);
|
|
1296
|
+
}
|
|
1297
|
+
throw normalized;
|
|
1036
1298
|
} finally {
|
|
1037
1299
|
if (timeout) clearTimeout(timeout);
|
|
1038
1300
|
if (this.runPromise === runPromise) {
|
package/src/webusb.ts
CHANGED
|
@@ -33,7 +33,7 @@ import type {
|
|
|
33
33
|
TransportCallOptions,
|
|
34
34
|
} from '@onekeyfe/hd-transport';
|
|
35
35
|
|
|
36
|
-
const {
|
|
36
|
+
const { parseTransportConfigure, check, ProtocolV1 } = transport;
|
|
37
37
|
|
|
38
38
|
const CONFIGURATION_ID = 1;
|
|
39
39
|
const INTERFACE_ID = 0;
|
|
@@ -135,10 +135,10 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
|
|
|
135
135
|
|
|
136
136
|
private deviceLogIds = new WeakMap<USBDevice, number>();
|
|
137
137
|
|
|
138
|
-
messages: ReturnType<typeof transport.
|
|
138
|
+
messages: ReturnType<typeof transport.parseTransportConfigure> | undefined;
|
|
139
139
|
|
|
140
140
|
/** Protobuf schema for Protocol V2 transports. */
|
|
141
|
-
messagesV2: ReturnType<typeof transport.
|
|
141
|
+
messagesV2: ReturnType<typeof transport.parseTransportConfigure> | undefined;
|
|
142
142
|
|
|
143
143
|
private protocolV2SchemaSource: string | undefined;
|
|
144
144
|
|
|
@@ -505,7 +505,7 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
|
|
|
505
505
|
* Configure Protocol V1 protobuf schema (legacy chunked 0x3F framing).
|
|
506
506
|
*/
|
|
507
507
|
configure(signedData: any) {
|
|
508
|
-
const messages =
|
|
508
|
+
const messages = parseTransportConfigure(signedData);
|
|
509
509
|
this.configured = true;
|
|
510
510
|
this.messages = messages;
|
|
511
511
|
}
|
|
@@ -521,7 +521,7 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
|
|
|
521
521
|
if (schemaSource === this.protocolV2SchemaSource) return;
|
|
522
522
|
|
|
523
523
|
const hadProtocolV2Schema = this.protocolV2SchemaSource !== undefined;
|
|
524
|
-
this.messagesV2 =
|
|
524
|
+
this.messagesV2 = parseTransportConfigure(signedData);
|
|
525
525
|
this.protocolV2SchemaSource = schemaSource;
|
|
526
526
|
if (!hadProtocolV2Schema) return;
|
|
527
527
|
|
|
@@ -1828,8 +1828,7 @@ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string>
|
|
|
1828
1828
|
}
|
|
1829
1829
|
}
|
|
1830
1830
|
decoded.reset();
|
|
1831
|
-
|
|
1832
|
-
return Buffer.from(result as unknown as ArrayBuffer).toString('hex');
|
|
1831
|
+
return decoded.toString('hex');
|
|
1833
1832
|
}
|
|
1834
1833
|
|
|
1835
1834
|
/**
|