@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.js CHANGED
@@ -105,11 +105,12 @@ var TronSignRequest = class _TronSignRequest extends import_bc_ur_registry.Regis
105
105
  static parsePath(path, xfp) {
106
106
  const segments = path.replace(/^[mM]\//, "").split("/");
107
107
  const components = segments.map((segment) => {
108
- const hardened = segment.endsWith("'");
109
- return new import_bc_ur_registry.PathComponent({
110
- index: parseInt(hardened ? segment.slice(0, -1) : segment, 10),
111
- hardened
112
- });
108
+ const match = /^(\d+)('?)$/.exec(segment);
109
+ const index = match ? Number(match[1]) : NaN;
110
+ if (!match || index >= 2147483648) {
111
+ throw new Error(`Invalid TRON derivation path segment (${segment})`);
112
+ }
113
+ return new import_bc_ur_registry.PathComponent({ index, hardened: match[2] === "'" });
113
114
  });
114
115
  return new import_bc_ur_registry.CryptoKeypath(components, Buffer.from(xfp, "hex"));
115
116
  }
@@ -167,7 +168,7 @@ var DERIVATION_CURVE = {
167
168
  ed25519: import_keystone_sdk.Curve.ed25519
168
169
  };
169
170
  function toSdkUr(ur) {
170
- return new import_keystone_sdk.UR(Buffer.from(ur.urData, "hex"), ur.urType);
171
+ return new import_keystone_sdk.UR((0, import_hwk_adapter_core.boundedCborFromHex)(ur.urData), ur.urType);
171
172
  }
172
173
  function fromSdkUr(ur) {
173
174
  return { urType: ur.type, urData: ur.cbor.toString("hex") };
@@ -205,8 +206,24 @@ function toParsedAccount(key) {
205
206
  name: key.name
206
207
  };
207
208
  }
209
+ var BIP32_HARDENED_OFFSET = 2147483648;
208
210
  function relativeHdPath(relativeDerivePath) {
209
- return `m/${relativeDerivePath.replace(/^m\//i, "")}`;
211
+ const segments = relativeDerivePath.replace(/^m\//i, "").split("/");
212
+ const valid = segments.every(
213
+ (segment) => /^\d+$/.test(segment) && Number(segment) < BIP32_HARDENED_OFFSET
214
+ );
215
+ if (!valid) {
216
+ throw (0, import_hwk_adapter_core.createHwkError)({
217
+ code: import_hwk_adapter_core.HardwareErrorCode.InvalidParams,
218
+ message: `Invalid change/index segments in derivation path (${relativeDerivePath})`
219
+ });
220
+ }
221
+ return `m/${segments.join("/")}`;
222
+ }
223
+ var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.]{1,20})?$/;
224
+ var DEVICE_TEXT = /^[^\p{Cc}\p{Cf}]{1,64}$/u;
225
+ function deviceText(value, pattern) {
226
+ return typeof value === "string" && pattern.test(value) ? value : void 0;
210
227
  }
211
228
  var KeystoneUrEngine = class {
212
229
  constructor(origin = "OneKey") {
@@ -217,9 +234,9 @@ var KeystoneUrEngine = class {
217
234
  const parsed = this.sdk.parseMultiAccounts(toSdkUr(ur));
218
235
  return {
219
236
  masterFingerprint: requireBip32MasterFingerprint(parsed.masterFingerprint),
220
- device: parsed.device,
221
- deviceId: parsed.deviceId,
222
- deviceVersion: parsed.deviceVersion,
237
+ device: deviceText(parsed.device, DEVICE_TEXT),
238
+ deviceId: deviceText(parsed.deviceId, DEVICE_TEXT),
239
+ deviceVersion: deviceText(parsed.deviceVersion, FIRMWARE_VERSION),
223
240
  accounts: parsed.keys.map(toParsedAccount)
224
241
  };
225
242
  }
@@ -281,10 +298,7 @@ var KeystoneUrEngine = class {
281
298
  return (0, import_bc_ur_registry_eth.generateAddressFromXpub)(xpub, relativeHdPath(relativeDerivePath));
282
299
  }
283
300
  // --- BTC (PSBT transaction signing + plain message signing) ---
284
- /**
285
- * `CryptoHDKey` always emits mainnet xpub version bytes (`0488B21E`), so `hdkey` parses it as is.
286
- * `p2tr` needs an ECC lib for BIP-341 tweaking, not wired here.
287
- */
301
+ /** `CryptoHDKey` always emits mainnet xpub version bytes (`0488B21E`), so `hdkey` parses it as is. */
288
302
  deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType) {
289
303
  const node = import_hdkey.default.fromExtendedKey(xpub).derive(relativeHdPath(relativeDerivePath));
290
304
  if (!node.publicKey) throw new Error("HDKey derivation did not produce a public key");
@@ -330,9 +344,27 @@ var KeystoneUrEngine = class {
330
344
  const ur = this.sdk.btc.generatePSBT(Buffer.from(unsignedPsbtHex, "hex"));
331
345
  return fromSdkUr(ur);
332
346
  }
333
- /** Returns the hex-encoded (possibly still-unsigned-in-part) PSBT the device replied with. */
334
- parseBtcPsbt(ur) {
335
- return this.sdk.btc.parsePSBT(toSdkUr(ur));
347
+ /**
348
+ * Returns the hex-encoded (possibly still-unsigned-in-part) PSBT the device replied with. A PSBT
349
+ * carries no request id, so the reply is bound to the request by its unsigned transaction, which
350
+ * signing never changes (BIP-174); a scan of another PSBT's signature is refused.
351
+ */
352
+ parseBtcPsbt(ur, requestPsbtHex) {
353
+ const signedPsbtHex = this.sdk.btc.parsePSBT(toSdkUr(ur));
354
+ let sameTransaction = false;
355
+ try {
356
+ const unsignedTx = (hex) => Buffer.from(bitcoin.Psbt.fromHex(hex).data.globalMap.unsignedTx.toBuffer());
357
+ sameTransaction = unsignedTx(signedPsbtHex).equals(unsignedTx(requestPsbtHex));
358
+ } catch {
359
+ sameTransaction = false;
360
+ }
361
+ if (!sameTransaction) {
362
+ throw (0, import_hwk_adapter_core.createHwkError)({
363
+ code: import_hwk_adapter_core.HardwareErrorCode.DeviceMismatch,
364
+ message: "Keystone returned a PSBT for another transaction than the one requested"
365
+ });
366
+ }
367
+ return signedPsbtHex;
336
368
  }
337
369
  buildBtcMessageSignRequest(params) {
338
370
  const ur = this.sdk.btc.generateSignRequest({
@@ -392,7 +424,7 @@ var KeystoneUrEngine = class {
392
424
  if (ur.urType !== "tron-signature") {
393
425
  throw new Error(`Expected a tron-signature UR, got ${ur.urType}`);
394
426
  }
395
- const signature = TronSignature.fromCBOR(Buffer.from(ur.urData, "hex"));
427
+ const signature = TronSignature.fromCBOR((0, import_hwk_adapter_core.boundedCborFromHex)(ur.urData));
396
428
  const requestId = signature.getRequestId();
397
429
  return {
398
430
  requestId: requestId ? (0, import_uuid.stringify)(requestId) : void 0,
@@ -436,6 +468,14 @@ function normalizePath(path) {
436
468
  const trimmed = path.trim();
437
469
  return /^m\//i.test(trimmed) ? `m/${trimmed.slice(2)}` : `m/${trimmed}`;
438
470
  }
471
+ var BIP32_HARDENED_OFFSET2 = 2147483648;
472
+ function isBip32Path(path) {
473
+ const segments = normalizePath(path).slice(2).split("/");
474
+ return segments.every((segment) => {
475
+ const match = /^(\d+)'?$/.exec(segment);
476
+ return match !== null && Number(match[1]) < BIP32_HARDENED_OFFSET2;
477
+ });
478
+ }
439
479
  function splitAccountPath(path) {
440
480
  const normalized = normalizePath(path);
441
481
  const segments = normalized.slice(2).split("/");
@@ -546,11 +586,24 @@ function keystoneCancelQueueKeys(identifiers) {
546
586
  }
547
587
 
548
588
  // src/adapter/KeystoneAdapter.ts
589
+ function keystoneBtcParamsFailure(params) {
590
+ const { coin, addressIndex, change } = params;
591
+ if (coin !== void 0 && !["btc", "bitcoin"].includes(String(coin).toLowerCase())) {
592
+ return (0, import_hwk_adapter_core3.failure)(
593
+ import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
594
+ `Keystone BTC supports Bitcoin mainnet only, not ${String(coin)}`
595
+ );
596
+ }
597
+ if (addressIndex !== void 0 || change !== void 0) {
598
+ return (0, import_hwk_adapter_core3.failure)(
599
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
600
+ "Keystone BTC takes the full address path; addressIndex and change are not supported"
601
+ );
602
+ }
603
+ return void 0;
604
+ }
549
605
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
550
606
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
551
- function resolveHardwareOperationTarget(positionalTargetId, operationId) {
552
- return (0, import_hwk_adapter_core3.resolveHardwareOperationTarget)(positionalTargetId, operationId, "keystone");
553
- }
554
607
  function keySchema(chain, path) {
555
608
  return { path, curve: chain === "sol" ? "ed25519" : "secp256k1" };
556
609
  }
@@ -559,21 +612,52 @@ function waitForKeystoneUsbReattachProbe() {
559
612
  setTimeout(resolve, KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS);
560
613
  });
561
614
  }
562
- function buildCancelledFailure(signal) {
563
- const reason = signal.reason;
564
- const code = typeof reason?.code === "number" ? reason.code : import_hwk_adapter_core3.HardwareErrorCode.UserAborted;
565
- const message = typeof reason?.message === "string" ? reason.message : "";
566
- return (0, import_hwk_adapter_core3.failure)(code, message || "All-network get-address cancelled");
567
- }
568
615
  var BIP44_COIN_TYPE_TO_CHAIN = {
569
616
  60: "evm",
570
617
  0: "btc",
571
618
  501: "sol",
572
619
  195: "tron"
573
620
  };
574
- function inferHwkChainFromPath(path) {
621
+ function hasChainCoinType(chain, path) {
575
622
  const match = normalizePath(path).match(/^m\/\d+'\/(\d+)'/);
576
- return match ? BIP44_COIN_TYPE_TO_CHAIN[Number(match[1])] : void 0;
623
+ return Boolean(match) && BIP44_COIN_TYPE_TO_CHAIN[Number(match?.[1])] === chain;
624
+ }
625
+ function exactHex(value) {
626
+ const hex = value.replace(/^0x/i, "");
627
+ return /^(?:[0-9a-f]{2})*$/i.test(hex) ? hex : void 0;
628
+ }
629
+ function invalidHexFailure(field) {
630
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${field} must be an even-length hex string`);
631
+ }
632
+ function requireExportedPath(parsed, path) {
633
+ const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
634
+ if (!account) {
635
+ throw (0, import_hwk_adapter_core3.createHwkError)({
636
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
637
+ message: `Keystone did not return the requested derivation path (${path})`
638
+ });
639
+ }
640
+ return account;
641
+ }
642
+ function coinTypeFailure(chain, path) {
643
+ if (hasChainCoinType(chain, path)) return void 0;
644
+ return (0, import_hwk_adapter_core3.failure)(
645
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
646
+ `Keystone ${chain} needs a path with its own BIP44 coin type, not ${path}`
647
+ );
648
+ }
649
+ function btcAccountFailure(accountPath) {
650
+ if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
651
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
652
+ }
653
+ function missingParamFailure(method, param) {
654
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${method} requires ${param}`);
655
+ }
656
+ function messageToHex(message, hex) {
657
+ return hex ? exactHex(message) : Buffer.from(message, "utf8").toString("hex");
658
+ }
659
+ function evmMessageSignature(sig) {
660
+ return { signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) };
577
661
  }
578
662
  var KeystoneAdapter = class _KeystoneAdapter {
579
663
  constructor(options) {
@@ -589,6 +673,15 @@ var KeystoneAdapter = class _KeystoneAdapter {
589
673
  const route = this._operationRoutes.get(operation.connectId);
590
674
  if (route?.operationId === operation.operationId) {
591
675
  this._operationRoutes.delete(operation.connectId);
676
+ if (route.connectionType === "qr") {
677
+ const ended = (0, import_hwk_adapter_core3.createHwkError)({
678
+ code: import_hwk_adapter_core3.HardwareErrorCode.OperationEnded,
679
+ message: "Keystone operation has ended",
680
+ params: { operationId: operation.operationId, reason }
681
+ });
682
+ this._jobQueue.cancelActiveAndPending(operation.operationId, ended);
683
+ this._uiRegistry.cancel(void 0, void 0, operation.operationId);
684
+ }
592
685
  }
593
686
  this.emitter.emit(import_hwk_adapter_core3.SDK.OPERATION_ENDED, {
594
687
  type: import_hwk_adapter_core3.SDK.OPERATION_ENDED,
@@ -629,18 +722,30 @@ var KeystoneAdapter = class _KeystoneAdapter {
629
722
  // All-network bundle, dispatched to the per-chain methods below.
630
723
  // ---------------------------------------------------------------------------
631
724
  this.allNetworkGetAddress = async (connectId, deviceId, params) => {
632
- const operationTarget = resolveHardwareOperationTarget(connectId, params.operationId);
725
+ const operationTarget = this._resolveOperationTarget(connectId, params.operationId);
633
726
  if (!operationTarget.success) return operationTarget;
634
727
  const effectiveConnectId = operationTarget.payload.targetId ?? "";
635
728
  const { operationId } = operationTarget.payload;
729
+ const namedWallets = new Set(
730
+ [deviceId, ...params.bundle.map((item) => item.deviceId)].filter(
731
+ (id) => typeof id === "string" && id.length > 0
732
+ )
733
+ );
734
+ if (namedWallets.size > 1) {
735
+ return (0, import_hwk_adapter_core3.failure)(
736
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
737
+ "Keystone all-network items name different wallets"
738
+ );
739
+ }
740
+ const [expectedDeviceId = ""] = namedWallets;
636
741
  let cancelScope;
637
742
  try {
638
- const prefetched = await this._prefetchAllNetworkAccounts(effectiveConnectId, deviceId, {
743
+ const prepared = await this._prepareAllNetworkBundle(effectiveConnectId, expectedDeviceId, {
639
744
  ...params,
640
745
  operationId
641
746
  });
642
- const { book } = prefetched;
643
- const itemDeviceId = deviceId || prefetched.masterFingerprint || "";
747
+ const { access } = prepared;
748
+ const itemDeviceId = expectedDeviceId || prepared.masterFingerprint || "";
644
749
  const scope = this._jobQueue.createCancelScope(
645
750
  keystoneQueueKey(effectiveConnectId, itemDeviceId)
646
751
  );
@@ -653,7 +758,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
653
758
  callItem: async ({ method, item, index }) => {
654
759
  if (scope.signal.aborted) {
655
760
  cancelledIndexes.add(index);
656
- return buildCancelledFailure(scope.signal);
761
+ return (0, import_hwk_adapter_core3.buildAllNetworkCancelledFailure)(scope.signal);
657
762
  }
658
763
  const commonArgs = {
659
764
  path: item.path,
@@ -662,20 +767,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
662
767
  };
663
768
  switch (method) {
664
769
  case "evmGetAddress":
665
- return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
770
+ return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
666
771
  case "btcGetAddress":
667
- return this.btcGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
668
- case "btcGetPublicKey":
669
- return this.btcGetPublicKey(effectiveConnectId, itemDeviceId, commonArgs, book);
772
+ case "btcGetPublicKey": {
773
+ const btcArgs = {
774
+ ...commonArgs,
775
+ coin: item.coin ?? item.network
776
+ };
777
+ return method === "btcGetAddress" ? this.btcGetAddress(effectiveConnectId, itemDeviceId, btcArgs, access) : this.btcGetPublicKey(effectiveConnectId, itemDeviceId, btcArgs, access);
778
+ }
670
779
  case "solGetAddress":
671
- return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
780
+ return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
672
781
  case "tronGetAddress":
673
- return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
674
- default:
675
- return (0, import_hwk_adapter_core3.failure)(
676
- import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
677
- `Unsupported method: ${String(method)}`
678
- );
782
+ return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
679
783
  }
680
784
  },
681
785
  attachIdentity: (context) => {
@@ -694,11 +798,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
694
798
  }
695
799
  });
696
800
  },
697
- // Cancel, refusal or a lost session ends the batch; other per-item
698
- // failures carry on with the next chain.
801
+ // Cancel, refusal, a lost connection or a safety answer (another wallet, a locked
802
+ // device) ends the batch; other per-item failures carry on with the next chain.
699
803
  shouldAbortBundle: (response, { index }) => {
700
804
  const { code } = response.payload ?? {};
701
- return cancelledIndexes.has(index) || (0, import_hwk_adapter_core3.isUserRefusal)(code) || (0, import_hwk_adapter_core3.isConnectionLost)(code);
805
+ const usbSessionLost = access?.channel === "usb" && this._resolveTarget(effectiveConnectId, itemDeviceId).record?.usbSessionId !== access.usbSessionId;
806
+ return cancelledIndexes.has(index) || usbSessionLost || (0, import_hwk_adapter_core3.isWalletSafetyFailure)(code) || (0, import_hwk_adapter_core3.isUserRefusal)(code) || (0, import_hwk_adapter_core3.isConnectionLost)(code);
702
807
  }
703
808
  });
704
809
  } catch (err) {
@@ -715,9 +820,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
715
820
  this._usbConnector?.on("device-disconnect", this._handleUsbDisconnect);
716
821
  this._usbConnector?.on("ui-event", this._handleUsbUiEvent);
717
822
  }
718
- // ---------------------------------------------------------------------------
719
- // Lifecycle / transport
720
- // ---------------------------------------------------------------------------
721
823
  get activeTransport() {
722
824
  if (this._devices.size === 0) return null;
723
825
  const hasUsbSession = Array.from(this._devices.values()).some((r) => r.usbSessionId);
@@ -747,9 +849,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
747
849
  this._devices.clear();
748
850
  this.emitter.removeAllListeners();
749
851
  }
750
- // ---------------------------------------------------------------------------
751
- // Device table
752
- // ---------------------------------------------------------------------------
753
852
  /**
754
853
  * Returns known wallets plus USB scan results; USB entries have no mfp until `connectDevice()`
755
854
  * claims them. Explicit QR discovery returns one virtual target.
@@ -822,11 +921,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
822
921
  }
823
922
  /** Best-effort disconnect; the session is retired either way so it cannot be selected again. */
824
923
  async _retireUsbSession(sessionId) {
825
- if (this._usbConnector) {
826
- try {
827
- await this._usbConnector.disconnect(sessionId);
828
- } catch {
829
- }
924
+ try {
925
+ await this._usbConnector?.disconnect(sessionId);
926
+ } catch {
830
927
  }
831
928
  this._handleUsbDisconnect({ connectId: sessionId });
832
929
  }
@@ -845,13 +942,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
845
942
  serialNumber: device.serialNumber
846
943
  }));
847
944
  }
848
- async listConnectionTargets(options) {
849
- const targets = await this.searchDeviceTargets(options);
850
- return targets.map(({ searchTargetId, ...target }) => ({
851
- ...target,
852
- targetId: searchTargetId
853
- }));
854
- }
855
945
  async connectDevice(searchTargetId) {
856
946
  const scope = this._jobQueue.createCancelScope(searchTargetId);
857
947
  try {
@@ -860,16 +950,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
860
950
  const discoveredConnectionType = this._searchDeviceTargets.get(searchTargetId);
861
951
  if (discoveredConnectionType === "qr") {
862
952
  selectedConnectionType = "qr";
863
- const abortColdStart = () => this._jobQueue.cancelActiveAndPending(
864
- KEYSTONE_COLD_START_JOB_LABEL,
865
- scope.signal.reason
953
+ connected = await _KeystoneAdapter._untilAborted(
954
+ scope.signal,
955
+ this._importFromQr({}, searchTargetId)
866
956
  );
867
- scope.signal.addEventListener("abort", abortColdStart, { once: true });
868
- try {
869
- connected = await this.importFromQr();
870
- } finally {
871
- scope.signal.removeEventListener("abort", abortColdStart);
872
- }
873
957
  } else if (discoveredConnectionType === "usb") {
874
958
  selectedConnectionType = "usb";
875
959
  if (!this._usbConnector) {
@@ -878,7 +962,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
878
962
  "No USB connector configured for this Keystone adapter"
879
963
  );
880
964
  }
881
- connected = await this._connectUsb({}, searchTargetId, scope.signal);
965
+ connected = await this._connectUsb(this._usbConnector, {}, searchTargetId, scope.signal);
882
966
  } else if ((0, import_hwk_adapter_core3.hasHardwareRuntimeIdPrefix)(searchTargetId)) {
883
967
  return (0, import_hwk_adapter_core3.failure)(
884
968
  import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
@@ -899,7 +983,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
899
983
  );
900
984
  } else {
901
985
  selectedConnectionType = "usb";
902
- connected = await this._connectUsb(target, void 0, scope.signal);
986
+ connected = await this._connectUsb(this._usbConnector, target, void 0, scope.signal);
903
987
  }
904
988
  }
905
989
  _KeystoneAdapter._throwIfAborted(scope.signal);
@@ -958,10 +1042,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
958
1042
  const { record } = this._resolveTarget(connectId, deviceId);
959
1043
  if (!record) {
960
1044
  return Promise.resolve(
961
- (0, import_hwk_adapter_core3.failure)(
962
- import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
963
- `Unknown Keystone device: ${connectId || deviceId}`
964
- )
1045
+ (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound, "Unknown Keystone device")
965
1046
  );
966
1047
  }
967
1048
  return Promise.resolve((0, import_hwk_adapter_core3.success)(toDeviceInfo(record)));
@@ -1000,6 +1081,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1000
1081
  this._uiRegistry.cancel();
1001
1082
  }
1002
1083
  }
1084
+ /**
1085
+ * Derived from the wallet's master fingerprint, which the caller already holds as deviceId; the
1086
+ * device is never asked. It names the wallet but cannot check which device is attached.
1087
+ */
1003
1088
  getChainFingerprint(connectId, deviceId, chain) {
1004
1089
  try {
1005
1090
  const target = this._resolveTarget(connectId, deviceId);
@@ -1033,18 +1118,21 @@ var KeystoneAdapter = class _KeystoneAdapter {
1033
1118
  // Explicit account import: call before signing to avoid a cold sync per call.
1034
1119
  // ---------------------------------------------------------------------------
1035
1120
  async importFromQr(options = {}) {
1121
+ return this._importFromQr(options, KEYSTONE_COLD_START_JOB_LABEL);
1122
+ }
1123
+ async _importFromQr(options, jobKey) {
1036
1124
  try {
1037
- return await this._jobQueue.enqueue(KEYSTONE_COLD_START_JOB_LABEL, async (signal) => {
1125
+ return await this._jobQueue.enqueue(jobKey, async (signal) => {
1038
1126
  const displayDevice = placeholderDeviceInfo();
1039
1127
  let responseUr;
1040
1128
  if (options.mode === "scan") {
1041
- responseUr = await this._requestQrScanAndAwaitResponse(displayDevice, signal);
1129
+ responseUr = await this._requestQrAndAwaitResponse(displayDevice, void 0, signal);
1042
1130
  } else {
1043
1131
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1044
1132
  schemas: [keySchema("evm", KEYSTONE_COLD_START_PATH)],
1045
1133
  origin: this._origin
1046
1134
  });
1047
- responseUr = await this._requestQrDisplayAndAwaitResponse(
1135
+ responseUr = await this._requestQrAndAwaitResponse(
1048
1136
  displayDevice,
1049
1137
  { ...requestUr, animated: false },
1050
1138
  signal
@@ -1052,6 +1140,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1052
1140
  }
1053
1141
  _KeystoneAdapter._throwIfAborted(signal);
1054
1142
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1143
+ if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1055
1144
  const record = this._upsertDeviceRecord(parsed);
1056
1145
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
1057
1146
  });
@@ -1059,161 +1148,105 @@ var KeystoneAdapter = class _KeystoneAdapter {
1059
1148
  return this._errorToFailure(err);
1060
1149
  }
1061
1150
  }
1062
- // ---------------------------------------------------------------------------
1063
- // EVM
1064
- // ---------------------------------------------------------------------------
1065
- async evmGetAddress(connectIdArg, deviceIdArg, params, book) {
1066
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1067
- if (!operationTarget.success) return operationTarget;
1068
- const connectId = operationTarget.payload.targetId;
1069
- const deviceId = deviceIdArg ?? void 0;
1070
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmGetAddress requires params");
1071
- if (!params.path)
1072
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmGetAddress requires params.path");
1073
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1074
- if (!relativeDerivePath) {
1075
- return (0, import_hwk_adapter_core3.failure)(
1076
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1077
- "evmGetAddress requires a full leaf path, e.g. m/44'/60'/0'/0/0"
1078
- );
1079
- }
1080
- return this._runJob(connectId, deviceId, async (signal) => {
1081
- const xpub = await this._fetchAccountXpub(
1082
- connectId,
1083
- deviceId,
1084
- "evm",
1085
- accountPath,
1086
- signal,
1087
- book
1088
- );
1089
- const address = this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath);
1090
- return (0, import_hwk_adapter_core3.success)({ address, path: normalizePath(params.path) });
1091
- });
1151
+ async evmGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1152
+ const call = this._beginCall("evmGetAddress", connectIdArg, deviceIdArg, paramsArg);
1153
+ if (!call.success) return call;
1154
+ const { params } = call.payload;
1155
+ if (!params.path) return missingParamFailure("evmGetAddress", "params.path");
1156
+ const evmCoinTypeFailure = coinTypeFailure("evm", params.path);
1157
+ if (evmCoinTypeFailure) return evmCoinTypeFailure;
1158
+ return this._addressFromAccountXpub(
1159
+ "evmGetAddress",
1160
+ "evm",
1161
+ call.payload,
1162
+ params.path,
1163
+ "m/44'/60'/0'/0/0",
1164
+ bundle,
1165
+ (xpub, relativeDerivePath) => this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath)
1166
+ );
1092
1167
  }
1093
- async evmSignTransaction(connectIdArg, deviceIdArg, params) {
1094
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1095
- if (!operationTarget.success) return operationTarget;
1096
- const connectId = operationTarget.payload.targetId;
1097
- const deviceId = deviceIdArg ?? void 0;
1098
- if (!params)
1099
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTransaction requires params");
1100
- if (!params.path) {
1101
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTransaction requires params.path");
1102
- }
1168
+ async evmSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1169
+ const call = this._beginCall("evmSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1170
+ if (!call.success) return call;
1171
+ const { params } = call.payload;
1172
+ if (!params.path) return missingParamFailure("evmSignTransaction", "params.path");
1103
1173
  if (!("serializedTx" in params) || typeof params.serializedTx !== "string" || !params.serializedTx) {
1104
1174
  return (0, import_hwk_adapter_core3.failure)(
1105
1175
  import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1106
1176
  "Keystone only signs a fully RLP-serialized transaction (params.serializedTx) \u2014 structured-field signing is not supported"
1107
1177
  );
1108
1178
  }
1109
- const rawTxHex = (0, import_hwk_adapter_core3.stripHex)(params.serializedTx);
1110
- const path = normalizePath(params.path);
1179
+ const rawTxHex = exactHex(params.serializedTx);
1180
+ if (rawTxHex === void 0) return invalidHexFailure("serializedTx");
1111
1181
  const dataType = parseInt(rawTxHex.slice(0, 2), 16) < 192 ? "typedTransaction" : "transaction";
1112
- return this._signWithWallet({
1113
- connectId,
1114
- deviceId,
1115
- chain: "evm",
1116
- operationName: "evmSignTransaction",
1117
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1118
- requestId,
1119
- unsignedTxHex: rawTxHex,
1120
- dataType,
1121
- path,
1122
- xfp,
1123
- chainId: params.chainId,
1124
- origin: this._origin
1125
- }),
1126
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1127
- toPayload: (sig) => ({
1128
- v: (0, import_hwk_adapter_core3.ensure0x)(sig.v),
1129
- r: (0, import_hwk_adapter_core3.ensure0x)(sig.r),
1130
- s: (0, import_hwk_adapter_core3.ensure0x)(sig.s)
1131
- })
1132
- });
1182
+ return this._evmSign(
1183
+ "evmSignTransaction",
1184
+ call.payload,
1185
+ params.path,
1186
+ params.chainId,
1187
+ rawTxHex,
1188
+ dataType,
1189
+ (sig) => ({ v: (0, import_hwk_adapter_core3.ensure0x)(sig.v), r: (0, import_hwk_adapter_core3.ensure0x)(sig.r), s: (0, import_hwk_adapter_core3.ensure0x)(sig.s) })
1190
+ );
1133
1191
  }
1134
- async evmSignMessage(connectIdArg, deviceIdArg, params) {
1135
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1136
- if (!operationTarget.success) return operationTarget;
1137
- const connectId = operationTarget.payload.targetId;
1138
- const deviceId = deviceIdArg ?? void 0;
1139
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignMessage requires params");
1192
+ async evmSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1193
+ const call = this._beginCall("evmSignMessage", connectIdArg, deviceIdArg, paramsArg);
1194
+ if (!call.success) return call;
1195
+ const { params } = call.payload;
1140
1196
  if (!params.path || params.message === void 0) {
1141
- return (0, import_hwk_adapter_core3.failure)(
1142
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1143
- "evmSignMessage requires params.path and params.message"
1144
- );
1145
- }
1146
- const messageHex = params.hex ? (0, import_hwk_adapter_core3.stripHex)(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1147
- const path = normalizePath(params.path);
1148
- return this._signWithWallet({
1149
- connectId,
1150
- deviceId,
1151
- chain: "evm",
1152
- operationName: "evmSignMessage",
1153
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1154
- requestId,
1155
- unsignedTxHex: messageHex,
1156
- dataType: "personalMessage",
1157
- path,
1158
- xfp,
1159
- chainId: params.chainId,
1160
- origin: this._origin
1161
- }),
1162
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1163
- toPayload: (sig) => ({ signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) })
1164
- });
1197
+ return missingParamFailure("evmSignMessage", "params.path and params.message");
1198
+ }
1199
+ const messageHex = messageToHex(params.message, params.hex);
1200
+ if (messageHex === void 0) return invalidHexFailure("message");
1201
+ return this._evmSign(
1202
+ "evmSignMessage",
1203
+ call.payload,
1204
+ params.path,
1205
+ params.chainId,
1206
+ messageHex,
1207
+ "personalMessage",
1208
+ evmMessageSignature
1209
+ );
1165
1210
  }
1166
- async evmSignTypedData(connectIdArg, deviceIdArg, params) {
1167
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1168
- if (!operationTarget.success) return operationTarget;
1169
- const connectId = operationTarget.payload.targetId;
1170
- const deviceId = deviceIdArg ?? void 0;
1171
- if (!params)
1172
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTypedData requires params");
1173
- if (!params.path) {
1174
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTypedData requires params.path");
1175
- }
1211
+ async evmSignTypedData(connectIdArg, deviceIdArg, paramsArg) {
1212
+ const call = this._beginCall("evmSignTypedData", connectIdArg, deviceIdArg, paramsArg);
1213
+ if (!call.success) return call;
1214
+ const { params } = call.payload;
1215
+ if (!params.path) return missingParamFailure("evmSignTypedData", "params.path");
1176
1216
  if (params.mode === "hash") {
1177
1217
  return (0, import_hwk_adapter_core3.failure)(
1178
1218
  import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1179
1219
  "Keystone always displays the full EIP-712 payload for on-device review \u2014 pre-hashed signing is not supported"
1180
1220
  );
1181
1221
  }
1182
- const signDataHex = Buffer.from(
1183
- params.dataJson ?? JSON.stringify(params.data),
1184
- "utf8"
1185
- ).toString("hex");
1186
- const path = normalizePath(params.path);
1187
- return this._signWithWallet({
1188
- connectId,
1189
- deviceId,
1190
- chain: "evm",
1191
- operationName: "evmSignTypedData",
1192
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1193
- requestId,
1194
- unsignedTxHex: signDataHex,
1195
- dataType: "typedData",
1196
- path,
1197
- xfp,
1198
- chainId: params.chainId,
1199
- origin: this._origin
1200
- }),
1201
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1202
- toPayload: (sig) => ({ signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) })
1203
- });
1222
+ if (typeof params.dataJson !== "string" || !params.dataJson) {
1223
+ return (0, import_hwk_adapter_core3.failure)(
1224
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1225
+ "Keystone evmSignTypedData requires params.dataJson, the original typed-data JSON text"
1226
+ );
1227
+ }
1228
+ const signDataHex = Buffer.from(params.dataJson, "utf8").toString("hex");
1229
+ return this._evmSign(
1230
+ "evmSignTypedData",
1231
+ call.payload,
1232
+ params.path,
1233
+ params.chainId,
1234
+ signDataHex,
1235
+ "typedData",
1236
+ evmMessageSignature
1237
+ );
1204
1238
  }
1205
1239
  // ---------------------------------------------------------------------------
1206
1240
  // BTC: 44'/49'/84' addresses derive offline from the account xpub; P2TR addresses
1207
1241
  // and structured-field tx signing are unsupported (the host builds a PSBT instead).
1208
1242
  // ---------------------------------------------------------------------------
1209
- async btcGetAddress(connectIdArg, deviceIdArg, params, book) {
1210
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1211
- if (!operationTarget.success) return operationTarget;
1212
- const connectId = operationTarget.payload.targetId;
1213
- const deviceId = deviceIdArg ?? void 0;
1214
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetAddress requires params");
1215
- if (!params.path)
1216
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetAddress requires params.path");
1243
+ async btcGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1244
+ const call = this._beginCall("btcGetAddress", connectIdArg, deviceIdArg, paramsArg);
1245
+ if (!call.success) return call;
1246
+ const { params } = call.payload;
1247
+ if (!params.path) return missingParamFailure("btcGetAddress", "params.path");
1248
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1249
+ if (btcParamsFailure) return btcParamsFailure;
1217
1250
  const scriptType = btcScriptTypeFromPath(params.path);
1218
1251
  if (!scriptType) {
1219
1252
  return (0, import_hwk_adapter_core3.failure)(
@@ -1227,42 +1260,27 @@ var KeystoneAdapter = class _KeystoneAdapter {
1227
1260
  "P2TR (purpose 86') needs an elliptic-curve library for BIP-341 tweaking, not yet wired in \u2014 44'/49'/84' work"
1228
1261
  );
1229
1262
  }
1230
- const normalizedPath = normalizePath(params.path);
1231
- const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1232
- if (!relativeDerivePath) {
1233
- return (0, import_hwk_adapter_core3.failure)(
1234
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1235
- "btcGetAddress requires a full leaf path, e.g. m/84'/0'/0'/0/0"
1236
- );
1237
- }
1238
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1239
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1240
- }
1241
- return this._runJob(connectId, deviceId, async (signal) => {
1242
- const xpub = await this._fetchAccountXpub(
1243
- connectId,
1244
- deviceId,
1245
- "btc",
1246
- accountPath,
1247
- signal,
1248
- book
1249
- );
1250
- const address = this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType);
1251
- return (0, import_hwk_adapter_core3.success)({ address, path: normalizedPath });
1252
- });
1263
+ return this._addressFromAccountXpub(
1264
+ "btcGetAddress",
1265
+ "btc",
1266
+ call.payload,
1267
+ params.path,
1268
+ "m/84'/0'/0'/0/0",
1269
+ bundle,
1270
+ (xpub, relativeDerivePath) => this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType)
1271
+ );
1253
1272
  }
1254
1273
  /**
1255
1274
  * `params.path` must be an account path (`m/84'/0'/0'`), the level Keystone syncs. An xpub is
1256
1275
  * script-type agnostic, so `86'` works here even though `btcGetAddress` rejects it.
1257
1276
  */
1258
- async btcGetPublicKey(connectIdArg, deviceIdArg, params, book) {
1259
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1260
- if (!operationTarget.success) return operationTarget;
1261
- const connectId = operationTarget.payload.targetId;
1262
- const deviceId = deviceIdArg ?? void 0;
1263
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params");
1264
- if (!params.path)
1265
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params.path");
1277
+ async btcGetPublicKey(connectIdArg, deviceIdArg, paramsArg, bundle) {
1278
+ const call = this._beginCall("btcGetPublicKey", connectIdArg, deviceIdArg, paramsArg);
1279
+ if (!call.success) return call;
1280
+ const { connectId, deviceId, params } = call.payload;
1281
+ if (!params.path) return missingParamFailure("btcGetPublicKey", "params.path");
1282
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1283
+ if (btcParamsFailure) return btcParamsFailure;
1266
1284
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1267
1285
  if (relativeDerivePath) {
1268
1286
  return (0, import_hwk_adapter_core3.failure)(
@@ -1270,9 +1288,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1270
1288
  "btcGetPublicKey requires an account path, e.g. m/84'/0'/0' (not a leaf path)"
1271
1289
  );
1272
1290
  }
1273
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1274
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1275
- }
1291
+ const accountFailure = btcAccountFailure(accountPath);
1292
+ if (accountFailure) return accountFailure;
1276
1293
  return this._runJob(connectId, deviceId, async (signal) => {
1277
1294
  const xpub = await this._fetchAccountXpub(
1278
1295
  connectId,
@@ -1280,7 +1297,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1280
1297
  "btc",
1281
1298
  accountPath,
1282
1299
  signal,
1283
- book
1300
+ bundle
1284
1301
  );
1285
1302
  const meta = this.urEngine.parseXpubMeta(xpub);
1286
1303
  return (0, import_hwk_adapter_core3.success)({
@@ -1289,7 +1306,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1289
1306
  chainCode: meta.chainCode,
1290
1307
  depth: meta.depth,
1291
1308
  fingerprint: meta.parentFingerprint,
1292
- path: normalizePath(accountPath)
1309
+ path: normalizePath(accountPath),
1310
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1293
1311
  });
1294
1312
  });
1295
1313
  }
@@ -1299,23 +1317,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1299
1317
  "use btcSignPsbt \u2014 structured input/output signing needs host-side PSBT construction, not yet wired in"
1300
1318
  );
1301
1319
  }
1302
- async btcSignPsbt(connectIdArg, deviceIdArg, params) {
1303
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1304
- if (!operationTarget.success) return operationTarget;
1305
- const connectId = operationTarget.payload.targetId;
1306
- const deviceId = deviceIdArg ?? void 0;
1307
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignPsbt requires params");
1308
- if (!params.psbt)
1309
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.psbt");
1310
- if (!params.path)
1311
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.path");
1312
- if (!isKeystoneSignableBtcAccountPath(splitAccountPath(params.path).accountPath)) {
1313
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1314
- }
1320
+ async btcSignPsbt(connectIdArg, deviceIdArg, paramsArg) {
1321
+ const call = this._beginCall("btcSignPsbt", connectIdArg, deviceIdArg, paramsArg);
1322
+ if (!call.success) return call;
1323
+ const { connectId, deviceId, params } = call.payload;
1324
+ if (!params.psbt) return missingParamFailure("btcSignPsbt", "params.psbt");
1325
+ if (!params.path) return missingParamFailure("btcSignPsbt", "params.path");
1326
+ const accountFailure = btcAccountFailure(splitAccountPath(params.path).accountPath);
1327
+ if (accountFailure) return accountFailure;
1328
+ const requestPsbtHex = exactHex(params.psbt);
1329
+ if (requestPsbtHex === void 0) return invalidHexFailure("psbt");
1315
1330
  return this._runJob(connectId, deviceId, async (signal) => {
1316
1331
  const { record } = await this._ensureWalletKnown(connectId, deviceId, "btc", signal);
1317
1332
  _KeystoneAdapter._throwIfAborted(signal);
1318
- const requestUr = this.urEngine.buildBtcPsbtRequest((0, import_hwk_adapter_core3.stripHex)(params.psbt));
1333
+ const requestUr = this.urEngine.buildBtcPsbtRequest(requestPsbtHex);
1319
1334
  const responseUr = await this._resolveUr(
1320
1335
  record,
1321
1336
  requestUr,
@@ -1325,30 +1340,26 @@ var KeystoneAdapter = class _KeystoneAdapter {
1325
1340
  "btcSignPsbt"
1326
1341
  );
1327
1342
  _KeystoneAdapter._throwIfAborted(signal);
1328
- const signedPsbt = this.urEngine.parseBtcPsbt(responseUr);
1343
+ const signedPsbt = this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex);
1329
1344
  return (0, import_hwk_adapter_core3.success)({ signedPsbt });
1330
1345
  });
1331
1346
  }
1332
- async btcSignMessage(connectIdArg, deviceIdArg, params) {
1333
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1334
- if (!operationTarget.success) return operationTarget;
1335
- const connectId = operationTarget.payload.targetId;
1336
- const deviceId = deviceIdArg ?? void 0;
1337
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignMessage requires params");
1347
+ async btcSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1348
+ const call = this._beginCall("btcSignMessage", connectIdArg, deviceIdArg, paramsArg);
1349
+ if (!call.success) return call;
1350
+ const { connectId, deviceId, params } = call.payload;
1338
1351
  if (!params.path || params.message === void 0) {
1339
- return (0, import_hwk_adapter_core3.failure)(
1340
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1341
- "btcSignMessage requires params.path and params.message"
1342
- );
1352
+ return missingParamFailure("btcSignMessage", "params.path and params.message");
1343
1353
  }
1344
- const messageHex = params.hex ? (0, import_hwk_adapter_core3.stripHex)(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1354
+ const messageHex = messageToHex(params.message, params.hex);
1355
+ if (messageHex === void 0) return invalidHexFailure("message");
1345
1356
  const path = normalizePath(params.path);
1346
- if (!isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1347
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1348
- }
1357
+ const accountFailure = btcAccountFailure(splitAccountPath(path).accountPath);
1358
+ if (accountFailure) return accountFailure;
1349
1359
  return this._signWithWallet({
1350
1360
  connectId,
1351
1361
  deviceId,
1362
+ path,
1352
1363
  chain: "btc",
1353
1364
  operationName: "btcSignMessage",
1354
1365
  buildRequest: (requestId, xfp) => this.urEngine.buildBtcMessageSignRequest({
@@ -1361,8 +1372,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1361
1372
  toPayload: (sig) => ({ signature: sig.signature })
1362
1373
  });
1363
1374
  }
1375
+ /**
1376
+ * Returns the known master fingerprint for the named wallet without asking the device (a QR
1377
+ * round trip only to repeat it would cost a scan). Use it to name the wallet, for example as a
1378
+ * PSBT xfp, which the device itself checks when signing; it cannot check the attached device.
1379
+ */
1364
1380
  async btcGetMasterFingerprint(connectIdArg, deviceIdArg, paramsArg) {
1365
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, paramsArg?.operationId);
1381
+ const operationTarget = this._resolveOperationTarget(connectIdArg, paramsArg?.operationId);
1366
1382
  if (!operationTarget.success) return operationTarget;
1367
1383
  const connectId = operationTarget.payload.targetId;
1368
1384
  const deviceId = deviceIdArg ?? void 0;
@@ -1371,193 +1387,242 @@ var KeystoneAdapter = class _KeystoneAdapter {
1371
1387
  return (0, import_hwk_adapter_core3.success)({ masterFingerprint: record.masterFingerprint });
1372
1388
  });
1373
1389
  }
1374
- // ---------------------------------------------------------------------------
1375
- // SOL
1376
- // ---------------------------------------------------------------------------
1377
- async solGetAddress(connectIdArg, deviceIdArg, params, book) {
1378
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1379
- if (!operationTarget.success) return operationTarget;
1380
- const connectId = operationTarget.payload.targetId;
1381
- const deviceId = deviceIdArg ?? void 0;
1382
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solGetAddress requires params");
1383
- if (!params.path)
1384
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solGetAddress requires params.path");
1390
+ async solGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1391
+ const call = this._beginCall("solGetAddress", connectIdArg, deviceIdArg, paramsArg);
1392
+ if (!call.success) return call;
1393
+ const { connectId, deviceId, params } = call.payload;
1394
+ if (!params.path) return missingParamFailure("solGetAddress", "params.path");
1395
+ const solCoinTypeFailure = coinTypeFailure("sol", params.path);
1396
+ if (solCoinTypeFailure) return solCoinTypeFailure;
1385
1397
  const path = normalizePath(params.path);
1386
- return this._runJob(connectId, deviceId, async (signal) => {
1387
- const { account } = await this._fetchAccount(connectId, deviceId, "sol", path, signal, book);
1388
- _KeystoneAdapter._throwIfAborted(signal);
1389
- const address = import_bs58.default.encode(Buffer.from(account.publicKey, "hex"));
1390
- return (0, import_hwk_adapter_core3.success)({ address, path });
1391
- });
1392
- }
1393
- async solSignTransaction(connectIdArg, deviceIdArg, params) {
1394
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1395
- if (!operationTarget.success) return operationTarget;
1396
- const connectId = operationTarget.payload.targetId;
1397
- const deviceId = deviceIdArg ?? void 0;
1398
- if (!params)
1399
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solSignTransaction requires params");
1400
- if (!params.path || !params.serializedTx) {
1398
+ if (!/^m(\/\d+')+$/.test(path)) {
1401
1399
  return (0, import_hwk_adapter_core3.failure)(
1402
1400
  import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1403
- "solSignTransaction requires params.path and params.serializedTx"
1401
+ "solGetAddress requires a fully hardened path, e.g. m/44'/501'/0'/0'"
1404
1402
  );
1405
1403
  }
1406
- const path = normalizePath(params.path);
1407
- return this._signWithWallet({
1408
- connectId,
1409
- deviceId,
1410
- chain: "sol",
1411
- operationName: "solSignTransaction",
1412
- buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1413
- requestId,
1414
- unsignedPayloadHex: (0, import_hwk_adapter_core3.stripHex)(params.serializedTx),
1415
- dataType: "transaction",
1404
+ return this._runJob(connectId, deviceId, async (signal) => {
1405
+ const { account } = await this._fetchAccount(
1406
+ connectId,
1407
+ deviceId,
1408
+ "sol",
1416
1409
  path,
1417
- xfp,
1418
- origin: this._origin
1419
- }),
1420
- parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1421
- toPayload: (sig) => ({ signature: sig.signature })
1410
+ signal,
1411
+ bundle
1412
+ );
1413
+ _KeystoneAdapter._throwIfAborted(signal);
1414
+ if (!/^[0-9a-f]{64}$/i.test(account.publicKey)) {
1415
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1416
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1417
+ message: "Keystone returned a Solana key that is not a 32-byte Ed25519 public key"
1418
+ });
1419
+ }
1420
+ const address = import_bs58.default.encode(Buffer.from(account.publicKey, "hex"));
1421
+ return (0, import_hwk_adapter_core3.success)({
1422
+ address,
1423
+ path,
1424
+ accountKey: { path, publicKey: account.publicKey }
1425
+ });
1422
1426
  });
1423
1427
  }
1424
- async solSignMessage(connectIdArg, deviceIdArg, params) {
1425
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1426
- if (!operationTarget.success) return operationTarget;
1427
- const connectId = operationTarget.payload.targetId;
1428
- const deviceId = deviceIdArg ?? void 0;
1429
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solSignMessage requires params");
1428
+ async solSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1429
+ const call = this._beginCall("solSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1430
+ if (!call.success) return call;
1431
+ const { params } = call.payload;
1432
+ if (!params.path || !params.serializedTx) {
1433
+ return missingParamFailure("solSignTransaction", "params.path and params.serializedTx");
1434
+ }
1435
+ const unsignedPayloadHex = exactHex(params.serializedTx);
1436
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("serializedTx");
1437
+ return this._solSign(
1438
+ "solSignTransaction",
1439
+ call.payload,
1440
+ params.path,
1441
+ unsignedPayloadHex,
1442
+ "transaction"
1443
+ );
1444
+ }
1445
+ async solSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1446
+ const call = this._beginCall("solSignMessage", connectIdArg, deviceIdArg, paramsArg);
1447
+ if (!call.success) return call;
1448
+ const { params } = call.payload;
1430
1449
  if (!params.path || !params.message) {
1450
+ return missingParamFailure("solSignMessage", "params.path and params.message");
1451
+ }
1452
+ if (params.messageVersion !== void 0) {
1431
1453
  return (0, import_hwk_adapter_core3.failure)(
1432
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1433
- "solSignMessage requires params.path and params.message"
1454
+ import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1455
+ "Keystone signs Solana messages as raw bytes only; off-chain message format is not supported"
1434
1456
  );
1435
1457
  }
1436
- const path = normalizePath(params.path);
1437
- return this._signWithWallet({
1438
- connectId,
1439
- deviceId,
1440
- chain: "sol",
1441
- operationName: "solSignMessage",
1442
- buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1443
- requestId,
1444
- unsignedPayloadHex: (0, import_hwk_adapter_core3.stripHex)(params.message),
1445
- dataType: "message",
1446
- path,
1447
- xfp,
1448
- origin: this._origin
1449
- }),
1450
- parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1451
- toPayload: (sig) => ({ signature: sig.signature })
1452
- });
1458
+ const unsignedPayloadHex = exactHex(params.message);
1459
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("message");
1460
+ return this._solSign(
1461
+ "solSignMessage",
1462
+ call.payload,
1463
+ params.path,
1464
+ unsignedPayloadHex,
1465
+ "message"
1466
+ );
1453
1467
  }
1454
1468
  // ---------------------------------------------------------------------------
1455
1469
  // TRON: keystone-sdk-rust layout (tags 5201/5202, firmware >= 2.5.0), not sdk.tron's
1456
1470
  // protobuf module; OneKey Pro's encoding under the same tag is rejected by the firmware.
1457
1471
  // ---------------------------------------------------------------------------
1458
- async tronGetAddress(connectIdArg, deviceIdArg, params, book) {
1459
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1472
+ async tronGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1473
+ const call = this._beginCall("tronGetAddress", connectIdArg, deviceIdArg, paramsArg);
1474
+ if (!call.success) return call;
1475
+ const { params } = call.payload;
1476
+ if (!params.path) return missingParamFailure("tronGetAddress", "params.path");
1477
+ const tronCoinTypeFailure = coinTypeFailure("tron", params.path);
1478
+ if (tronCoinTypeFailure) return tronCoinTypeFailure;
1479
+ return this._addressFromAccountXpub(
1480
+ "tronGetAddress",
1481
+ "tron",
1482
+ call.payload,
1483
+ params.path,
1484
+ "m/44'/195'/0'/0/0",
1485
+ bundle,
1486
+ (xpub, relativeDerivePath) => this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath)
1487
+ );
1488
+ }
1489
+ async tronSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1490
+ const call = this._beginCall("tronSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1491
+ if (!call.success) return call;
1492
+ const { params } = call.payload;
1493
+ if (!params.path) return missingParamFailure("tronSignTransaction", "params.path");
1494
+ if (!params.rawTxHex) {
1495
+ return (0, import_hwk_adapter_core3.failure)(
1496
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1497
+ "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1498
+ );
1499
+ }
1500
+ const rawTxHex = exactHex(params.rawTxHex);
1501
+ if (rawTxHex === void 0) return invalidHexFailure("rawTxHex");
1502
+ return this._tronSign("tronSignTransaction", call.payload, params.path, rawTxHex);
1503
+ }
1504
+ async tronSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1505
+ const call = this._beginCall("tronSignMessage", connectIdArg, deviceIdArg, paramsArg);
1506
+ if (!call.success) return call;
1507
+ const { params } = call.payload;
1508
+ if (!params.path) return missingParamFailure("tronSignMessage", "params.path");
1509
+ if (!params.messageHex) return missingParamFailure("tronSignMessage", "params.messageHex");
1510
+ if (params.messageType !== "V2") {
1511
+ return (0, import_hwk_adapter_core3.failure)(
1512
+ import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1513
+ 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1514
+ );
1515
+ }
1516
+ const messageHex = exactHex(params.messageHex);
1517
+ if (messageHex === void 0) return invalidHexFailure("messageHex");
1518
+ return this._tronSign(
1519
+ "tronSignMessage",
1520
+ call.payload,
1521
+ params.path,
1522
+ messageHex,
1523
+ 2 /* PersonalMessage */
1524
+ );
1525
+ }
1526
+ /** Resolves the call's target and requires params, before any method-specific check. */
1527
+ _beginCall(method, connectIdArg, deviceIdArg, params) {
1528
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1460
1529
  if (!operationTarget.success) return operationTarget;
1461
- const connectId = operationTarget.payload.targetId;
1462
- const deviceId = deviceIdArg ?? void 0;
1463
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronGetAddress requires params");
1464
- if (!params.path)
1465
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronGetAddress requires params.path");
1466
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1530
+ if (!params) return missingParamFailure(method, "params");
1531
+ return (0, import_hwk_adapter_core3.success)({
1532
+ connectId: operationTarget.payload.targetId,
1533
+ deviceId: deviceIdArg ?? void 0,
1534
+ params
1535
+ });
1536
+ }
1537
+ /** Derives a leaf address offline from its account xpub. */
1538
+ async _addressFromAccountXpub(method, chain, { connectId, deviceId }, path, leafExample, bundle, derive) {
1539
+ const normalizedPath = normalizePath(path);
1540
+ const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1467
1541
  if (!relativeDerivePath) {
1468
1542
  return (0, import_hwk_adapter_core3.failure)(
1469
1543
  import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1470
- "tronGetAddress requires a full leaf path, e.g. m/44'/195'/0'/0/0"
1544
+ `${method} requires a full leaf path, e.g. ${leafExample}`
1471
1545
  );
1472
1546
  }
1547
+ const accountFailure = chain === "btc" ? btcAccountFailure(accountPath) : void 0;
1548
+ if (accountFailure) return accountFailure;
1473
1549
  return this._runJob(connectId, deviceId, async (signal) => {
1474
1550
  const xpub = await this._fetchAccountXpub(
1475
1551
  connectId,
1476
1552
  deviceId,
1477
- "tron",
1553
+ chain,
1478
1554
  accountPath,
1479
1555
  signal,
1480
- book
1556
+ bundle
1481
1557
  );
1482
- const address = this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath);
1483
- return (0, import_hwk_adapter_core3.success)({ address, path: normalizePath(params.path) });
1558
+ return (0, import_hwk_adapter_core3.success)({
1559
+ address: derive(xpub, relativeDerivePath),
1560
+ path: normalizedPath,
1561
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1562
+ });
1484
1563
  });
