@onekeyfe/hwk-adapter-core 1.2.3-alpha.7 → 1.2.3-alpha.8

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.
Files changed (37) hide show
  1. package/dist/{chunk-SZZF623R.js → chunk-CQM2P5IG.js} +155 -55
  2. package/dist/chunk-CQM2P5IG.js.map +1 -0
  3. package/dist/chunk-DB4JOPZO.mjs +74 -0
  4. package/dist/chunk-DB4JOPZO.mjs.map +1 -0
  5. package/dist/{chunk-U63HTLGJ.mjs → chunk-EQYPRCWU.mjs} +48 -12
  6. package/dist/chunk-EQYPRCWU.mjs.map +1 -0
  7. package/dist/{chunk-YA4BWFTZ.mjs → chunk-IOFMG7YO.mjs} +155 -55
  8. package/dist/chunk-IOFMG7YO.mjs.map +1 -0
  9. package/dist/{chunk-BAGEFFFY.js → chunk-WUIWRX56.js} +49 -13
  10. package/dist/chunk-WUIWRX56.js.map +1 -0
  11. package/dist/chunk-YLCHSNXO.js +74 -0
  12. package/dist/chunk-YLCHSNXO.js.map +1 -0
  13. package/dist/errors-Cm8XpjmX.d.mts +321 -0
  14. package/dist/errors-Cm8XpjmX.d.ts +321 -0
  15. package/dist/errors.d.mts +1 -207
  16. package/dist/errors.d.ts +1 -207
  17. package/dist/errors.js +8 -2
  18. package/dist/errors.js.map +1 -1
  19. package/dist/errors.mjs +9 -3
  20. package/dist/index.d.mts +635 -98
  21. package/dist/index.d.ts +635 -98
  22. package/dist/index.js +680 -82
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.mjs +671 -73
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/{ui-events-Cb7haAeE.d.mts → ui-events-BGUpXxvP.d.mts} +44 -3
  27. package/dist/{ui-events-Cb7haAeE.d.ts → ui-events-BGUpXxvP.d.ts} +44 -3
  28. package/dist/ui-events.d.mts +1 -1
  29. package/dist/ui-events.d.ts +1 -1
  30. package/dist/ui-events.js +3 -2
  31. package/dist/ui-events.js.map +1 -1
  32. package/dist/ui-events.mjs +2 -1
  33. package/package.json +2 -2
  34. package/dist/chunk-BAGEFFFY.js.map +0 -1
  35. package/dist/chunk-SZZF623R.js.map +0 -1
  36. package/dist/chunk-U63HTLGJ.mjs.map +0 -1
  37. package/dist/chunk-YA4BWFTZ.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,9 +1,6 @@
1
1
  import {
2
- HardwareErrorCode,
3
- ORPHAN_ELIGIBLE_ERROR_CODES,
4
- createHwkError,
5
2
  enrichErrorMessage
6
- } from "./chunk-YA4BWFTZ.mjs";
3
+ } from "./chunk-DB4JOPZO.mjs";
7
4
  import {
8
5
  UI_EVENT,
9
6
  UI_REQUEST,
@@ -13,19 +10,40 @@ import {
13
10
  UI_REQUEST_TIMEOUT_TAG,
14
11
  UI_RESPONSE,
15
12
  UiRequestRegistry
16
- } from "./chunk-U63HTLGJ.mjs";
13
+ } from "./chunk-EQYPRCWU.mjs";
14
+ import {
15
+ HardwareErrorCode,
16
+ ORPHAN_ELIGIBLE_ERROR_CODES,
17
+ createHwkError,
18
+ defaultOriginForCode,
19
+ defaultRecoveryForCode,
20
+ isHwkRecoveryHint,
21
+ operationMayHaveCompletedParams
22
+ } from "./chunk-IOFMG7YO.mjs";
17
23
 
18
24
  // src/types/response.ts
19
25
  function success(payload) {
20
26
  return { success: true, payload };
21
27
  }
