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

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