1485
1564
  }
1486
- async tronSignTransaction(connectIdArg, deviceIdArg, params) {
1487
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1488
- if (!operationTarget.success) return operationTarget;
1489
- const connectId = operationTarget.payload.targetId;
1490
- const deviceId = deviceIdArg ?? void 0;
1491
- if (!params)
1492
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignTransaction requires params");
1493
- if (!params.path) {
1494
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignTransaction requires params.path");
1495
- }
1496
- if (!params.rawTxHex) {
1497
- return (0, import_hwk_adapter_core3.failure)(
1498
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1499
- "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1500
- );
1501
- }
1502
- const rawTxHex = (0, import_hwk_adapter_core3.stripHex)(params.rawTxHex);
1503
- const path = normalizePath(params.path);
1565
+ _evmSign(method, target, rawPath, chainId, signDataHex, dataType, toPayload) {
1566
+ const path = normalizePath(rawPath);
1504
1567
  return this._signWithWallet({
1505
- connectId,
1506
- deviceId,
1507
- chain: "tron",
1508
- operationName: "tronSignTransaction",
1509
- buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1568
+ connectId: target.connectId,
1569
+ deviceId: target.deviceId,
1570
+ path,
1571
+ chain: "evm",
1572
+ operationName: method,
1573
+ buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1510
1574
  requestId,
1511
- rawTxHex,
1575
+ unsignedTxHex: signDataHex,
1576
+ dataType,
1512
1577
  path,
1513
1578
  xfp,
1579
+ chainId,
1514
1580
  origin: this._origin
1515
1581
  }),
1516
- parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1517
- // Keystone signs rawTxHex as given and returns only the signature, so no serializedTx.
1582
+ parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1583
+ toPayload
1584
+ });
1585
+ }
1586
+ _solSign(method, target, rawPath, unsignedPayloadHex, dataType) {
1587
+ const path = normalizePath(rawPath);
1588
+ return this._signWithWallet({
1589
+ connectId: target.connectId,
1590
+ deviceId: target.deviceId,
1591
+ path,
1592
+ chain: "sol",
1593
+ operationName: method,
1594
+ buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1595
+ requestId,
1596
+ unsignedPayloadHex,
1597
+ dataType,
1598
+ path,
1599
+ xfp,
1600
+ origin: this._origin
1601
+ }),
1602
+ parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1518
1603
  toPayload: (sig) => ({ signature: sig.signature })
1519
1604
  });
