@onekeyfe/hwk-keystone-adapter 1.2.6-alpha.0 → 1.2.8-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -5,7 +5,12 @@ import bs58check from "bs58check";
5
5
  import * as bitcoin from "bitcoinjs-lib";
6
6
  import HDKey from "hdkey";
7
7
  import { parse as uuidParse, stringify as uuidStringify } from "uuid";
8
- import { parseWalletMasterFingerprint } from "@onekeyfe/hwk-adapter-core";
8
+ import {
9
+ HardwareErrorCode,
10
+ boundedCborFromHex,
11
+ createHwkError,
12
+ parseWalletMasterFingerprint
13
+ } from "@onekeyfe/hwk-adapter-core";
9
14
 
10
15
  // src/urEngine/TronSignRequest.ts
11
16
  import {
@@ -66,11 +71,12 @@ var TronSignRequest = class _TronSignRequest extends RegistryItem {
66
71
  static parsePath(path, xfp) {
67
72
  const segments = path.replace(/^[mM]\//, "").split("/");
68
73
  const components = segments.map((segment) => {
69
- const hardened = segment.endsWith("'");
70
- return new PathComponent({
71
- index: parseInt(hardened ? segment.slice(0, -1) : segment, 10),
72
- hardened
73
- });
74
+ const match = /^(\d+)('?)$/.exec(segment);
75
+ const index = match ? Number(match[1]) : NaN;
76
+ if (!match || index >= 2147483648) {
77
+ throw new Error(`Invalid TRON derivation path segment (${segment})`);
78
+ }
79
+ return new PathComponent({ index, hardened: match[2] === "'" });
74
80
  });
75
81
  return new CryptoKeypath(components, Buffer.from(xfp, "hex"));
76
82
  }
@@ -134,7 +140,7 @@ var DERIVATION_CURVE = {
134
140
  ed25519: Curve.ed25519
135
141
  };
136
142
  function toSdkUr(ur) {
137
- return new UR(Buffer.from(ur.urData, "hex"), ur.urType);
143
+ return new UR(boundedCborFromHex(ur.urData), ur.urType);
138
144
  }
139
145
  function fromSdkUr(ur) {
140
146
  return { urType: ur.type, urData: ur.cbor.toString("hex") };
@@ -172,8 +178,24 @@ function toParsedAccount(key) {
172
178
  name: key.name
173
179
  };
174
180
  }
181
+ var BIP32_HARDENED_OFFSET = 2147483648;
175
182
  function relativeHdPath(relativeDerivePath) {
176
- return `m/${relativeDerivePath.replace(/^m\//i, "")}`;
183
+ const segments = relativeDerivePath.replace(/^m\//i, "").split("/");
184
+ const valid = segments.every(
185
+ (segment) => /^\d+$/.test(segment) && Number(segment) < BIP32_HARDENED_OFFSET
186
+ );
187
+ if (!valid) {
188
+ throw createHwkError({
189
+ code: HardwareErrorCode.InvalidParams,
190
+ message: `Invalid change/index segments in derivation path (${relativeDerivePath})`
191
+ });
192
+ }
193
+ return `m/${segments.join("/")}`;
194
+ }
195
+ var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.]{1,20})?$/;
196
+ var DEVICE_TEXT = /^[^\p{Cc}\p{Cf}]{1,64}$/u;
197
+ function deviceText(value, pattern) {
198
+ return typeof value === "string" && pattern.test(value) ? value : void 0;
177
199
  }
178
200
  var KeystoneUrEngine = class {
179
201
  constructor(origin = "OneKey") {
@@ -184,9 +206,9 @@ var KeystoneUrEngine = class {
184
206
  const parsed = this.sdk.parseMultiAccounts(toSdkUr(ur));
185
207
  return {
186
208
  masterFingerprint: requireBip32MasterFingerprint(parsed.masterFingerprint),
187
- device: parsed.device,
188
- deviceId: parsed.deviceId,
189
- deviceVersion: parsed.deviceVersion,
209
+ device: deviceText(parsed.device, DEVICE_TEXT),
210
+ deviceId: deviceText(parsed.deviceId, DEVICE_TEXT),
211
+ deviceVersion: deviceText(parsed.deviceVersion, FIRMWARE_VERSION),
190
212
  accounts: parsed.keys.map(toParsedAccount)
191
213
  };
192
214
  }
@@ -248,10 +270,7 @@ var KeystoneUrEngine = class {
248
270
  return generateAddressFromXpub(xpub, relativeHdPath(relativeDerivePath));
249
271
  }
250
272
  // --- BTC (PSBT transaction signing + plain message signing) ---
251
- /**
252
- * `CryptoHDKey` always emits mainnet xpub version bytes (`0488B21E`), so `hdkey` parses it as is.
253
- * `p2tr` needs an ECC lib for BIP-341 tweaking, not wired here.
254
- */
273
+ /** `CryptoHDKey` always emits mainnet xpub version bytes (`0488B21E`), so `hdkey` parses it as is. */
255
274
  deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType) {
256
275
  const node = HDKey.fromExtendedKey(xpub).derive(relativeHdPath(relativeDerivePath));
257
276
  if (!node.publicKey) throw new Error("HDKey derivation did not produce a public key");
@@ -297,9 +316,27 @@ var KeystoneUrEngine = class {
297
316
  const ur = this.sdk.btc.generatePSBT(Buffer.from(unsignedPsbtHex, "hex"));
298
317
  return fromSdkUr(ur);
299
318
  }
300
- /** Returns the hex-encoded (possibly still-unsigned-in-part) PSBT the device replied with. */
301
- parseBtcPsbt(ur) {
302
- return this.sdk.btc.parsePSBT(toSdkUr(ur));
319
+ /**
320
+ * Returns the hex-encoded (possibly still-unsigned-in-part) PSBT the device replied with. A PSBT
321
+ * carries no request id, so the reply is bound to the request by its unsigned transaction, which
322
+ * signing never changes (BIP-174); a scan of another PSBT's signature is refused.
323
+ */
324
+ parseBtcPsbt(ur, requestPsbtHex) {
325
+ const signedPsbtHex = this.sdk.btc.parsePSBT(toSdkUr(ur));
326
+ let sameTransaction = false;
327
+ try {
328
+ const unsignedTx = (hex) => Buffer.from(bitcoin.Psbt.fromHex(hex).data.globalMap.unsignedTx.toBuffer());
329
+ sameTransaction = unsignedTx(signedPsbtHex).equals(unsignedTx(requestPsbtHex));
330
+ } catch {
331
+ sameTransaction = false;
332
+ }
333
+ if (!sameTransaction) {
334
+ throw createHwkError({
335
+ code: HardwareErrorCode.DeviceMismatch,
336
+ message: "Keystone returned a PSBT for another transaction than the one requested"
337
+ });
338
+ }
339
+ return signedPsbtHex;
303
340
  }
304
341
  buildBtcMessageSignRequest(params) {
305
342
  const ur = this.sdk.btc.generateSignRequest({
@@ -359,7 +396,7 @@ var KeystoneUrEngine = class {
359
396
  if (ur.urType !== "tron-signature") {
360
397
  throw new Error(`Expected a tron-signature UR, got ${ur.urType}`);
361
398
  }
362
- const signature = TronSignature.fromCBOR(Buffer.from(ur.urData, "hex"));
399
+ const signature = TronSignature.fromCBOR(boundedCborFromHex(ur.urData));
363
400
  const requestId = signature.getRequestId();
364
401
  return {
365
402
  requestId: requestId ? uuidStringify(requestId) : void 0,
@@ -400,7 +437,7 @@ import {
400
437
  CHAIN_FINGERPRINT_PATHS,
401
438
  DEVICE,
402
439
  DeviceJobQueue,
403
- HardwareErrorCode,
440
+ HardwareErrorCode as HardwareErrorCode2,
404
441
  MISSING_BIP32_MASTER_FINGERPRINT,
405
442
  OperationRegistry,
406
443
  SDK,
@@ -411,8 +448,9 @@ import {
411
448
  UI_REQUEST_TIMEOUT_TAG,
412
449
  UI_RESPONSE,
413
450
  UiRequestRegistry,
451
+ buildAllNetworkCancelledFailure,
414
452
  createHardwareSearchTargetId,
415
- createHwkError,
453
+ createHwkError as createHwkError2,
416
454
  deriveDeviceFingerprint,
417
455
  ensure0x,
418
456
  failure,
@@ -423,13 +461,13 @@ import {
423
461
  isHardwareOperationId as isHardwareOperationId2,
424
462
  isHwkRecoveryHint,
425
463
  isUserRefusal,
464
+ isWalletSafetyFailure,
426
465
  operationMayHaveCompletedParams,
427
466
  parseBip32MasterFingerprint,
428
467
  parseWalletMasterFingerprint as parseWalletMasterFingerprint3,
429
468
  rehydrateConnectorError,
430
469
  resolveHardwareOperationTarget as resolveGenericHardwareOperationTarget,
431
470
  runAllNetworkGetAddress,
432
- stripHex,
433
471
  success
434
472
  } from "@onekeyfe/hwk-adapter-core";
435
473
 
@@ -438,6 +476,14 @@ function normalizePath(path) {
438
476
  const trimmed = path.trim();
439
477
  return /^m\//i.test(trimmed) ? `m/${trimmed.slice(2)}` : `m/${trimmed}`;
440
478
  }
479
+ var BIP32_HARDENED_OFFSET2 = 2147483648;
480
+ function isBip32Path(path) {
481
+ const segments = normalizePath(path).slice(2).split("/");
482
+ return segments.every((segment) => {
483
+ const match = /^(\d+)'?$/.exec(segment);
484
+ return match !== null && Number(match[1]) < BIP32_HARDENED_OFFSET2;
485
+ });
486
+ }
441
487
  function splitAccountPath(path) {
442
488
  const normalized = normalizePath(path);
443
489
  const segments = normalized.slice(2).split("/");
@@ -548,11 +594,24 @@ function keystoneCancelQueueKeys(identifiers) {
548
594
  }
549
595
 
550
596
  // src/adapter/KeystoneAdapter.ts
597
+ function keystoneBtcParamsFailure(params) {
598
+ const { coin, addressIndex, change } = params;
599
+ if (coin !== void 0 && !["btc", "bitcoin"].includes(String(coin).toLowerCase())) {
600
+ return failure(
601
+ HardwareErrorCode2.ChainNotSupported,
602
+ `Keystone BTC supports Bitcoin mainnet only, not ${String(coin)}`
603
+ );
604
+ }
605
+ if (addressIndex !== void 0 || change !== void 0) {
606
+ return failure(
607
+ HardwareErrorCode2.InvalidParams,
608
+ "Keystone BTC takes the full address path; addressIndex and change are not supported"
609
+ );
610
+ }
611
+ return void 0;
612
+ }
551
613
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
552
614
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
553
- function resolveHardwareOperationTarget(positionalTargetId, operationId) {
554
- return resolveGenericHardwareOperationTarget(positionalTargetId, operationId, "keystone");
555
- }
556
615
  function keySchema(chain, path) {
557
616
  return { path, curve: chain === "sol" ? "ed25519" : "secp256k1" };
558
617
  }
@@ -561,21 +620,52 @@ function waitForKeystoneUsbReattachProbe() {
561
620
  setTimeout(resolve, KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS);
562
621
  });
563
622
  }
564
- function buildCancelledFailure(signal) {
565
- const reason = signal.reason;
566
- const code = typeof reason?.code === "number" ? reason.code : HardwareErrorCode.UserAborted;
567
- const message = typeof reason?.message === "string" ? reason.message : "";
568
- return failure(code, message || "All-network get-address cancelled");
569
- }
570
623
  var BIP44_COIN_TYPE_TO_CHAIN = {
571
624
  60: "evm",
572
625
  0: "btc",
573
626
  501: "sol",
574
627
  195: "tron"
575
628
  };
576
- function inferHwkChainFromPath(path) {
629
+ function hasChainCoinType(chain, path) {
577
630
  const match = normalizePath(path).match(/^m\/\d+'\/(\d+)'/);
578
- return match ? BIP44_COIN_TYPE_TO_CHAIN[Number(match[1])] : void 0;
631
+ return Boolean(match) && BIP44_COIN_TYPE_TO_CHAIN[Number(match?.[1])] === chain;
632
+ }
633
+ function exactHex(value) {
634
+ const hex = value.replace(/^0x/i, "");
635
+ return /^(?:[0-9a-f]{2})*$/i.test(hex) ? hex : void 0;
636
+ }
637
+ function invalidHexFailure(field) {
638
+ return failure(HardwareErrorCode2.InvalidParams, `${field} must be an even-length hex string`);
639
+ }
640
+ function requireExportedPath(parsed, path) {
641
+ const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
642
+ if (!account) {
643
+ throw createHwkError2({
644
+ code: HardwareErrorCode2.DeviceMismatch,
645
+ message: `Keystone did not return the requested derivation path (${path})`
646
+ });
647
+ }
648
+ return account;
649
+ }
650
+ function coinTypeFailure(chain, path) {
651
+ if (hasChainCoinType(chain, path)) return void 0;
652
+ return failure(
653
+ HardwareErrorCode2.InvalidParams,
654
+ `Keystone ${chain} needs a path with its own BIP44 coin type, not ${path}`
655
+ );
656
+ }
657
+ function btcAccountFailure(accountPath) {
658
+ if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
659
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
660
+ }
661
+ function missingParamFailure(method, param) {
662
+ return failure(HardwareErrorCode2.InvalidParams, `${method} requires ${param}`);
663
+ }
664
+ function messageToHex(message, hex) {
665
+ return hex ? exactHex(message) : Buffer.from(message, "utf8").toString("hex");
666
+ }
667
+ function evmMessageSignature(sig) {
668
+ return { signature: ensure0x(sig.r + sig.s + sig.v) };
579
669
  }
580
670
  var KeystoneAdapter = class _KeystoneAdapter {
581
671
  constructor(options) {
@@ -591,6 +681,15 @@ var KeystoneAdapter = class _KeystoneAdapter {
591
681
  const route = this._operationRoutes.get(operation.connectId);
592
682
  if (route?.operationId === operation.operationId) {
593
683
  this._operationRoutes.delete(operation.connectId);
684
+ if (route.connectionType === "qr") {
685
+ const ended = createHwkError2({
686
+ code: HardwareErrorCode2.OperationEnded,
687
+ message: "Keystone operation has ended",
688
+ params: { operationId: operation.operationId, reason }
689
+ });
690
+ this._jobQueue.cancelActiveAndPending(operation.operationId, ended);
691
+ this._uiRegistry.cancel(void 0, void 0, operation.operationId);
692
+ }
594
693
  }
595
694
  this.emitter.emit(SDK.OPERATION_ENDED, {
596
695
  type: SDK.OPERATION_ENDED,
@@ -631,18 +730,30 @@ var KeystoneAdapter = class _KeystoneAdapter {
631
730
  // All-network bundle, dispatched to the per-chain methods below.
632
731
  // ---------------------------------------------------------------------------
633
732
  this.allNetworkGetAddress = async (connectId, deviceId, params) => {
634
- const operationTarget = resolveHardwareOperationTarget(connectId, params.operationId);
733
+ const operationTarget = this._resolveOperationTarget(connectId, params.operationId);
635
734
  if (!operationTarget.success) return operationTarget;
636
735
  const effectiveConnectId = operationTarget.payload.targetId ?? "";
637
736
  const { operationId } = operationTarget.payload;
737
+ const namedWallets = new Set(
738
+ [deviceId, ...params.bundle.map((item) => item.deviceId)].filter(
739
+ (id) => typeof id === "string" && id.length > 0
740
+ )
741
+ );
742
+ if (namedWallets.size > 1) {
743
+ return failure(
744
+ HardwareErrorCode2.InvalidParams,
745
+ "Keystone all-network items name different wallets"
746
+ );
747
+ }
748
+ const [expectedDeviceId = ""] = namedWallets;
638
749
  let cancelScope;
639
750
  try {
640
- const prefetched = await this._prefetchAllNetworkAccounts(effectiveConnectId, deviceId, {
751
+ const prepared = await this._prepareAllNetworkBundle(effectiveConnectId, expectedDeviceId, {
641
752
  ...params,
642
753
  operationId
643
754
  });
644
- const { book } = prefetched;
645
- const itemDeviceId = deviceId || prefetched.masterFingerprint || "";
755
+ const { access } = prepared;
756
+ const itemDeviceId = expectedDeviceId || prepared.masterFingerprint || "";
646
757
  const scope = this._jobQueue.createCancelScope(
647
758
  keystoneQueueKey(effectiveConnectId, itemDeviceId)
648
759
  );
@@ -655,7 +766,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
655
766
  callItem: async ({ method, item, index }) => {
656
767
  if (scope.signal.aborted) {
657
768
  cancelledIndexes.add(index);
658
- return buildCancelledFailure(scope.signal);
769
+ return buildAllNetworkCancelledFailure(scope.signal);
659
770
  }
660
771
  const commonArgs = {
661
772
  path: item.path,
@@ -664,20 +775,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
664
775
  };
665
776
  switch (method) {
666
777
  case "evmGetAddress":
667
- return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
778
+ return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
668
779
  case "btcGetAddress":
669
- return this.btcGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
670
- case "btcGetPublicKey":
671
- return this.btcGetPublicKey(effectiveConnectId, itemDeviceId, commonArgs, book);
780
+ case "btcGetPublicKey": {
781
+ const btcArgs = {
782
+ ...commonArgs,
783
+ coin: item.coin ?? item.network
784
+ };
785
+ return method === "btcGetAddress" ? this.btcGetAddress(effectiveConnectId, itemDeviceId, btcArgs, access) : this.btcGetPublicKey(effectiveConnectId, itemDeviceId, btcArgs, access);
786
+ }
672
787
  case "solGetAddress":
673
- return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
788
+ return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
674
789
  case "tronGetAddress":
675
- return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
676
- default:
677
- return failure(
678
- HardwareErrorCode.MethodNotSupported,
679
- `Unsupported method: ${String(method)}`
680
- );
790
+ return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
681
791
  }
682
792
  },
683
793
  attachIdentity: (context) => {
@@ -696,11 +806,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
696
806
  }
697
807
  });
698
808
  },
699
- // Cancel, refusal or a lost session ends the batch; other per-item
700
- // failures carry on with the next chain.
809
+ // Cancel, refusal, a lost connection or a safety answer (another wallet, a locked
810
+ // device) ends the batch; other per-item failures carry on with the next chain.
701
811
  shouldAbortBundle: (response, { index }) => {
702
812
  const { code } = response.payload ?? {};
703
- return cancelledIndexes.has(index) || isUserRefusal(code) || isConnectionLost(code);
813
+ const usbSessionLost = access?.channel === "usb" && this._resolveTarget(effectiveConnectId, itemDeviceId).record?.usbSessionId !== access.usbSessionId;
814
+ return cancelledIndexes.has(index) || usbSessionLost || isWalletSafetyFailure(code) || isUserRefusal(code) || isConnectionLost(code);
704
815
  }
705
816
  });
706
817
  } catch (err) {
@@ -717,9 +828,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
717
828
  this._usbConnector?.on("device-disconnect", this._handleUsbDisconnect);
718
829
  this._usbConnector?.on("ui-event", this._handleUsbUiEvent);
719
830
  }
720
- // ---------------------------------------------------------------------------
721
- // Lifecycle / transport
722
- // ---------------------------------------------------------------------------
723
831
  get activeTransport() {
724
832
  if (this._devices.size === 0) return null;
725
833
  const hasUsbSession = Array.from(this._devices.values()).some((r) => r.usbSessionId);
@@ -749,9 +857,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
749
857
  this._devices.clear();
750
858
  this.emitter.removeAllListeners();
751
859
  }
752
- // ---------------------------------------------------------------------------
753
- // Device table
754
- // ---------------------------------------------------------------------------
755
860
  /**
756
861
  * Returns known wallets plus USB scan results; USB entries have no mfp until `connectDevice()`
757
862
  * claims them. Explicit QR discovery returns one virtual target.
@@ -824,11 +929,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
824
929
  }
825
930
  /** Best-effort disconnect; the session is retired either way so it cannot be selected again. */
826
931
  async _retireUsbSession(sessionId) {
827
- if (this._usbConnector) {
828
- try {
829
- await this._usbConnector.disconnect(sessionId);
830
- } catch {
831
- }
932
+ try {
933
+ await this._usbConnector?.disconnect(sessionId);
934
+ } catch {
832
935
  }
833
936
  this._handleUsbDisconnect({ connectId: sessionId });
834
937
  }
@@ -847,13 +950,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
847
950
  serialNumber: device.serialNumber
848
951
  }));
849
952
  }
850
- async listConnectionTargets(options) {
851
- const targets = await this.searchDeviceTargets(options);
852
- return targets.map(({ searchTargetId, ...target }) => ({
853
- ...target,
854
- targetId: searchTargetId
855
- }));
856
- }
857
953
  async connectDevice(searchTargetId) {
858
954
  const scope = this._jobQueue.createCancelScope(searchTargetId);
859
955
  try {
@@ -862,28 +958,22 @@ var KeystoneAdapter = class _KeystoneAdapter {
862
958
  const discoveredConnectionType = this._searchDeviceTargets.get(searchTargetId);
863
959
  if (discoveredConnectionType === "qr") {
864
960
  selectedConnectionType = "qr";
865
- const abortColdStart = () => this._jobQueue.cancelActiveAndPending(
866
- KEYSTONE_COLD_START_JOB_LABEL,
867
- scope.signal.reason
961
+ connected = await _KeystoneAdapter._untilAborted(
962
+ scope.signal,
963
+ this._importFromQr({}, searchTargetId)
868
964
  );
869
- scope.signal.addEventListener("abort", abortColdStart, { once: true });
870
- try {
871
- connected = await this.importFromQr();
872
- } finally {
873
- scope.signal.removeEventListener("abort", abortColdStart);
874
- }
875
965
  } else if (discoveredConnectionType === "usb") {
876
966
  selectedConnectionType = "usb";
877
967
  if (!this._usbConnector) {
878
968
  return failure(
879
- HardwareErrorCode.TransportNotAvailable,
969
+ HardwareErrorCode2.TransportNotAvailable,
880
970
  "No USB connector configured for this Keystone adapter"
881
971
  );
882
972
  }
883
- connected = await this._connectUsb({}, searchTargetId, scope.signal);
973
+ connected = await this._connectUsb(this._usbConnector, {}, searchTargetId, scope.signal);
884
974
  } else if (hasHardwareRuntimeIdPrefix(searchTargetId)) {
885
975
  return failure(
886
- HardwareErrorCode.DeviceNotFound,
976
+ HardwareErrorCode2.DeviceNotFound,
887
977
  "Keystone search target has expired; search for devices again",
888
978
  void 0,
889
979
  void 0,
@@ -896,12 +986,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
896
986
  connected = success(toDeviceInfo(target.record));
897
987
  } else if (!this._usbConnector) {
898
988
  return failure(
899
- HardwareErrorCode.DeviceNotFound,
989
+ HardwareErrorCode2.DeviceNotFound,
900
990
  `Unknown Keystone device search target: ${searchTargetId}`
901
991
  );
902
992
  } else {
903
993
  selectedConnectionType = "usb";
904
- connected = await this._connectUsb(target, void 0, scope.signal);
994
+ connected = await this._connectUsb(this._usbConnector, target, void 0, scope.signal);
905
995
  }
906
996
  }
907
997
  _KeystoneAdapter._throwIfAborted(scope.signal);
@@ -960,10 +1050,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
960
1050
  const { record } = this._resolveTarget(connectId, deviceId);
961
1051
  if (!record) {
962
1052
  return Promise.resolve(
963
- failure(
964
- HardwareErrorCode.DeviceNotFound,
965
- `Unknown Keystone device: ${connectId || deviceId}`
966
- )
1053
+ failure(HardwareErrorCode2.DeviceNotFound, "Unknown Keystone device")
967
1054
  );
968
1055
  }
969
1056
  return Promise.resolve(success(toDeviceInfo(record)));
@@ -980,8 +1067,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
980
1067
  return;
981
1068
  }
982
1069
  }
983
- const reason = createHwkError({
984
- code: HardwareErrorCode.UserAborted,
1070
+ const reason = createHwkError2({
1071
+ code: HardwareErrorCode2.UserAborted,
985
1072
  message: "User aborted operation"
986
1073
  });
987
1074
  if (connectId) {
@@ -1002,13 +1089,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
1002
1089
  this._uiRegistry.cancel();
1003
1090
  }
1004
1091
  }
1092
+ /**
1093
+ * Derived from the wallet's master fingerprint, which the caller already holds as deviceId; the
1094
+ * device is never asked. It names the wallet but cannot check which device is attached.
1095
+ */
1005
1096
  getChainFingerprint(connectId, deviceId, chain) {
1006
1097
  try {
1007
1098
  const target = this._resolveTarget(connectId, deviceId);
1008
1099
  const masterFingerprint = target.expectedMasterFingerprint;
1009
1100
  if (!masterFingerprint) {
1010
1101
  return Promise.resolve(
1011
- failure(HardwareErrorCode.DeviceNotFound, "Unknown Keystone wallet identity")
1102
+ failure(HardwareErrorCode2.DeviceNotFound, "Unknown Keystone wallet identity")
1012
1103
  );
1013
1104
  }
1014
1105
  return Promise.resolve(
@@ -1035,18 +1126,21 @@ var KeystoneAdapter = class _KeystoneAdapter {
1035
1126
  // Explicit account import: call before signing to avoid a cold sync per call.
1036
1127
  // ---------------------------------------------------------------------------
1037
1128
  async importFromQr(options = {}) {
1129
+ return this._importFromQr(options, KEYSTONE_COLD_START_JOB_LABEL);
1130
+ }
1131
+ async _importFromQr(options, jobKey) {
1038
1132
  try {
1039
- return await this._jobQueue.enqueue(KEYSTONE_COLD_START_JOB_LABEL, async (signal) => {
1133
+ return await this._jobQueue.enqueue(jobKey, async (signal) => {
1040
1134
  const displayDevice = placeholderDeviceInfo();
1041
1135
  let responseUr;
1042
1136
  if (options.mode === "scan") {
1043
- responseUr = await this._requestQrScanAndAwaitResponse(displayDevice, signal);
1137
+ responseUr = await this._requestQrAndAwaitResponse(displayDevice, void 0, signal);
1044
1138
  } else {
1045
1139
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1046
1140
  schemas: [keySchema("evm", KEYSTONE_COLD_START_PATH)],
1047
1141
  origin: this._origin
1048
1142
  });
1049
- responseUr = await this._requestQrDisplayAndAwaitResponse(
1143
+ responseUr = await this._requestQrAndAwaitResponse(
1050
1144
  displayDevice,
1051
1145
  { ...requestUr, animated: false },
1052
1146
  signal
@@ -1054,6 +1148,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1054
1148
  }
1055
1149
  _KeystoneAdapter._throwIfAborted(signal);
1056
1150
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1151
+ if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1057
1152
  const record = this._upsertDeviceRecord(parsed);
1058
1153
  return success(toDeviceInfo(record));
1059
1154
  });
@@ -1061,165 +1156,109 @@ var KeystoneAdapter = class _KeystoneAdapter {
1061
1156
  return this._errorToFailure(err);
1062
1157
  }
1063
1158
  }
1064
- // ---------------------------------------------------------------------------
1065
- // EVM
1066
- // ---------------------------------------------------------------------------
1067
- async evmGetAddress(connectIdArg, deviceIdArg, params, book) {
1068
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1069
- if (!operationTarget.success) return operationTarget;
1070
- const connectId = operationTarget.payload.targetId;
1071
- const deviceId = deviceIdArg ?? void 0;
1072
- if (!params) return failure(HardwareErrorCode.InvalidParams, "evmGetAddress requires params");
1073
- if (!params.path)
1074
- return failure(HardwareErrorCode.InvalidParams, "evmGetAddress requires params.path");
1075
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1076
- if (!relativeDerivePath) {
1077
- return failure(
1078
- HardwareErrorCode.InvalidParams,
1079
- "evmGetAddress requires a full leaf path, e.g. m/44'/60'/0'/0/0"
1080
- );
1081
- }
1082
- return this._runJob(connectId, deviceId, async (signal) => {
1083
- const xpub = await this._fetchAccountXpub(
1084
- connectId,
1085
- deviceId,
1086
- "evm",
1087
- accountPath,
1088
- signal,
1089
- book
1090
- );
1091
- const address = this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath);
1092
- return success({ address, path: normalizePath(params.path) });
1093
- });
1159
+ async evmGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1160
+ const call = this._beginCall("evmGetAddress", connectIdArg, deviceIdArg, paramsArg);
1161
+ if (!call.success) return call;
1162
+ const { params } = call.payload;
1163
+ if (!params.path) return missingParamFailure("evmGetAddress", "params.path");
1164
+ const evmCoinTypeFailure = coinTypeFailure("evm", params.path);
1165
+ if (evmCoinTypeFailure) return evmCoinTypeFailure;
1166
+ return this._addressFromAccountXpub(
1167
+ "evmGetAddress",
1168
+ "evm",
1169
+ call.payload,
1170
+ params.path,
1171
+ "m/44'/60'/0'/0/0",
1172
+ bundle,
1173
+ (xpub, relativeDerivePath) => this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath)
1174
+ );
1094
1175
  }
1095
- async evmSignTransaction(connectIdArg, deviceIdArg, params) {
1096
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1097
- if (!operationTarget.success) return operationTarget;
1098
- const connectId = operationTarget.payload.targetId;
1099
- const deviceId = deviceIdArg ?? void 0;
1100
- if (!params)
1101
- return failure(HardwareErrorCode.InvalidParams, "evmSignTransaction requires params");
1102
- if (!params.path) {
1103
- return failure(HardwareErrorCode.InvalidParams, "evmSignTransaction requires params.path");
1104
- }
1176
+ async evmSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1177
+ const call = this._beginCall("evmSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1178
+ if (!call.success) return call;
1179
+ const { params } = call.payload;
1180
+ if (!params.path) return missingParamFailure("evmSignTransaction", "params.path");
1105
1181
  if (!("serializedTx" in params) || typeof params.serializedTx !== "string" || !params.serializedTx) {
1106
1182
  return failure(
1107
- HardwareErrorCode.MethodNotSupported,
1183
+ HardwareErrorCode2.MethodNotSupported,
1108
1184
  "Keystone only signs a fully RLP-serialized transaction (params.serializedTx) \u2014 structured-field signing is not supported"
1109
1185
  );
1110
1186
  }
1111
- const rawTxHex = stripHex(params.serializedTx);
1112
- const path = normalizePath(params.path);
1187
+ const rawTxHex = exactHex(params.serializedTx);
1188
+ if (rawTxHex === void 0) return invalidHexFailure("serializedTx");
1113
1189
  const dataType = parseInt(rawTxHex.slice(0, 2), 16) < 192 ? "typedTransaction" : "transaction";
1114
- return this._signWithWallet({
1115
- connectId,
1116
- deviceId,
1117
- chain: "evm",
1118
- operationName: "evmSignTransaction",
1119
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1120
- requestId,
1121
- unsignedTxHex: rawTxHex,
1122
- dataType,
1123
- path,
1124
- xfp,
1125
- chainId: params.chainId,
1126
- origin: this._origin
1127
- }),
1128
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1129
- toPayload: (sig) => ({
1130
- v: ensure0x(sig.v),
1131
- r: ensure0x(sig.r),
1132
- s: ensure0x(sig.s)
1133
- })
1134
- });
1190
+ return this._evmSign(
1191
+ "evmSignTransaction",
1192
+ call.payload,
1193
+ params.path,
1194
+ params.chainId,
1195
+ rawTxHex,
1196
+ dataType,
1197
+ (sig) => ({ v: ensure0x(sig.v), r: ensure0x(sig.r), s: ensure0x(sig.s) })
1198
+ );
1135
1199
  }
1136
- async evmSignMessage(connectIdArg, deviceIdArg, params) {
1137
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1138
- if (!operationTarget.success) return operationTarget;
1139
- const connectId = operationTarget.payload.targetId;
1140
- const deviceId = deviceIdArg ?? void 0;
1141
- if (!params) return failure(HardwareErrorCode.InvalidParams, "evmSignMessage requires params");
1200
+ async evmSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1201
+ const call = this._beginCall("evmSignMessage", connectIdArg, deviceIdArg, paramsArg);
1202
+ if (!call.success) return call;
1203
+ const { params } = call.payload;
1142
1204
  if (!params.path || params.message === void 0) {
1143
- return failure(
1144
- HardwareErrorCode.InvalidParams,
1145
- "evmSignMessage requires params.path and params.message"
1146
- );
1147
- }
1148
- const messageHex = params.hex ? stripHex(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1149
- const path = normalizePath(params.path);
1150
- return this._signWithWallet({
1151
- connectId,
1152
- deviceId,
1153
- chain: "evm",
1154
- operationName: "evmSignMessage",
1155
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1156
- requestId,
1157
- unsignedTxHex: messageHex,
1158
- dataType: "personalMessage",
1159
- path,
1160
- xfp,
1161
- chainId: params.chainId,
1162
- origin: this._origin
1163
- }),
1164
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1165
- toPayload: (sig) => ({ signature: ensure0x(sig.r + sig.s + sig.v) })
1166
- });
1205
+ return missingParamFailure("evmSignMessage", "params.path and params.message");
1206
+ }
1207
+ const messageHex = messageToHex(params.message, params.hex);
1208
+ if (messageHex === void 0) return invalidHexFailure("message");
1209
+ return this._evmSign(
1210
+ "evmSignMessage",
1211
+ call.payload,
1212
+ params.path,
1213
+ params.chainId,
1214
+ messageHex,
1215
+ "personalMessage",
1216
+ evmMessageSignature
1217
+ );
1167
1218
  }
1168
- async evmSignTypedData(connectIdArg, deviceIdArg, params) {
1169
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1170
- if (!operationTarget.success) return operationTarget;
1171
- const connectId = operationTarget.payload.targetId;
1172
- const deviceId = deviceIdArg ?? void 0;
1173
- if (!params)
1174
- return failure(HardwareErrorCode.InvalidParams, "evmSignTypedData requires params");
1175
- if (!params.path) {
1176
- return failure(HardwareErrorCode.InvalidParams, "evmSignTypedData requires params.path");
1177
- }
1219
+ async evmSignTypedData(connectIdArg, deviceIdArg, paramsArg) {
1220
+ const call = this._beginCall("evmSignTypedData", connectIdArg, deviceIdArg, paramsArg);
1221
+ if (!call.success) return call;
1222
+ const { params } = call.payload;
1223
+ if (!params.path) return missingParamFailure("evmSignTypedData", "params.path");
1178
1224
  if (params.mode === "hash") {
1179
1225
  return failure(
1180
- HardwareErrorCode.MethodNotSupported,
1226
+ HardwareErrorCode2.MethodNotSupported,
1181
1227
  "Keystone always displays the full EIP-712 payload for on-device review \u2014 pre-hashed signing is not supported"
1182
1228
  );
1183
1229
  }
1184
- const signDataHex = Buffer.from(
1185
- params.dataJson ?? JSON.stringify(params.data),
1186
- "utf8"
1187
- ).toString("hex");
1188
- const path = normalizePath(params.path);
1189
- return this._signWithWallet({
1190
- connectId,
1191
- deviceId,
1192
- chain: "evm",
1193
- operationName: "evmSignTypedData",
1194
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1195
- requestId,
1196
- unsignedTxHex: signDataHex,
1197
- dataType: "typedData",
1198
- path,
1199
- xfp,
1200
- chainId: params.chainId,
1201
- origin: this._origin
1202
- }),
1203
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1204
- toPayload: (sig) => ({ signature: ensure0x(sig.r + sig.s + sig.v) })
1205
- });
1230
+ if (typeof params.dataJson !== "string" || !params.dataJson) {
1231
+ return failure(
1232
+ HardwareErrorCode2.InvalidParams,
1233
+ "Keystone evmSignTypedData requires params.dataJson, the original typed-data JSON text"
1234
+ );
1235
+ }
1236
+ const signDataHex = Buffer.from(params.dataJson, "utf8").toString("hex");
1237
+ return this._evmSign(
1238
+ "evmSignTypedData",
1239
+ call.payload,
1240
+ params.path,
1241
+ params.chainId,
1242
+ signDataHex,
1243
+ "typedData",
1244
+ evmMessageSignature
1245
+ );
1206
1246
  }
1207
1247
  // ---------------------------------------------------------------------------
1208
1248
  // BTC: 44'/49'/84' addresses derive offline from the account xpub; P2TR addresses
1209
1249
  // and structured-field tx signing are unsupported (the host builds a PSBT instead).
1210
1250
  // ---------------------------------------------------------------------------
1211
- async btcGetAddress(connectIdArg, deviceIdArg, params, book) {
1212
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1213
- if (!operationTarget.success) return operationTarget;
1214
- const connectId = operationTarget.payload.targetId;
1215
- const deviceId = deviceIdArg ?? void 0;
1216
- if (!params) return failure(HardwareErrorCode.InvalidParams, "btcGetAddress requires params");
1217
- if (!params.path)
1218
- return failure(HardwareErrorCode.InvalidParams, "btcGetAddress requires params.path");
1251
+ async btcGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1252
+ const call = this._beginCall("btcGetAddress", connectIdArg, deviceIdArg, paramsArg);
1253
+ if (!call.success) return call;
1254
+ const { params } = call.payload;
1255
+ if (!params.path) return missingParamFailure("btcGetAddress", "params.path");
1256
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1257
+ if (btcParamsFailure) return btcParamsFailure;
1219
1258
  const scriptType = btcScriptTypeFromPath(params.path);
1220
1259
  if (!scriptType) {
1221
1260
  return failure(
1222
- HardwareErrorCode.InvalidParams,
1261
+ HardwareErrorCode2.InvalidParams,
1223
1262
  "btcGetAddress requires a path whose purpose is 44'/49'/84'/86' (P2PKH/P2SH-P2WPKH/P2WPKH/P2TR)"
1224
1263
  );
1225
1264
  }
@@ -1229,52 +1268,36 @@ var KeystoneAdapter = class _KeystoneAdapter {
1229
1268
  "P2TR (purpose 86') needs an elliptic-curve library for BIP-341 tweaking, not yet wired in \u2014 44'/49'/84' work"
1230
1269
  );
1231
1270
  }
1232
- const normalizedPath = normalizePath(params.path);
1233
- const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1234
- if (!relativeDerivePath) {
1235
- return failure(
1236
- HardwareErrorCode.InvalidParams,
1237
- "btcGetAddress requires a full leaf path, e.g. m/84'/0'/0'/0/0"
1238
- );
1239
- }
1240
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1241
- return failure(HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1242
- }
1243
- return this._runJob(connectId, deviceId, async (signal) => {
1244
- const xpub = await this._fetchAccountXpub(
1245
- connectId,
1246
- deviceId,
1247
- "btc",
1248
- accountPath,
1249
- signal,
1250
- book
1251
- );
1252
- const address = this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType);
1253
- return success({ address, path: normalizedPath });
1254
- });
1271
+ return this._addressFromAccountXpub(
1272
+ "btcGetAddress",
1273
+ "btc",
1274
+ call.payload,
1275
+ params.path,
1276
+ "m/84'/0'/0'/0/0",
1277
+ bundle,
1278
+ (xpub, relativeDerivePath) => this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType)
1279
+ );
1255
1280
  }
1256
1281
  /**
1257
1282
  * `params.path` must be an account path (`m/84'/0'/0'`), the level Keystone syncs. An xpub is
1258
1283
  * script-type agnostic, so `86'` works here even though `btcGetAddress` rejects it.
1259
1284
  */
1260
- async btcGetPublicKey(connectIdArg, deviceIdArg, params, book) {
1261
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1262
- if (!operationTarget.success) return operationTarget;
1263
- const connectId = operationTarget.payload.targetId;
1264
- const deviceId = deviceIdArg ?? void 0;
1265
- if (!params) return failure(HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params");
1266
- if (!params.path)
1267
- return failure(HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params.path");
1285
+ async btcGetPublicKey(connectIdArg, deviceIdArg, paramsArg, bundle) {
1286
+ const call = this._beginCall("btcGetPublicKey", connectIdArg, deviceIdArg, paramsArg);
1287
+ if (!call.success) return call;
1288
+ const { connectId, deviceId, params } = call.payload;
1289
+ if (!params.path) return missingParamFailure("btcGetPublicKey", "params.path");
1290
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1291
+ if (btcParamsFailure) return btcParamsFailure;
1268
1292
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1269
1293
  if (relativeDerivePath) {
1270
1294
  return failure(
1271
- HardwareErrorCode.InvalidParams,
1295
+ HardwareErrorCode2.InvalidParams,
1272
1296
  "btcGetPublicKey requires an account path, e.g. m/84'/0'/0' (not a leaf path)"
1273
1297
  );
1274
1298
  }
1275
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1276
- return failure(HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1277
- }
1299
+ const accountFailure = btcAccountFailure(accountPath);
1300
+ if (accountFailure) return accountFailure;
1278
1301
  return this._runJob(connectId, deviceId, async (signal) => {
1279
1302
  const xpub = await this._fetchAccountXpub(
1280
1303
  connectId,
@@ -1282,7 +1305,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1282
1305
  "btc",
1283
1306
  accountPath,
1284
1307
  signal,
1285
- book
1308
+ bundle
1286
1309
  );
1287
1310
  const meta = this.urEngine.parseXpubMeta(xpub);
1288
1311
  return success({
@@ -1291,7 +1314,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1291
1314
  chainCode: meta.chainCode,
1292
1315
  depth: meta.depth,
1293
1316
  fingerprint: meta.parentFingerprint,
1294
- path: normalizePath(accountPath)
1317
+ path: normalizePath(accountPath),
1318
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1295
1319
  });
1296
1320
  });
1297
1321
  }
@@ -1301,23 +1325,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1301
1325
  "use btcSignPsbt \u2014 structured input/output signing needs host-side PSBT construction, not yet wired in"
1302
1326
  );
1303
1327
  }
1304
- async btcSignPsbt(connectIdArg, deviceIdArg, params) {
1305
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1306
- if (!operationTarget.success) return operationTarget;
1307
- const connectId = operationTarget.payload.targetId;
1308
- const deviceId = deviceIdArg ?? void 0;
1309
- if (!params) return failure(HardwareErrorCode.InvalidParams, "btcSignPsbt requires params");
1310
- if (!params.psbt)
1311
- return failure(HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.psbt");
1312
- if (!params.path)
1313
- return failure(HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.path");
1314
- if (!isKeystoneSignableBtcAccountPath(splitAccountPath(params.path).accountPath)) {
1315
- return failure(HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1316
- }
1328
+ async btcSignPsbt(connectIdArg, deviceIdArg, paramsArg) {
1329
+ const call = this._beginCall("btcSignPsbt", connectIdArg, deviceIdArg, paramsArg);
1330
+ if (!call.success) return call;
1331
+ const { connectId, deviceId, params } = call.payload;
1332
+ if (!params.psbt) return missingParamFailure("btcSignPsbt", "params.psbt");
1333
+ if (!params.path) return missingParamFailure("btcSignPsbt", "params.path");
1334
+ const accountFailure = btcAccountFailure(splitAccountPath(params.path).accountPath);
1335
+ if (accountFailure) return accountFailure;
1336
+ const requestPsbtHex = exactHex(params.psbt);
1337
+ if (requestPsbtHex === void 0) return invalidHexFailure("psbt");
1317
1338
  return this._runJob(connectId, deviceId, async (signal) => {
1318
1339
  const { record } = await this._ensureWalletKnown(connectId, deviceId, "btc", signal);
1319
1340
  _KeystoneAdapter._throwIfAborted(signal);
1320
- const requestUr = this.urEngine.buildBtcPsbtRequest(stripHex(params.psbt));
1341
+ const requestUr = this.urEngine.buildBtcPsbtRequest(requestPsbtHex);
1321
1342
  const responseUr = await this._resolveUr(
1322
1343
  record,
1323
1344
  requestUr,
@@ -1327,30 +1348,26 @@ var KeystoneAdapter = class _KeystoneAdapter {
1327
1348
  "btcSignPsbt"
1328
1349
  );
1329
1350
  _KeystoneAdapter._throwIfAborted(signal);
1330
- const signedPsbt = this.urEngine.parseBtcPsbt(responseUr);
1351
+ const signedPsbt = this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex);
1331
1352
  return success({ signedPsbt });
1332
1353
  });
1333
1354
  }
1334
- async btcSignMessage(connectIdArg, deviceIdArg, params) {
1335
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1336
- if (!operationTarget.success) return operationTarget;
1337
- const connectId = operationTarget.payload.targetId;
1338
- const deviceId = deviceIdArg ?? void 0;
1339
- if (!params) return failure(HardwareErrorCode.InvalidParams, "btcSignMessage requires params");
1355
+ async btcSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1356
+ const call = this._beginCall("btcSignMessage", connectIdArg, deviceIdArg, paramsArg);
1357
+ if (!call.success) return call;
1358
+ const { connectId, deviceId, params } = call.payload;
1340
1359
  if (!params.path || params.message === void 0) {
1341
- return failure(
1342
- HardwareErrorCode.InvalidParams,
1343
- "btcSignMessage requires params.path and params.message"
1344
- );
1360
+ return missingParamFailure("btcSignMessage", "params.path and params.message");
1345
1361
  }
1346
- const messageHex = params.hex ? stripHex(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1362
+ const messageHex = messageToHex(params.message, params.hex);
1363
+ if (messageHex === void 0) return invalidHexFailure("message");
1347
1364
  const path = normalizePath(params.path);
1348
- if (!isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1349
- return failure(HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1350
- }
1365
+ const accountFailure = btcAccountFailure(splitAccountPath(path).accountPath);
1366
+ if (accountFailure) return accountFailure;
1351
1367
  return this._signWithWallet({
1352
1368
  connectId,
1353
1369
  deviceId,
1370
+ path,
1354
1371
  chain: "btc",
1355
1372
  operationName: "btcSignMessage",
1356
1373
  buildRequest: (requestId, xfp) => this.urEngine.buildBtcMessageSignRequest({
@@ -1363,8 +1380,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1363
1380
  toPayload: (sig) => ({ signature: sig.signature })
1364
1381
  });
1365
1382
  }
1383
+ /**
1384
+ * Returns the known master fingerprint for the named wallet without asking the device (a QR
1385
+ * round trip only to repeat it would cost a scan). Use it to name the wallet, for example as a
1386
+ * PSBT xfp, which the device itself checks when signing; it cannot check the attached device.
1387
+ */
1366
1388
  async btcGetMasterFingerprint(connectIdArg, deviceIdArg, paramsArg) {
1367
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, paramsArg?.operationId);
1389
+ const operationTarget = this._resolveOperationTarget(connectIdArg, paramsArg?.operationId);
1368
1390
  if (!operationTarget.success) return operationTarget;
1369
1391
  const connectId = operationTarget.payload.targetId;
1370
1392
  const deviceId = deviceIdArg ?? void 0;
@@ -1373,193 +1395,242 @@ var KeystoneAdapter = class _KeystoneAdapter {
1373
1395
  return success({ masterFingerprint: record.masterFingerprint });
1374
1396
  });
1375
1397
  }
1376
- // ---------------------------------------------------------------------------
1377
- // SOL
1378
- // ---------------------------------------------------------------------------
1379
- async solGetAddress(connectIdArg, deviceIdArg, params, book) {
1380
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1381
- if (!operationTarget.success) return operationTarget;
1382
- const connectId = operationTarget.payload.targetId;
1383
- const deviceId = deviceIdArg ?? void 0;
1384
- if (!params) return failure(HardwareErrorCode.InvalidParams, "solGetAddress requires params");
1385
- if (!params.path)
1386
- return failure(HardwareErrorCode.InvalidParams, "solGetAddress requires params.path");
1398
+ async solGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1399
+ const call = this._beginCall("solGetAddress", connectIdArg, deviceIdArg, paramsArg);
1400
+ if (!call.success) return call;
1401
+ const { connectId, deviceId, params } = call.payload;
1402
+ if (!params.path) return missingParamFailure("solGetAddress", "params.path");
1403
+ const solCoinTypeFailure = coinTypeFailure("sol", params.path);
1404
+ if (solCoinTypeFailure) return solCoinTypeFailure;
1387
1405
  const path = normalizePath(params.path);
1406
+ if (!/^m(\/\d+')+$/.test(path)) {
1407
+ return failure(
1408
+ HardwareErrorCode2.InvalidParams,
1409
+ "solGetAddress requires a fully hardened path, e.g. m/44'/501'/0'/0'"
1410
+ );
1411
+ }
1388
1412
  return this._runJob(connectId, deviceId, async (signal) => {
1389
- const { account } = await this._fetchAccount(connectId, deviceId, "sol", path, signal, book);
1413
+ const { account } = await this._fetchAccount(
1414
+ connectId,
1415
+ deviceId,
1416
+ "sol",
1417
+ path,
1418
+ signal,
1419
+ bundle
1420
+ );
1390
1421
  _KeystoneAdapter._throwIfAborted(signal);
1422
+ if (!/^[0-9a-f]{64}$/i.test(account.publicKey)) {
1423
+ throw createHwkError2({
1424
+ code: HardwareErrorCode2.DeviceMismatch,
1425
+ message: "Keystone returned a Solana key that is not a 32-byte Ed25519 public key"
1426
+ });
1427
+ }
1391
1428
  const address = bs58.encode(Buffer.from(account.publicKey, "hex"));
1392
- return success({ address, path });
1429
+ return success({
1430
+ address,
1431
+ path,
1432
+ accountKey: { path, publicKey: account.publicKey }
1433
+ });
1393
1434
  });
1394
1435
  }
1395
- async solSignTransaction(connectIdArg, deviceIdArg, params) {
1396
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1397
- if (!operationTarget.success) return operationTarget;
1398
- const connectId = operationTarget.payload.targetId;
1399
- const deviceId = deviceIdArg ?? void 0;
1400
- if (!params)
1401
- return failure(HardwareErrorCode.InvalidParams, "solSignTransaction requires params");
1436
+ async solSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1437
+ const call = this._beginCall("solSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1438
+ if (!call.success) return call;
1439
+ const { params } = call.payload;
1402
1440
  if (!params.path || !params.serializedTx) {
1403
- return failure(
1404
- HardwareErrorCode.InvalidParams,
1405
- "solSignTransaction requires params.path and params.serializedTx"
1406
- );
1407
- }
1408
- const path = normalizePath(params.path);
1409
- return this._signWithWallet({
1410
- connectId,
1411
- deviceId,
1412
- chain: "sol",
1413
- operationName: "solSignTransaction",
1414
- buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1415
- requestId,
1416
- unsignedPayloadHex: stripHex(params.serializedTx),
1417
- dataType: "transaction",
1418
- path,
1419
- xfp,
1420
- origin: this._origin
1421
- }),
1422
- parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1423
- toPayload: (sig) => ({ signature: sig.signature })
1424
- });
1441
+ return missingParamFailure("solSignTransaction", "params.path and params.serializedTx");
1442
+ }
1443
+ const unsignedPayloadHex = exactHex(params.serializedTx);
1444
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("serializedTx");
1445
+ return this._solSign(
1446
+ "solSignTransaction",
1447
+ call.payload,
1448
+ params.path,
1449
+ unsignedPayloadHex,
1450
+ "transaction"
1451
+ );
1425
1452
  }
1426
- async solSignMessage(connectIdArg, deviceIdArg, params) {
1427
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1428
- if (!operationTarget.success) return operationTarget;
1429
- const connectId = operationTarget.payload.targetId;
1430
- const deviceId = deviceIdArg ?? void 0;
1431
- if (!params) return failure(HardwareErrorCode.InvalidParams, "solSignMessage requires params");
1453
+ async solSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1454
+ const call = this._beginCall("solSignMessage", connectIdArg, deviceIdArg, paramsArg);
1455
+ if (!call.success) return call;
1456
+ const { params } = call.payload;
1432
1457
  if (!params.path || !params.message) {
1458
+ return missingParamFailure("solSignMessage", "params.path and params.message");
1459
+ }
1460
+ if (params.messageVersion !== void 0) {
1433
1461
  return failure(
1434
- HardwareErrorCode.InvalidParams,
1435
- "solSignMessage requires params.path and params.message"
1462
+ HardwareErrorCode2.MethodNotSupported,
1463
+ "Keystone signs Solana messages as raw bytes only; off-chain message format is not supported"
1436
1464
  );
1437
1465
  }
1438
- const path = normalizePath(params.path);
1439
- return this._signWithWallet({
1440
- connectId,
1441
- deviceId,
1442
- chain: "sol",
1443
- operationName: "solSignMessage",
1444
- buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1445
- requestId,
1446
- unsignedPayloadHex: stripHex(params.message),
1447
- dataType: "message",
1448
- path,
1449
- xfp,
1450
- origin: this._origin
1451
- }),
1452
- parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1453
- toPayload: (sig) => ({ signature: sig.signature })
1454
- });
1466
+ const unsignedPayloadHex = exactHex(params.message);
1467
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("message");
1468
+ return this._solSign(
1469
+ "solSignMessage",
1470
+ call.payload,
1471
+ params.path,
1472
+ unsignedPayloadHex,
1473
+ "message"
1474
+ );
1455
1475
  }
1456
1476
  // ---------------------------------------------------------------------------
1457
1477
  // TRON: keystone-sdk-rust layout (tags 5201/5202, firmware >= 2.5.0), not sdk.tron's
1458
1478
  // protobuf module; OneKey Pro's encoding under the same tag is rejected by the firmware.
1459
1479
  // ---------------------------------------------------------------------------
1460
- async tronGetAddress(connectIdArg, deviceIdArg, params, book) {
1461
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1480
+ async tronGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1481
+ const call = this._beginCall("tronGetAddress", connectIdArg, deviceIdArg, paramsArg);
1482
+ if (!call.success) return call;
1483
+ const { params } = call.payload;
1484
+ if (!params.path) return missingParamFailure("tronGetAddress", "params.path");
1485
+ const tronCoinTypeFailure = coinTypeFailure("tron", params.path);
1486
+ if (tronCoinTypeFailure) return tronCoinTypeFailure;
1487
+ return this._addressFromAccountXpub(
1488
+ "tronGetAddress",
1489
+ "tron",
1490
+ call.payload,
1491
+ params.path,
1492
+ "m/44'/195'/0'/0/0",
1493
+ bundle,
1494
+ (xpub, relativeDerivePath) => this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath)
1495
+ );
1496
+ }
1497
+ async tronSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1498
+ const call = this._beginCall("tronSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1499
+ if (!call.success) return call;
1500
+ const { params } = call.payload;
1501
+ if (!params.path) return missingParamFailure("tronSignTransaction", "params.path");
1502
+ if (!params.rawTxHex) {
1503
+ return failure(
1504
+ HardwareErrorCode2.InvalidParams,
1505
+ "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1506
+ );
1507
+ }
1508
+ const rawTxHex = exactHex(params.rawTxHex);
1509
+ if (rawTxHex === void 0) return invalidHexFailure("rawTxHex");
1510
+ return this._tronSign("tronSignTransaction", call.payload, params.path, rawTxHex);
1511
+ }
1512
+ async tronSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1513
+ const call = this._beginCall("tronSignMessage", connectIdArg, deviceIdArg, paramsArg);
1514
+ if (!call.success) return call;
1515
+ const { params } = call.payload;
1516
+ if (!params.path) return missingParamFailure("tronSignMessage", "params.path");
1517
+ if (!params.messageHex) return missingParamFailure("tronSignMessage", "params.messageHex");
1518
+ if (params.messageType !== "V2") {
1519
+ return failure(
1520
+ HardwareErrorCode2.MethodNotSupported,
1521
+ 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1522
+ );
1523
+ }
1524
+ const messageHex = exactHex(params.messageHex);
1525
+ if (messageHex === void 0) return invalidHexFailure("messageHex");
1526
+ return this._tronSign(
1527
+ "tronSignMessage",
1528
+ call.payload,
1529
+ params.path,
1530
+ messageHex,
1531
+ 2 /* PersonalMessage */
1532
+ );
1533
+ }
1534
+ /** Resolves the call's target and requires params, before any method-specific check. */
1535
+ _beginCall(method, connectIdArg, deviceIdArg, params) {
1536
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1462
1537
  if (!operationTarget.success) return operationTarget;
1463
- const connectId = operationTarget.payload.targetId;
1464
- const deviceId = deviceIdArg ?? void 0;
1465
- if (!params) return failure(HardwareErrorCode.InvalidParams, "tronGetAddress requires params");
1466
- if (!params.path)
1467
- return failure(HardwareErrorCode.InvalidParams, "tronGetAddress requires params.path");
1468
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1538
+ if (!params) return missingParamFailure(method, "params");
1539
+ return success({
1540
+ connectId: operationTarget.payload.targetId,
1541
+ deviceId: deviceIdArg ?? void 0,
1542
+ params
1543
+ });
1544
+ }
1545
+ /** Derives a leaf address offline from its account xpub. */
1546
+ async _addressFromAccountXpub(method, chain, { connectId, deviceId }, path, leafExample, bundle, derive) {
1547
+ const normalizedPath = normalizePath(path);
1548
+ const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1469
1549
  if (!relativeDerivePath) {
1470
1550
  return failure(
1471
- HardwareErrorCode.InvalidParams,
1472
- "tronGetAddress requires a full leaf path, e.g. m/44'/195'/0'/0/0"
1551
+ HardwareErrorCode2.InvalidParams,
1552
+ `${method} requires a full leaf path, e.g. ${leafExample}`
1473
1553
  );
1474
1554
  }
1555
+ const accountFailure = chain === "btc" ? btcAccountFailure(accountPath) : void 0;
1556
+ if (accountFailure) return accountFailure;
1475
1557
  return this._runJob(connectId, deviceId, async (signal) => {
1476
1558
  const xpub = await this._fetchAccountXpub(
1477
1559
  connectId,
1478
1560
  deviceId,
1479
- "tron",
1561
+ chain,
1480
1562
  accountPath,
1481
1563
  signal,
1482
- book
1564
+ bundle
1483
1565
  );
1484
- const address = this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath);
1485
- return success({ address, path: normalizePath(params.path) });
1566
+ return success({
1567
+ address: derive(xpub, relativeDerivePath),
1568
+ path: normalizedPath,
1569
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1570
+ });
1486
1571
  });
1487
1572
  }
1488
- async tronSignTransaction(connectIdArg, deviceIdArg, params) {
1489
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1490
- if (!operationTarget.success) return operationTarget;
1491
- const connectId = operationTarget.payload.targetId;
1492
- const deviceId = deviceIdArg ?? void 0;
1493
- if (!params)
1494
- return failure(HardwareErrorCode.InvalidParams, "tronSignTransaction requires params");
1495
- if (!params.path) {
1496
- return failure(HardwareErrorCode.InvalidParams, "tronSignTransaction requires params.path");
1497
- }
1498
- if (!params.rawTxHex) {
1499
- return failure(
1500
- HardwareErrorCode.InvalidParams,
1501
- "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1502
- );
1503
- }
1504
- const rawTxHex = stripHex(params.rawTxHex);
1505
- const path = normalizePath(params.path);
1573
+ _evmSign(method, target, rawPath, chainId, signDataHex, dataType, toPayload) {
1574
+ const path = normalizePath(rawPath);
1506
1575
  return this._signWithWallet({
1507
- connectId,
1508
- deviceId,
1509
- chain: "tron",
1510
- operationName: "tronSignTransaction",
1511
- buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1576
+ connectId: target.connectId,
1577
+ deviceId: target.deviceId,
1578
+ path,
1579
+ chain: "evm",
1580
+ operationName: method,
1581
+ buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1512
1582
  requestId,
1513
- rawTxHex,
1583
+ unsignedTxHex: signDataHex,
1584
+ dataType,
1514
1585
  path,
1515
1586
  xfp,
1587
+ chainId,
1516
1588
  origin: this._origin
1517
1589
  }),
1518
- parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1519
- // Keystone signs rawTxHex as given and returns only the signature, so no serializedTx.
1590
+ parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1591
+ toPayload
1592
+ });
1593
+ }
1594
+ _solSign(method, target, rawPath, unsignedPayloadHex, dataType) {
1595
+ const path = normalizePath(rawPath);
1596
+ return this._signWithWallet({
1597
+ connectId: target.connectId,
1598
+ deviceId: target.deviceId,
1599
+ path,
1600
+ chain: "sol",
1601
+ operationName: method,
1602
+ buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1603
+ requestId,
1604
+ unsignedPayloadHex,
1605
+ dataType,
1606
+ path,
1607
+ xfp,
1608
+ origin: this._origin
1609
+ }),
1610
+ parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1520
1611
  toPayload: (sig) => ({ signature: sig.signature })
1521
1612
  });
1522
1613
  }
1523
- async tronSignMessage(connectIdArg, deviceIdArg, params) {
1524
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1525
- if (!operationTarget.success) return operationTarget;
1526
- const connectId = operationTarget.payload.targetId;
1527
- const deviceId = deviceIdArg ?? void 0;
1528
- if (!params) return failure(HardwareErrorCode.InvalidParams, "tronSignMessage requires params");
1529
- if (!params.path) {
1530
- return failure(HardwareErrorCode.InvalidParams, "tronSignMessage requires params.path");
1531
- }
1532
- if (!params.messageHex) {
1533
- return failure(HardwareErrorCode.InvalidParams, "tronSignMessage requires params.messageHex");
1534
- }
1535
- if (params.messageType !== "V2") {
1536
- return failure(
1537
- HardwareErrorCode.MethodNotSupported,
1538
- 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1539
- );
1540
- }
1541
- const messageHex = stripHex(params.messageHex);
1542
- const path = normalizePath(params.path);
1614
+ _tronSign(method, target, rawPath, signDataHex, signType) {
1615
+ const path = normalizePath(rawPath);
1543
1616
  return this._signWithWallet({
1544
- connectId,
1545
- deviceId,
1617
+ connectId: target.connectId,
1618
+ deviceId: target.deviceId,
1619
+ path,
1546
1620
  chain: "tron",
1547
- operationName: "tronSignMessage",
1621
+ operationName: method,
1548
1622
  buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1549
1623
  requestId,
1550
- rawTxHex: messageHex,
1624
+ rawTxHex: signDataHex,
1551
1625
  path,
1552
1626
  xfp,
1553
- signType: 2 /* PersonalMessage */,
1627
+ signType,
1554
1628
  origin: this._origin
1555
1629
  }),
1556
1630
  parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1557
1631
  toPayload: (sig) => ({ signature: sig.signature })
1558
1632
  });
1559
1633
  }
1560
- // ---------------------------------------------------------------------------
1561
- // Internals
1562
- // ---------------------------------------------------------------------------
1563
1634
  async _runJob(connectId, deviceId, job) {
1564
1635
  try {
1565
1636
  return await this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), job);
@@ -1567,30 +1638,49 @@ var KeystoneAdapter = class _KeystoneAdapter {
1567
1638
  return this._errorToFailure(err);
1568
1639
  }
1569
1640
  }
1570
- async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, book) {
1641
+ async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, bundle) {
1571
1642
  const { account } = await this._fetchAccount(
1572
1643
  connectId,
1573
1644
  deviceId,
1574
1645
  hwkChain,
1575
1646
  accountPath,
1576
1647
  signal,
1577
- book
1648
+ bundle
1578
1649
  );
1579
1650
  _KeystoneAdapter._throwIfAborted(signal);
1580
1651
  if (!account.extendedPublicKey) {
1581
- throw createHwkError({
1582
- code: HardwareErrorCode.MethodNotSupported,
1652
+ throw createHwkError2({
1653
+ code: HardwareErrorCode2.MethodNotSupported,
1583
1654
  message: "Keystone did not return an extended public key for this account path"
1584
1655
  });
1585
1656
  }
1657
+ const { publicKey } = this.urEngine.parseXpubMeta(account.extendedPublicKey);
1658
+ if (!/^0[23]/.test(publicKey)) {
1659
+ throw createHwkError2({
1660
+ code: HardwareErrorCode2.DeviceMismatch,
1661
+ message: "Keystone returned an account key that is not a public key"
1662
+ });
1663
+ }
1586
1664
  return account.extendedPublicKey;
1587
1665
  }
1666
+ /** The exported key behind an address, reduced to the fields that identify it. */
1667
+ _exportedAccountKey(accountPath, xpub) {
1668
+ const { publicKey, chainCode } = this.urEngine.parseXpubMeta(xpub);
1669
+ return { path: normalizePath(accountPath), publicKey, chainCode, xpub };
1670
+ }
1588
1671
  /**
1589
1672
  * Signing needs only the wallet's mfp: the device re-derives the key from path+xfp, so no
1590
1673
  * per-path account lookup happens here.
1591
1674
  */
1592
1675
  _signWithWallet(args) {
1593
1676
  const { connectId, deviceId } = args;
1677
+ if (!isBip32Path(args.path)) {
1678
+ return Promise.resolve(
1679
+ failure(HardwareErrorCode2.InvalidParams, `Invalid derivation path (${args.path})`)
1680
+ );
1681
+ }
1682
+ const chainCoinTypeFailure = coinTypeFailure(args.chain, args.path);
1683
+ if (chainCoinTypeFailure) return Promise.resolve(chainCoinTypeFailure);
1594
1684
  return this._runJob(connectId, deviceId, async (signal) => {
1595
1685
  const { record } = await this._ensureWalletKnown(connectId, deviceId, args.chain, signal);
1596
1686
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1615,6 +1705,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1615
1705
  const method = item.methodName;
1616
1706
  const hwkChain = getAllNetworkMethodChain(method);
1617
1707
  const path = normalizePath(item.path);
1708
+ if (!hasChainCoinType(hwkChain, path)) return void 0;
1618
1709
  if (hwkChain === "btc" && !isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1619
1710
  return void 0;
1620
1711
  }
@@ -1626,15 +1717,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1626
1717
  case "btcGetPublicKey":
1627
1718
  case "solGetAddress":
1628
1719
  return { hwkChain, path };
1629
- default:
1630
- return void 0;
1631
1720
  }
1632
1721
  }
1633
1722
  /**
1634
- * QR answers the whole bundle with one request QR and one scan. USB exports one path per
1635
- * request because the device limits that channel.
1723
+ * Picks the bundle's channel. QR answers every item with one request QR and one scan; USB items
1724
+ * each ask the device directly, like other vendors, on the session found here.
1636
1725
  */
1637
- async _prefetchAllNetworkAccounts(connectId, deviceId, params) {
1726
+ async _prepareAllNetworkBundle(connectId, deviceId, params) {
1638
1727
  return this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), async (signal) => {
1639
1728
  const target = this._resolveTarget(connectId, deviceId);
1640
1729
  let { record } = target;
@@ -1643,21 +1732,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1643
1732
  const schema = this._allNetworkSyncSchema(item);
1644
1733
  if (schema) requestedByKey.set(accountKey(schema.hwkChain, schema.path), schema);
1645
1734
  }
1646
- const book = /* @__PURE__ */ new Map();
1735
+ const scanned = /* @__PURE__ */ new Map();
1647
1736
  if (!requestedByKey.size) {
1648
- return { book };
1737
+ return { access: { channel: "qr", scanned } };
1649
1738
  }
1650
- const requestedSchemas = Array.from(requestedByKey.values());
1651
- const assertAllBooked = () => {
1652
- for (const schema of requestedSchemas) {
1653
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1654
- throw createHwkError({
1655
- code: HardwareErrorCode.DeviceMismatch,
1656
- message: `Keystone did not return the requested derivation path (${schema.path})`
1657
- });
1658
- }
1659
- }
1660
- };
1661
1739
  const operation = isHardwareOperationId2(params.operationId) ? this._operations.find(params.operationId) : void 0;
1662
1740
  const operationRoute = operation ? this._operationRoutes.get(operation.connectId) : void 0;
1663
1741
  const routedToQr = operationRoute?.operationId === operation?.operationId && operationRoute?.connectionType === "qr";
@@ -1666,45 +1744,23 @@ var KeystoneAdapter = class _KeystoneAdapter {
1666
1744
  _KeystoneAdapter._throwIfAborted(signal);
1667
1745
  }
1668
1746
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1669
- const bundleSessionId = record.usbSessionId;
1670
- const assertBundleSession = () => {
1671
- if (record?.usbSessionId !== bundleSessionId) {
1672
- throw createHwkError({
1673
- code: HardwareErrorCode.TransportNotAvailable,
1674
- message: "Keystone USB connection was lost during account export"
1675
- });
1676
- }
1747
+ return {
1748
+ access: { channel: "usb", usbSessionId: record.usbSessionId },
1749
+ masterFingerprint: record.masterFingerprint
1677
1750
  };
1678
- for (const schema of requestedSchemas) {
1679
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1680
- assertBundleSession();
1681
- const synced = await this._fetchAccount(
1682
- connectId,
1683
- deviceId,
1684
- schema.hwkChain,
1685
- schema.path,
1686
- signal,
1687
- book
1688
- );
1689
- record = synced.record;
1690
- assertBundleSession();
1691
- }
1692
- }
1693
- assertAllBooked();
1694
- return { book, masterFingerprint: record.masterFingerprint };
1695
1751
  }
1696
- if (this._forcedTransport === "usb") {
1697
- throw createHwkError({
1698
- code: HardwareErrorCode.TransportNotAvailable,
1752
+ if (this._forcedTransport === "usb" && !routedToQr) {
1753
+ throw createHwkError2({
1754
+ code: HardwareErrorCode2.TransportNotAvailable,
1699
1755
  message: "USB channel is not connected for this Keystone wallet"
1700
1756
  });
1701
1757
  }
1702
- const schemas = requestedSchemas;
1758
+ const schemas = Array.from(requestedByKey.values());
1703
1759
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1704
1760
  schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1705
1761
  origin: this._origin
1706
1762
  });
1707
- const responseUr = await this._requestQrDisplayAndAwaitResponse(
1763
+ const responseUr = await this._requestQrAndAwaitResponse(
1708
1764
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1709
1765
  { ...requestUr, animated: false },
1710
1766
  signal
@@ -1712,22 +1768,41 @@ var KeystoneAdapter = class _KeystoneAdapter {
1712
1768
  _KeystoneAdapter._throwIfAborted(signal);
1713
1769
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1714
1770
  this._assertParsedIdentity(parsed, target);
1715
- record = this._upsertDeviceRecord(parsed);
1716
- const requestedChainByPath = new Map(
1717
- schemas.map((schema) => [normalizePath(schema.path), schema.hwkChain])
1718
- );
1719
- for (const account of parsed.accounts) {
1720
- const normalizedPath = normalizePath(account.path);
1721
- const hwkChain = requestedChainByPath.get(normalizedPath) ?? inferHwkChainFromPath(normalizedPath);
1722
- if (hwkChain) {
1723
- book.set(accountKey(hwkChain, normalizedPath), { ...account, hwkChain });
1724
- }
1771
+ for (const schema of schemas) {
1772
+ scanned.set(accountKey(schema.hwkChain, schema.path), {
1773
+ ...requireExportedPath(parsed, schema.path),
1774
+ hwkChain: schema.hwkChain
1775
+ });
1725
1776
  }
1726
- assertAllBooked();
1727
- return { book, masterFingerprint: record.masterFingerprint };
1777
+ record = this._upsertDeviceRecord(parsed);
1778
+ return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1728
1779
  });
1729
1780
  }
1730
- /** Resolve the wallet's master fingerprint from the connectId and/or deviceId the caller passed. */
1781
+ /**
1782
+ * A positional wallet id and an operation id must name the same wallet: otherwise the call
1783
+ * would run on the operation's wallet while the caller files the result under the other one.
1784
+ * Ids that do not carry a master fingerprint cannot be compared and pass through.
1785
+ */
1786
+ _resolveOperationTarget(positionalTargetId, operationId) {
1787
+ const target = resolveGenericHardwareOperationTarget(
1788
+ positionalTargetId,
1789
+ operationId,
1790
+ "keystone"
1791
+ );
1792
+ if (!target.success || !operationId || !positionalTargetId || isHardwareOperationId2(positionalTargetId)) {
1793
+ return target;
1794
+ }
1795
+ const operation = this._operations.find(operationId);
1796
+ const positionalMfp = keystoneMfpFromIdentifier(positionalTargetId);
1797
+ const operationMfp = operation ? keystoneMfpFromIdentifier(operation.connectId) : void 0;
1798
+ if (positionalMfp && operationMfp && positionalMfp !== operationMfp) {
1799
+ return failure(
1800
+ HardwareErrorCode2.InvalidParams,
1801
+ "Keystone connectId and operationId name different wallets"
1802
+ );
1803
+ }
1804
+ return target;
1805
+ }
1731
1806
  _resolveTarget(connectId, deviceId) {
1732
1807
  const resolvedConnectId = isHardwareOperationId2(connectId) ? this._operations.resolve(connectId).connectId : connectId;
1733
1808
  const identifiers = [deviceId, resolvedConnectId].filter(
@@ -1737,14 +1812,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1737
1812
  const fingerprints = identifiers.map((identifier) => keystoneMfpFromIdentifier(identifier));
1738
1813
  const expectedMasterFingerprint = fingerprints[0];
1739
1814
  if (!expectedMasterFingerprint || fingerprints.some((value) => !value)) {
1740
- throw createHwkError({
1741
- code: HardwareErrorCode.DeviceNotFound,
1815
+ throw createHwkError2({
1816
+ code: HardwareErrorCode2.DeviceNotFound,
1742
1817
  message: "Keystone device lookup requires the wallet master fingerprint"
1743
1818
  });
1744
1819
  }
1745
1820
  if (fingerprints.some((value) => value !== expectedMasterFingerprint)) {
1746
- throw createHwkError({
1747
- code: HardwareErrorCode.DeviceMismatch,
1821
+ throw createHwkError2({
1822
+ code: HardwareErrorCode2.DeviceMismatch,
1748
1823
  message: "Keystone connectId and deviceId identify different wallets"
1749
1824
  });
1750
1825
  }
@@ -1755,9 +1830,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1755
1830
  }
1756
1831
  _assertParsedIdentity(parsed, expected) {
1757
1832
  if (expected.expectedMasterFingerprint && parsed.masterFingerprint !== expected.expectedMasterFingerprint) {
1758
- throw createHwkError({
1759
- code: HardwareErrorCode.DeviceMismatch,
1760
- message: `Connected Keystone wallet (mfp ${parsed.masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1833
+ throw createHwkError2({
1834
+ code: HardwareErrorCode2.DeviceMismatch,
1835
+ // The master fingerprint identifies the wallet; keep it out of messages that reach logs.
1836
+ message: "Connected Keystone wallet does not match the requested wallet"
1761
1837
  });
1762
1838
  }
1763
1839
  }
@@ -1787,10 +1863,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1787
1863
  * Opens a permitted USB Keystone and takes its mfp as the wallet identity. A known wallet gains
1788
1864
  * USB in place (`device-changed`); an unseen one becomes USB-only.
1789
1865
  */
1790
- async _connectUsb(expected, searchTargetId, signal) {
1866
+ async _connectUsb(connector, expected, searchTargetId, signal) {
1791
1867
  if (this._pendingUsbTeardowns > 0 || this._abandonedUsbConnects > 0) {
1792
1868
  return failure(
1793
- HardwareErrorCode.DeviceBusyInternal,
1869
+ HardwareErrorCode2.DeviceBusyInternal,
1794
1870
  "Keystone USB session is being released"
1795
1871
  );
1796
1872
  }
@@ -1800,28 +1876,22 @@ var KeystoneAdapter = class _KeystoneAdapter {
1800
1876
  abandoned = true;
1801
1877
  this._abandonedUsbConnects += 1;
1802
1878
  };
1803
- signal?.addEventListener("abort", onAbort, { once: true });
1879
+ signal.addEventListener("abort", onAbort, { once: true });
1804
1880
  const pending = this._usbConnectTail.then(async () => {
1805
1881
  _KeystoneAdapter._throwIfAborted(signal);
1806
- return this._connectUsbExclusive(expected, searchTargetId, signal);
1882
+ return this._connectUsbExclusive(connector, expected, searchTargetId, signal);
1807
1883
  });
1808
1884
  const settled = pending.finally(() => {
1809
- signal?.removeEventListener("abort", onAbort);
1885
+ signal.removeEventListener("abort", onAbort);
1810
1886
  if (abandoned) this._abandonedUsbConnects -= 1;
1811
1887
  });
1812
1888
  this._usbConnectTail = settled.then(
1813
1889
  () => void 0,
1814
1890
  () => void 0
1815
1891
  );
1816
- return signal ? _KeystoneAdapter._abortable(signal, settled) : settled;
1892
+ return _KeystoneAdapter._abortable(signal, settled);
1817
1893
  }
1818
- async _connectUsbExclusive(expected, searchTargetId, signal) {
1819
- if (!this._usbConnector) {
1820
- return failure(
1821
- HardwareErrorCode.TransportNotAvailable,
1822
- "No USB connector configured for this Keystone adapter"
1823
- );
1824
- }
1894
+ async _connectUsbExclusive(connector, expected, searchTargetId, signal) {
1825
1895
  let sessionId;
1826
1896
  try {
1827
1897
  let connectTarget = { type: "default" };
@@ -1833,7 +1903,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1833
1903
  deviceIdentity: expected.expectedMasterFingerprint
1834
1904
  };
1835
1905
  }
1836
- const connector = this._usbConnector;
1837
1906
  const session = await (connector.connectTarget ? connector.connectTarget(connectTarget) : connector.connect(searchTargetId ?? expected.expectedMasterFingerprint));
1838
1907
  sessionId = session.sessionId;
1839
1908
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1841,22 +1910,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
1841
1910
  const mfpValue = parseWalletMasterFingerprint3(raw?.masterFingerprint);
1842
1911
  if (!mfpValue) {
1843
1912
  const empty = parseBip32MasterFingerprint(raw?.masterFingerprint) === MISSING_BIP32_MASTER_FINGERPRINT;
1844
- throw createHwkError({
1845
- code: empty ? HardwareErrorCode.DeviceNotInitialized : HardwareErrorCode.DeviceMismatch,
1913
+ throw createHwkError2({
1914
+ code: empty ? HardwareErrorCode2.DeviceNotInitialized : HardwareErrorCode2.DeviceMismatch,
1846
1915
  message: empty ? "Keystone has no wallet yet; it reported an empty master fingerprint" : "Keystone USB did not report a master fingerprint"
1847
1916
  });
1848
1917
  }
1849
1918
  const masterFingerprint = mfpValue.toLowerCase();
1850
- if (expected.expectedMasterFingerprint && masterFingerprint !== expected.expectedMasterFingerprint) {
1851
- throw createHwkError({
1852
- code: HardwareErrorCode.DeviceMismatch,
1853
- message: `Connected Keystone wallet (mfp ${masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1854
- });
1855
- }
1919
+ this._assertParsedIdentity({ masterFingerprint, accounts: [] }, expected);
1856
1920
  const previousUsbSessionId = this._devices.get(masterFingerprint)?.usbSessionId;
1857
1921
  if (previousUsbSessionId && previousUsbSessionId !== session.sessionId) {
1858
1922
  try {
1859
- await this._usbConnector.disconnect(previousUsbSessionId);
1923
+ await connector.disconnect(previousUsbSessionId);
1860
1924
  } catch {
1861
1925
  }
1862
1926
  }
@@ -1876,7 +1940,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1876
1940
  } catch (err) {
1877
1941
  if (sessionId) {
1878
1942
  try {
1879
- await this._usbConnector.disconnect(sessionId);
1943
+ await connector.disconnect(sessionId);
1880
1944
  } catch {
1881
1945
  }
1882
1946
  }
@@ -1915,15 +1979,22 @@ var KeystoneAdapter = class _KeystoneAdapter {
1915
1979
  }
1916
1980
  }
1917
1981
  if (!availableDevices.length) {
1982
+ const record = options?.waitForReenumeration ? this._devices.get(expectedMasterFingerprint) : void 0;
1983
+ if (record) record.hadUsbSession = false;
1918
1984
  if (this._forcedTransport === "usb" && lastSearchError) {
1919
1985
  throw lastSearchError instanceof Error ? lastSearchError : new Error(String(lastSearchError));
1920
1986
  }
1921
1987
  return void 0;
1922
1988
  }
1923
- const attached = await this._connectUsb({ expectedMasterFingerprint }, void 0, signal);
1989
+ const attached = await this._connectUsb(
1990
+ this._usbConnector,
1991
+ { expectedMasterFingerprint },
1992
+ void 0,
1993
+ signal
1994
+ );
1924
1995
  _KeystoneAdapter._throwIfAborted(signal);
1925
- if (!attached.success && attached.payload.code === HardwareErrorCode.DeviceBusyInternal) {
1926
- throw createHwkError({
1996
+ if (!attached.success && (attached.payload.code === HardwareErrorCode2.DeviceBusyInternal || attached.payload.code === HardwareErrorCode2.DeviceOneDeviceOnly)) {
1997
+ throw createHwkError2({
1927
1998
  ...attached.payload,
1928
1999
  message: attached.payload.error
1929
2000
  });
@@ -1931,8 +2002,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1931
2002
  return attached.success ? this._devices.get(expectedMasterFingerprint) : void 0;
1932
2003
  }
1933
2004
  /**
1934
- * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session fails closed;
1935
- * otherwise a failed USB reattach leaves the call on QR.
2005
+ * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
2006
+ * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
1936
2007
  */
1937
2008
  async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
1938
2009
  const releaseOperationRetention = isHardwareOperationId2(operationId) ? this._operations.retain(operationId) : void 0;
@@ -1963,7 +2034,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1963
2034
  }
1964
2035
  interactionRoute = route;
1965
2036
  }
1966
- if (!interactionRoute && !this._forcedTransport && record && !record.usbSessionId && this._usbConnector) {
2037
+ if (!interactionRoute && this._forcedTransport !== "qr" && record && !record.usbSessionId && this._usbConnector) {
1967
2038
  record = await this._tryUsbAttach(signal, record.masterFingerprint, {
1968
2039
  waitForReenumeration: record.hadUsbSession
1969
2040
  }) ?? record;
@@ -1977,38 +2048,35 @@ var KeystoneAdapter = class _KeystoneAdapter {
1977
2048
  "Keystone operation USB connection was lost"
1978
2049
  );
1979
2050
  }
1980
- throw createHwkError({
1981
- code: HardwareErrorCode.TransportNotAvailable,
2051
+ throw createHwkError2({
2052
+ code: HardwareErrorCode2.TransportNotAvailable,
1982
2053
  message: "USB channel is not connected for this Keystone wallet"
1983
2054
  });
1984
2055
  }
1985
- const result = await this._callUsbConnector(
2056
+ const result = await this._callUsbResolveUr(
2057
+ this._usbConnector,
1986
2058
  record.usbSessionId,
1987
- "resolveUr",
1988
2059
  requestUr,
1989
2060
  signal
1990
2061
  );
1991
2062
  if (result.success) return result.payload;
1992
2063
  const usbError = rehydrateConnectorError(result.error);
1993
2064
  const { origin: usbErrorOrigin, code: usbErrorCode } = usbError;
1994
- if (usbErrorCode === HardwareErrorCode.PayloadTooLarge && usbErrorOrigin !== "device") {
2065
+ if (usbErrorCode === HardwareErrorCode2.PayloadTooLarge && usbErrorOrigin !== "device") {
1995
2066
  if (!interactionRoute && !this._forcedTransport) {
1996
2067
  const displayDevice2 = toDeviceInfo(record);
1997
- return this._requestQrDisplayAndAwaitResponse(
1998
- displayDevice2,
1999
- { ...requestUr, animated },
2000
- signal
2001
- );
2068
+ return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2002
2069
  }
2003
2070
  throw usbError;
2004
2071
  }
2005
- const deviceAnswered = usbErrorOrigin !== void 0 ? usbErrorOrigin === "device" : usbErrorCode === HardwareErrorCode.UserRejected || usbErrorCode === HardwareErrorCode.UserAborted || usbErrorCode === HardwareErrorCode.DeviceLocked || usbErrorCode === HardwareErrorCode.DeviceMismatch;
2072
+ const deviceAnswered = usbErrorOrigin !== void 0 ? usbErrorOrigin === "device" : usbErrorCode === HardwareErrorCode2.UserRejected || usbErrorCode === HardwareErrorCode2.UserAborted || usbErrorCode === HardwareErrorCode2.DeviceLocked || usbErrorCode === HardwareErrorCode2.DeviceMismatch;
2006
2073
  if (!deviceAnswered) {
2007
2074
  const lostSessionId = record.usbSessionId;
2008
2075
  if (lostSessionId) {
2009
2076
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2010
2077
  }
2011
2078
  record.usbSessionId = void 0;
2079
+ this.emitter.emit(DEVICE.CHANGED, { type: DEVICE.CHANGED, payload: toDeviceInfo(record) });
2012
2080
  if (interactionRoute) {
2013
2081
  throw this._endDisconnectedOperation(
2014
2082
  interactionRoute.operationId,
@@ -2017,8 +2085,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
2017
2085
  );
2018
2086
  }
2019
2087
  if (operationName) {
2020
- throw createHwkError({
2021
- code: usbErrorCode ?? HardwareErrorCode.TransportError,
2088
+ throw createHwkError2({
2089
+ code: usbErrorCode ?? HardwareErrorCode2.TransportError,
2022
2090
  message: `Keystone ${operationName} may have completed before the USB connection was lost`,
2023
2091
  origin: "transport",
2024
2092
  recovery: { scope: "unknown" },
@@ -2026,20 +2094,29 @@ var KeystoneAdapter = class _KeystoneAdapter {
2026
2094
  });
2027
2095
  }
2028
2096
  }
2097
+ if (operationName && usbError.replyUnreadable === true) {
2098
+ throw createHwkError2({
2099
+ code: usbErrorCode ?? HardwareErrorCode2.UnknownError,
2100
+ message: `Keystone ${operationName} may have completed but its reply could not be read`,
2101
+ origin: "device",
2102
+ recovery: { scope: "unknown" },
2103
+ params: operationMayHaveCompletedParams(operationName)
2104
+ });
2105
+ }
2029
2106
  throw usbError;
2030
2107
  }
2031
2108
  const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
2032
2109
  try {
2033
- return await this._requestQrDisplayAndAwaitResponse(
2110
+ return await this._requestQrAndAwaitResponse(
2034
2111
  displayDevice,
2035
2112
  { ...requestUr, animated },
2036
2113
  signal
2037
2114
  );
2038
2115
  } catch (error) {
2039
2116
  const { code, _tag: tag } = error;
2040
- if (operationName && (code === HardwareErrorCode.OperationTimeout || tag === UI_REQUEST_TIMEOUT_TAG)) {
2041
- throw createHwkError({
2042
- code: HardwareErrorCode.OperationTimeout,
2117
+ if (operationName && (code === HardwareErrorCode2.OperationTimeout || tag === UI_REQUEST_TIMEOUT_TAG)) {
2118
+ throw createHwkError2({
2119
+ code: HardwareErrorCode2.OperationTimeout,
2043
2120
  message: `Keystone ${operationName} may have completed before the QR response timed out`,
2044
2121
  recovery: { scope: "unknown" },
2045
2122
  params: operationMayHaveCompletedParams(operationName)
@@ -2052,48 +2129,54 @@ var KeystoneAdapter = class _KeystoneAdapter {
2052
2129
  _endDisconnectedOperation(operationId, message, operationName) {
2053
2130
  this._operations.end(operationId, "disconnect");
2054
2131
  const params = { operationId, reason: "disconnect" };
2055
- return createHwkError({
2056
- code: HardwareErrorCode.OperationEnded,
2132
+ return createHwkError2({
2133
+ code: HardwareErrorCode2.OperationEnded,
2057
2134
  message,
2058
2135
  recovery: operationName ? { scope: "unknown" } : void 0,
2059
2136
  params: operationName ? operationMayHaveCompletedParams(operationName, params) : params
2060
2137
  });
2061
2138
  }
2062
2139
  /**
2063
- * Fetches one account's key material for this operation only; `book` reuses earlier fetches. A
2064
- * failed USB export ends the operation without replaying or switching transports.
2140
+ * Fetches one account's key material. An all-network QR item takes it from the bundle's scan; a
2141
+ * USB item asks the device on the bundle's session. A failed USB export ends the operation
2142
+ * without replaying or switching transports.
2065
2143
  */
2066
- async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, book) {
2144
+ async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, bundle) {
2067
2145
  const target = this._resolveTarget(connectId, deviceId);
2146
+ if (bundle?.channel === "qr") {
2147
+ const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2148
+ if (!target.record || !scanned) {
2149
+ throw createHwkError2({
2150
+ code: HardwareErrorCode2.DeviceMismatch,
2151
+ message: `Keystone did not return the requested derivation path (${syncPath})`
2152
+ });
2153
+ }
2154
+ return { record: target.record, account: scanned };
2155
+ }
2156
+ if (bundle?.channel === "usb" && target.record?.usbSessionId !== bundle.usbSessionId) {
2157
+ throw createHwkError2({
2158
+ code: HardwareErrorCode2.TransportNotAvailable,
2159
+ message: "Keystone USB connection was lost during the bundle"
2160
+ });
2161
+ }
2068
2162
  const operationConnectionType = isHardwareOperationId2(connectId) ? this._operations.resolve(connectId).connectionType : void 0;
2069
- const key = accountKey(hwkChain, syncPath);
2070
2163
  let existingRecord = target.record;
2071
2164
  if (!existingRecord) {
2072
2165
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2073
2166
  _KeystoneAdapter._throwIfAborted(signal);
2074
2167
  }
2075
- const booked = book?.get(key);
2076
- if (existingRecord && booked) {
2077
- return { record: existingRecord, account: booked };
2078
- }
2079
- if (!operationConnectionType && existingRecord && !existingRecord.usbSessionId && this._forcedTransport === "usb") {
2080
- await this._tryUsbAttach(signal, existingRecord.masterFingerprint, {
2081
- waitForReenumeration: existingRecord.hadUsbSession
2082
- });
2083
- _KeystoneAdapter._throwIfAborted(signal);
2084
- existingRecord = this._devices.get(existingRecord.masterFingerprint) ?? existingRecord;
2085
- }
2086
- const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2168
+ const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2087
2169
  const schemas = [keySchema(hwkChain, syncPath)];
2088
2170
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2089
2171
  const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2090
2172
  _KeystoneAdapter._throwIfAborted(signal);
2091
2173
  const parsed = this.urEngine.parseAccountResponse(responseUr);
2174
+ const account = requireExportedPath(parsed, syncPath);
2092
2175
  let record;
2093
2176
  if (useSinglePathUsbExport && existingRecord) {
2094
2177
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
2095
- throw createHwkError({
2096
- code: HardwareErrorCode.DeviceMismatch,
2178
+ throw createHwkError2({
2179
+ code: HardwareErrorCode2.DeviceMismatch,
2097
2180
  message: "Keystone USB account export returned a different master fingerprint"
2098
2181
  });
2099
2182
  }
@@ -2104,27 +2187,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2104
2187
  viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2105
2188
  });
2106
2189
  }
2107
- const account = parsed.accounts.find((a) => normalizePath(a.path) === syncPath);
2108
- if (!account) {
2109
- throw createHwkError({
2110
- code: HardwareErrorCode.DeviceMismatch,
2111
- message: `Keystone did not return the requested derivation path (${syncPath})`
2112
- });
2113
- }
2114
- const entry = { ...account, hwkChain };
2115
- if (book) {
2116
- for (const returned of parsed.accounts) {
2117
- const returnedChain = inferHwkChainFromPath(returned.path);
2118
- if (returnedChain) {
2119
- book.set(accountKey(returnedChain, returned.path), {
2120
- ...returned,
2121
- hwkChain: returnedChain
2122
- });
2123
- }
2124
- }
2125
- book.set(key, entry);
2126
- }
2127
- return { record, account: entry };
2190
+ return { record, account: { ...account, hwkChain } };
2128
2191
  }
2129
2192
  /**
2130
2193
  * Resolves which wallet is attached, without a per-path account. `CHAIN_FINGERPRINT_PATHS.evm` is
@@ -2146,7 +2209,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2146
2209
  });
2147
2210
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2148
2211
  _KeystoneAdapter._throwIfAborted(signal);
2149
- return { record: this._upsertDeviceRecord(this.urEngine.parseAccountResponse(responseUr)) };
2212
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
2213
+ requireExportedPath(parsed, normalizePath(accountPath));
2214
+ return { record: this._upsertDeviceRecord(parsed) };
2150
2215
  }
2151
2216
  /**
2152
2217
  * The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
@@ -2172,7 +2237,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2172
2237
  * a cancel reach the wait before the QR timeout.
2173
2238
  */
2174
2239
  async _awaitQrResponse(requestType, pending, signal) {
2175
- if (!signal) return pending;
2176
2240
  let settled = false;
2177
2241
  const onAbort = () => {
2178
2242
  if (!settled) this._uiRegistry.cancel(requestType);
@@ -2181,69 +2245,64 @@ var KeystoneAdapter = class _KeystoneAdapter {
2181
2245
  else signal.addEventListener("abort", onAbort, { once: true });
2182
2246
  try {
2183
2247
  return await pending;
2248
+ } catch (error) {
2249
+ const reason = signal.reason;
2250
+ if (signal.aborted && reason?.code === HardwareErrorCode2.OperationEnded) throw signal.reason;
2251
+ throw error;
2184
2252
  } finally {
2185
2253
  settled = true;
2186
2254
  signal.removeEventListener("abort", onAbort);
2187
2255
  }
2188
2256
  }
2189
- async _requestQrDisplayAndAwaitResponse(device, data, signal) {
2257
+ /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2258
+ async _requestQrAndAwaitResponse(device, data, signal) {
2259
+ const requestType = data ? UI_REQUEST.REQUEST_QR_DISPLAY : UI_REQUEST.REQUEST_QR_SCAN;
2190
2260
  const operationId = this._activeOperationId();
2191
- const waitPromise = this._uiRegistry.wait(
2192
- UI_REQUEST.REQUEST_QR_DISPLAY,
2193
- { timeoutMs: this._qrTimeoutMs, operationId }
2194
- );
2195
- this.emitter.emit(UI_REQUEST.REQUEST_QR_DISPLAY, {
2196
- type: UI_REQUEST.REQUEST_QR_DISPLAY,
2197
- payload: { device, data, operationId }
2198
- });
2199
- const response = await this._awaitQrResponse(
2200
- UI_REQUEST.REQUEST_QR_DISPLAY,
2201
- waitPromise,
2202
- signal
2203
- );
2204
- return { urType: response.urType, urData: response.urData };
2205
- }
2206
- async _requestQrScanAndAwaitResponse(device, signal) {
2207
- const operationId = this._activeOperationId();
2208
- const waitPromise = this._uiRegistry.wait(
2209
- UI_REQUEST.REQUEST_QR_SCAN,
2210
- { timeoutMs: this._qrTimeoutMs, operationId }
2211
- );
2212
- this.emitter.emit(UI_REQUEST.REQUEST_QR_SCAN, {
2213
- type: UI_REQUEST.REQUEST_QR_SCAN,
2214
- payload: { device, operationId }
2215
- });
2216
- const response = await this._awaitQrResponse(UI_REQUEST.REQUEST_QR_SCAN, waitPromise, signal);
2217
- return { urType: response.urType, urData: response.urData };
2218
- }
2219
- async _callUsbConnector(sessionId, method, params, signal) {
2220
- if (!this._usbConnector) {
2221
- throw createHwkError({
2222
- code: HardwareErrorCode.TransportNotAvailable,
2223
- message: "No USB connector configured for this Keystone adapter"
2261
+ const release = operationId ? this._operations.retain(operationId) : void 0;
2262
+ try {
2263
+ const waitPromise = this._uiRegistry.wait(requestType, {
2264
+ timeoutMs: this._qrTimeoutMs,
2265
+ operationId
2224
2266
  });
2267
+ if (data) {
2268
+ this.emitter.emit(UI_REQUEST.REQUEST_QR_DISPLAY, {
2269
+ type: UI_REQUEST.REQUEST_QR_DISPLAY,
2270
+ payload: { device, data, operationId }
2271
+ });
2272
+ } else {
2273
+ this.emitter.emit(UI_REQUEST.REQUEST_QR_SCAN, {
2274
+ type: UI_REQUEST.REQUEST_QR_SCAN,
2275
+ payload: { device, operationId }
2276
+ });
2277
+ }
2278
+ const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2279
+ return { urType: response.urType, urData: response.urData };
2280
+ } finally {
2281
+ release?.();
2225
2282
  }
2283
+ }
2284
+ async _callUsbResolveUr(connector, sessionId, requestUr, signal) {
2226
2285
  if (this._pendingUsbTeardowns > 0 || this._unsettledUsbOperations.size > 0) {
2227
- throw createHwkError({
2228
- code: HardwareErrorCode.DeviceBusyInternal,
2229
- message: `Keystone USB is busy while calling ${method}`
2286
+ throw createHwkError2({
2287
+ code: HardwareErrorCode2.DeviceBusyInternal,
2288
+ message: "Keystone USB is busy while calling resolveUr"
2230
2289
  });
2231
2290
  }
2232
- if (signal?.aborted) {
2233
- throw signal.reason instanceof Error ? signal.reason : createHwkError({
2234
- code: HardwareErrorCode.UserAborted,
2291
+ if (signal.aborted) {
2292
+ throw signal.reason instanceof Error ? signal.reason : createHwkError2({
2293
+ code: HardwareErrorCode2.UserAborted,
2235
2294
  message: "User aborted operation"
2236
2295
  });
2237
2296
  }
2238
2297
  const releaseOperation = this._retainUsbOperation(`call:${sessionId}`);
2239
2298
  let rawCall;
2240
2299
  try {
2241
- rawCall = this._usbConnector.call(sessionId, method, params).finally(releaseOperation);
2300
+ rawCall = connector.call(sessionId, "resolveUr", requestUr).finally(releaseOperation);
2242
2301
  } catch (error) {
2243
2302
  releaseOperation();
2244
2303
  throw error;
2245
2304
  }
2246
- return signal ? _KeystoneAdapter._abortable(signal, rawCall) : rawCall;
2305
+ return _KeystoneAdapter._abortable(signal, rawCall);
2247
2306
  }
2248
2307
  _runUsbTeardown(task) {
2249
2308
  const previous = this._usbTeardownTail;
@@ -2305,6 +2364,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
2305
2364
  );
2306
2365
  });
2307
2366
  }
2367
+ /** Settles with `signal`'s reason once it aborts; a later outcome of `promise` is dropped. */
2368
+ static _untilAborted(signal, promise) {
2369
+ promise.catch(() => void 0);
2370
+ if (signal.aborted) return Promise.reject(signal.reason);
2371
+ return new Promise((resolve, reject) => {
2372
+ const onAbort = () => reject(signal.reason);
2373
+ signal.addEventListener("abort", onAbort, { once: true });
2374
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort)).catch(() => void 0);
2375
+ });
2376
+ }
2308
2377
  static _throwIfAborted(signal) {
2309
2378
  if (signal?.aborted) {
2310
2379
  throw signal.reason instanceof Error ? signal.reason : new Error("Operation aborted");
@@ -2313,8 +2382,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
2313
2382
  /** A response without the request's id is as unrelated as one with another id. */
2314
2383
  static _assertRequestIdMatches(expected, actual) {
2315
2384
  if (!actual || actual.toLowerCase() !== expected.toLowerCase()) {
2316
- throw createHwkError({
2317
- code: HardwareErrorCode.DeviceMismatch,
2385
+ throw createHwkError2({
2386
+ code: HardwareErrorCode2.DeviceMismatch,
2318
2387
  message: actual ? "Keystone response requestId does not match the pending request \u2014 discarding a stale or unrelated scan" : "Keystone response carries no requestId \u2014 discarding a stale or unrelated scan"
2319
2388
  });
2320
2389
  }
@@ -2322,7 +2391,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2322
2391
  _unsupported(method, reason) {
2323
2392
  return Promise.resolve(
2324
2393
  failure(
2325
- HardwareErrorCode.MethodNotSupported,
2394
+ HardwareErrorCode2.MethodNotSupported,
2326
2395
  `KeystoneAdapter.${method} is not implemented yet: ${reason}`
2327
2396
  )
2328
2397
  );
@@ -2342,20 +2411,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2342
2411
  }
2343
2412
  if (e._tag === UI_REQUEST_CANCELLED_TAG || e._tag === UI_REQUEST_PREEMPTED_TAG) {
2344
2413
  return failure(
2345
- HardwareErrorCode.UserAborted,
2414
+ HardwareErrorCode2.UserAborted,
2346
2415
  e.message ?? "Keystone QR operation was cancelled"
2347
2416
  );
2348
2417
  }
2349
2418
  if (e._tag === UI_REQUEST_TIMEOUT_TAG) {
2350
2419
  return failure(
2351
- HardwareErrorCode.OperationTimeout,
2420
+ HardwareErrorCode2.OperationTimeout,
2352
2421
  e.message ?? "Keystone QR operation timed out"
2353
2422
  );
2354
2423
  }
2355
2424
  }
2356
2425
  const message = err instanceof Error ? err.message : String(err);
2357
2426
  const params = err instanceof Error && err.stack ? { stack: err.stack } : void 0;
2358
- return failure(HardwareErrorCode.UnknownError, message, params);
2427
+ return failure(HardwareErrorCode2.UnknownError, message, params);
2359
2428
  }
2360
2429
  };
2361
2430
  export {