@onekeyfe/hwk-desktop-noble-ble 1.2.11-alpha.1 → 1.2.11-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/README.md ADDED
@@ -0,0 +1,173 @@
1
+ # Desktop BLE for third-party hardware wallets
2
+
3
+ `@onekeyfe/hwk-desktop-noble-ble` owns Ledger/Trezor BLE discovery, GATT I/O,
4
+ Windows OS pairing, cancellation, and connection cleanup in the Electron main
5
+ process. The host owns the native Windows pairing executable, IPC sender authorization,
6
+ UI, translations, and packaging.
7
+ It does not replace the separate OneKey `hd-transport-electron` transport.
8
+
9
+ ## Main-process setup
10
+
11
+ Use `initThirdPartyBleSupport` once per active renderer. Existing integrations
12
+ without `windowsPairing` retain native-only behavior. On macOS/Linux the Windows
13
+ option is ignored; this option does not enable Linux BLE support.
14
+
15
+ ```ts
16
+ import path from 'path';
17
+ import { app, dialog, ipcMain } from 'electron';
18
+ import {
19
+ initThirdPartyBleSupport,
20
+ withThirdPartyBleIpcErrors,
21
+ } from '@onekeyfe/hwk-desktop-noble-ble';
22
+ import type { IpcMainLike } from '@onekeyfe/hwk-desktop-noble-ble';
23
+
24
+ // Run after creating your BrowserWindow. Do not expose these handlers to DApps.
25
+ const authorizedIpcMain: IpcMainLike = {
26
+ handle(channel, listener) {
27
+ ipcMain.handle(channel, (event, ...args) => {
28
+ if (window.isDestroyed() || event.sender !== window.webContents) {
29
+ throw new Error('BLE IPC sender is not authorized');
30
+ }
31
+ return listener(event, ...args);
32
+ });
33
+ },
34
+ removeHandler: channel => ipcMain.removeHandler(channel),
35
+ };
36
+
37
+ const ble = initThirdPartyBleSupport(window.webContents, {
38
+ ipcMain: withThirdPartyBleIpcErrors(authorizedIpcMain),
39
+ windowsPairing: process.platform === 'win32' ? {
40
+ helperPath: app.isPackaged
41
+ ? path.join(process.resourcesPath, 'ble-pair', 'onekey-ble-pair.exe')
42
+ : path.join(
43
+ app.getAppPath(), 'resources', 'ble-pair', `win-${process.arch}`,
44
+ 'onekey-ble-pair.exe'
45
+ ),
46
+ async onPairingRequest({ pin, signal }) {
47
+ if (signal.aborted || window.isDestroyed()) return 'cancel';
48
+ const { response } = await dialog.showMessageBox(window, {
49
+ message: pin,
50
+ detail: 'Compare this code with your device before confirming.',
51
+ buttons: ['Confirm', 'Cancel'],
52
+ cancelId: 1,
53
+ defaultId: 0,
54
+ noLink: true,
55
+ signal,
56
+ });
57
+ return !signal.aborted && response === 0 ? 'confirm' : 'cancel';
58
+ },
59
+ } : undefined,
60
+ });
61
+ ```
62
+
63
+ The same `windowsPairing` option works with `new NobleBleHandler(options)` for
64
+ hosts that do not use Electron IPC. Neither integration needs an IPC wrapper,
65
+ vendor timeout switches, a global decision callback, or a copy of the pairing
66
+ state machine. The helper path must be host-controlled, never renderer input.
67
+ Missing/unexecutable helpers fail with a structured `BleConnectFailed` error
68
+ instead of silently skipping a configured Windows pairing flow.
69
+
70
+ `onPairingRequest` is a numeric-comparison UI callback, not a device PIN entry or
71
+ Trezor THP authorization callback. Display the supplied code, require an explicit
72
+ user decision, and never log/persist it. A throwing or rejected callback declines
73
+ the OS request. Observe `signal`: close the UI as soon as it aborts, even if the
74
+ underlying Windows process is still cleaning up. A late answer is ignored and
75
+ cannot confirm a later ceremony. With a custom UI, implement the same lifetime
76
+ contract rather than adding an independent timeout.
77
+
78
+ ## Windows packaging
79
+
80
+ The SDK does not include or build a native pairing executable. The host must
81
+ provide a trusted, compatible helper through `windowsPairing.helperPath`, along
82
+ with `onPairingRequest`. The OneKey Rust implementation and its x64/ARM64 binaries
83
+ are maintained in the
84
+ [App monorepo](https://github.com/OneKeyHQ/app-monorepo/tree/b8bb5cf4a5fb359c44ea2fbd3f39d00855bf8e15/apps/desktop/native-modules/onekey-ble-pair).
85
+ Use the matching [x64/ARM64 binaries from the same revision](https://github.com/OneKeyHQ/app-monorepo/tree/b8bb5cf4a5fb359c44ea2fbd3f39d00855bf8e15/apps/desktop/public/static/bin/ble-pair),
86
+ not assets from a different branch. That repository owns native builds and binary
87
+ updates. This revision emits structured `link` and `pairing-result` events and
88
+ continues reading host cancellation after confirmation.
89
+
90
+ Copy the **target build architecture** outside ASAR. For example, if the host
91
+ stores its executables under `resources/ble-pair/win-{x64,arm64}`, add this to its
92
+ electron-builder Windows configuration:
93
+
94
+ ```js
95
+ win: {
96
+ extraResources: [{
97
+ from: 'resources/ble-pair/win-${arch}',
98
+ to: 'ble-pair',
99
+ filter: ['onekey-ble-pair.exe'],
100
+ }],
101
+ }
102
+ ```
103
+
104
+ Keep this SDK package external when bundling the main process, and install a
105
+ compatible `@stoprocent/noble` Electron native build. Do not put the helper inside
106
+ ASAR or choose its architecture from the machine performing a cross build.
107
+ Store/MSIX builds must include the same resource. Installing this package does
108
+ not download or compile a helper, and does not supply the host's native Noble
109
+ patches or Electron build.
110
+
111
+ The host helper must implement the process protocol used by
112
+ `src/windowsPairingHelper.ts`: accept `pair --address`, emit JSON events on stdout,
113
+ and read `confirm`/`cancel` decisions from stdin. Keep host binary updates
114
+ compatible with that protocol. Without the `windowsPairing` option, the SDK
115
+ retains its existing native-only connection behavior.
116
+
117
+ ## Lifecycle and error recovery
118
+
119
+ The SDK validates the vendor/GATT profile before any pairing work. It uses the
120
+ selected vendor's discovered address, pauses scanning while retaining the target,
121
+ and serializes Windows ceremonies across handler instances. It never chooses a
122
+ different device automatically. Native GATT connect timeout starts after OS
123
+ pairing, so user confirmation does not consume the 31-second connect deadline.
124
+ Discovery and scan pause have a separate deadline using `connectTimeoutMs`.
125
+ Cancellation or that deadline settles the caller independently of native scan
126
+ cleanup; a late discovery cannot start a cancelled pairing.
127
+
128
+ - Ledger numeric comparison expires after 30 seconds. A pending prompt closes on
129
+ device disconnection.
130
+ - Trezor permits a one-second recovery window for transient pairing link changes.
131
+ A persistent disconnection closes an unanswered prompt. This observation is a
132
+ pairing failure, not proof that the user explicitly cancelled on the device.
133
+ - An unanswered ceremony is bounded at 60 seconds; completion after host
134
+ confirmation is bounded at 30 seconds. Cancelling declines the WinRT deferral
135
+ before a five-second fallback kills a stuck helper.
136
+ - Only the first GATT connection after a **fresh bond** may retry once. The SDK
137
+ does not retry a timed-out native connect or replay address/signing commands.
138
+ - A bonded Ledger's immediate GATT link drop can report `BleBondInvalid`. The same
139
+ symptom on Trezor is left as a connection error because locking can cause it.
140
+
141
+ Call `cancelPairing({ vendor, id })` to cancel one target, `{ vendor }` for one
142
+ vendor, or omit the argument to cancel all. This also covers queued OS pairing,
143
+ native connect, and the delayed fresh-bond retry. Cancellation never answers
144
+ another device's prompt. `disconnect(id)` releases an established connection.
145
+
146
+ On window retirement, await `ble.dispose()` before registering replacement IPC
147
+ handlers. This cancels pending OS pairing and closes its prompt. For app shutdown,
148
+ use `disposeForAppQuit`; when sharing noble with another transport, dispose both
149
+ first and deduplicate their `releaseNoble` callbacks before stopping the native
150
+ manager, as documented by `ThirdPartyBleSupportHandle`.
151
+
152
+ Errors preserve `code`, `message`, and `params` across
153
+ `withThirdPartyBleIpcErrors`. The preload must check
154
+ `isThirdPartyBleIpcErrorResponse(response)` and throw `response.error` as data.
155
+ The renderer-side connector uses `rehydrateElectronBleErrors` to restore these
156
+ rejections as structured errors; that function does not unwrap successful IPC
157
+ responses. Forward the normal response unchanged.
158
+ Keep renderer sender authorization outside the error envelope as in the example.
159
+ Do not reduce structured errors to message-only strings.
160
+
161
+ Host recovery UI should offer these steps:
162
+
163
+ | Failure | User action |
164
+ | --- | --- |
165
+ | `BlePairingCancelled` | Return to device selection; let the user retry when ready. |
166
+ | Pairing timeout/device disconnect | Unlock/wake the device and reopen pairing, then retry. |
167
+ | Trezor no longer reachable | Open **Pair new device** on the Safe 7, rescan, and select the current numbered entry. BLE address/name are discovery locators, not wallet identity. |
168
+ | `BleBondInvalid` | Forget the device in Windows Bluetooth settings, reset its host pairing if needed, then pair again. |
169
+ | Repeated GATT failure | Offer system Bluetooth pairing repair as troubleshooting; do not claim every unreachable device has an invalid bond. |
170
+
171
+ Use live SDK device identity for wallet matching, not a remembered BLE address or
172
+ Trezor name suffix. Windows OS bonding and Trezor THP authorization are separate
173
+ layers; the vendor adapter still owns THP events and permissions.
package/dist/index.d.mts CHANGED
@@ -13,6 +13,22 @@ type BleDebugLogger = (entry: BleDebugLogEntry) => void;
13
13
  /** Replace sensitive values at any depth; everything else is forwarded verbatim. */
14
14
  declare function redactBleDebugLogData(data?: Record<string, unknown>): Record<string, unknown> | undefined;
15
15
 
16
+ type WindowsBlePairingDecision = 'confirm' | 'cancel';
17
+ interface WindowsBlePairingRequest {
18
+ id: string;
19
+ vendor: string;
20
+ /** Numeric comparison only. Never persist or log this value. */
21
+ pin: string;
22
+ /** Close the prompt immediately when aborted; ignore any later UI answer. */
23
+ signal: AbortSignal;
24
+ }
25
+ interface WindowsBlePairingOptions {
26
+ /** Absolute path to the host-provided helper, copied outside Electron's ASAR. */
27
+ helperPath: string;
28
+ /** Resolve only after the user compares the code and confirms or cancels. */
29
+ onPairingRequest(request: WindowsBlePairingRequest): Promise<WindowsBlePairingDecision>;
30
+ }
31
+
16
32
  /**
17
33
  * Main-process allowlist entry for one vendor key. The renderer only names the vendor; which
18
34
  * peripherals it may see and which GATT profile and framing it may use are decided here, so an
@@ -35,7 +51,7 @@ declare const DEFAULT_THIRD_PARTY_BLE_VENDORS: Readonly<Record<string, ThirdPart
35
51
 
36
52
  /** Device info the main process returns to the renderer over IPC. */
37
53
  interface ThirdPartyBleDeviceInfo {
38
- /** Stable id (noble peripheral.id) used as connectId. */
54
+ /** Discovery locator (noble peripheral.id), used as connectId. May rotate; not wallet identity. */
39
55
  id: string;
40
56
  name?: string;
41
57
  rssi?: number;
@@ -155,9 +171,11 @@ interface NobleCharacteristicLike {
155
171
  }
156
172
  type NobleFactory = () => NobleLike;
157
173
  interface NobleBleHandlerOptions {
174
+ /** Windows OS bonding before GATT connect. Omit to retain native-only behavior. */
175
+ windowsPairing?: WindowsBlePairingOptions;
158
176
  /** Override for tests; defaults to `require('@stoprocent/noble')`. */
159
177
  nobleFactory?: NobleFactory;
160
- /** Override the overall connect timeout (tests only; defaults to 31s). */
178
+ /** Override GATT connect timeout (tests only; defaults to 31s), excluding OS pairing. */
161
179
  connectTimeoutMs?: number;
162
180
  /** Override the subscribe timeout (tests only; defaults to 60s). */
163
181
  subscribeTimeoutMs?: number;
@@ -172,6 +190,7 @@ interface NobleBleHandlerOptions {
172
190
  declare class NobleBleHandler {
173
191
  private _noble;
174
192
  private readonly _factory;
193
+ private readonly _windowsPairing?;
175
194
  private readonly _connectTimeoutMs;
176
195
  private readonly _subscribeTimeoutMs;
177
196
  private readonly _logger?;
@@ -185,6 +204,7 @@ declare class NobleBleHandler {
185
204
  private _scanning;
186
205
  private readonly _scanOwners;
187
206
  private _scanTransition;
207
+ private _pairingScanPauses;
188
208
  private _idleStopTimer?;
189
209
  private _onNotification?;
190
210
  private _onDeviceDisconnected?;
@@ -227,6 +247,7 @@ declare class NobleBleHandler {
227
247
  private _setScanning;
228
248
  /** Stop scanning but keep the discovered cache (used before connect). */
229
249
  private _pauseScan;
250
+ private _pauseScanForPairing;
230
251
  /** Stop scanning and forget discovered devices (idle timeout / teardown). */
231
252
  private _stopContinuousScan;
232
253
  /** A vendor releasing discovery must not stop another vendor's scan. */
@@ -258,15 +279,11 @@ declare class NobleBleHandler {
258
279
  id: string;
259
280
  name?: string;
260
281
  }>;
282
+ private _connectWithTimeout;
261
283
  private _connectInner;
262
284
  disconnect(id: string): Promise<void>;
263
285
  subscribe(id: string): Promise<void>;
264
286
  private _withSubscribeTimeout;
265
- /**
266
- * noble-win reports a failed subscribe only as `status: <AsyncStatus>`. Error (3) on a live
267
- * link is a device refusing the bond Windows holds; a link already gone fails it the same way.
268
- */
269
- private _toSubscribeError;
270
287
  unsubscribe(id: string): Promise<void>;
271
288
  write(id: string, hexData: string): Promise<void>;
272
289
  /** Retire a renderer's handler without stopping a process-wide native manager. */
@@ -327,4 +344,4 @@ declare function withThirdPartyBleIpcErrors(ipcMain: IpcMainLike): IpcMainLike;
327
344
  */
328
345
  declare function initThirdPartyBleSupport(webContents: WebContentsLike, options?: InitThirdPartyBleSupportOptions): ThirdPartyBleSupportHandle;
329
346
 
330
- export { type BleDebugLogEntry, type BleDebugLogLevel, type BleDebugLogger, DEFAULT_THIRD_PARTY_BLE_VENDORS, type InitThirdPartyBleSupportOptions, type IpcMainLike, NobleBleHandler, type NobleBleHandlerOptions, type ThirdPartyBleApi, type ThirdPartyBleAvailability, type ThirdPartyBleDeviceInfo, ThirdPartyBleIpcErrorResponse, type ThirdPartyBleSupportHandle, type ThirdPartyBleVendorProfile, createThirdPartyBleIpcErrorResponse, initThirdPartyBleSupport, redactBleDebugLogData, withThirdPartyBleIpcErrors };
347
+ export { type BleDebugLogEntry, type BleDebugLogLevel, type BleDebugLogger, DEFAULT_THIRD_PARTY_BLE_VENDORS, type InitThirdPartyBleSupportOptions, type IpcMainLike, NobleBleHandler, type NobleBleHandlerOptions, type ThirdPartyBleApi, type ThirdPartyBleAvailability, type ThirdPartyBleDeviceInfo, ThirdPartyBleIpcErrorResponse, type ThirdPartyBleSupportHandle, type ThirdPartyBleVendorProfile, type WindowsBlePairingDecision, type WindowsBlePairingOptions, type WindowsBlePairingRequest, createThirdPartyBleIpcErrorResponse, initThirdPartyBleSupport, redactBleDebugLogData, withThirdPartyBleIpcErrors };
package/dist/index.d.ts CHANGED
@@ -13,6 +13,22 @@ type BleDebugLogger = (entry: BleDebugLogEntry) => void;
13
13
  /** Replace sensitive values at any depth; everything else is forwarded verbatim. */
14
14
  declare function redactBleDebugLogData(data?: Record<string, unknown>): Record<string, unknown> | undefined;
15
15
 
16
+ type WindowsBlePairingDecision = 'confirm' | 'cancel';
17
+ interface WindowsBlePairingRequest {
18
+ id: string;
19
+ vendor: string;
20
+ /** Numeric comparison only. Never persist or log this value. */
21
+ pin: string;
22
+ /** Close the prompt immediately when aborted; ignore any later UI answer. */
23
+ signal: AbortSignal;
24
+ }
25
+ interface WindowsBlePairingOptions {
26
+ /** Absolute path to the host-provided helper, copied outside Electron's ASAR. */
27
+ helperPath: string;
28
+ /** Resolve only after the user compares the code and confirms or cancels. */
29
+ onPairingRequest(request: WindowsBlePairingRequest): Promise<WindowsBlePairingDecision>;
30
+ }
31
+
16
32
  /**
17
33
  * Main-process allowlist entry for one vendor key. The renderer only names the vendor; which
18
34
  * peripherals it may see and which GATT profile and framing it may use are decided here, so an
@@ -35,7 +51,7 @@ declare const DEFAULT_THIRD_PARTY_BLE_VENDORS: Readonly<Record<string, ThirdPart
35
51
 
36
52
  /** Device info the main process returns to the renderer over IPC. */
37
53
  interface ThirdPartyBleDeviceInfo {
38
- /** Stable id (noble peripheral.id) used as connectId. */
54
+ /** Discovery locator (noble peripheral.id), used as connectId. May rotate; not wallet identity. */
39
55
  id: string;
40
56
  name?: string;
41
57
  rssi?: number;
@@ -155,9 +171,11 @@ interface NobleCharacteristicLike {
155
171
  }
156
172
  type NobleFactory = () => NobleLike;
157
173
  interface NobleBleHandlerOptions {
174
+ /** Windows OS bonding before GATT connect. Omit to retain native-only behavior. */
175
+ windowsPairing?: WindowsBlePairingOptions;
158
176
  /** Override for tests; defaults to `require('@stoprocent/noble')`. */
159
177
  nobleFactory?: NobleFactory;
160
- /** Override the overall connect timeout (tests only; defaults to 31s). */
178
+ /** Override GATT connect timeout (tests only; defaults to 31s), excluding OS pairing. */
161
179
  connectTimeoutMs?: number;
162
180
  /** Override the subscribe timeout (tests only; defaults to 60s). */
163
181
  subscribeTimeoutMs?: number;
@@ -172,6 +190,7 @@ interface NobleBleHandlerOptions {
172
190
  declare class NobleBleHandler {
173
191
  private _noble;
174
192
  private readonly _factory;
193
+ private readonly _windowsPairing?;
175
194
  private readonly _connectTimeoutMs;
176
195
  private readonly _subscribeTimeoutMs;
177
196
  private readonly _logger?;
@@ -185,6 +204,7 @@ declare class NobleBleHandler {
185
204
  private _scanning;
186
205
  private readonly _scanOwners;
187
206
  private _scanTransition;
207
+ private _pairingScanPauses;
188
208
  private _idleStopTimer?;
189
209
  private _onNotification?;
190
210
  private _onDeviceDisconnected?;
@@ -227,6 +247,7 @@ declare class NobleBleHandler {
227
247
  private _setScanning;
228
248
  /** Stop scanning but keep the discovered cache (used before connect). */
229
249
  private _pauseScan;
250
+ private _pauseScanForPairing;
230
251
  /** Stop scanning and forget discovered devices (idle timeout / teardown). */
231
252
  private _stopContinuousScan;
232
253
  /** A vendor releasing discovery must not stop another vendor's scan. */
@@ -258,15 +279,11 @@ declare class NobleBleHandler {
258
279
  id: string;
259
280
  name?: string;
260
281
  }>;
282
+ private _connectWithTimeout;
261
283
  private _connectInner;
262
284
  disconnect(id: string): Promise<void>;
263
285
  subscribe(id: string): Promise<void>;
264
286
  private _withSubscribeTimeout;
265
- /**
266
- * noble-win reports a failed subscribe only as `status: <AsyncStatus>`. Error (3) on a live
267
- * link is a device refusing the bond Windows holds; a link already gone fails it the same way.
268
- */
269
- private _toSubscribeError;
270
287
  unsubscribe(id: string): Promise<void>;
271
288
  write(id: string, hexData: string): Promise<void>;
272
289
  /** Retire a renderer's handler without stopping a process-wide native manager. */
@@ -327,4 +344,4 @@ declare function withThirdPartyBleIpcErrors(ipcMain: IpcMainLike): IpcMainLike;
327
344
  */
328
345
  declare function initThirdPartyBleSupport(webContents: WebContentsLike, options?: InitThirdPartyBleSupportOptions): ThirdPartyBleSupportHandle;
329
346
 
330
- export { type BleDebugLogEntry, type BleDebugLogLevel, type BleDebugLogger, DEFAULT_THIRD_PARTY_BLE_VENDORS, type InitThirdPartyBleSupportOptions, type IpcMainLike, NobleBleHandler, type NobleBleHandlerOptions, type ThirdPartyBleApi, type ThirdPartyBleAvailability, type ThirdPartyBleDeviceInfo, ThirdPartyBleIpcErrorResponse, type ThirdPartyBleSupportHandle, type ThirdPartyBleVendorProfile, createThirdPartyBleIpcErrorResponse, initThirdPartyBleSupport, redactBleDebugLogData, withThirdPartyBleIpcErrors };
347
+ export { type BleDebugLogEntry, type BleDebugLogLevel, type BleDebugLogger, DEFAULT_THIRD_PARTY_BLE_VENDORS, type InitThirdPartyBleSupportOptions, type IpcMainLike, NobleBleHandler, type NobleBleHandlerOptions, type ThirdPartyBleApi, type ThirdPartyBleAvailability, type ThirdPartyBleDeviceInfo, ThirdPartyBleIpcErrorResponse, type ThirdPartyBleSupportHandle, type ThirdPartyBleVendorProfile, type WindowsBlePairingDecision, type WindowsBlePairingOptions, type WindowsBlePairingRequest, createThirdPartyBleIpcErrorResponse, initThirdPartyBleSupport, redactBleDebugLogData, withThirdPartyBleIpcErrors };