1520
1605
  }
1521
- async tronSignMessage(connectIdArg, deviceIdArg, params) {
1522
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1523
- if (!operationTarget.success) return operationTarget;
1524
- const connectId = operationTarget.payload.targetId;
1525
- const deviceId = deviceIdArg ?? void 0;
1526
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignMessage requires params");
1527
- if (!params.path) {
1528
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignMessage requires params.path");
1529
- }
1530
- if (!params.messageHex) {
1531
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignMessage requires params.messageHex");
1532
- }
1533
- if (params.messageType !== "V2") {
1534
- return (0, import_hwk_adapter_core3.failure)(
1535
- import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1536
- 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1537
- );
1538
- }
1539
- const messageHex = (0, import_hwk_adapter_core3.stripHex)(params.messageHex);
1540
- const path = normalizePath(params.path);
1606
+ _tronSign(method, target, rawPath, signDataHex, signType) {
1607
+ const path = normalizePath(rawPath);
1541
1608
  return this._signWithWallet({
1542
- connectId,
1543
- deviceId,
1609
+ connectId: target.connectId,
1610
+ deviceId: target.deviceId,
1611
+ path,
1544
1612
  chain: "tron",
1545
- operationName: "tronSignMessage",
1613
+ operationName: method,
1546
1614
  buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1547
1615
  requestId,
1548
- rawTxHex: messageHex,
1616
+ rawTxHex: signDataHex,
1549
1617
  path,
1550
1618
  xfp,
1551
- signType: 2 /* PersonalMessage */,
1619
+ signType,
1552
1620
  origin: this._origin
1553
1621
  }),
1554
1622
  parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1555
1623
  toPayload: (sig) => ({ signature: sig.signature })
1556
1624
  });
