@onekeyfe/hwk-keystone-adapter 1.2.5-alpha.4 → 1.2.8-alpha.1

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,11 @@ 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 { parseBip32MasterFingerprint } from "@onekeyfe/hwk-adapter-core";
8
+ import {
9
+ HardwareErrorCode,
10
+ createHwkError,
11
+ parseWalletMasterFingerprint
12
+ } from "@onekeyfe/hwk-adapter-core";
9
13
 
10
14
  // src/urEngine/TronSignRequest.ts
11
15
  import {
@@ -155,10 +159,9 @@ function requireSignatureBytes(hex, expectedBytes, chain) {
155
159
  }
156
160
  return hex;
157
161
  }
158
- var MISSING_MASTER_FINGERPRINT = "00000000";
159
162
  function requireBip32MasterFingerprint(value) {
160
- const fingerprint = parseBip32MasterFingerprint(value);
161
- if (!fingerprint || fingerprint === MISSING_MASTER_FINGERPRINT) {
163
+ const fingerprint = parseWalletMasterFingerprint(value);
164
+ if (!fingerprint) {
162
165
  throw new Error("Keystone master fingerprint must be exactly 4 bytes (8 hex characters)");
163
166
  }
164
167
  return fingerprint;
@@ -173,8 +176,19 @@ function toParsedAccount(key) {
173
176
  name: key.name
174
177
  };
175
178
  }
179
+ var BIP32_HARDENED_OFFSET = 2147483648;
176
180
  function relativeHdPath(relativeDerivePath) {
177
- return `m/${relativeDerivePath.replace(/^m\//i, "")}`;
181
+ const segments = relativeDerivePath.replace(/^m\//i, "").split("/");
182
+ const valid = segments.every(
183
+ (segment) => /^\d+$/.test(segment) && Number(segment) < BIP32_HARDENED_OFFSET
184
+ );
185
+ if (!valid) {
186
+ throw createHwkError({
187
+ code: HardwareErrorCode.InvalidParams,
188
+ message: `Invalid change/index segments in derivation path (${relativeDerivePath})`
189
+ });
190
+ }
191
+ return `m/${segments.join("/")}`;
178
192
  }
179
193
  var KeystoneUrEngine = class {
180
194
  constructor(origin = "OneKey") {
@@ -401,7 +415,8 @@ import {
401
415
  CHAIN_FINGERPRINT_PATHS,
402
416
  DEVICE,
403
417
  DeviceJobQueue,
404
- HardwareErrorCode,
418
+ HardwareErrorCode as HardwareErrorCode2,
419
+ MISSING_BIP32_MASTER_FINGERPRINT,
405
420
  OperationRegistry,
406
421
  SDK,
407
422
  TypedEventEmitter,
@@ -412,7 +427,7 @@ import {
412
427
  UI_RESPONSE,
413
428
  UiRequestRegistry,
414
429
  createHardwareSearchTargetId,
415
- createHwkError,
430
+ createHwkError as createHwkError2,
416
431
  deriveDeviceFingerprint,
417
432
  ensure0x,
418
433
  failure,
@@ -423,8 +438,10 @@ import {
423
438
  isHardwareOperationId as isHardwareOperationId2,
424
439
  isHwkRecoveryHint,
425
440
  isUserRefusal,
441
+ isWalletSafetyFailure,
426
442
  operationMayHaveCompletedParams,
427
- parseBip32MasterFingerprint as parseBip32MasterFingerprint3,
443
+ parseBip32MasterFingerprint,
444
+ parseWalletMasterFingerprint as parseWalletMasterFingerprint3,
428
445
  rehydrateConnectorError,
429
446
  resolveHardwareOperationTarget as resolveGenericHardwareOperationTarget,
430
447
  runAllNetworkGetAddress,
@@ -525,14 +542,14 @@ function placeholderDeviceInfo() {
525
542
  }
526
543
 
527
544
  // src/utils/queueKey.ts
528
- import { isHardwareOperationId, parseBip32MasterFingerprint as parseBip32MasterFingerprint2 } from "@onekeyfe/hwk-adapter-core";
545
+ import { isHardwareOperationId, parseWalletMasterFingerprint as parseWalletMasterFingerprint2 } from "@onekeyfe/hwk-adapter-core";
529
546
  var KEYSTONE_COLD_START_JOB_LABEL = "keystone-cold-start";
530
547
  function keystoneQueueKey(connectId, deviceId) {
531
548
  return isHardwareOperationId(connectId) ? connectId : deviceId || connectId || KEYSTONE_COLD_START_JOB_LABEL;
532
549
  }
533
550
  function keystoneMfpFromIdentifier(identifier) {
534
551
  const value = identifier.startsWith(KEYSTONE_WALLET_CONNECT_ID_PREFIX) ? identifier.slice(KEYSTONE_WALLET_CONNECT_ID_PREFIX.length) : identifier;
535
- return parseBip32MasterFingerprint2(value);
552
+ return parseWalletMasterFingerprint2(value);
536
553
  }
537
554
  function keystoneCancelQueueKeys(identifiers) {
538
555
  const keys = /* @__PURE__ */ new Set();
@@ -547,11 +564,24 @@ function keystoneCancelQueueKeys(identifiers) {
547
564
  }
548
565
 
549
566
  // src/adapter/KeystoneAdapter.ts
567
+ function keystoneBtcParamsFailure(params) {
568
+ const { coin, addressIndex, change } = params;
569
+ if (coin !== void 0 && !["btc", "bitcoin"].includes(String(coin).toLowerCase())) {
570
+ return failure(
571
+ HardwareErrorCode2.ChainNotSupported,
572
+ `Keystone BTC supports Bitcoin mainnet only, not ${String(coin)}`
573
+ );
574
+ }
575
+ if (addressIndex !== void 0 || change !== void 0) {
576
+ return failure(
577
+ HardwareErrorCode2.InvalidParams,
578
+ "Keystone BTC takes the full address path; addressIndex and change are not supported"
579
+ );
580
+ }
581
+ return void 0;
582
+ }
550
583
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
551
584
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
552
- function resolveHardwareOperationTarget(positionalTargetId, operationId) {
553
- return resolveGenericHardwareOperationTarget(positionalTargetId, operationId, "keystone");
554
- }
555
585
  function keySchema(chain, path) {
556
586
  return { path, curve: chain === "sol" ? "ed25519" : "secp256k1" };
557
587
  }
@@ -562,7 +592,7 @@ function waitForKeystoneUsbReattachProbe() {
562
592
  }
563
593
  function buildCancelledFailure(signal) {
564
594
  const reason = signal.reason;
565
- const code = typeof reason?.code === "number" ? reason.code : HardwareErrorCode.UserAborted;
595
+ const code = typeof reason?.code === "number" ? reason.code : HardwareErrorCode2.UserAborted;
566
596
  const message = typeof reason?.message === "string" ? reason.message : "";
567
597
  return failure(code, message || "All-network get-address cancelled");
568
598
  }
@@ -572,9 +602,16 @@ var BIP44_COIN_TYPE_TO_CHAIN = {
572
602
  501: "sol",
573
603
  195: "tron"
574
604
  };
575
- function inferHwkChainFromPath(path) {
605
+ function hasChainCoinType(chain, path) {
576
606
  const match = normalizePath(path).match(/^m\/\d+'\/(\d+)'/);
577
- return match ? BIP44_COIN_TYPE_TO_CHAIN[Number(match[1])] : void 0;
607
+ return Boolean(match) && BIP44_COIN_TYPE_TO_CHAIN[Number(match?.[1])] === chain;
608
+ }
609
+ function coinTypeFailure(chain, path) {
610
+ if (hasChainCoinType(chain, path)) return void 0;
611
+ return failure(
612
+ HardwareErrorCode2.InvalidParams,
613
+ `Keystone ${chain} needs a path with its own BIP44 coin type, not ${path}`
614
+ );
578
615
  }
579
616
  var KeystoneAdapter = class _KeystoneAdapter {
580
617
  constructor(options) {
@@ -630,18 +667,30 @@ var KeystoneAdapter = class _KeystoneAdapter {
630
667
  // All-network bundle, dispatched to the per-chain methods below.
631
668
  // ---------------------------------------------------------------------------
632
669
  this.allNetworkGetAddress = async (connectId, deviceId, params) => {
633
- const operationTarget = resolveHardwareOperationTarget(connectId, params.operationId);
670
+ const operationTarget = this._resolveOperationTarget(connectId, params.operationId);
634
671
  if (!operationTarget.success) return operationTarget;
635
672
  const effectiveConnectId = operationTarget.payload.targetId ?? "";
636
673
  const { operationId } = operationTarget.payload;
674
+ const namedWallets = new Set(
675
+ [deviceId, ...params.bundle.map((item) => item.deviceId)].filter(
676
+ (id) => typeof id === "string" && id.length > 0
677
+ )
678
+ );
679
+ if (namedWallets.size > 1) {
680
+ return failure(
681
+ HardwareErrorCode2.InvalidParams,
682
+ "Keystone all-network items name different wallets"
683
+ );
684
+ }
685
+ const [expectedDeviceId = ""] = namedWallets;
637
686
  let cancelScope;
638
687
  try {
639
- const prefetched = await this._prefetchAllNetworkAccounts(effectiveConnectId, deviceId, {
688
+ const prepared = await this._prepareAllNetworkBundle(effectiveConnectId, expectedDeviceId, {
640
689
  ...params,
641
690
  operationId
642
691
  });
643
- const { book } = prefetched;
644
- const itemDeviceId = deviceId || prefetched.masterFingerprint || "";
692
+ const { access } = prepared;
693
+ const itemDeviceId = expectedDeviceId || prepared.masterFingerprint || "";
645
694
  const scope = this._jobQueue.createCancelScope(
646
695
  keystoneQueueKey(effectiveConnectId, itemDeviceId)
647
696
  );
@@ -663,18 +712,22 @@ var KeystoneAdapter = class _KeystoneAdapter {
663
712
  };
664
713
  switch (method) {
665
714
  case "evmGetAddress":
666
- return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
715
+ return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
667
716
  case "btcGetAddress":
668
- return this.btcGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
669
- case "btcGetPublicKey":
670
- return this.btcGetPublicKey(effectiveConnectId, itemDeviceId, commonArgs, book);
717
+ case "btcGetPublicKey": {
718
+ const btcArgs = {
719
+ ...commonArgs,
720
+ coin: item.coin ?? item.network
721
+ };
722
+ return method === "btcGetAddress" ? this.btcGetAddress(effectiveConnectId, itemDeviceId, btcArgs, access) : this.btcGetPublicKey(effectiveConnectId, itemDeviceId, btcArgs, access);
723
+ }
671
724
  case "solGetAddress":
672
- return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
725
+ return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
673
726
  case "tronGetAddress":
674
- return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
727
+ return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
675
728
  default:
676
729
  return failure(
677
- HardwareErrorCode.MethodNotSupported,
730
+ HardwareErrorCode2.MethodNotSupported,
678
731
  `Unsupported method: ${String(method)}`
679
732
  );
680
733
  }
@@ -695,11 +748,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
695
748
  }
696
749
  });
697
750
  },
698
- // Cancel, refusal or a lost session ends the batch; other per-item
699
- // failures carry on with the next chain.
751
+ // Cancel, refusal, a lost connection or a safety answer (another wallet, a locked
752
+ // device) ends the batch; other per-item failures carry on with the next chain.
700
753
  shouldAbortBundle: (response, { index }) => {
701
754
  const { code } = response.payload ?? {};
702
- return cancelledIndexes.has(index) || isUserRefusal(code) || isConnectionLost(code);
755
+ const usbSessionLost = access?.channel === "usb" && this._resolveTarget(effectiveConnectId, itemDeviceId).record?.usbSessionId !== access.usbSessionId;
756
+ return cancelledIndexes.has(index) || usbSessionLost || isWalletSafetyFailure(code) || isUserRefusal(code) || isConnectionLost(code);
703
757
  }
704
758
  });
705
759
  } catch (err) {
@@ -875,14 +929,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
875
929
  selectedConnectionType = "usb";
876
930
  if (!this._usbConnector) {
877
931
  return failure(
878
- HardwareErrorCode.TransportNotAvailable,
932
+ HardwareErrorCode2.TransportNotAvailable,
879
933
  "No USB connector configured for this Keystone adapter"
880
934
  );
881
935
  }
882
936
  connected = await this._connectUsb({}, searchTargetId, scope.signal);
883
937
  } else if (hasHardwareRuntimeIdPrefix(searchTargetId)) {
884
938
  return failure(
885
- HardwareErrorCode.DeviceNotFound,
939
+ HardwareErrorCode2.DeviceNotFound,
886
940
  "Keystone search target has expired; search for devices again",
887
941
  void 0,
888
942
  void 0,
@@ -895,7 +949,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
895
949
  connected = success(toDeviceInfo(target.record));
896
950
  } else if (!this._usbConnector) {
897
951
  return failure(
898
- HardwareErrorCode.DeviceNotFound,
952
+ HardwareErrorCode2.DeviceNotFound,
899
953
  `Unknown Keystone device search target: ${searchTargetId}`
900
954
  );
901
955
  } else {
@@ -960,7 +1014,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
960
1014
  if (!record) {
961
1015
  return Promise.resolve(
962
1016
  failure(
963
- HardwareErrorCode.DeviceNotFound,
1017
+ HardwareErrorCode2.DeviceNotFound,
964
1018
  `Unknown Keystone device: ${connectId || deviceId}`
965
1019
  )
966
1020
  );
@@ -979,8 +1033,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
979
1033
  return;
980
1034
  }
981
1035
  }
982
- const reason = createHwkError({
983
- code: HardwareErrorCode.UserAborted,
1036
+ const reason = createHwkError2({
1037
+ code: HardwareErrorCode2.UserAborted,
984
1038
  message: "User aborted operation"
985
1039
  });
986
1040
  if (connectId) {
@@ -1001,13 +1055,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
1001
1055
  this._uiRegistry.cancel();
1002
1056
  }
1003
1057
  }
1058
+ /**
1059
+ * Derived from the wallet's master fingerprint, which the caller already holds as deviceId; the
1060
+ * device is never asked. It names the wallet but cannot check which device is attached.
1061
+ */
1004
1062
  getChainFingerprint(connectId, deviceId, chain) {
1005
1063
  try {
1006
1064
  const target = this._resolveTarget(connectId, deviceId);
1007
1065
  const masterFingerprint = target.expectedMasterFingerprint;
1008
1066
  if (!masterFingerprint) {
1009
1067
  return Promise.resolve(
1010
- failure(HardwareErrorCode.DeviceNotFound, "Unknown Keystone wallet identity")
1068
+ failure(HardwareErrorCode2.DeviceNotFound, "Unknown Keystone wallet identity")
1011
1069
  );
1012
1070
  }
1013
1071
  return Promise.resolve(
@@ -1063,18 +1121,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1063
1121
  // ---------------------------------------------------------------------------
1064
1122
  // EVM
1065
1123
  // ---------------------------------------------------------------------------
1066
- async evmGetAddress(connectIdArg, deviceIdArg, params, book) {
1067
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1124
+ async evmGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1125
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1068
1126
  if (!operationTarget.success) return operationTarget;
1069
1127
  const connectId = operationTarget.payload.targetId;
1070
1128
  const deviceId = deviceIdArg ?? void 0;
1071
- if (!params) return failure(HardwareErrorCode.InvalidParams, "evmGetAddress requires params");
1129
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "evmGetAddress requires params");
1072
1130
  if (!params.path)
1073
- return failure(HardwareErrorCode.InvalidParams, "evmGetAddress requires params.path");
1131
+ return failure(HardwareErrorCode2.InvalidParams, "evmGetAddress requires params.path");
1132
+ const evmCoinTypeFailure = coinTypeFailure("evm", params.path);
1133
+ if (evmCoinTypeFailure) return evmCoinTypeFailure;
1074
1134
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1075
1135
  if (!relativeDerivePath) {
1076
1136
  return failure(
1077
- HardwareErrorCode.InvalidParams,
1137
+ HardwareErrorCode2.InvalidParams,
1078
1138
  "evmGetAddress requires a full leaf path, e.g. m/44'/60'/0'/0/0"
1079
1139
  );
1080
1140
  }
@@ -1085,25 +1145,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
1085
1145
  "evm",
1086
1146
  accountPath,
1087
1147
  signal,
1088
- book
1148
+ bundle
1089
1149
  );
1090
1150
  const address = this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath);
1091
1151
  return success({ address, path: normalizePath(params.path) });
1092
1152
  });
1093
1153
  }
1094
1154
  async evmSignTransaction(connectIdArg, deviceIdArg, params) {
1095
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1155
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1096
1156
  if (!operationTarget.success) return operationTarget;
1097
1157
  const connectId = operationTarget.payload.targetId;
1098
1158
  const deviceId = deviceIdArg ?? void 0;
1099
1159
  if (!params)
1100
- return failure(HardwareErrorCode.InvalidParams, "evmSignTransaction requires params");
1160
+ return failure(HardwareErrorCode2.InvalidParams, "evmSignTransaction requires params");
1101
1161
  if (!params.path) {
1102
- return failure(HardwareErrorCode.InvalidParams, "evmSignTransaction requires params.path");
1162
+ return failure(HardwareErrorCode2.InvalidParams, "evmSignTransaction requires params.path");
1103
1163
  }
1104
1164
  if (!("serializedTx" in params) || typeof params.serializedTx !== "string" || !params.serializedTx) {
1105
1165
  return failure(
1106
- HardwareErrorCode.MethodNotSupported,
1166
+ HardwareErrorCode2.MethodNotSupported,
1107
1167
  "Keystone only signs a fully RLP-serialized transaction (params.serializedTx) \u2014 structured-field signing is not supported"
1108
1168
  );
1109
1169
  }
@@ -1133,14 +1193,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1133
1193
  });
1134
1194
  }
1135
1195
  async evmSignMessage(connectIdArg, deviceIdArg, params) {
1136
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1196
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1137
1197
  if (!operationTarget.success) return operationTarget;
1138
1198
  const connectId = operationTarget.payload.targetId;
1139
1199
  const deviceId = deviceIdArg ?? void 0;
1140
- if (!params) return failure(HardwareErrorCode.InvalidParams, "evmSignMessage requires params");
1200
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "evmSignMessage requires params");
1141
1201
  if (!params.path || params.message === void 0) {
1142
1202
  return failure(
1143
- HardwareErrorCode.InvalidParams,
1203
+ HardwareErrorCode2.InvalidParams,
1144
1204
  "evmSignMessage requires params.path and params.message"
1145
1205
  );
1146
1206
  }
@@ -1165,18 +1225,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1165
1225
  });
1166
1226
  }
1167
1227
  async evmSignTypedData(connectIdArg, deviceIdArg, params) {
1168
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1228
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1169
1229
  if (!operationTarget.success) return operationTarget;
1170
1230
  const connectId = operationTarget.payload.targetId;
1171
1231
  const deviceId = deviceIdArg ?? void 0;
1172
1232
  if (!params)
1173
- return failure(HardwareErrorCode.InvalidParams, "evmSignTypedData requires params");
1233
+ return failure(HardwareErrorCode2.InvalidParams, "evmSignTypedData requires params");
1174
1234
  if (!params.path) {
1175
- return failure(HardwareErrorCode.InvalidParams, "evmSignTypedData requires params.path");
1235
+ return failure(HardwareErrorCode2.InvalidParams, "evmSignTypedData requires params.path");
1176
1236
  }
1177
1237
  if (params.mode === "hash") {
1178
1238
  return failure(
1179
- HardwareErrorCode.MethodNotSupported,
1239
+ HardwareErrorCode2.MethodNotSupported,
1180
1240
  "Keystone always displays the full EIP-712 payload for on-device review \u2014 pre-hashed signing is not supported"
1181
1241
  );
1182
1242
  }
@@ -1207,18 +1267,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1207
1267
  // BTC: 44'/49'/84' addresses derive offline from the account xpub; P2TR addresses
1208
1268
  // and structured-field tx signing are unsupported (the host builds a PSBT instead).
1209
1269
  // ---------------------------------------------------------------------------
1210
- async btcGetAddress(connectIdArg, deviceIdArg, params, book) {
1211
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1270
+ async btcGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1271
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1212
1272
  if (!operationTarget.success) return operationTarget;
1213
1273
  const connectId = operationTarget.payload.targetId;
1214
1274
  const deviceId = deviceIdArg ?? void 0;
1215
- if (!params) return failure(HardwareErrorCode.InvalidParams, "btcGetAddress requires params");
1275
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "btcGetAddress requires params");
1216
1276
  if (!params.path)
1217
- return failure(HardwareErrorCode.InvalidParams, "btcGetAddress requires params.path");
1277
+ return failure(HardwareErrorCode2.InvalidParams, "btcGetAddress requires params.path");
1278
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1279
+ if (btcParamsFailure) return btcParamsFailure;
1218
1280
  const scriptType = btcScriptTypeFromPath(params.path);
1219
1281
  if (!scriptType) {
1220
1282
  return failure(
1221
- HardwareErrorCode.InvalidParams,
1283
+ HardwareErrorCode2.InvalidParams,
1222
1284
  "btcGetAddress requires a path whose purpose is 44'/49'/84'/86' (P2PKH/P2SH-P2WPKH/P2WPKH/P2TR)"
1223
1285
  );
1224
1286
  }
@@ -1232,12 +1294,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
1232
1294
  const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1233
1295
  if (!relativeDerivePath) {
1234
1296
  return failure(
1235
- HardwareErrorCode.InvalidParams,
1297
+ HardwareErrorCode2.InvalidParams,
1236
1298
  "btcGetAddress requires a full leaf path, e.g. m/84'/0'/0'/0/0"
1237
1299
  );
1238
1300
  }
1239
1301
  if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1240
- return failure(HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1302
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1241
1303
  }
1242
1304
  return this._runJob(connectId, deviceId, async (signal) => {
1243
1305
  const xpub = await this._fetchAccountXpub(
@@ -1246,7 +1308,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1246
1308
  "btc",
1247
1309
  accountPath,
1248
1310
  signal,
1249
- book
1311
+ bundle
1250
1312
  );
1251
1313
  const address = this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType);
1252
1314
  return success({ address, path: normalizedPath });
@@ -1256,23 +1318,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
1256
1318
  * `params.path` must be an account path (`m/84'/0'/0'`), the level Keystone syncs. An xpub is
1257
1319
  * script-type agnostic, so `86'` works here even though `btcGetAddress` rejects it.
1258
1320
  */
1259
- async btcGetPublicKey(connectIdArg, deviceIdArg, params, book) {
1260
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1321
+ async btcGetPublicKey(connectIdArg, deviceIdArg, params, bundle) {
1322
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1261
1323
  if (!operationTarget.success) return operationTarget;
1262
1324
  const connectId = operationTarget.payload.targetId;
1263
1325
  const deviceId = deviceIdArg ?? void 0;
1264
- if (!params) return failure(HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params");
1326
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "btcGetPublicKey requires params");
1265
1327
  if (!params.path)
1266
- return failure(HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params.path");
1328
+ return failure(HardwareErrorCode2.InvalidParams, "btcGetPublicKey requires params.path");
1329
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1330
+ if (btcParamsFailure) return btcParamsFailure;
1267
1331
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1268
1332
  if (relativeDerivePath) {
1269
1333
  return failure(
1270
- HardwareErrorCode.InvalidParams,
1334
+ HardwareErrorCode2.InvalidParams,
1271
1335
  "btcGetPublicKey requires an account path, e.g. m/84'/0'/0' (not a leaf path)"
1272
1336
  );
1273
1337
  }
1274
1338
  if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1275
- return failure(HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1339
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1276
1340
  }
1277
1341
  return this._runJob(connectId, deviceId, async (signal) => {
1278
1342
  const xpub = await this._fetchAccountXpub(
@@ -1281,7 +1345,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1281
1345
  "btc",
1282
1346
  accountPath,
1283
1347
  signal,
1284
- book
1348
+ bundle
1285
1349
  );
1286
1350
  const meta = this.urEngine.parseXpubMeta(xpub);
1287
1351
  return success({
@@ -1301,17 +1365,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
1301
1365
  );
1302
1366
  }
1303
1367
  async btcSignPsbt(connectIdArg, deviceIdArg, params) {
1304
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1368
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1305
1369
  if (!operationTarget.success) return operationTarget;
1306
1370
  const connectId = operationTarget.payload.targetId;
1307
1371
  const deviceId = deviceIdArg ?? void 0;
1308
- if (!params) return failure(HardwareErrorCode.InvalidParams, "btcSignPsbt requires params");
1372
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "btcSignPsbt requires params");
1309
1373
  if (!params.psbt)
1310
- return failure(HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.psbt");
1374
+ return failure(HardwareErrorCode2.InvalidParams, "btcSignPsbt requires params.psbt");
1311
1375
  if (!params.path)
1312
- return failure(HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.path");
1376
+ return failure(HardwareErrorCode2.InvalidParams, "btcSignPsbt requires params.path");
1313
1377
  if (!isKeystoneSignableBtcAccountPath(splitAccountPath(params.path).accountPath)) {
1314
- return failure(HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1378
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1315
1379
  }
1316
1380
  return this._runJob(connectId, deviceId, async (signal) => {
1317
1381
  const { record } = await this._ensureWalletKnown(connectId, deviceId, "btc", signal);
@@ -1331,21 +1395,21 @@ var KeystoneAdapter = class _KeystoneAdapter {
1331
1395
  });
1332
1396
  }
1333
1397
  async btcSignMessage(connectIdArg, deviceIdArg, params) {
1334
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1398
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1335
1399
  if (!operationTarget.success) return operationTarget;
1336
1400
  const connectId = operationTarget.payload.targetId;
1337
1401
  const deviceId = deviceIdArg ?? void 0;
1338
- if (!params) return failure(HardwareErrorCode.InvalidParams, "btcSignMessage requires params");
1402
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "btcSignMessage requires params");
1339
1403
  if (!params.path || params.message === void 0) {
1340
1404
  return failure(
1341
- HardwareErrorCode.InvalidParams,
1405
+ HardwareErrorCode2.InvalidParams,
1342
1406
  "btcSignMessage requires params.path and params.message"
1343
1407
  );
1344
1408
  }
1345
1409
  const messageHex = params.hex ? stripHex(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1346
1410
  const path = normalizePath(params.path);
1347
1411
  if (!isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1348
- return failure(HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1412
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1349
1413
  }
1350
1414
  return this._signWithWallet({
1351
1415
  connectId,
@@ -1362,8 +1426,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1362
1426
  toPayload: (sig) => ({ signature: sig.signature })
1363
1427
  });
1364
1428
  }
1429
+ /**
1430
+ * Returns the known master fingerprint for the named wallet without asking the device (a QR
1431
+ * round trip only to repeat it would cost a scan). Use it to name the wallet, for example as a
1432
+ * PSBT xfp, which the device itself checks when signing; it cannot check the attached device.
1433
+ */
1365
1434
  async btcGetMasterFingerprint(connectIdArg, deviceIdArg, paramsArg) {
1366
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, paramsArg?.operationId);
1435
+ const operationTarget = this._resolveOperationTarget(connectIdArg, paramsArg?.operationId);
1367
1436
  if (!operationTarget.success) return operationTarget;
1368
1437
  const connectId = operationTarget.payload.targetId;
1369
1438
  const deviceId = deviceIdArg ?? void 0;
@@ -1375,32 +1444,47 @@ var KeystoneAdapter = class _KeystoneAdapter {
1375
1444
  // ---------------------------------------------------------------------------
1376
1445
  // SOL
1377
1446
  // ---------------------------------------------------------------------------
1378
- async solGetAddress(connectIdArg, deviceIdArg, params, book) {
1379
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1447
+ async solGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1448
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1380
1449
  if (!operationTarget.success) return operationTarget;
1381
1450
  const connectId = operationTarget.payload.targetId;
1382
1451
  const deviceId = deviceIdArg ?? void 0;
1383
- if (!params) return failure(HardwareErrorCode.InvalidParams, "solGetAddress requires params");
1452
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "solGetAddress requires params");
1384
1453
  if (!params.path)
1385
- return failure(HardwareErrorCode.InvalidParams, "solGetAddress requires params.path");
1454
+ return failure(HardwareErrorCode2.InvalidParams, "solGetAddress requires params.path");
1455
+ const solCoinTypeFailure = coinTypeFailure("sol", params.path);
1456
+ if (solCoinTypeFailure) return solCoinTypeFailure;
1386
1457
  const path = normalizePath(params.path);
1458
+ if (!/^m(\/\d+')+$/.test(path)) {
1459
+ return failure(
1460
+ HardwareErrorCode2.InvalidParams,
1461
+ "solGetAddress requires a fully hardened path, e.g. m/44'/501'/0'/0'"
1462
+ );
1463
+ }
1387
1464
  return this._runJob(connectId, deviceId, async (signal) => {
1388
- const { account } = await this._fetchAccount(connectId, deviceId, "sol", path, signal, book);
1465
+ const { account } = await this._fetchAccount(
1466
+ connectId,
1467
+ deviceId,
1468
+ "sol",
1469
+ path,
1470
+ signal,
1471
+ bundle
1472
+ );
1389
1473
  _KeystoneAdapter._throwIfAborted(signal);
1390
1474
  const address = bs58.encode(Buffer.from(account.publicKey, "hex"));
1391
1475
  return success({ address, path });
1392
1476
  });
1393
1477
  }
1394
1478
  async solSignTransaction(connectIdArg, deviceIdArg, params) {
1395
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1479
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1396
1480
  if (!operationTarget.success) return operationTarget;
1397
1481
  const connectId = operationTarget.payload.targetId;
1398
1482
  const deviceId = deviceIdArg ?? void 0;
1399
1483
  if (!params)
1400
- return failure(HardwareErrorCode.InvalidParams, "solSignTransaction requires params");
1484
+ return failure(HardwareErrorCode2.InvalidParams, "solSignTransaction requires params");
1401
1485
  if (!params.path || !params.serializedTx) {
1402
1486
  return failure(
1403
- HardwareErrorCode.InvalidParams,
1487
+ HardwareErrorCode2.InvalidParams,
1404
1488
  "solSignTransaction requires params.path and params.serializedTx"
1405
1489
  );
1406
1490
  }
@@ -1423,14 +1507,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1423
1507
  });
1424
1508
  }
1425
1509
  async solSignMessage(connectIdArg, deviceIdArg, params) {
1426
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1510
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1427
1511
  if (!operationTarget.success) return operationTarget;
1428
1512
  const connectId = operationTarget.payload.targetId;
1429
1513
  const deviceId = deviceIdArg ?? void 0;
1430
- if (!params) return failure(HardwareErrorCode.InvalidParams, "solSignMessage requires params");
1514
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "solSignMessage requires params");
1431
1515
  if (!params.path || !params.message) {
1432
1516
  return failure(
1433
- HardwareErrorCode.InvalidParams,
1517
+ HardwareErrorCode2.InvalidParams,
1434
1518
  "solSignMessage requires params.path and params.message"
1435
1519
  );
1436
1520
  }
@@ -1456,18 +1540,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1456
1540
  // TRON: keystone-sdk-rust layout (tags 5201/5202, firmware >= 2.5.0), not sdk.tron's
1457
1541
  // protobuf module; OneKey Pro's encoding under the same tag is rejected by the firmware.
1458
1542
  // ---------------------------------------------------------------------------
1459
- async tronGetAddress(connectIdArg, deviceIdArg, params, book) {
1460
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1543
+ async tronGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1544
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1461
1545
  if (!operationTarget.success) return operationTarget;
1462
1546
  const connectId = operationTarget.payload.targetId;
1463
1547
  const deviceId = deviceIdArg ?? void 0;
1464
- if (!params) return failure(HardwareErrorCode.InvalidParams, "tronGetAddress requires params");
1548
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "tronGetAddress requires params");
1465
1549
  if (!params.path)
1466
- return failure(HardwareErrorCode.InvalidParams, "tronGetAddress requires params.path");
1550
+ return failure(HardwareErrorCode2.InvalidParams, "tronGetAddress requires params.path");
1551
+ const tronCoinTypeFailure = coinTypeFailure("tron", params.path);
1552
+ if (tronCoinTypeFailure) return tronCoinTypeFailure;
1467
1553
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1468
1554
  if (!relativeDerivePath) {
1469
1555
  return failure(
1470
- HardwareErrorCode.InvalidParams,
1556
+ HardwareErrorCode2.InvalidParams,
1471
1557
  "tronGetAddress requires a full leaf path, e.g. m/44'/195'/0'/0/0"
1472
1558
  );
1473
1559
  }
@@ -1478,25 +1564,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
1478
1564
  "tron",
1479
1565
  accountPath,
1480
1566
  signal,
1481
- book
1567
+ bundle
1482
1568
  );
1483
1569
  const address = this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath);
1484
1570
  return success({ address, path: normalizePath(params.path) });
1485
1571
  });
1486
1572
  }
1487
1573
  async tronSignTransaction(connectIdArg, deviceIdArg, params) {
1488
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1574
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1489
1575
  if (!operationTarget.success) return operationTarget;
1490
1576
  const connectId = operationTarget.payload.targetId;
1491
1577
  const deviceId = deviceIdArg ?? void 0;
1492
1578
  if (!params)
1493
- return failure(HardwareErrorCode.InvalidParams, "tronSignTransaction requires params");
1579
+ return failure(HardwareErrorCode2.InvalidParams, "tronSignTransaction requires params");
1494
1580
  if (!params.path) {
1495
- return failure(HardwareErrorCode.InvalidParams, "tronSignTransaction requires params.path");
1581
+ return failure(HardwareErrorCode2.InvalidParams, "tronSignTransaction requires params.path");
1496
1582
  }
1497
1583
  if (!params.rawTxHex) {
1498
1584
  return failure(
1499
- HardwareErrorCode.InvalidParams,
1585
+ HardwareErrorCode2.InvalidParams,
1500
1586
  "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1501
1587
  );
1502
1588
  }
@@ -1520,20 +1606,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1520
1606
  });
1521
1607
  }
1522
1608
  async tronSignMessage(connectIdArg, deviceIdArg, params) {
1523
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1609
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1524
1610
  if (!operationTarget.success) return operationTarget;
1525
1611
  const connectId = operationTarget.payload.targetId;
1526
1612
  const deviceId = deviceIdArg ?? void 0;
1527
- if (!params) return failure(HardwareErrorCode.InvalidParams, "tronSignMessage requires params");
1613
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "tronSignMessage requires params");
1528
1614
  if (!params.path) {
1529
- return failure(HardwareErrorCode.InvalidParams, "tronSignMessage requires params.path");
1615
+ return failure(HardwareErrorCode2.InvalidParams, "tronSignMessage requires params.path");
1530
1616
  }
1531
1617
  if (!params.messageHex) {
1532
- return failure(HardwareErrorCode.InvalidParams, "tronSignMessage requires params.messageHex");
1618
+ return failure(HardwareErrorCode2.InvalidParams, "tronSignMessage requires params.messageHex");
1533
1619
  }
1534
1620
  if (params.messageType !== "V2") {
1535
1621
  return failure(
1536
- HardwareErrorCode.MethodNotSupported,
1622
+ HardwareErrorCode2.MethodNotSupported,
1537
1623
  'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1538
1624
  );
1539
1625
  }
@@ -1566,19 +1652,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
1566
1652
  return this._errorToFailure(err);
1567
1653
  }
1568
1654
  }
1569
- async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, book) {
1655
+ async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, bundle) {
1570
1656
  const { account } = await this._fetchAccount(
1571
1657
  connectId,
1572
1658
  deviceId,
1573
1659
  hwkChain,
1574
1660
  accountPath,
1575
1661
  signal,
1576
- book
1662
+ bundle
1577
1663
  );
1578
1664
  _KeystoneAdapter._throwIfAborted(signal);
1579
1665
  if (!account.extendedPublicKey) {
1580
- throw createHwkError({
1581
- code: HardwareErrorCode.MethodNotSupported,
1666
+ throw createHwkError2({
1667
+ code: HardwareErrorCode2.MethodNotSupported,
1582
1668
  message: "Keystone did not return an extended public key for this account path"
1583
1669
  });
1584
1670
  }
@@ -1614,6 +1700,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1614
1700
  const method = item.methodName;
1615
1701
  const hwkChain = getAllNetworkMethodChain(method);
1616
1702
  const path = normalizePath(item.path);
1703
+ if (!hasChainCoinType(hwkChain, path)) return void 0;
1617
1704
  if (hwkChain === "btc" && !isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1618
1705
  return void 0;
1619
1706
  }
@@ -1630,10 +1717,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1630
1717
  }
1631
1718
  }
1632
1719
  /**
1633
- * QR answers the whole bundle with one request QR and one scan. USB exports one path per
1634
- * request because the device limits that channel.
1720
+ * Picks the bundle's channel. QR answers every item with one request QR and one scan; USB items
1721
+ * each ask the device directly, like other vendors, on the session found here.
1635
1722
  */
1636
- async _prefetchAllNetworkAccounts(connectId, deviceId, params) {
1723
+ async _prepareAllNetworkBundle(connectId, deviceId, params) {
1637
1724
  return this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), async (signal) => {
1638
1725
  const target = this._resolveTarget(connectId, deviceId);
1639
1726
  let { record } = target;
@@ -1642,21 +1729,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1642
1729
  const schema = this._allNetworkSyncSchema(item);
1643
1730
  if (schema) requestedByKey.set(accountKey(schema.hwkChain, schema.path), schema);
1644
1731
  }
1645
- const book = /* @__PURE__ */ new Map();
1732
+ const scanned = /* @__PURE__ */ new Map();
1646
1733
  if (!requestedByKey.size) {
1647
- return { book };
1734
+ return { access: { channel: "qr", scanned } };
1648
1735
  }
1649
- const requestedSchemas = Array.from(requestedByKey.values());
1650
- const assertAllBooked = () => {
1651
- for (const schema of requestedSchemas) {
1652
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1653
- throw createHwkError({
1654
- code: HardwareErrorCode.DeviceMismatch,
1655
- message: `Keystone did not return the requested derivation path (${schema.path})`
1656
- });
1657
- }
1658
- }
1659
- };
1660
1736
  const operation = isHardwareOperationId2(params.operationId) ? this._operations.find(params.operationId) : void 0;
1661
1737
  const operationRoute = operation ? this._operationRoutes.get(operation.connectId) : void 0;
1662
1738
  const routedToQr = operationRoute?.operationId === operation?.operationId && operationRoute?.connectionType === "qr";
@@ -1665,40 +1741,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1665
1741
  _KeystoneAdapter._throwIfAborted(signal);
1666
1742
  }
1667
1743
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1668
- const bundleSessionId = record.usbSessionId;
1669
- const assertBundleSession = () => {
1670
- if (record?.usbSessionId !== bundleSessionId) {
1671
- throw createHwkError({
1672
- code: HardwareErrorCode.TransportNotAvailable,
1673
- message: "Keystone USB connection was lost during account export"
1674
- });
1675
- }
1744
+ return {
1745
+ access: { channel: "usb", usbSessionId: record.usbSessionId },
1746
+ masterFingerprint: record.masterFingerprint
1676
1747
  };
1677
- for (const schema of requestedSchemas) {
1678
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1679
- assertBundleSession();
1680
- const synced = await this._fetchAccount(
1681
- connectId,
1682
- deviceId,
1683
- schema.hwkChain,
1684
- schema.path,
1685
- signal,
1686
- book
1687
- );
1688
- record = synced.record;
1689
- assertBundleSession();
1690
- }
1691
- }
1692
- assertAllBooked();
1693
- return { book, masterFingerprint: record.masterFingerprint };
1694
1748
  }
1695
- if (this._forcedTransport === "usb") {
1696
- throw createHwkError({
1697
- code: HardwareErrorCode.TransportNotAvailable,
1749
+ if (this._forcedTransport === "usb" && !routedToQr) {
1750
+ throw createHwkError2({
1751
+ code: HardwareErrorCode2.TransportNotAvailable,
1698
1752
  message: "USB channel is not connected for this Keystone wallet"
1699
1753
  });
1700
1754
  }
1701
- const schemas = requestedSchemas;
1755
+ const schemas = Array.from(requestedByKey.values());
1702
1756
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1703
1757
  schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1704
1758
  origin: this._origin
@@ -1712,21 +1766,50 @@ var KeystoneAdapter = class _KeystoneAdapter {
1712
1766
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1713
1767
  this._assertParsedIdentity(parsed, target);
1714
1768
  record = this._upsertDeviceRecord(parsed);
1715
- const requestedChainByPath = new Map(
1716
- schemas.map((schema) => [normalizePath(schema.path), schema.hwkChain])
1717
- );
1718
- for (const account of parsed.accounts) {
1719
- const normalizedPath = normalizePath(account.path);
1720
- const hwkChain = requestedChainByPath.get(normalizedPath) ?? inferHwkChainFromPath(normalizedPath);
1721
- if (hwkChain) {
1722
- book.set(accountKey(hwkChain, normalizedPath), { ...account, hwkChain });
1769
+ for (const schema of schemas) {
1770
+ const account = parsed.accounts.find(
1771
+ (returned) => normalizePath(returned.path) === schema.path
1772
+ );
1773
+ if (!account) {
1774
+ throw createHwkError2({
1775
+ code: HardwareErrorCode2.DeviceMismatch,
1776
+ message: `Keystone did not return the requested derivation path (${schema.path})`
1777
+ });
1723
1778
  }
1779
+ scanned.set(accountKey(schema.hwkChain, schema.path), {
1780
+ ...account,
1781
+ hwkChain: schema.hwkChain
1782
+ });
1724
1783
  }
1725
- assertAllBooked();
1726
- return { book, masterFingerprint: record.masterFingerprint };
1784
+ return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1727
1785
  });
1728
1786
  }
1729
1787
  /** Resolve the wallet's master fingerprint from the connectId and/or deviceId the caller passed. */
1788
+ /**
1789
+ * A positional wallet id and an operation id must name the same wallet: otherwise the call
1790
+ * would run on the operation's wallet while the caller files the result under the other one.
1791
+ * Ids that do not carry a master fingerprint cannot be compared and pass through.
1792
+ */
1793
+ _resolveOperationTarget(positionalTargetId, operationId) {
1794
+ const target = resolveGenericHardwareOperationTarget(
1795
+ positionalTargetId,
1796
+ operationId,
1797
+ "keystone"
1798
+ );
1799
+ if (!target.success || !operationId || !positionalTargetId || isHardwareOperationId2(positionalTargetId)) {
1800
+ return target;
1801
+ }
1802
+ const operation = this._operations.find(operationId);
1803
+ const positionalMfp = keystoneMfpFromIdentifier(positionalTargetId);
1804
+ const operationMfp = operation ? keystoneMfpFromIdentifier(operation.connectId) : void 0;
1805
+ if (positionalMfp && operationMfp && positionalMfp !== operationMfp) {
1806
+ return failure(
1807
+ HardwareErrorCode2.InvalidParams,
1808
+ "Keystone connectId and operationId name different wallets"
1809
+ );
1810
+ }
1811
+ return target;
1812
+ }
1730
1813
  _resolveTarget(connectId, deviceId) {
1731
1814
  const resolvedConnectId = isHardwareOperationId2(connectId) ? this._operations.resolve(connectId).connectId : connectId;
1732
1815
  const identifiers = [deviceId, resolvedConnectId].filter(
@@ -1736,14 +1819,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1736
1819
  const fingerprints = identifiers.map((identifier) => keystoneMfpFromIdentifier(identifier));
1737
1820
  const expectedMasterFingerprint = fingerprints[0];
1738
1821
  if (!expectedMasterFingerprint || fingerprints.some((value) => !value)) {
1739
- throw createHwkError({
1740
- code: HardwareErrorCode.DeviceNotFound,
1822
+ throw createHwkError2({
1823
+ code: HardwareErrorCode2.DeviceNotFound,
1741
1824
  message: "Keystone device lookup requires the wallet master fingerprint"
1742
1825
  });
1743
1826
  }
1744
1827
  if (fingerprints.some((value) => value !== expectedMasterFingerprint)) {
1745
- throw createHwkError({
1746
- code: HardwareErrorCode.DeviceMismatch,
1828
+ throw createHwkError2({
1829
+ code: HardwareErrorCode2.DeviceMismatch,
1747
1830
  message: "Keystone connectId and deviceId identify different wallets"
1748
1831
  });
1749
1832
  }
@@ -1754,8 +1837,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1754
1837
  }
1755
1838
  _assertParsedIdentity(parsed, expected) {
1756
1839
  if (expected.expectedMasterFingerprint && parsed.masterFingerprint !== expected.expectedMasterFingerprint) {
1757
- throw createHwkError({
1758
- code: HardwareErrorCode.DeviceMismatch,
1840
+ throw createHwkError2({
1841
+ code: HardwareErrorCode2.DeviceMismatch,
1759
1842
  message: `Connected Keystone wallet (mfp ${parsed.masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1760
1843
  });
1761
1844
  }
@@ -1789,7 +1872,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1789
1872
  async _connectUsb(expected, searchTargetId, signal) {
1790
1873
  if (this._pendingUsbTeardowns > 0 || this._abandonedUsbConnects > 0) {
1791
1874
  return failure(
1792
- HardwareErrorCode.DeviceBusyInternal,
1875
+ HardwareErrorCode2.DeviceBusyInternal,
1793
1876
  "Keystone USB session is being released"
1794
1877
  );
1795
1878
  }
@@ -1817,7 +1900,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1817
1900
  async _connectUsbExclusive(expected, searchTargetId, signal) {
1818
1901
  if (!this._usbConnector) {
1819
1902
  return failure(
1820
- HardwareErrorCode.TransportNotAvailable,
1903
+ HardwareErrorCode2.TransportNotAvailable,
1821
1904
  "No USB connector configured for this Keystone adapter"
1822
1905
  );
1823
1906
  }
@@ -1837,17 +1920,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1837
1920
  sessionId = session.sessionId;
1838
1921
  _KeystoneAdapter._throwIfAborted(signal);
1839
1922
  const raw = session.deviceInfo.raw;
1840
- const mfpValue = parseBip32MasterFingerprint3(raw?.masterFingerprint);
1923
+ const mfpValue = parseWalletMasterFingerprint3(raw?.masterFingerprint);
1841
1924
  if (!mfpValue) {
1842
- throw createHwkError({
1843
- code: HardwareErrorCode.DeviceMismatch,
1844
- message: "Keystone USB did not report a master fingerprint"
1925
+ const empty = parseBip32MasterFingerprint(raw?.masterFingerprint) === MISSING_BIP32_MASTER_FINGERPRINT;
1926
+ throw createHwkError2({
1927
+ code: empty ? HardwareErrorCode2.DeviceNotInitialized : HardwareErrorCode2.DeviceMismatch,
1928
+ message: empty ? "Keystone has no wallet yet; it reported an empty master fingerprint" : "Keystone USB did not report a master fingerprint"
1845
1929
  });
1846
1930
  }
1847
1931
  const masterFingerprint = mfpValue.toLowerCase();
1848
1932
  if (expected.expectedMasterFingerprint && masterFingerprint !== expected.expectedMasterFingerprint) {
1849
- throw createHwkError({
1850
- code: HardwareErrorCode.DeviceMismatch,
1933
+ throw createHwkError2({
1934
+ code: HardwareErrorCode2.DeviceMismatch,
1851
1935
  message: `Connected Keystone wallet (mfp ${masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1852
1936
  });
1853
1937
  }
@@ -1913,6 +1997,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1913
1997
  }
1914
1998
  }
1915
1999
  if (!availableDevices.length) {
2000
+ const record = options?.waitForReenumeration ? this._devices.get(expectedMasterFingerprint) : void 0;
2001
+ if (record) record.hadUsbSession = false;
1916
2002
  if (this._forcedTransport === "usb" && lastSearchError) {
1917
2003
  throw lastSearchError instanceof Error ? lastSearchError : new Error(String(lastSearchError));
1918
2004
  }
@@ -1920,8 +2006,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1920
2006
  }
1921
2007
  const attached = await this._connectUsb({ expectedMasterFingerprint }, void 0, signal);
1922
2008
  _KeystoneAdapter._throwIfAborted(signal);
1923
- if (!attached.success && attached.payload.code === HardwareErrorCode.DeviceBusyInternal) {
1924
- throw createHwkError({
2009
+ if (!attached.success && attached.payload.code === HardwareErrorCode2.DeviceBusyInternal) {
2010
+ throw createHwkError2({
1925
2011
  ...attached.payload,
1926
2012
  message: attached.payload.error
1927
2013
  });
@@ -1929,8 +2015,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1929
2015
  return attached.success ? this._devices.get(expectedMasterFingerprint) : void 0;
1930
2016
  }
1931
2017
  /**
1932
- * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session fails closed;
1933
- * otherwise a failed USB reattach leaves the call on QR.
2018
+ * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
2019
+ * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
1934
2020
  */
1935
2021
  async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
1936
2022
  const releaseOperationRetention = isHardwareOperationId2(operationId) ? this._operations.retain(operationId) : void 0;
@@ -1961,7 +2047,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1961
2047
  }
1962
2048
  interactionRoute = route;
1963
2049
  }
1964
- if (!interactionRoute && !this._forcedTransport && record && !record.usbSessionId && this._usbConnector) {
2050
+ if (!interactionRoute && this._forcedTransport !== "qr" && record && !record.usbSessionId && this._usbConnector) {
1965
2051
  record = await this._tryUsbAttach(signal, record.masterFingerprint, {
1966
2052
  waitForReenumeration: record.hadUsbSession
1967
2053
  }) ?? record;
@@ -1975,8 +2061,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1975
2061
  "Keystone operation USB connection was lost"
1976
2062
  );
1977
2063
  }
1978
- throw createHwkError({
1979
- code: HardwareErrorCode.TransportNotAvailable,
2064
+ throw createHwkError2({
2065
+ code: HardwareErrorCode2.TransportNotAvailable,
1980
2066
  message: "USB channel is not connected for this Keystone wallet"
1981
2067
  });
1982
2068
  }
@@ -1989,7 +2075,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1989
2075
  if (result.success) return result.payload;
1990
2076
  const usbError = rehydrateConnectorError(result.error);
1991
2077
  const { origin: usbErrorOrigin, code: usbErrorCode } = usbError;
1992
- if (usbErrorCode === HardwareErrorCode.PayloadTooLarge && usbErrorOrigin !== "device") {
2078
+ if (usbErrorCode === HardwareErrorCode2.PayloadTooLarge && usbErrorOrigin !== "device") {
1993
2079
  if (!interactionRoute && !this._forcedTransport) {
1994
2080
  const displayDevice2 = toDeviceInfo(record);
1995
2081
  return this._requestQrDisplayAndAwaitResponse(
@@ -2000,7 +2086,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2000
2086
  }
2001
2087
  throw usbError;
2002
2088
  }
2003
- const deviceAnswered = usbErrorOrigin !== void 0 ? usbErrorOrigin === "device" : usbErrorCode === HardwareErrorCode.UserRejected || usbErrorCode === HardwareErrorCode.UserAborted || usbErrorCode === HardwareErrorCode.DeviceLocked || usbErrorCode === HardwareErrorCode.DeviceMismatch;
2089
+ const deviceAnswered = usbErrorOrigin !== void 0 ? usbErrorOrigin === "device" : usbErrorCode === HardwareErrorCode2.UserRejected || usbErrorCode === HardwareErrorCode2.UserAborted || usbErrorCode === HardwareErrorCode2.DeviceLocked || usbErrorCode === HardwareErrorCode2.DeviceMismatch;
2004
2090
  if (!deviceAnswered) {
2005
2091
  const lostSessionId = record.usbSessionId;
2006
2092
  if (lostSessionId) {
@@ -2015,8 +2101,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
2015
2101
  );
2016
2102
  }
2017
2103
  if (operationName) {
2018
- throw createHwkError({
2019
- code: usbErrorCode ?? HardwareErrorCode.TransportError,
2104
+ throw createHwkError2({
2105
+ code: usbErrorCode ?? HardwareErrorCode2.TransportError,
2020
2106
  message: `Keystone ${operationName} may have completed before the USB connection was lost`,
2021
2107
  origin: "transport",
2022
2108
  recovery: { scope: "unknown" },
@@ -2035,9 +2121,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2035
2121
  );
2036
2122
  } catch (error) {
2037
2123
  const { code, _tag: tag } = error;
2038
- if (operationName && (code === HardwareErrorCode.OperationTimeout || tag === UI_REQUEST_TIMEOUT_TAG)) {
2039
- throw createHwkError({
2040
- code: HardwareErrorCode.OperationTimeout,
2124
+ if (operationName && (code === HardwareErrorCode2.OperationTimeout || tag === UI_REQUEST_TIMEOUT_TAG)) {
2125
+ throw createHwkError2({
2126
+ code: HardwareErrorCode2.OperationTimeout,
2041
2127
  message: `Keystone ${operationName} may have completed before the QR response timed out`,
2042
2128
  recovery: { scope: "unknown" },
2043
2129
  params: operationMayHaveCompletedParams(operationName)
@@ -2050,38 +2136,43 @@ var KeystoneAdapter = class _KeystoneAdapter {
2050
2136
  _endDisconnectedOperation(operationId, message, operationName) {
2051
2137
  this._operations.end(operationId, "disconnect");
2052
2138
  const params = { operationId, reason: "disconnect" };
2053
- return createHwkError({
2054
- code: HardwareErrorCode.OperationEnded,
2139
+ return createHwkError2({
2140
+ code: HardwareErrorCode2.OperationEnded,
2055
2141
  message,
2056
2142
  recovery: operationName ? { scope: "unknown" } : void 0,
2057
2143
  params: operationName ? operationMayHaveCompletedParams(operationName, params) : params
2058
2144
  });
2059
2145
  }
2060
2146
  /**
2061
- * Fetches one account's key material for this operation only; `book` reuses earlier fetches. A
2062
- * failed USB export ends the operation without replaying or switching transports.
2147
+ * Fetches one account's key material. An all-network QR item takes it from the bundle's scan; a
2148
+ * USB item asks the device on the bundle's session. A failed USB export ends the operation
2149
+ * without replaying or switching transports.
2063
2150
  */
2064
- async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, book) {
2151
+ async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, bundle) {
2065
2152
  const target = this._resolveTarget(connectId, deviceId);
2153
+ if (bundle?.channel === "qr") {
2154
+ const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2155
+ if (!target.record || !scanned) {
2156
+ throw createHwkError2({
2157
+ code: HardwareErrorCode2.DeviceMismatch,
2158
+ message: `Keystone did not return the requested derivation path (${syncPath})`
2159
+ });
2160
+ }
2161
+ return { record: target.record, account: scanned };
2162
+ }
2163
+ if (bundle?.channel === "usb" && target.record?.usbSessionId !== bundle.usbSessionId) {
2164
+ throw createHwkError2({
2165
+ code: HardwareErrorCode2.TransportNotAvailable,
2166
+ message: "Keystone USB connection was lost during the bundle"
2167
+ });
2168
+ }
2066
2169
  const operationConnectionType = isHardwareOperationId2(connectId) ? this._operations.resolve(connectId).connectionType : void 0;
2067
- const key = accountKey(hwkChain, syncPath);
2068
2170
  let existingRecord = target.record;
2069
2171
  if (!existingRecord) {
2070
2172
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2071
2173
  _KeystoneAdapter._throwIfAborted(signal);
2072
2174
  }
2073
- const booked = book?.get(key);
2074
- if (existingRecord && booked) {
2075
- return { record: existingRecord, account: booked };
2076
- }
2077
- if (!operationConnectionType && existingRecord && !existingRecord.usbSessionId && this._forcedTransport === "usb") {
2078
- await this._tryUsbAttach(signal, existingRecord.masterFingerprint, {
2079
- waitForReenumeration: existingRecord.hadUsbSession
2080
- });
2081
- _KeystoneAdapter._throwIfAborted(signal);
2082
- existingRecord = this._devices.get(existingRecord.masterFingerprint) ?? existingRecord;
2083
- }
2084
- const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2175
+ const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2085
2176
  const schemas = [keySchema(hwkChain, syncPath)];
2086
2177
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2087
2178
  const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
@@ -2090,8 +2181,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
2090
2181
  let record;
2091
2182
  if (useSinglePathUsbExport && existingRecord) {
2092
2183
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
2093
- throw createHwkError({
2094
- code: HardwareErrorCode.DeviceMismatch,
2184
+ throw createHwkError2({
2185
+ code: HardwareErrorCode2.DeviceMismatch,
2095
2186
  message: "Keystone USB account export returned a different master fingerprint"
2096
2187
  });
2097
2188
  }
@@ -2104,25 +2195,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2104
2195
  }
2105
2196
  const account = parsed.accounts.find((a) => normalizePath(a.path) === syncPath);
2106
2197
  if (!account) {
2107
- throw createHwkError({
2108
- code: HardwareErrorCode.DeviceMismatch,
2198
+ throw createHwkError2({
2199
+ code: HardwareErrorCode2.DeviceMismatch,
2109
2200
  message: `Keystone did not return the requested derivation path (${syncPath})`
2110
2201
  });
2111
2202
  }
2112
- const entry = { ...account, hwkChain };
2113
- if (book) {
2114
- for (const returned of parsed.accounts) {
2115
- const returnedChain = inferHwkChainFromPath(returned.path);
2116
- if (returnedChain) {
2117
- book.set(accountKey(returnedChain, returned.path), {
2118
- ...returned,
2119
- hwkChain: returnedChain
2120
- });
2121
- }
2122
- }
2123
- book.set(key, entry);
2124
- }
2125
- return { record, account: entry };
2203
+ return { record, account: { ...account, hwkChain } };
2126
2204
  }
2127
2205
  /**
2128
2206
  * Resolves which wallet is attached, without a per-path account. `CHAIN_FINGERPRINT_PATHS.evm` is
@@ -2216,20 +2294,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2216
2294
  }
2217
2295
  async _callUsbConnector(sessionId, method, params, signal) {
2218
2296
  if (!this._usbConnector) {
2219
- throw createHwkError({
2220
- code: HardwareErrorCode.TransportNotAvailable,
2297
+ throw createHwkError2({
2298
+ code: HardwareErrorCode2.TransportNotAvailable,
2221
2299
  message: "No USB connector configured for this Keystone adapter"
2222
2300
  });
2223
2301
  }
2224
2302
  if (this._pendingUsbTeardowns > 0 || this._unsettledUsbOperations.size > 0) {
2225
- throw createHwkError({
2226
- code: HardwareErrorCode.DeviceBusyInternal,
2303
+ throw createHwkError2({
2304
+ code: HardwareErrorCode2.DeviceBusyInternal,
2227
2305
  message: `Keystone USB is busy while calling ${method}`
2228
2306
  });
2229
2307
  }
2230
2308
  if (signal?.aborted) {
2231
- throw signal.reason instanceof Error ? signal.reason : createHwkError({
2232
- code: HardwareErrorCode.UserAborted,
2309
+ throw signal.reason instanceof Error ? signal.reason : createHwkError2({
2310
+ code: HardwareErrorCode2.UserAborted,
2233
2311
  message: "User aborted operation"
2234
2312
  });
2235
2313
  }
@@ -2308,18 +2386,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
2308
2386
  throw signal.reason instanceof Error ? signal.reason : new Error("Operation aborted");
2309
2387
  }
2310
2388
  }
2389
+ /** A response without the request's id is as unrelated as one with another id. */
2311
2390
  static _assertRequestIdMatches(expected, actual) {
2312
- if (actual && actual.toLowerCase() !== expected.toLowerCase()) {
2313
- throw createHwkError({
2314
- code: HardwareErrorCode.DeviceMismatch,
2315
- message: "Keystone response requestId does not match the pending request \u2014 discarding a stale or unrelated scan"
2391
+ if (!actual || actual.toLowerCase() !== expected.toLowerCase()) {
2392
+ throw createHwkError2({
2393
+ code: HardwareErrorCode2.DeviceMismatch,
2394
+ 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"
2316
2395
  });
2317
2396
  }
2318
2397
  }
2319
2398
  _unsupported(method, reason) {
2320
2399
  return Promise.resolve(
2321
2400
  failure(
2322
- HardwareErrorCode.MethodNotSupported,
2401
+ HardwareErrorCode2.MethodNotSupported,
2323
2402
  `KeystoneAdapter.${method} is not implemented yet: ${reason}`
2324
2403
  )
2325
2404
  );
@@ -2339,20 +2418,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2339
2418
  }
2340
2419
  if (e._tag === UI_REQUEST_CANCELLED_TAG || e._tag === UI_REQUEST_PREEMPTED_TAG) {
2341
2420
  return failure(
2342
- HardwareErrorCode.UserAborted,
2421
+ HardwareErrorCode2.UserAborted,
2343
2422
  e.message ?? "Keystone QR operation was cancelled"
2344
2423
  );
2345
2424
  }
2346
2425
  if (e._tag === UI_REQUEST_TIMEOUT_TAG) {
2347
2426
  return failure(
2348
- HardwareErrorCode.OperationTimeout,
2427
+ HardwareErrorCode2.OperationTimeout,
2349
2428
  e.message ?? "Keystone QR operation timed out"
2350
2429
  );
2351
2430
  }
2352
2431
  }
2353
2432
  const message = err instanceof Error ? err.message : String(err);
2354
2433
  const params = err instanceof Error && err.stack ? { stack: err.stack } : void 0;
2355
- return failure(HardwareErrorCode.UnknownError, message, params);
2434
+ return failure(HardwareErrorCode2.UnknownError, message, params);
2356
2435
  }
2357
2436
  };
2358
2437
  export {