22
- function failure(code, error, params) {
28
+ function failure(code, error, params, origin, recovery) {
23
29
  return {
24
30
  success: false,
25
- payload: { error, code, ...params ? { params } : {} }
31
+ payload: {
32
+ error,
33
+ code,
34
+ ...origin !== void 0 ? { origin } : {},
35
+ recovery: recovery ?? defaultRecoveryForCode(code),
36
+ ...params ? { params } : {}
37
+ }
26
38
  };
27
39
  }
28
40
 
41
+ // src/types/device.ts
42
+ function resolveSearchTargetReusePolicy(device) {
43
+ if (device.capabilities?.persistentDeviceIdentity) return "reconnectable";
44
+ return "current-discovery";
45
+ }
46
+
29
47
  // src/types/fingerprint.ts
30
48
  import { sha256 } from "@noble/hashes/sha256";
31
49
  import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils";
@@ -35,11 +53,21 @@ var CHAIN_FINGERPRINT_PATHS = {
35
53
  // Cointype 1 (testnet) is rejected by some Ledger BTC App configurations.
36
54
  btc: "m/44'/0'/0'",
37
55
  sol: "m/44'/501'/0'",
38
- tron: "m/44'/195'/0'/0/0"
56
+ tron: "m/44'/195'/0'/0/0",
57
+ // Shielded UA (single Orchard receiver) derived from the transparent path.
58
+ zcash: "m/44'/133'/0'/0/0"
39
59
  };
60
+ function parseBip32MasterFingerprint(value) {
61
+ if (typeof value !== "string") return void 0;
62
+ const normalized = value.trim().toLowerCase();
63
+ return /^[0-9a-f]{8}$/.test(normalized) ? normalized : void 0;
64
+ }
40
65
  function deriveDeviceFingerprint(value) {
41
66
  return bytesToHex(sha256(utf8ToBytes(value))).slice(0, 16);
42
67
  }
68
+ function deriveWalletId(canonicalPublicMaterial) {
69
+ return bytesToHex(sha256(utf8ToBytes(`onekey-hwk-wallet-id:v1:${canonicalPublicMaterial}`)));
70
+ }
43
71
 
44
72
  // src/events/device.ts
45
73
  var DEVICE_EVENT = "DEVICE_EVENT";
@@ -66,7 +94,8 @@ var SDK = {
66
94
  DEVICE_STUCK: "device-stuck",
67
95
  DEVICE_UNRESPONSIVE: "device-unresponsive",
68
96
  DEVICE_RECOVERED: "device-recovered",
69
- DEVICE_INTERACTION: "device-interaction"
97
+ DEVICE_INTERACTION: "device-interaction",
98
+ OPERATION_ENDED: "operation-ended"
70
99
  };
71
100
 
72
101
  // src/utils/DeviceJobQueue.ts
@@ -75,6 +104,7 @@ var DeviceJobQueue = class {
75
104
  this._tail = Promise.resolve();
76
105
  this._active = null;
77
106
  this._jobs = /* @__PURE__ */ new Map();
107
+ this._cancelScopes = /* @__PURE__ */ new Map();
78
108
  /** Incremented on clear() so queued-but-not-yet-running jobs detect invalidation. */
79
109
  this._generation = 0;
80
110
  this._generationCancelReasons = /* @__PURE__ */ new Map();
@@ -97,12 +127,13 @@ var DeviceJobQueue = class {
97
127
  abortController: ac,
98
128
  startedAt: Date.now()
99
129
  };
100
- this._jobs.set(jobToken, { deviceId });
130
+ this._jobs.set(jobToken, activeJob);
101
131
  const next = prev.catch(() => {
102
132
  }).then(async () => {
103
133
  if (this._generation !== gen) {
104
134
  throw this._generationCancelReasons.get(gen) ?? new Error("Job cancelled: queue was cleared");
105
135
  }
136
+ if (ac.signal.aborted) throw ac.signal.reason;
106
137
  this._active = activeJob;
107
138
  try {
108
139
  return await job(ac.signal);
@@ -118,32 +149,69 @@ var DeviceJobQueue = class {
118
149
  });
119
150
  return next;
120
151
  }
121
- /** Cancel the active job. If `deviceId` is given, only cancels when it matches. */
122
- cancelActive(deviceId) {
123
- if (!this._active) return false;
124
- if (deviceId && this._active.deviceId !== deviceId) return false;
125
- this._active.abortController.abort(new Error("Manually cancelled"));
126
- return true;
152
+ /**
153
+ * Open a cancellation scope that outlives the individual jobs under it.
154
+ *
155
+ * A bundle (all-network) does not enqueue itself it enqueues one job per
156
+ * item. Between two items the queue is empty, so a cancel landing in that
157
+ * gap finds nothing to abort and the next item goes to the device anyway.
158
+ * The scope holds the cancel across those gaps; the bundle checks its
159
+ * signal before each item. Callers must `release()` when the bundle ends.
160
+ */
161
+ createCancelScope(deviceId) {
162
+ const scopeToken = {};
163
+ const abortController = new AbortController();
164
+ this._cancelScopes.set(scopeToken, { deviceId, abortController });
165
+ return {
166
+ signal: abortController.signal,
167
+ release: () => {
168
+ this._cancelScopes.delete(scopeToken);
169
+ }
170
+ };
127
171
  }
128
- /** Force cancel the active job. `reason` becomes signal.reason. */
129
- forceCancelActive(deviceId, reason) {
172
+ /**
173
+ * Cancel the running job. `reason` becomes signal.reason.
174
+ *
175
+ * No caller today: every adapter cancel wants the queued work invalidated
176
+ * too and uses `cancelActiveAndPending`. Kept for a connector layer that
177
+ * needs to stop only what is on the wire and leave the queue behind it.
178
+ */
179
+ cancelActive(deviceId, reason) {
130
180
  if (!this._active) return false;
131
181
  if (deviceId && this._active.deviceId !== deviceId) return false;
132
- this._active.abortController.abort(reason ?? new Error("Force cancelled for recovery"));
182
+ this._active.abortController.abort(reason ?? new Error("Cancelled"));
133
183
  return true;
134
184
  }
135
- /** Cancel the active job (alias for callers that previously needed multi-device cancel). */
136
- cancelAllActive(reason) {
137
- if (!this._active) return;
138
- this._active.abortController.abort(reason ?? new Error("Cancelled by cancelAllActive"));
139
- }
140
- /** Cancel the active job and invalidate queued jobs that have not started. */
185
+ /**
186
+ * Cancel the active job and invalidate queued jobs that have not started.
187
+ *
188
+ * Only `undefined` means "everything". An empty string is a queue key that
189
+ * derived to nothing, so it matches nothing and reports `false` rather than
190
+ * silently tearing the whole queue down.
191
+ *
192
+ * Returns what the cancel actually reached, not whether it was accepted.
193
+ */
141
194
  cancelActiveAndPending(deviceId, reason) {
142
- if (deviceId && this._active && this._active.deviceId !== deviceId) {
143
- return false;
195
+ const cancelReason = reason ?? new Error("Cancelled by cancelActiveAndPending");
196
+ if (deviceId !== void 0) {
197
+ let cancelled = false;
198
+ for (const job of this._jobs.values()) {
199
+ if (job.deviceId === deviceId) {
200
+ job.abortController.abort(cancelReason);
201
+ cancelled = true;
202
+ }
203
+ }
204
+ for (const scope of this._cancelScopes.values()) {
205
+ if (scope.deviceId === deviceId) {
206
+ scope.abortController.abort(cancelReason);
207
+ cancelled = true;
208
+ }
209
+ }
210
+ return cancelled;
144
211
  }
145
- this.clear(reason ?? new Error("Cancelled by cancelActiveAndPending"));
146
- return true;
212
+ const reached = this._active !== null || this._jobs.size > 0 || this._cancelScopes.size > 0;
213
+ this.clear(cancelReason);
214
+ return reached;
147
215
  }
148
216
  /** Get info about the currently active job, or null if idle. */
149
217
  getActiveJob(deviceId) {
@@ -155,10 +223,6 @@ var DeviceJobQueue = class {
155
223
  startedAt: this._active.startedAt
156
224
  };
157
225
  }
158
- /** True if any job is currently running. */
159
- isBusy() {
160
- return this._jobs.size > 0;
161
- }
162
226
  clear(reason) {
163
227
  const cancelledGeneration = this._generation;
164
228
  this._generation++;
@@ -172,9 +236,232 @@ var DeviceJobQueue = class {
172
236
  if (this._active) {
173
237
  this._active.abortController.abort(cancelReason);
174
238
  }
239
+ for (const scope of this._cancelScopes.values()) {
240
+ scope.abortController.abort(cancelReason);
241
+ }
242
+ }
243
+ };
244
+
245
+ // src/utils/hardwareRuntimeId.ts
246
+ import { bytesToHex as bytesToHex2, randomBytes } from "@noble/hashes/utils";
247
+ var HARDWARE_RUNTIME_ID_PREFIX = "hwk:runtime";
248
+ var RANDOM_ID_BYTES = 16;
249
+ var RANDOM_ID_PATTERN = /^[0-9a-f]{32}$/;
250
+ var KINDS = /* @__PURE__ */ new Set([
251
+ "operation",
252
+ "search-target",
253
+ "link"
254
+ ]);
255
+ var VENDORS = /* @__PURE__ */ new Set(["trezor", "ledger", "keystone"]);
256
+ function create(kind, vendor) {
257
+ return `${HARDWARE_RUNTIME_ID_PREFIX}:${kind}:${vendor}:${bytesToHex2(
258
+ randomBytes(RANDOM_ID_BYTES)
259
+ )}`;
260
+ }
261
+ function createHardwareOperationId(vendor) {
262
+ return create("operation", vendor);
263
+ }
264
+ function createHardwareSearchTargetId(vendor) {
265
+ return create("search-target", vendor);
266
+ }
267
+ function createHardwareLinkId(vendor) {
268
+ return create("link", vendor);
269
+ }
270
+ function hasHardwareRuntimeIdPrefix(value) {
271
+ return typeof value === "string" && value.startsWith(`${HARDWARE_RUNTIME_ID_PREFIX}:`);
272
+ }
273
+ function parseHardwareRuntimeId(value) {
274
+ if (!hasHardwareRuntimeIdPrefix(value)) return void 0;
275
+ const parts = value.split(":");
276
+ if (parts.length !== 5) return void 0;
277
+ const [, , kind, vendor, nonce] = parts;
278
+ if (!KINDS.has(kind) || !VENDORS.has(vendor) || !RANDOM_ID_PATTERN.test(nonce)) {
279
+ return void 0;
280
+ }
281
+ return { kind, vendor };
282
+ }
283
+ function isHardwareOperationId(value) {
284
+ return parseHardwareRuntimeId(value)?.kind === "operation";
285
+ }
286
+
287
+ // src/utils/OperationRegistry.ts
288
+ var OPERATION_DEFAULT_TTL_MS = 6e5;
289
+ var OperationRegistry = class {
290
+ constructor(options) {
291
+ this._active = /* @__PURE__ */ new Map();
292
+ this._ended = /* @__PURE__ */ new Map();
293
+ this._vendor = options.vendor;
294
+ this._ttlMs = options.ttlMs ?? OPERATION_DEFAULT_TTL_MS;
295
+ this._onEnded = options.onEnded;
296
+ }
297
+ create(params) {
298
+ const now = Date.now();
299
+ const operationId = createHardwareOperationId(this._vendor);
300
+ const operation = {
301
+ operationId,
302
+ connectId: params.connectId,
303
+ device: params.device,
304
+ connectionType: params.connectionType,
305
+ connectionKeys: Array.from(
306
+ new Set(
307
+ [params.searchTargetId, params.connectId, ...params.connectionKeys ?? []].filter(
308
+ Boolean
309
+ )
310
+ )
311
+ ),
312
+ createdAt: now,
313
+ lastActiveAt: now
314
+ };
315
+ const timer = this._createTimer(operationId);
316
+ this._active.set(operationId, { ...operation, timer, retainCount: 0 });
317
+ return operation;
318
+ }
319
+ resolve(operationId) {
320
+ const active = this._active.get(operationId);
321
+ if (!active) {
322
+ const ended = this._ended.get(operationId);
323
+ if (ended) {
324
+ throw createHwkError({
325
+ code: 10113 /* OperationEnded */,
326
+ message: `Hardware operation has ended (${ended.reason})`,
327
+ params: { operationId, reason: ended.reason }
328
+ });
329
+ }
330
+ throw createHwkError({
331
+ code: 10112 /* OperationNotFound */,
332
+ message: "Hardware operation was not found",
333
+ params: { operationId }
334
+ });
335
+ }
336
+ if (active.timer) clearTimeout(active.timer);
337
+ active.lastActiveAt = Date.now();
338
+ active.timer = active.retainCount === 0 ? this._createTimer(operationId) : void 0;
339
+ return active;
340
+ }
341
+ /** Keep an operation alive while one device job is actively using it. */
342
+ retain(operationId) {
343
+ const active = this.resolve(operationId);
344
+ if (active.timer) clearTimeout(active.timer);
345
+ active.timer = void 0;
346
+ active.retainCount += 1;
347
+ let released = false;
348
+ return () => {
349
+ if (released) return;
350
+ released = true;
351
+ const current = this._active.get(operationId);
352
+ if (!current) return;
353
+ current.retainCount = Math.max(0, current.retainCount - 1);
354
+ current.lastActiveAt = Date.now();
355
+ if (current.retainCount === 0) {
356
+ current.timer = this._createTimer(operationId);
357
+ }
358
+ };
359
+ }
360
+ /** Return active or tombstoned binding data without refreshing its TTL. */
361
+ find(operationId) {
362
+ return this._active.get(operationId) ?? this._ended.get(operationId)?.operation;
363
+ }
364
+ findActiveByConnectionKey(connectionKey) {
365
+ if (!connectionKey) return void 0;
366
+ return [...this._active.values()].find(
367
+ (operation) => operation.connectionKeys.includes(connectionKey)
368
+ );
369
+ }
370
+ /** Replace the live transport binding after the same target was reconnected. */
371
+ rebind(operationId, params) {
372
+ const active = this._active.get(operationId);
373
+ if (!active) {
374
+ this.resolve(operationId);
375
+ throw new Error("Unreachable operation rebind");
376
+ }
377
+ if (active.timer) clearTimeout(active.timer);
378
+ active.connectId = params.connectId;
379
+ active.device = params.device;
380
+ active.connectionType = params.connectionType;
381
+ active.connectionKeys = Array.from(
382
+ new Set([params.connectId, ...params.connectionKeys ?? []].filter(Boolean))
383
+ );
384
+ active.lastActiveAt = Date.now();
385
+ active.timer = active.retainCount === 0 ? this._createTimer(operationId) : void 0;
386
+ return active;
387
+ }
388
+ end(operationId, reason) {
389
+ const active = this._active.get(operationId);
390
+ if (!active) return void 0;
391
+ if (active.timer) clearTimeout(active.timer);
392
+ this._active.delete(operationId);
393
+ this._rememberEnded(active, reason);
394
+ this._onEnded?.(active, reason);
395
+ return active;
396
+ }
397
+ endByConnectionKey(connectionKey, reason, exceptOperationId) {
398
+ if (!connectionKey) return;
399
+ for (const operation of [...this._active.values()]) {
400
+ if (operation.operationId === exceptOperationId) continue;
401
+ if (operation.connectionKeys.includes(connectionKey)) {
402
+ this.end(operation.operationId, reason);
403
+ }
404
+ }
405
+ }
406
+ endAll(reason, exceptOperationId) {
407
+ for (const operationId of [...this._active.keys()]) {
408
+ if (operationId === exceptOperationId) continue;
409
+ this.end(operationId, reason);
410
+ }
411
+ }
412
+ _createTimer(operationId) {
413
+ const timer = setTimeout(() => {
414
+ this.end(operationId, "timeout");
415
+ }, this._ttlMs);
416
+ timer.unref?.();
417
+ return timer;
418
+ }
419
+ _rememberEnded(operation, reason) {
420
+ this._ended.set(operation.operationId, { reason, operation });
421
+ if (this._ended.size <= 100) return;
422
+ const oldest = this._ended.keys().next().value;
423
+ if (oldest) this._ended.delete(oldest);
175
424
  }
176
425
  };
177
426
 
427
+ // src/utils/hardwareOperationTarget.ts
428
+ function resolveHardwareOperationTarget(positionalTargetId, commonOperationId, expectedVendor) {
429
+ const normalizedPositionalTargetId = positionalTargetId ?? void 0;
430
+ const normalizedCommonOperationId = commonOperationId || void 0;
431
+ const positionalOperationId = isHardwareOperationId(normalizedPositionalTargetId) ? normalizedPositionalTargetId : void 0;
432
+ const parsedPositionalTarget = parseHardwareRuntimeId(normalizedPositionalTargetId);
433
+ const parsedCommonOperation = parseHardwareRuntimeId(normalizedCommonOperationId);
434
+ if (normalizedPositionalTargetId && hasHardwareRuntimeIdPrefix(normalizedPositionalTargetId) && !parsedPositionalTarget) {
435
+ return failure(10002 /* InvalidParams */, "Invalid hardware operation target id");
436
+ }
437
+ if (parsedPositionalTarget?.kind === "link") {
438
+ return failure(
439
+ 10002 /* InvalidParams */,
440
+ "Hardware transport link id cannot be used as an operation target"
441
+ );
442
+ }
443
+ if (normalizedCommonOperationId && parsedCommonOperation?.kind !== "operation") {
444
+ return failure(10002 /* InvalidParams */, "Invalid hardware operation id");
445
+ }
446
+ if (expectedVendor && (parsedPositionalTarget && parsedPositionalTarget.vendor !== expectedVendor || parsedCommonOperation && parsedCommonOperation.vendor !== expectedVendor)) {
447
+ return failure(
448
+ 10002 /* InvalidParams */,
449
+ `Hardware operation does not belong to ${expectedVendor}`
450
+ );
451
+ }
452
+ if (positionalOperationId && normalizedCommonOperationId && positionalOperationId !== normalizedCommonOperationId) {
453
+ return failure(10002 /* InvalidParams */, "Conflicting hardware operation ids", {
454
+ positionalOperationId,
455
+ commonOperationId: normalizedCommonOperationId
456
+ });
457
+ }
458
+ const operationId = normalizedCommonOperationId ?? positionalOperationId;
459
+ return success({
460
+ operationId,
461
+ targetId: operationId ?? normalizedPositionalTargetId
462
+ });
463
+ }
464
+
178
465
  // src/types/connector.ts
179
466
  var EConnectorInteraction = /* @__PURE__ */ ((EConnectorInteraction2) => {
180
467
  EConnectorInteraction2["Searching"] = "searching";
@@ -190,7 +477,7 @@ function createBridgedConnector(vendor, connectionType, bridge) {
190
477
  return {
191
478
  connectionType,
192
479
  searchDevices: (options) => bridge.searchDevices({ vendor, options }),
193
- connect: (deviceId) => bridge.connect({ vendor, deviceId }),
480
+ connect: (deviceId, options) => bridge.connect({ vendor, deviceId, ...options ? { options } : {} }),
194
481
  disconnect: (sessionId) => bridge.disconnect({ vendor, sessionId }),
195
482
  call: (sessionId, method, callParams) => bridge.call({ vendor, sessionId, method, callParams }),
196
483
  cancel: (sessionId) => bridge.cancel({ vendor, sessionId }),
@@ -331,10 +618,14 @@ function createCombinedConnector(connectors) {
331
618
  });
332
619
  }
333
620
  const searchDevices = async (options = {}) => {
621
+ const selectedConnectors = connectors.map((child, index) => ({ child, index })).filter(
622
+ ({ child }) => !options.transportType || child.connectionType === options.transportType
623
+ );
624
+ if (!selectedConnectors.length) return [];
334
625
  const perConnector = [];
335
- await new Promise((resolve) => {
626
+ await new Promise((resolve, reject) => {
336
627
  let finished = false;
337
- let remaining = connectors.length;
628
+ let remaining = selectedConnectors.length;
338
629
  let settleTimer;
339
630
  const finish = () => {
340
631
  if (finished) return;
@@ -342,19 +633,20 @@ function createCombinedConnector(connectors) {
342
633
  if (settleTimer) clearTimeout(settleTimer);
343
634
  resolve();
344
635
  };
345
- connectors.forEach((child, index) => {
346
- void child.searchDevices().then(
636
+ selectedConnectors.forEach(({ child, index }) => {
637
+ void child.searchDevices(options.purpose ? { purpose: options.purpose } : void 0).then(
347
638
  (devices) => devices.map((device) => ({
348
639
  ...device,
349
640
  connectionType: device.connectionType ?? child.connectionType
350
641
  }))
351
- ).catch(
352
- () => (
353
- // A transport that can't scan (powered off, unauthorized, absent)
354
- // must not fail the whole fused search.
355
- []
356
- )
357
- ).then((devices) => {
642
+ ).catch((error) => {
643
+ if (options.transportType) {
644
+ finished = true;
645
+ if (settleTimer) clearTimeout(settleTimer);
646
+ reject(error);
647
+ }
648
+ return [];
649
+ }).then((devices) => {
358
650
  remaining -= 1;
359
651
  if (!finished) {
360
652
  perConnector.push({ index, devices });
@@ -371,7 +663,12 @@ function createCombinedConnector(connectors) {
371
663
  });
372
664
  });
373
665
  perConnector.sort((a, b) => a.index - b.index);
374
- deviceOwner.clear();
666
+ if (!options.transportType) deviceOwner.clear();
667
+ else {
668
+ for (const [id, owner] of deviceOwner) {
669
+ if (owner.connectionType === options.transportType) deviceOwner.delete(id);
670
+ }
671
+ }
375
672
  const merged = [];
376
673
  perConnector.forEach(({ index, devices }) => {
377
674
  for (const device of devices) {
@@ -381,11 +678,11 @@ function createCombinedConnector(connectors) {
381
678
  });
382
679
  return merged.sort((a, b) => rank(a) - rank(b));
383
680
  };
384
- const resolveOwner = async (deviceId) => {
385
- if (deviceId && deviceOwner.has(deviceId)) {
681
+ const resolveOwner = async (deviceId, transportType) => {
682
+ if (deviceId && deviceOwner.has(deviceId) && (!transportType || deviceOwner.get(deviceId)?.connectionType === transportType)) {
386
683
  return { owner: deviceOwner.get(deviceId), deviceId };
387
684
  }
388
- const devices = await searchDevices({ waitForAll: Boolean(deviceId) });
685
+ const devices = await searchDevices({ waitForAll: Boolean(deviceId), transportType });
389
686
  if (deviceId) {
390
687
  const owner = deviceOwner.get(deviceId);
391
688
  if (!owner)
@@ -396,13 +693,14 @@ function createCombinedConnector(connectors) {
396
693
  if (!first) throw combinedDeviceNotFoundError("Combined connector: no devices found");
397
694
  return { owner: deviceOwner.get(first.connectId), deviceId: first.connectId };
398
695
  };
399
- const connectByExplicitId = async (deviceId) => {
696
+ const connectByExplicitId = async (deviceId, transportType) => {
400
697
  const cachedOwner = deviceOwner.get(deviceId);
401
- if (cachedOwner) {
698
+ if (cachedOwner && (!transportType || cachedOwner.connectionType === transportType)) {
402
699
  return { session: await cachedOwner.connect(deviceId), owner: cachedOwner };
403
700
  }
404
701
  let lastError;
405
702
  for (const child of connectors) {
703
+ if (transportType && child.connectionType !== transportType) continue;
406
704
  try {
407
705
  const session = await child.connect(deviceId);
408
706
  deviceOwner.set(deviceId, child);
@@ -424,14 +722,15 @@ function createCombinedConnector(connectors) {
424
722
  // Nominal value only — the per-device `connectionType` is authoritative
425
723
  // for a fused connector.
426
724
  connectionType: connectors[0].connectionType,
427
- searchDevices: (options) => searchDevices({ waitForAll: options?.waitForAll }),
428
- connect: async (deviceId) => {
725
+ availableTransports: [...new Set(connectors.map((child) => child.connectionType))],
726
+ searchDevices: (options) => searchDevices(options),
727
+ connect: async (deviceId, options) => {
429
728
  let owner;
430
729
  let session;
431
730
  if (deviceId) {
432
- ({ session, owner } = await connectByExplicitId(deviceId));
731
+ ({ session, owner } = await connectByExplicitId(deviceId, options?.transportType));
433
732
  } else {
434
- const resolved = await resolveOwner();
733
+ const resolved = await resolveOwner(void 0, options?.transportType);
435
734
  owner = resolved.owner;
436
735
  session = await owner.connect(resolved.deviceId);
437
736
  }
@@ -537,6 +836,148 @@ var TypedEventEmitter = class {
537
836
  }
538
837
  };
539
838
 
839
+ // src/utils/requestSaveDeviceBinding.ts
840
+ async function requestSaveDeviceBinding(emitter, registry, binding, signal) {
841
+ const type = UI_REQUEST.REQUEST_SAVE_DEVICE_BINDING;
842
+ const declined = (reason) => {
843
+ emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
844
+ type: UI_REQUEST.DEVICE_BINDING_STATUS,
845
+ payload: { selectionRequestId: binding.selectionRequestId, status: "failed" }
846
+ });
847
+ return { saved: false, reason };
848
+ };
849
+ if (!emitter.listenerCount(type)) {
850
+ return declined("skipped");
851
+ }
852
+ if (signal?.aborted) throw signal.reason;
853
+ const requestId = registry.createRequestId();
854
+ const pending = registry.wait(type, { requestId, operationId: binding.operationId });
855
+ void pending.catch(() => void 0);
856
+ const cancel = () => registry.cancel(type, requestId);
857
+ signal?.addEventListener("abort", cancel, { once: true });
858
+ try {
859
+ emitter.emit(type, { type, payload: { ...binding, requestId } });
860
+ const response = await pending;
861
+ if (signal?.aborted) throw signal.reason;
862
+ if (response?.saved !== true) {
863
+ return declined(response?.reason ?? "skipped");
864
+ }
865
+ emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
866
+ type: UI_REQUEST.DEVICE_BINDING_STATUS,
867
+ payload: { selectionRequestId: binding.selectionRequestId, status: "saved" }
868
+ });
869
+ return { saved: true };
870
+ } catch (error) {
871
+ emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
872
+ type: UI_REQUEST.DEVICE_BINDING_STATUS,
873
+ payload: {
874
+ selectionRequestId: binding.selectionRequestId,
875
+ status: signal?.aborted ? "cancelled" : "failed"
876
+ }
877
+ });
878
+ if (signal?.aborted) throw error;
879
+ return { saved: false, reason: "skipped" };
880
+ } finally {
881
+ signal?.removeEventListener("abort", cancel);
882
+ registry.cancel(type, requestId);
883
+ }
884
+ }
885
+
886
+ // src/utils/requestBleDeviceSelection.ts
887
+ async function requestBleDeviceSelection({
888
+ emitter,
889
+ registry,
890
+ request,
891
+ scan,
892
+ signal,
893
+ allowUsbFallback = false,
894
+ pollIntervalMs = 1500
895
+ }) {
896
+ const type = UI_REQUEST.REQUEST_SELECT_DEVICE;
897
+ if (signal.aborted) throw signal.reason;
898
+ if (!emitter.listenerCount(type)) {
899
+ throw createHwkError({
900
+ code: 10100 /* DeviceNotFound */,
901
+ message: "Select a Bluetooth device before continuing"
902
+ });
903
+ }
904
+ const requestId = registry.createRequestId();
905
+ const { operationId } = request;
906
+ let devices = allowUsbFallback ? request.devices.filter((device) => device.connectionType === "ble") : request.devices;
907
+ const publishedDevices = /* @__PURE__ */ new Map();
908
+ let stopped = false;
909
+ let timer;
910
+ let wake;
911
+ const stop = () => {
912
+ stopped = true;
913
+ if (timer !== void 0) clearTimeout(timer);
914
+ wake?.();
915
+ };
916
+ const waitForNextScan = () => new Promise((resolve) => {
917
+ wake = resolve;
918
+ timer = setTimeout(resolve, pollIntervalMs);
919
+ if (stopped) resolve();
920
+ });
921
+ const cancel = () => registry.cancel(type, requestId);
922
+ const reply = registry.wait(type, { requestId, operationId }).finally(stop);
923
+ void reply.catch(() => void 0);
924
+ const publish = () => {
925
+ for (const device of devices) publishedDevices.set(device.connectId, device);
926
+ emitter.emit(type, {
927
+ type,
928
+ payload: { ...request, devices, requestId, scanning: true }
929
+ });
930
+ };
931
+ signal.addEventListener("abort", cancel, { once: true });
932
+ let polling;
933
+ try {
934
+ publish();
935
+ polling = (async () => {
936
+ await Promise.resolve();
937
+ while (!stopped) {
938
+ const snapshot = await scan();
939
+ if (stopped || signal.aborted) return;
940
+ const usbFallback = allowUsbFallback ? snapshot.find((device2) => device2.connectionType === "usb") : void 0;
941
+ if (usbFallback) return usbFallback;
942
+ devices = snapshot;
943
+ publish();
944
+ if (stopped) return;
945
+ await waitForNextScan();
946
+ }
947
+ })();
948
+ const userSelection = reply.then((selected) => publishedDevices.get(selected.sdkConnectId));
949
+ const device = await Promise.race([
950
+ userSelection,
951
+ polling.then((usbFallback) => usbFallback ?? userSelection)
952
+ ]);
953
+ stop();
954
+ await polling;
955
+ if (signal.aborted) throw signal.reason;
956
+ if (!device) {
957
+ throw createHwkError({
958
+ code: 10100 /* DeviceNotFound */,
959
+ message: "Selected Bluetooth device is no longer available"
960
+ });
961
+ }
962
+ emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
963
+ type: UI_REQUEST.DEVICE_BINDING_STATUS,
964
+ payload: { selectionRequestId: requestId, status: "verifying" }
965
+ });
966
+ return { device, requestId };
967
+ } catch (error) {
968
+ emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
969
+ type: UI_REQUEST.DEVICE_BINDING_STATUS,
970
+ payload: { selectionRequestId: requestId, status: signal.aborted ? "cancelled" : "failed" }
971
+ });
972
+ throw error;
973
+ } finally {
974
+ stop();
975
+ signal.removeEventListener("abort", cancel);
976
+ registry.cancel(type, requestId);
977
+ await polling?.catch(() => void 0);
978
+ }
979
+ }
980
+
540
981
  // src/utils/semver.ts
541
982
  function compareSemver(a, b) {
542
983
  const pa = a.split(".").map(Number);
@@ -564,14 +1005,96 @@ function padHex64(hex) {
564
1005
  function hexToBytes(hex) {
565
1006
  return nobleHexToBytes(stripHex(hex));
566
1007
  }
567
- function bytesToHex2(bytes) {
1008
+ function bytesToHex3(bytes) {
568
1009
  return nobleBytesToHex(bytes);
569
1010
  }
570
1011
 
1012
+ // src/utils/solanaOffchainMessage.ts
1013
+ var SOLANA_OFFCHAIN_SIGNING_DOMAIN = Uint8Array.of(
1014
+ 255,
1015
+ ...Array.from("solana offchain", (character) => character.charCodeAt(0))
1016
+ );
1017
+ var SOLANA_PUBLIC_KEY_LENGTH = 32;
1018
+ var MAX_SOLANA_OFFCHAIN_SIGNERS = 255;
1019
+ function compareBytes(a, b) {
1020
+ for (let index = 0; index < a.length; index += 1) {
1021
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
1022
+ if (difference !== 0) return difference;
1023
+ }
1024
+ return a.length - b.length;
1025
+ }
1026
+ function bytesEqual(a, b) {
1027
+ return a.length === b.length && a.every((value, index) => value === b[index]);
1028
+ }
1029
+ function decodeUtf8Strict(bytes) {
1030
+ let encoded = "";
1031
+ for (const value of bytes) {
1032
+ encoded += `%${value.toString(16).padStart(2, "0")}`;
1033
+ }
1034
+ return decodeURIComponent(encoded);
1035
+ }
1036
+ function prepareSolanaOffchainMessageV1({
1037
+ message,
1038
+ requiredSigners
1039
+ }) {
1040
+ if (message.length === 0) {
1041
+ throw new Error("Solana off-chain message cannot be empty");
1042
+ }
1043
+ if (requiredSigners.length === 0 || requiredSigners.length > MAX_SOLANA_OFFCHAIN_SIGNERS) {
1044
+ throw new Error("Solana off-chain message requires between 1 and 255 signers");
1045
+ }
1046
+ let messageText;
1047
+ try {
1048
+ messageText = decodeUtf8Strict(message);
1049
+ } catch {
1050
+ throw new Error("Solana off-chain message must contain valid UTF-8");
1051
+ }
1052
+ const signerBytes = requiredSigners.map((signer, index) => {
1053
+ let bytes;
1054
+ try {
1055
+ bytes = hexToBytes(signer);
1056
+ } catch {
1057
+ throw new Error(`Solana off-chain signer ${index} must be a hex public key`);
1058
+ }
1059
+ if (bytes.length !== SOLANA_PUBLIC_KEY_LENGTH) {
1060
+ throw new Error(`Solana off-chain signer ${index} must be 32 bytes`);
1061
+ }
1062
+ return bytes;
1063
+ });
1064
+ signerBytes.sort(compareBytes);
1065
+ for (let index = 1; index < signerBytes.length; index += 1) {
1066
+ if (bytesEqual(signerBytes[index - 1], signerBytes[index])) {
1067
+ throw new Error("Solana off-chain signers must be unique");
1068
+ }
1069
+ }
1070
+ const serializedMessage = new Uint8Array(
1071
+ SOLANA_OFFCHAIN_SIGNING_DOMAIN.length + 2 + signerBytes.length * SOLANA_PUBLIC_KEY_LENGTH + message.length
1072
+ );
1073
+ let offset = 0;
1074
+ serializedMessage.set(SOLANA_OFFCHAIN_SIGNING_DOMAIN, offset);
1075
+ offset += SOLANA_OFFCHAIN_SIGNING_DOMAIN.length;
1076
+ serializedMessage[offset] = 1;
1077
+ offset += 1;
1078
+ serializedMessage[offset] = signerBytes.length;
1079
+ offset += 1;
1080
+ for (const signer of signerBytes) {
1081
+ serializedMessage.set(signer, offset);
1082
+ offset += SOLANA_PUBLIC_KEY_LENGTH;
1083
+ }
1084
+ serializedMessage.set(message, offset);
1085
+ return {
1086
+ messageText,
1087
+ requiredSigners: signerBytes.map(bytesToHex3),
1088
+ serializedMessage
1089
+ };
1090
+ }
1091
+
571
1092
  // src/utils/deviceIdentity.ts
572
1093
  var ONEKEY_BLE_SERVICE_UUID = "00000001-0000-1000-8000-00805f9b34fb";
573
1094
  var TREZOR_BLE_SERVICE_UUID = "8c000001-a59b-4d58-a9ad-073df69fa1b1";
574
1095
  var LEDGER_USB_VENDOR_ID = 11415;
1096
+ var KEYSTONE_USB_VENDOR_ID = 4617;
1097
+ var KEYSTONE_USB_PRODUCT_ID = 12289;
575
1098
  var lower = (value) => value?.trim().toLowerCase() ?? "";
576
1099
  var hasServiceUuid = (input, uuid) => {
577
1100
  const expected = uuid.toLowerCase();
@@ -594,6 +1117,11 @@ function detectHardwareVendorFromDescriptor(input) {
594
1117
  if (typeof input.vendor === "number" && input.vendor === LEDGER_USB_VENDOR_ID || input.vendorId === LEDGER_USB_VENDOR_ID || manufacturerName.includes("ledger")) {
595
1118
  return "ledger";
596
1119
  }
1120
+ const usbVendorId = typeof input.vendor === "number" ? input.vendor : input.vendorId;
1121
+ const usbProductId = typeof input.product === "number" ? input.product : input.productId;
1122
+ if (usbVendorId === KEYSTONE_USB_VENDOR_ID && usbProductId === KEYSTONE_USB_PRODUCT_ID || manufacturerName.includes("keystone")) {
1123
+ return "keystone";
1124
+ }
597
1125
  return void 0;
598
1126
  }
599
1127
  function isKnownNonTargetHardwareVendor(input, targetVendor) {
@@ -617,28 +1145,62 @@ async function batchCall(params, callFn, onProgress) {
617
1145
 
618
1146
  // src/utils/methodCatalog.ts
619
1147
  var HARDWARE_METHOD_CATALOG = {
620
- evmGetAddress: { chain: "evm", allNetwork: true },
621
- evmSignTransaction: { chain: "evm", allNetwork: false },
622
- evmSignMessage: { chain: "evm", allNetwork: false },
623
- evmSignTypedData: { chain: "evm", allNetwork: false },
624
- btcGetAddress: { chain: "btc", allNetwork: true },
625
- btcGetPublicKey: { chain: "btc", allNetwork: true },
626
- btcSignTransaction: { chain: "btc", allNetwork: false },
627
- btcSignPsbt: { chain: "btc", allNetwork: false },
628
- btcSignMessage: { chain: "btc", allNetwork: false },
629
- btcGetMasterFingerprint: { chain: "btc", allNetwork: false },
630
- solGetAddress: { chain: "sol", allNetwork: true },
631
- solSignTransaction: { chain: "sol", allNetwork: false },
632
- solSignMessage: { chain: "sol", allNetwork: false },
633
- tronGetAddress: { chain: "tron", allNetwork: true },
634
- tronSignTransaction: { chain: "tron", allNetwork: false },
635
- tronSignMessage: { chain: "tron", allNetwork: false }
1148
+ evmGetAddress: { chain: "evm", allNetwork: true, replayAfterTransportFailure: "safe" },
1149
+ evmSignTransaction: {
1150
+ chain: "evm",
1151
+ allNetwork: false,
1152
+ replayAfterTransportFailure: "unsafe"
1153
+ },
1154
+ evmSignMessage: { chain: "evm", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1155
+ evmSignTypedData: { chain: "evm", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1156
+ btcGetAddress: { chain: "btc", allNetwork: true, replayAfterTransportFailure: "safe" },
1157
+ btcGetPublicKey: { chain: "btc", allNetwork: true, replayAfterTransportFailure: "safe" },
1158
+ btcSignTransaction: {
1159
+ chain: "btc",
1160
+ allNetwork: false,
1161
+ replayAfterTransportFailure: "unsafe"
1162
+ },
1163
+ btcSignPsbt: { chain: "btc", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1164
+ btcSignMessage: { chain: "btc", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1165
+ btcGetMasterFingerprint: {
1166
+ chain: "btc",
1167
+ allNetwork: false,
1168
+ replayAfterTransportFailure: "safe"
1169
+ },
1170
+ solGetAddress: { chain: "sol", allNetwork: true, replayAfterTransportFailure: "safe" },
1171
+ solSignTransaction: {
1172
+ chain: "sol",
1173
+ allNetwork: false,
1174
+ replayAfterTransportFailure: "unsafe"
1175
+ },
1176
+ solSignMessage: { chain: "sol", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1177
+ tronGetAddress: { chain: "tron", allNetwork: true, replayAfterTransportFailure: "safe" },
1178
+ tronSignTransaction: {
1179
+ chain: "tron",
1180
+ allNetwork: false,
1181
+ replayAfterTransportFailure: "unsafe"
1182
+ },
1183
+ tronSignMessage: { chain: "tron", allNetwork: false, replayAfterTransportFailure: "unsafe" },
1184
+ zcashGetFullViewingKey: {
1185
+ chain: "zcash",
1186
+ allNetwork: false,
1187
+ replayAfterTransportFailure: "safe"
1188
+ },
1189
+ zcashGetShieldedAddress: {
1190
+ chain: "zcash",
1191
+ allNetwork: false,
1192
+ replayAfterTransportFailure: "safe"
1193
+ }
636
1194
  };
637
1195
  var ALL_NETWORK_METHOD_NAMES = Object.entries(HARDWARE_METHOD_CATALOG).filter(([, metadata]) => metadata.allNetwork).map(([method]) => method);
638
1196
  var ALL_NETWORK_METHOD_SET = new Set(ALL_NETWORK_METHOD_NAMES);
639
1197
  function getHardwareMethodMetadata(method) {
640
1198
  return HARDWARE_METHOD_CATALOG[method];
641
1199
  }
1200
+ var SAFE_NON_CHAIN_METHODS = /* @__PURE__ */ new Set(["getFeatures", "authenticateDevice"]);
1201
+ function canReplayHardwareMethodAfterTransportFailure(method) {
1202
+ return getHardwareMethodMetadata(method)?.replayAfterTransportFailure === "safe" || SAFE_NON_CHAIN_METHODS.has(method);
1203
+ }
642
1204
  function isAllNetworkMethodName(method) {
643
1205
  return ALL_NETWORK_METHOD_SET.has(method);
644
1206
  }
@@ -698,6 +1260,19 @@ async function runAllNetworkGetAddress({
698
1260
  }
699
1261
  return success(responses);
700
1262
  }
1263
+ function isUserRefusal(code) {
1264
+ return code === 10005 /* UserAborted */ || code === 10001 /* UserRejected */;
1265
+ }
1266
+ function isConnectionLost(code) {
1267
+ const codes = [
1268
+ 10101 /* DeviceDisconnected */,
1269
+ 10003 /* OperationTimeout */,
1270
+ 10300 /* TransportError */,
1271
+ 10113 /* OperationEnded */,
1272
+ 10112 /* OperationNotFound */
1273
+ ];
1274
+ return code !== void 0 && codes.includes(code);
1275
+ }
701
1276
  function buildUnsupportedMethodResponse(item) {
702
1277
  return {
703
1278
  ...item,
@@ -731,8 +1306,11 @@ export {
731
1306
  DeviceJobQueue,
732
1307
  EConnectorInteraction,
733
1308
  HARDWARE_METHOD_CATALOG,
1309
+ HARDWARE_RUNTIME_ID_PREFIX,
734
1310
  HardwareErrorCode,
1311
+ OPERATION_DEFAULT_TTL_MS,
735
1312
  ORPHAN_ELIGIBLE_ERROR_CODES,
1313
+ OperationRegistry,
736
1314
  SDK,
737
1315
  TypedEventEmitter,
738
1316
  UI_EVENT,
@@ -745,23 +1323,43 @@ export {
745
1323
  UiRequestRegistry,
746
1324
  batchCall,
747
1325
  buildUnsupportedMethodResponse,
748
- bytesToHex2 as bytesToHex,
1326
+ bytesToHex3 as bytesToHex,
1327
+ canReplayHardwareMethodAfterTransportFailure,
749
1328
  compareSemver,
750
1329
  createBridgedConnector,
751
1330
  createCombinedConnector,
1331
+ createHardwareLinkId,
1332
+ createHardwareOperationId,
1333
+ createHardwareSearchTargetId,
752
1334
  createHwkError,
1335
+ defaultOriginForCode,
1336
+ defaultRecoveryForCode,
753
1337
  deriveDeviceFingerprint,
1338
+ deriveWalletId,
754
1339
  detectHardwareVendorFromDescriptor,
755
1340
  enrichErrorMessage,
756
1341
  ensure0x,
757
1342
  failure,
758
1343
  getAllNetworkMethodChain,
759
1344
  getHardwareMethodMetadata,
1345
+ hasHardwareRuntimeIdPrefix,
760
1346
  hexToBytes,
761
1347
  isAllNetworkMethodName,
1348
+ isConnectionLost,
1349
+ isHardwareOperationId,
1350
+ isHwkRecoveryHint,
762
1351
  isKnownNonTargetHardwareVendor,
1352
+ isUserRefusal,
1353
+ operationMayHaveCompletedParams,
763
1354
  padHex64,
1355
+ parseBip32MasterFingerprint,
1356
+ parseHardwareRuntimeId,
1357
+ prepareSolanaOffchainMessageV1,
764
1358
  rehydrateConnectorError,
1359
+ requestBleDeviceSelection,
1360
+ requestSaveDeviceBinding,
1361
+ resolveHardwareOperationTarget,
1362
+ resolveSearchTargetReusePolicy,
765
1363
  runAllNetworkGetAddress,
766
1364
  serializeConnectorError,
767
1365
  stripHex,