1557
1625
  }
1558
- // ---------------------------------------------------------------------------
1559
- // Internals
1560
- // ---------------------------------------------------------------------------
1561
1626
  async _runJob(connectId, deviceId, job) {
1562
1627
  try {
1563
1628
  return await this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), job);
@@ -1565,14 +1630,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1565
1630
  return this._errorToFailure(err);
1566
1631
  }
1567
1632
  }
1568
- async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, book) {
1633
+ async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, bundle) {
1569
1634
  const { account } = await this._fetchAccount(
1570
1635
  connectId,
1571
1636
  deviceId,
1572
1637
  hwkChain,
1573
1638
  accountPath,
1574
1639
  signal,
1575
- book
1640
+ bundle
1576
1641
  );
1577
1642
  _KeystoneAdapter._throwIfAborted(signal);
1578
1643
  if (!account.extendedPublicKey) {
@@ -1581,14 +1646,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
1581
1646
  message: "Keystone did not return an extended public key for this account path"
1582
1647
  });
1583
1648
  }
1649
+ const { publicKey } = this.urEngine.parseXpubMeta(account.extendedPublicKey);
1650
+ if (!/^0[23]/.test(publicKey)) {
1651
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1652
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1653
+ message: "Keystone returned an account key that is not a public key"
1654
+ });
1655
+ }
1584
1656
  return account.extendedPublicKey;
1585
1657
  }
1658
+ /** The exported key behind an address, reduced to the fields that identify it. */
1659
+ _exportedAccountKey(accountPath, xpub) {
1660
+ const { publicKey, chainCode } = this.urEngine.parseXpubMeta(xpub);
1661
+ return { path: normalizePath(accountPath), publicKey, chainCode, xpub };
1662
+ }
1586
1663
  /**
1587
1664
  * Signing needs only the wallet's mfp: the device re-derives the key from path+xfp, so no
1588
1665
  * per-path account lookup happens here.
1589
1666
  */
1590
1667
  _signWithWallet(args) {
1591
1668
  const { connectId, deviceId } = args;
1669
+ if (!isBip32Path(args.path)) {
1670
+ return Promise.resolve(
1671
+ (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `Invalid derivation path (${args.path})`)
1672
+ );
1673
+ }
1674
+ const chainCoinTypeFailure = coinTypeFailure(args.chain, args.path);
1675
+ if (chainCoinTypeFailure) return Promise.resolve(chainCoinTypeFailure);
1592
1676
  return this._runJob(connectId, deviceId, async (signal) => {
1593
1677
  const { record } = await this._ensureWalletKnown(connectId, deviceId, args.chain, signal);
1594
1678
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1613,6 +1697,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1613
1697
  const method = item.methodName;
1614
1698
  const hwkChain = (0, import_hwk_adapter_core3.getAllNetworkMethodChain)(method);
1615
1699
  const path = normalizePath(item.path);
1700
+ if (!hasChainCoinType(hwkChain, path)) return void 0;
1616
1701
  if (hwkChain === "btc" && !isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1617
1702
  return void 0;
1618
1703
  }
@@ -1624,15 +1709,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1624
1709
  case "btcGetPublicKey":
1625
1710
  case "solGetAddress":
1626
1711
  return { hwkChain, path };
1627
- default:
1628
- return void 0;
1629
1712
  }
1630
1713
  }
1631
1714
  /**
1632
- * QR answers the whole bundle with one request QR and one scan. USB exports one path per
1633
- * request because the device limits that channel.
1715
+ * Picks the bundle's channel. QR answers every item with one request QR and one scan; USB items
1716
+ * each ask the device directly, like other vendors, on the session found here.
1634
1717
  */
1635
- async _prefetchAllNetworkAccounts(connectId, deviceId, params) {
1718
+ async _prepareAllNetworkBundle(connectId, deviceId, params) {
1636
1719
  return this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), async (signal) => {
1637
1720
  const target = this._resolveTarget(connectId, deviceId);
1638
1721
  let { record } = target;
@@ -1641,21 +1724,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1641
1724
  const schema = this._allNetworkSyncSchema(item);
1642
1725
  if (schema) requestedByKey.set(accountKey(schema.hwkChain, schema.path), schema);
1643
1726
  }
1644
- const book = /* @__PURE__ */ new Map();
1727
+ const scanned = /* @__PURE__ */ new Map();
1645
1728
  if (!requestedByKey.size) {
1646
- return { book };
1729
+ return { access: { channel: "qr", scanned } };
1647
1730
  }
1648
- const requestedSchemas = Array.from(requestedByKey.values());
1649
- const assertAllBooked = () => {
1650
- for (const schema of requestedSchemas) {
1651
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1652
- throw (0, import_hwk_adapter_core3.createHwkError)({
1653
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1654
- message: `Keystone did not return the requested derivation path (${schema.path})`
1655
- });
1656
- }
1657
- }
1658
- };
1659
1731
  const operation = (0, import_hwk_adapter_core3.isHardwareOperationId)(params.operationId) ? this._operations.find(params.operationId) : void 0;
1660
1732
  const operationRoute = operation ? this._operationRoutes.get(operation.connectId) : void 0;
1661
1733
  const routedToQr = operationRoute?.operationId === operation?.operationId && operationRoute?.connectionType === "qr";
@@ -1664,45 +1736,23 @@ var KeystoneAdapter = class _KeystoneAdapter {
1664
1736
  _KeystoneAdapter._throwIfAborted(signal);
1665
1737
  }
1666
1738
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1667
- const bundleSessionId = record.usbSessionId;
1668
- const assertBundleSession = () => {
1669
- if (record?.usbSessionId !== bundleSessionId) {
1670
- throw (0, import_hwk_adapter_core3.createHwkError)({
1671
- code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
1672
- message: "Keystone USB connection was lost during account export"
1673
- });
1674
- }
1739
+ return {
1740
+ access: { channel: "usb", usbSessionId: record.usbSessionId },
1741
+ masterFingerprint: record.masterFingerprint
1675
1742
  };
1676
- for (const schema of requestedSchemas) {
1677
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1678
- assertBundleSession();
1679
- const synced = await this._fetchAccount(
1680
- connectId,
1681
- deviceId,
1682
- schema.hwkChain,
1683
- schema.path,
1684
- signal,
1685
- book
1686
- );
1687
- record = synced.record;
1688
- assertBundleSession();
1689
- }
1690
- }
1691
- assertAllBooked();
1692
- return { book, masterFingerprint: record.masterFingerprint };
1693
1743
  }
1694
- if (this._forcedTransport === "usb") {
1744
+ if (this._forcedTransport === "usb" && !routedToQr) {
1695
1745
  throw (0, import_hwk_adapter_core3.createHwkError)({
1696
1746
  code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
1697
1747
  message: "USB channel is not connected for this Keystone wallet"
1698
1748
  });
1699
1749
  }
1700
- const schemas = requestedSchemas;
1750
+ const schemas = Array.from(requestedByKey.values());
1701
1751
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1702
1752
  schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1703
1753
  origin: this._origin
1704
1754
  });
1705
- const responseUr = await this._requestQrDisplayAndAwaitResponse(
1755
+ const responseUr = await this._requestQrAndAwaitResponse(
1706
1756
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1707
1757
  { ...requestUr, animated: false },
1708
1758
  signal
@@ -1710,22 +1760,41 @@ var KeystoneAdapter = class _KeystoneAdapter {
1710
1760
  _KeystoneAdapter._throwIfAborted(signal);
1711
1761
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1712
1762
  this._assertParsedIdentity(parsed, target);
1713
- record = this._upsertDeviceRecord(parsed);
1714
- const requestedChainByPath = new Map(
1715
- schemas.map((schema) => [normalizePath(schema.path), schema.hwkChain])
1716
- );
1717
- for (const account of parsed.accounts) {
1718
- const normalizedPath = normalizePath(account.path);
1719
- const hwkChain = requestedChainByPath.get(normalizedPath) ?? inferHwkChainFromPath(normalizedPath);
1720
- if (hwkChain) {
1721
- book.set(accountKey(hwkChain, normalizedPath), { ...account, hwkChain });
1722
- }
1763
+ for (const schema of schemas) {
1764
+ scanned.set(accountKey(schema.hwkChain, schema.path), {
1765
+ ...requireExportedPath(parsed, schema.path),
1766
+ hwkChain: schema.hwkChain
1767
+ });
1723
1768
  }
1724
- assertAllBooked();
1725
- return { book, masterFingerprint: record.masterFingerprint };
1769
+ record = this._upsertDeviceRecord(parsed);
1770
+ return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1726
1771
  });
1727
1772
  }
1728
- /** Resolve the wallet's master fingerprint from the connectId and/or deviceId the caller passed. */
1773
+ /**
1774
+ * A positional wallet id and an operation id must name the same wallet: otherwise the call
1775
+ * would run on the operation's wallet while the caller files the result under the other one.
1776
+ * Ids that do not carry a master fingerprint cannot be compared and pass through.
1777
+ */
1778
+ _resolveOperationTarget(positionalTargetId, operationId) {
1779
+ const target = (0, import_hwk_adapter_core3.resolveHardwareOperationTarget)(
1780
+ positionalTargetId,
1781
+ operationId,
1782
+ "keystone"
1783
+ );
1784
+ if (!target.success || !operationId || !positionalTargetId || (0, import_hwk_adapter_core3.isHardwareOperationId)(positionalTargetId)) {
1785
+ return target;
1786
+ }
1787
+ const operation = this._operations.find(operationId);
1788
+ const positionalMfp = keystoneMfpFromIdentifier(positionalTargetId);
1789
+ const operationMfp = operation ? keystoneMfpFromIdentifier(operation.connectId) : void 0;
1790
+ if (positionalMfp && operationMfp && positionalMfp !== operationMfp) {
1791
+ return (0, import_hwk_adapter_core3.failure)(
1792
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1793
+ "Keystone connectId and operationId name different wallets"
1794
+ );
1795
+ }
1796
+ return target;
1797
+ }
1729
1798
  _resolveTarget(connectId, deviceId) {
1730
1799
  const resolvedConnectId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? this._operations.resolve(connectId).connectId : connectId;
1731
1800
  const identifiers = [deviceId, resolvedConnectId].filter(
@@ -1755,7 +1824,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1755
1824
  if (expected.expectedMasterFingerprint && parsed.masterFingerprint !== expected.expectedMasterFingerprint) {
1756
1825
  throw (0, import_hwk_adapter_core3.createHwkError)({
1757
1826
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1758
- message: `Connected Keystone wallet (mfp ${parsed.masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1827
+ // The master fingerprint identifies the wallet; keep it out of messages that reach logs.
1828
+ message: "Connected Keystone wallet does not match the requested wallet"
1759
1829
  });
1760
1830
  }
1761
1831
  }
@@ -1785,7 +1855,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1785
1855
  * Opens a permitted USB Keystone and takes its mfp as the wallet identity. A known wallet gains
1786
1856
  * USB in place (`device-changed`); an unseen one becomes USB-only.
1787
1857
  */
1788
- async _connectUsb(expected, searchTargetId, signal) {
1858
+ async _connectUsb(connector, expected, searchTargetId, signal) {
1789
1859
  if (this._pendingUsbTeardowns > 0 || this._abandonedUsbConnects > 0) {
1790
1860
  return (0, import_hwk_adapter_core3.failure)(
1791
1861
  import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal,
@@ -1798,28 +1868,22 @@ var KeystoneAdapter = class _KeystoneAdapter {
1798
1868
  abandoned = true;
1799
1869
  this._abandonedUsbConnects += 1;
1800
1870
  };
1801
- signal?.addEventListener("abort", onAbort, { once: true });
1871
+ signal.addEventListener("abort", onAbort, { once: true });
1802
1872
  const pending = this._usbConnectTail.then(async () => {
1803
1873
  _KeystoneAdapter._throwIfAborted(signal);
1804
- return this._connectUsbExclusive(expected, searchTargetId, signal);
1874
+ return this._connectUsbExclusive(connector, expected, searchTargetId, signal);
1805
1875
  });
1806
1876
  const settled = pending.finally(() => {
1807
- signal?.removeEventListener("abort", onAbort);
1877
+ signal.removeEventListener("abort", onAbort);
1808
1878
  if (abandoned) this._abandonedUsbConnects -= 1;
1809
1879
  });
1810
1880
  this._usbConnectTail = settled.then(
1811
1881
  () => void 0,
1812
1882
  () => void 0
1813
1883
  );
1814
- return signal ? _KeystoneAdapter._abortable(signal, settled) : settled;
1884
+ return _KeystoneAdapter._abortable(signal, settled);
1815
1885
  }
1816
- async _connectUsbExclusive(expected, searchTargetId, signal) {
1817
- if (!this._usbConnector) {
1818
- return (0, import_hwk_adapter_core3.failure)(
1819
- import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
1820
- "No USB connector configured for this Keystone adapter"
1821
- );
1822
- }
1886
+ async _connectUsbExclusive(connector, expected, searchTargetId, signal) {
1823
1887
  let sessionId;
1824
1888
  try {
1825
1889
  let connectTarget = { type: "default" };
@@ -1831,7 +1895,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1831
1895
  deviceIdentity: expected.expectedMasterFingerprint
1832
1896
  };
1833
1897
  }
1834
- const connector = this._usbConnector;
1835
1898
  const session = await (connector.connectTarget ? connector.connectTarget(connectTarget) : connector.connect(searchTargetId ?? expected.expectedMasterFingerprint));
1836
1899
  sessionId = session.sessionId;
1837
1900
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1845,16 +1908,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1845
1908
  });
1846
1909
  }
1847
1910
  const masterFingerprint = mfpValue.toLowerCase();
1848
- if (expected.expectedMasterFingerprint && masterFingerprint !== expected.expectedMasterFingerprint) {
1849
- throw (0, import_hwk_adapter_core3.createHwkError)({
1850
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1851
- message: `Connected Keystone wallet (mfp ${masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1852
- });
1853
- }
1911
+ this._assertParsedIdentity({ masterFingerprint, accounts: [] }, expected);
1854
1912
  const previousUsbSessionId = this._devices.get(masterFingerprint)?.usbSessionId;
1855
1913
  if (previousUsbSessionId && previousUsbSessionId !== session.sessionId) {
1856
1914
  try {
1857
- await this._usbConnector.disconnect(previousUsbSessionId);
1915
+ await connector.disconnect(previousUsbSessionId);
1858
1916
  } catch {
1859
1917
  }
1860
1918
  }
@@ -1874,7 +1932,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1874
1932
  } catch (err) {
1875
1933
  if (sessionId) {
1876
1934
  try {
1877
- await this._usbConnector.disconnect(sessionId);
1935
+ await connector.disconnect(sessionId);
1878
1936
  } catch {
1879
1937
  }
1880
1938
  }
@@ -1913,14 +1971,21 @@ var KeystoneAdapter = class _KeystoneAdapter {
1913
1971
  }
1914
1972
  }
1915
1973
  if (!availableDevices.length) {
1974
+ const record = options?.waitForReenumeration ? this._devices.get(expectedMasterFingerprint) : void 0;
1975
+ if (record) record.hadUsbSession = false;
1916
1976
  if (this._forcedTransport === "usb" && lastSearchError) {
1917
1977
  throw lastSearchError instanceof Error ? lastSearchError : new Error(String(lastSearchError));
1918
1978
  }
1919
1979
  return void 0;
1920
1980
  }
1921
- const attached = await this._connectUsb({ expectedMasterFingerprint }, void 0, signal);
1981
+ const attached = await this._connectUsb(
1982
+ this._usbConnector,
1983
+ { expectedMasterFingerprint },
1984
+ void 0,
1985
+ signal
1986
+ );
1922
1987
  _KeystoneAdapter._throwIfAborted(signal);
1923
- if (!attached.success && attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal) {
1988
+ if (!attached.success && (attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal || attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceOneDeviceOnly)) {
1924
1989
  throw (0, import_hwk_adapter_core3.createHwkError)({
1925
1990
  ...attached.payload,
1926
1991
  message: attached.payload.error
@@ -1929,8 +1994,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1929
1994
  return attached.success ? this._devices.get(expectedMasterFingerprint) : void 0;
1930
1995
  }
1931
1996
  /**
1932
- * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session fails closed;
1933
- * otherwise a failed USB reattach leaves the call on QR.
1997
+ * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
1998
+ * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
1934
1999
  */
1935
2000
  async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
1936
2001
  const releaseOperationRetention = (0, import_hwk_adapter_core3.isHardwareOperationId)(operationId) ? this._operations.retain(operationId) : void 0;
@@ -1961,7 +2026,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1961
2026
  }
1962
2027
  interactionRoute = route;
1963
2028
  }
1964
- if (!interactionRoute && !this._forcedTransport && record && !record.usbSessionId && this._usbConnector) {
2029
+ if (!interactionRoute && this._forcedTransport !== "qr" && record && !record.usbSessionId && this._usbConnector) {
1965
2030
  record = await this._tryUsbAttach(signal, record.masterFingerprint, {
1966
2031
  waitForReenumeration: record.hadUsbSession
1967
2032
  }) ?? record;
@@ -1980,9 +2045,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
1980
2045
  message: "USB channel is not connected for this Keystone wallet"
1981
2046
  });
1982
2047
  }
1983
- const result = await this._callUsbConnector(
2048
+ const result = await this._callUsbResolveUr(
2049
+ this._usbConnector,
1984
2050
  record.usbSessionId,
1985
- "resolveUr",
1986
2051
  requestUr,
1987
2052
  signal
1988
2053
  );
@@ -1992,11 +2057,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1992
2057
  if (usbErrorCode === import_hwk_adapter_core3.HardwareErrorCode.PayloadTooLarge && usbErrorOrigin !== "device") {
1993
2058
  if (!interactionRoute && !this._forcedTransport) {
1994
2059
  const displayDevice2 = toDeviceInfo(record);
1995
- return this._requestQrDisplayAndAwaitResponse(
1996
- displayDevice2,
1997
- { ...requestUr, animated },
1998
- signal
1999
- );
2060
+ return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2000
2061
  }
2001
2062
  throw usbError;
2002
2063
  }
@@ -2007,6 +2068,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2007
2068
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2008
2069
  }
2009
2070
  record.usbSessionId = void 0;
2071
+ this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: toDeviceInfo(record) });
2010
2072
  if (interactionRoute) {
2011
2073
  throw this._endDisconnectedOperation(
2012
2074
  interactionRoute.operationId,
@@ -2024,11 +2086,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2024
2086
  });
2025
2087
  }
2026
2088
  }
2089
+ if (operationName && usbError.replyUnreadable === true) {
2090
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2091
+ code: usbErrorCode ?? import_hwk_adapter_core3.HardwareErrorCode.UnknownError,
2092
+ message: `Keystone ${operationName} may have completed but its reply could not be read`,
2093
+ origin: "device",
2094
+ recovery: { scope: "unknown" },
2095
+ params: (0, import_hwk_adapter_core3.operationMayHaveCompletedParams)(operationName)
2096
+ });
2097
+ }
2027
2098
  throw usbError;
2028
2099
  }
2029
2100
  const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
2030
2101
  try {
2031
- return await this._requestQrDisplayAndAwaitResponse(
2102
+ return await this._requestQrAndAwaitResponse(
2032
2103
  displayDevice,
2033
2104
  { ...requestUr, animated },
2034
2105
  signal
@@ -2058,35 +2129,41 @@ var KeystoneAdapter = class _KeystoneAdapter {
2058
2129
  });
2059
2130
  }
2060
2131
  /**
2061
- * Fetches one account's key material for this operation only; `book` reuses earlier fetches. A
2062
- * failed USB export ends the operation without replaying or switching transports.
2132
+ * Fetches one account's key material. An all-network QR item takes it from the bundle's scan; a
2133
+ * USB item asks the device on the bundle's session. A failed USB export ends the operation
2134
+ * without replaying or switching transports.
2063
2135
  */
2064
- async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, book) {
2136
+ async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, bundle) {
2065
2137
  const target = this._resolveTarget(connectId, deviceId);
2138
+ if (bundle?.channel === "qr") {
2139
+ const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2140
+ if (!target.record || !scanned) {
2141
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2142
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2143
+ message: `Keystone did not return the requested derivation path (${syncPath})`
2144
+ });
2145
+ }
2146
+ return { record: target.record, account: scanned };
2147
+ }
2148
+ if (bundle?.channel === "usb" && target.record?.usbSessionId !== bundle.usbSessionId) {
2149
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2150
+ code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
2151
+ message: "Keystone USB connection was lost during the bundle"
2152
+ });
2153
+ }
2066
2154
  const operationConnectionType = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? this._operations.resolve(connectId).connectionType : void 0;
2067
- const key = accountKey(hwkChain, syncPath);
2068
2155
  let existingRecord = target.record;
2069
2156
  if (!existingRecord) {
2070
2157
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2071
2158
  _KeystoneAdapter._throwIfAborted(signal);
2072
2159
  }
2073
- const booked = book?.get(key);
2074
- if (existingRecord && booked) {
2075
- return { record: existingRecord, account: booked };
2076
- }
2077
- if (!operationConnectionType && existingRecord && !existingRecord.usbSessionId && this._forcedTransport === "usb") {
2078
- await this._tryUsbAttach(signal, existingRecord.masterFingerprint, {
2079
- waitForReenumeration: existingRecord.hadUsbSession
2080
- });
2081
- _KeystoneAdapter._throwIfAborted(signal);
2082
- existingRecord = this._devices.get(existingRecord.masterFingerprint) ?? existingRecord;
2083
- }
2084
- const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2160
+ const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2085
2161
  const schemas = [keySchema(hwkChain, syncPath)];
2086
2162
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2087
2163
  const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2088
2164
  _KeystoneAdapter._throwIfAborted(signal);
2089
2165
  const parsed = this.urEngine.parseAccountResponse(responseUr);
2166
+ const account = requireExportedPath(parsed, syncPath);
2090
2167
  let record;
2091
2168
  if (useSinglePathUsbExport && existingRecord) {
2092
2169
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2102,27 +2179,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2102
2179
  viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2103
2180
  });
2104
2181
  }
2105
- const account = parsed.accounts.find((a) => normalizePath(a.path) === syncPath);
2106
- if (!account) {
2107
- throw (0, import_hwk_adapter_core3.createHwkError)({
2108
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2109
- message: `Keystone did not return the requested derivation path (${syncPath})`
2110
- });
2111
- }
2112
- const entry = { ...account, hwkChain };
2113
- if (book) {
2114
- for (const returned of parsed.accounts) {
2115
- const returnedChain = inferHwkChainFromPath(returned.path);
2116
- if (returnedChain) {
2117
- book.set(accountKey(returnedChain, returned.path), {
2118
- ...returned,
2119
- hwkChain: returnedChain
2120
- });
2121
- }
2122
- }
2123
- book.set(key, entry);
2124
- }
2125
- return { record, account: entry };
2182
+ return { record, account: { ...account, hwkChain } };
2126
2183
  }
2127
2184
  /**
2128
2185
  * Resolves which wallet is attached, without a per-path account. `CHAIN_FINGERPRINT_PATHS.evm` is
@@ -2144,7 +2201,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2144
2201
  });
2145
2202
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2146
2203
  _KeystoneAdapter._throwIfAborted(signal);
2147
- return { record: this._upsertDeviceRecord(this.urEngine.parseAccountResponse(responseUr)) };
2204
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
2205
+ requireExportedPath(parsed, normalizePath(accountPath));
2206
+ return { record: this._upsertDeviceRecord(parsed) };
2148
2207
  }
2149
2208
  /**
2150
2209
  * The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
@@ -2170,7 +2229,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2170
2229
  * a cancel reach the wait before the QR timeout.
2171
2230
  */
2172
2231
  async _awaitQrResponse(requestType, pending, signal) {
2173
- if (!signal) return pending;
2174
2232
  let settled = false;
2175
2233
  const onAbort = () => {
2176
2234
  if (!settled) this._uiRegistry.cancel(requestType);
@@ -2179,55 +2237,50 @@ var KeystoneAdapter = class _KeystoneAdapter {
2179
2237
  else signal.addEventListener("abort", onAbort, { once: true });
2180
2238
  try {
2181
2239
  return await pending;
2240
+ } catch (error) {
2241
+ const reason = signal.reason;
2242
+ if (signal.aborted && reason?.code === import_hwk_adapter_core3.HardwareErrorCode.OperationEnded) throw signal.reason;
2243
+ throw error;
2182
2244
  } finally {
2183
2245
  settled = true;
2184
2246
  signal.removeEventListener("abort", onAbort);
2185
2247
  }
2186
2248
  }
2187
- async _requestQrDisplayAndAwaitResponse(device, data, signal) {
2249
+ /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2250
+ async _requestQrAndAwaitResponse(device, data, signal) {
2251
+ const requestType = data ? import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY : import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN;
2188
2252
  const operationId = this._activeOperationId();
2189
- const waitPromise = this._uiRegistry.wait(
2190
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2191
- { timeoutMs: this._qrTimeoutMs, operationId }
2192
- );
2193
- this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY, {
2194
- type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2195
- payload: { device, data, operationId }
2196
- });
2197
- const response = await this._awaitQrResponse(
2198
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2199
- waitPromise,
2200
- signal
2201
- );
2202
- return { urType: response.urType, urData: response.urData };
2203
- }
2204
- async _requestQrScanAndAwaitResponse(device, signal) {
2205
- const operationId = this._activeOperationId();
2206
- const waitPromise = this._uiRegistry.wait(
2207
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN,
2208
- { timeoutMs: this._qrTimeoutMs, operationId }
2209
- );
2210
- this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN, {
2211
- type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN,
2212
- payload: { device, operationId }
2213
- });
2214
- const response = await this._awaitQrResponse(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN, waitPromise, signal);
2215
- return { urType: response.urType, urData: response.urData };
2216
- }
2217
- async _callUsbConnector(sessionId, method, params, signal) {
2218
- if (!this._usbConnector) {
2219
- throw (0, import_hwk_adapter_core3.createHwkError)({
2220
- code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
2221
- message: "No USB connector configured for this Keystone adapter"
2253
+ const release = operationId ? this._operations.retain(operationId) : void 0;
2254
+ try {
2255
+ const waitPromise = this._uiRegistry.wait(requestType, {
2256
+ timeoutMs: this._qrTimeoutMs,
2257
+ operationId
2222
2258
  });
2259
+ if (data) {
2260
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY, {
2261
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2262
+ payload: { device, data, operationId }
2263
+ });
2264
+ } else {
2265
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN, {
2266
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN,
2267
+ payload: { device, operationId }
2268
+ });
2269
+ }
2270
+ const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2271
+ return { urType: response.urType, urData: response.urData };
2272
+ } finally {
2273
+ release?.();
2223
2274
  }
2275
+ }
2276
+ async _callUsbResolveUr(connector, sessionId, requestUr, signal) {
2224
2277
  if (this._pendingUsbTeardowns > 0 || this._unsettledUsbOperations.size > 0) {
2225
2278
  throw (0, import_hwk_adapter_core3.createHwkError)({
2226
2279
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal,
2227
- message: `Keystone USB is busy while calling ${method}`
2280
+ message: "Keystone USB is busy while calling resolveUr"
2228
2281
  });
2229
2282
  }
2230
- if (signal?.aborted) {
2283
+ if (signal.aborted) {
2231
2284
  throw signal.reason instanceof Error ? signal.reason : (0, import_hwk_adapter_core3.createHwkError)({
2232
2285
  code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
2233
2286
  message: "User aborted operation"
@@ -2236,12 +2289,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2236
2289
  const releaseOperation = this._retainUsbOperation(`call:${sessionId}`);
2237
2290
  let rawCall;
2238
2291
  try {
2239
- rawCall = this._usbConnector.call(sessionId, method, params).finally(releaseOperation);
2292
+ rawCall = connector.call(sessionId, "resolveUr", requestUr).finally(releaseOperation);
2240
2293
  } catch (error) {
2241
2294
  releaseOperation();
2242
2295
  throw error;
2243
2296
  }
2244
- return signal ? _KeystoneAdapter._abortable(signal, rawCall) : rawCall;
2297
+ return _KeystoneAdapter._abortable(signal, rawCall);
2245
2298
  }
2246
2299
  _runUsbTeardown(task) {
2247
2300
  const previous = this._usbTeardownTail;
@@ -2303,6 +2356,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
2303
2356
  );
2304
2357
  });
2305
2358
  }
2359
+ /** Settles with `signal`'s reason once it aborts; a later outcome of `promise` is dropped. */
2360
+ static _untilAborted(signal, promise) {
2361
+ promise.catch(() => void 0);
2362
+ if (signal.aborted) return Promise.reject(signal.reason);
2363
+ return new Promise((resolve, reject) => {
2364
+ const onAbort = () => reject(signal.reason);
2365
+ signal.addEventListener("abort", onAbort, { once: true });
2366
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort)).catch(() => void 0);
2367
+ });
2368
+ }
2306
2369
  static _throwIfAborted(signal) {
2307
2370
  if (signal?.aborted) {
2308
2371
  throw signal.reason instanceof Error ? signal.reason : new Error("Operation aborted");