@onekeyfe/hwk-keystone-adapter 1.2.6-alpha.0 → 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.js CHANGED
@@ -205,8 +205,19 @@ function toParsedAccount(key) {
205
205
  name: key.name
206
206
  };
207
207
  }
208
+ var BIP32_HARDENED_OFFSET = 2147483648;
208
209
  function relativeHdPath(relativeDerivePath) {
209
- return `m/${relativeDerivePath.replace(/^m\//i, "")}`;
210
+ const segments = relativeDerivePath.replace(/^m\//i, "").split("/");
211
+ const valid = segments.every(
212
+ (segment) => /^\d+$/.test(segment) && Number(segment) < BIP32_HARDENED_OFFSET
213
+ );
214
+ if (!valid) {
215
+ throw (0, import_hwk_adapter_core.createHwkError)({
216
+ code: import_hwk_adapter_core.HardwareErrorCode.InvalidParams,
217
+ message: `Invalid change/index segments in derivation path (${relativeDerivePath})`
218
+ });
219
+ }
220
+ return `m/${segments.join("/")}`;
210
221
  }
211
222
  var KeystoneUrEngine = class {
212
223
  constructor(origin = "OneKey") {
@@ -546,11 +557,24 @@ function keystoneCancelQueueKeys(identifiers) {
546
557
  }
547
558
 
548
559
  // src/adapter/KeystoneAdapter.ts
560
+ function keystoneBtcParamsFailure(params) {
561
+ const { coin, addressIndex, change } = params;
562
+ if (coin !== void 0 && !["btc", "bitcoin"].includes(String(coin).toLowerCase())) {
563
+ return (0, import_hwk_adapter_core3.failure)(
564
+ import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
565
+ `Keystone BTC supports Bitcoin mainnet only, not ${String(coin)}`
566
+ );
567
+ }
568
+ if (addressIndex !== void 0 || change !== void 0) {
569
+ return (0, import_hwk_adapter_core3.failure)(
570
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
571
+ "Keystone BTC takes the full address path; addressIndex and change are not supported"
572
+ );
573
+ }
574
+ return void 0;
575
+ }
549
576
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
550
577
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
551
- function resolveHardwareOperationTarget(positionalTargetId, operationId) {
552
- return (0, import_hwk_adapter_core3.resolveHardwareOperationTarget)(positionalTargetId, operationId, "keystone");
553
- }
554
578
  function keySchema(chain, path) {
555
579
  return { path, curve: chain === "sol" ? "ed25519" : "secp256k1" };
556
580
  }
@@ -571,9 +595,16 @@ var BIP44_COIN_TYPE_TO_CHAIN = {
571
595
  501: "sol",
572
596
  195: "tron"
573
597
  };
574
- function inferHwkChainFromPath(path) {
598
+ function hasChainCoinType(chain, path) {
575
599
  const match = normalizePath(path).match(/^m\/\d+'\/(\d+)'/);
576
- return match ? BIP44_COIN_TYPE_TO_CHAIN[Number(match[1])] : void 0;
600
+ return Boolean(match) && BIP44_COIN_TYPE_TO_CHAIN[Number(match?.[1])] === chain;
601
+ }
602
+ function coinTypeFailure(chain, path) {
603
+ if (hasChainCoinType(chain, path)) return void 0;
604
+ return (0, import_hwk_adapter_core3.failure)(
605
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
606
+ `Keystone ${chain} needs a path with its own BIP44 coin type, not ${path}`
607
+ );
577
608
  }
578
609
  var KeystoneAdapter = class _KeystoneAdapter {
579
610
  constructor(options) {
@@ -629,18 +660,30 @@ var KeystoneAdapter = class _KeystoneAdapter {
629
660
  // All-network bundle, dispatched to the per-chain methods below.
630
661
  // ---------------------------------------------------------------------------
631
662
  this.allNetworkGetAddress = async (connectId, deviceId, params) => {
632
- const operationTarget = resolveHardwareOperationTarget(connectId, params.operationId);
663
+ const operationTarget = this._resolveOperationTarget(connectId, params.operationId);
633
664
  if (!operationTarget.success) return operationTarget;
634
665
  const effectiveConnectId = operationTarget.payload.targetId ?? "";
635
666
  const { operationId } = operationTarget.payload;
667
+ const namedWallets = new Set(
668
+ [deviceId, ...params.bundle.map((item) => item.deviceId)].filter(
669
+ (id) => typeof id === "string" && id.length > 0
670
+ )
671
+ );
672
+ if (namedWallets.size > 1) {
673
+ return (0, import_hwk_adapter_core3.failure)(
674
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
675
+ "Keystone all-network items name different wallets"
676
+ );
677
+ }
678
+ const [expectedDeviceId = ""] = namedWallets;
636
679
  let cancelScope;
637
680
  try {
638
- const prefetched = await this._prefetchAllNetworkAccounts(effectiveConnectId, deviceId, {
681
+ const prepared = await this._prepareAllNetworkBundle(effectiveConnectId, expectedDeviceId, {
639
682
  ...params,
640
683
  operationId
641
684
  });
642
- const { book } = prefetched;
643
- const itemDeviceId = deviceId || prefetched.masterFingerprint || "";
685
+ const { access } = prepared;
686
+ const itemDeviceId = expectedDeviceId || prepared.masterFingerprint || "";
644
687
  const scope = this._jobQueue.createCancelScope(
645
688
  keystoneQueueKey(effectiveConnectId, itemDeviceId)
646
689
  );
@@ -662,15 +705,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
662
705
  };
663
706
  switch (method) {
664
707
  case "evmGetAddress":
665
- return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
708
+ return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
666
709
  case "btcGetAddress":
667
- return this.btcGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
668
- case "btcGetPublicKey":
669
- return this.btcGetPublicKey(effectiveConnectId, itemDeviceId, commonArgs, book);
710
+ case "btcGetPublicKey": {
711
+ const btcArgs = {
712
+ ...commonArgs,
713
+ coin: item.coin ?? item.network
714
+ };
715
+ return method === "btcGetAddress" ? this.btcGetAddress(effectiveConnectId, itemDeviceId, btcArgs, access) : this.btcGetPublicKey(effectiveConnectId, itemDeviceId, btcArgs, access);
716
+ }
670
717
  case "solGetAddress":
671
- return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
718
+ return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
672
719
  case "tronGetAddress":
673
- return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
720
+ return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
674
721
  default:
675
722
  return (0, import_hwk_adapter_core3.failure)(
676
723
  import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
@@ -694,11 +741,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
694
741
  }
695
742
  });
696
743
  },
697
- // Cancel, refusal or a lost session ends the batch; other per-item
698
- // failures carry on with the next chain.
744
+ // Cancel, refusal, a lost connection or a safety answer (another wallet, a locked
745
+ // device) ends the batch; other per-item failures carry on with the next chain.
699
746
  shouldAbortBundle: (response, { index }) => {
700
747
  const { code } = response.payload ?? {};
701
- return cancelledIndexes.has(index) || (0, import_hwk_adapter_core3.isUserRefusal)(code) || (0, import_hwk_adapter_core3.isConnectionLost)(code);
748
+ const usbSessionLost = access?.channel === "usb" && this._resolveTarget(effectiveConnectId, itemDeviceId).record?.usbSessionId !== access.usbSessionId;
749
+ return cancelledIndexes.has(index) || usbSessionLost || (0, import_hwk_adapter_core3.isWalletSafetyFailure)(code) || (0, import_hwk_adapter_core3.isUserRefusal)(code) || (0, import_hwk_adapter_core3.isConnectionLost)(code);
702
750
  }
703
751
  });
704
752
  } catch (err) {
@@ -1000,6 +1048,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1000
1048
  this._uiRegistry.cancel();
1001
1049
  }
1002
1050
  }
1051
+ /**
1052
+ * Derived from the wallet's master fingerprint, which the caller already holds as deviceId; the
1053
+ * device is never asked. It names the wallet but cannot check which device is attached.
1054
+ */
1003
1055
  getChainFingerprint(connectId, deviceId, chain) {
1004
1056
  try {
1005
1057
  const target = this._resolveTarget(connectId, deviceId);
@@ -1062,14 +1114,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
1062
1114
  // ---------------------------------------------------------------------------
1063
1115
  // EVM
1064
1116
  // ---------------------------------------------------------------------------
1065
- async evmGetAddress(connectIdArg, deviceIdArg, params, book) {
1066
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1117
+ async evmGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1118
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1067
1119
  if (!operationTarget.success) return operationTarget;
1068
1120
  const connectId = operationTarget.payload.targetId;
1069
1121
  const deviceId = deviceIdArg ?? void 0;
1070
1122
  if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmGetAddress requires params");
1071
1123
  if (!params.path)
1072
1124
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmGetAddress requires params.path");
1125
+ const evmCoinTypeFailure = coinTypeFailure("evm", params.path);
1126
+ if (evmCoinTypeFailure) return evmCoinTypeFailure;
1073
1127
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1074
1128
  if (!relativeDerivePath) {
1075
1129
  return (0, import_hwk_adapter_core3.failure)(
@@ -1084,14 +1138,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1084
1138
  "evm",
1085
1139
  accountPath,
1086
1140
  signal,
1087
- book
1141
+ bundle
1088
1142
  );
1089
1143
  const address = this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath);
1090
1144
  return (0, import_hwk_adapter_core3.success)({ address, path: normalizePath(params.path) });
1091
1145
  });
1092
1146
  }
1093
1147
  async evmSignTransaction(connectIdArg, deviceIdArg, params) {
1094
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1148
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1095
1149
  if (!operationTarget.success) return operationTarget;
1096
1150
  const connectId = operationTarget.payload.targetId;
1097
1151
  const deviceId = deviceIdArg ?? void 0;
@@ -1132,7 +1186,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1132
1186
  });
1133
1187
  }
1134
1188
  async evmSignMessage(connectIdArg, deviceIdArg, params) {
1135
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1189
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1136
1190
  if (!operationTarget.success) return operationTarget;
1137
1191
  const connectId = operationTarget.payload.targetId;
1138
1192
  const deviceId = deviceIdArg ?? void 0;
@@ -1164,7 +1218,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1164
1218
  });
1165
1219
  }
1166
1220
  async evmSignTypedData(connectIdArg, deviceIdArg, params) {
1167
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1221
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1168
1222
  if (!operationTarget.success) return operationTarget;
1169
1223
  const connectId = operationTarget.payload.targetId;
1170
1224
  const deviceId = deviceIdArg ?? void 0;
@@ -1206,14 +1260,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
1206
1260
  // BTC: 44'/49'/84' addresses derive offline from the account xpub; P2TR addresses
1207
1261
  // and structured-field tx signing are unsupported (the host builds a PSBT instead).
1208
1262
  // ---------------------------------------------------------------------------
1209
- async btcGetAddress(connectIdArg, deviceIdArg, params, book) {
1210
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1263
+ async btcGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1264
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1211
1265
  if (!operationTarget.success) return operationTarget;
1212
1266
  const connectId = operationTarget.payload.targetId;
1213
1267
  const deviceId = deviceIdArg ?? void 0;
1214
1268
  if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetAddress requires params");
1215
1269
  if (!params.path)
1216
1270
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetAddress requires params.path");
1271
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1272
+ if (btcParamsFailure) return btcParamsFailure;
1217
1273
  const scriptType = btcScriptTypeFromPath(params.path);
1218
1274
  if (!scriptType) {
1219
1275
  return (0, import_hwk_adapter_core3.failure)(
@@ -1245,7 +1301,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1245
1301
  "btc",
1246
1302
  accountPath,
1247
1303
  signal,
1248
- book
1304
+ bundle
1249
1305
  );
1250
1306
  const address = this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType);
1251
1307
  return (0, import_hwk_adapter_core3.success)({ address, path: normalizedPath });
@@ -1255,14 +1311,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
1255
1311
  * `params.path` must be an account path (`m/84'/0'/0'`), the level Keystone syncs. An xpub is
1256
1312
  * script-type agnostic, so `86'` works here even though `btcGetAddress` rejects it.
1257
1313
  */
1258
- async btcGetPublicKey(connectIdArg, deviceIdArg, params, book) {
1259
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1314
+ async btcGetPublicKey(connectIdArg, deviceIdArg, params, bundle) {
1315
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1260
1316
  if (!operationTarget.success) return operationTarget;
1261
1317
  const connectId = operationTarget.payload.targetId;
1262
1318
  const deviceId = deviceIdArg ?? void 0;
1263
1319
  if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params");
1264
1320
  if (!params.path)
1265
1321
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params.path");
1322
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1323
+ if (btcParamsFailure) return btcParamsFailure;
1266
1324
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1267
1325
  if (relativeDerivePath) {
1268
1326
  return (0, import_hwk_adapter_core3.failure)(
@@ -1280,7 +1338,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1280
1338
  "btc",
1281
1339
  accountPath,
1282
1340
  signal,
1283
- book
1341
+ bundle
1284
1342
  );
1285
1343
  const meta = this.urEngine.parseXpubMeta(xpub);
1286
1344
  return (0, import_hwk_adapter_core3.success)({
@@ -1300,7 +1358,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1300
1358
  );
1301
1359
  }
1302
1360
  async btcSignPsbt(connectIdArg, deviceIdArg, params) {
1303
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1361
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1304
1362
  if (!operationTarget.success) return operationTarget;
1305
1363
  const connectId = operationTarget.payload.targetId;
1306
1364
  const deviceId = deviceIdArg ?? void 0;
@@ -1330,7 +1388,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1330
1388
  });
1331
1389
  }
1332
1390
  async btcSignMessage(connectIdArg, deviceIdArg, params) {
1333
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1391
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1334
1392
  if (!operationTarget.success) return operationTarget;
1335
1393
  const connectId = operationTarget.payload.targetId;
1336
1394
  const deviceId = deviceIdArg ?? void 0;
@@ -1361,8 +1419,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1361
1419
  toPayload: (sig) => ({ signature: sig.signature })
1362
1420
  });
1363
1421
  }
1422
+ /**
1423
+ * Returns the known master fingerprint for the named wallet without asking the device (a QR
1424
+ * round trip only to repeat it would cost a scan). Use it to name the wallet, for example as a
1425
+ * PSBT xfp, which the device itself checks when signing; it cannot check the attached device.
1426
+ */
1364
1427
  async btcGetMasterFingerprint(connectIdArg, deviceIdArg, paramsArg) {
1365
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, paramsArg?.operationId);
1428
+ const operationTarget = this._resolveOperationTarget(connectIdArg, paramsArg?.operationId);
1366
1429
  if (!operationTarget.success) return operationTarget;
1367
1430
  const connectId = operationTarget.payload.targetId;
1368
1431
  const deviceId = deviceIdArg ?? void 0;
@@ -1374,24 +1437,39 @@ var KeystoneAdapter = class _KeystoneAdapter {
1374
1437
  // ---------------------------------------------------------------------------
1375
1438
  // SOL
1376
1439
  // ---------------------------------------------------------------------------
1377
- async solGetAddress(connectIdArg, deviceIdArg, params, book) {
1378
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1440
+ async solGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1441
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1379
1442
  if (!operationTarget.success) return operationTarget;
1380
1443
  const connectId = operationTarget.payload.targetId;
1381
1444
  const deviceId = deviceIdArg ?? void 0;
1382
1445
  if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solGetAddress requires params");
1383
1446
  if (!params.path)
1384
1447
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solGetAddress requires params.path");
1448
+ const solCoinTypeFailure = coinTypeFailure("sol", params.path);
1449
+ if (solCoinTypeFailure) return solCoinTypeFailure;
1385
1450
  const path = normalizePath(params.path);
1451
+ if (!/^m(\/\d+')+$/.test(path)) {
1452
+ return (0, import_hwk_adapter_core3.failure)(
1453
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1454
+ "solGetAddress requires a fully hardened path, e.g. m/44'/501'/0'/0'"
1455
+ );
1456
+ }
1386
1457
  return this._runJob(connectId, deviceId, async (signal) => {
1387
- const { account } = await this._fetchAccount(connectId, deviceId, "sol", path, signal, book);
1458
+ const { account } = await this._fetchAccount(
1459
+ connectId,
1460
+ deviceId,
1461
+ "sol",
1462
+ path,
1463
+ signal,
1464
+ bundle
1465
+ );
1388
1466
  _KeystoneAdapter._throwIfAborted(signal);
1389
1467
  const address = import_bs58.default.encode(Buffer.from(account.publicKey, "hex"));
1390
1468
  return (0, import_hwk_adapter_core3.success)({ address, path });
1391
1469
  });
1392
1470
  }
1393
1471
  async solSignTransaction(connectIdArg, deviceIdArg, params) {
1394
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1472
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1395
1473
  if (!operationTarget.success) return operationTarget;
1396
1474
  const connectId = operationTarget.payload.targetId;
1397
1475
  const deviceId = deviceIdArg ?? void 0;
@@ -1422,7 +1500,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1422
1500
  });
1423
1501
  }
1424
1502
  async solSignMessage(connectIdArg, deviceIdArg, params) {
1425
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1503
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1426
1504
  if (!operationTarget.success) return operationTarget;
1427
1505
  const connectId = operationTarget.payload.targetId;
1428
1506
  const deviceId = deviceIdArg ?? void 0;
@@ -1455,14 +1533,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
1455
1533
  // TRON: keystone-sdk-rust layout (tags 5201/5202, firmware >= 2.5.0), not sdk.tron's
1456
1534
  // protobuf module; OneKey Pro's encoding under the same tag is rejected by the firmware.
1457
1535
  // ---------------------------------------------------------------------------
1458
- async tronGetAddress(connectIdArg, deviceIdArg, params, book) {
1459
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1536
+ async tronGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1537
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1460
1538
  if (!operationTarget.success) return operationTarget;
1461
1539
  const connectId = operationTarget.payload.targetId;
1462
1540
  const deviceId = deviceIdArg ?? void 0;
1463
1541
  if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronGetAddress requires params");
1464
1542
  if (!params.path)
1465
1543
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronGetAddress requires params.path");
1544
+ const tronCoinTypeFailure = coinTypeFailure("tron", params.path);
1545
+ if (tronCoinTypeFailure) return tronCoinTypeFailure;
1466
1546
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1467
1547
  if (!relativeDerivePath) {
1468
1548
  return (0, import_hwk_adapter_core3.failure)(
@@ -1477,14 +1557,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1477
1557
  "tron",
1478
1558
  accountPath,
1479
1559
  signal,
1480
- book
1560
+ bundle
1481
1561
  );
1482
1562
  const address = this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath);
1483
1563
  return (0, import_hwk_adapter_core3.success)({ address, path: normalizePath(params.path) });
1484
1564
  });
1485
1565
  }
1486
1566
  async tronSignTransaction(connectIdArg, deviceIdArg, params) {
1487
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1567
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1488
1568
  if (!operationTarget.success) return operationTarget;
1489
1569
  const connectId = operationTarget.payload.targetId;
1490
1570
  const deviceId = deviceIdArg ?? void 0;
@@ -1519,7 +1599,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1519
1599
  });
1520
1600
  }
1521
1601
  async tronSignMessage(connectIdArg, deviceIdArg, params) {
1522
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1602
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1523
1603
  if (!operationTarget.success) return operationTarget;
1524
1604
  const connectId = operationTarget.payload.targetId;
1525
1605
  const deviceId = deviceIdArg ?? void 0;
@@ -1565,14 +1645,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1565
1645
  return this._errorToFailure(err);
1566
1646
  }
1567
1647
  }
1568
- async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, book) {
1648
+ async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, bundle) {
1569
1649
  const { account } = await this._fetchAccount(
1570
1650
  connectId,
1571
1651
  deviceId,
1572
1652
  hwkChain,
1573
1653
  accountPath,
1574
1654
  signal,
1575
- book
1655
+ bundle
1576
1656
  );
1577
1657
  _KeystoneAdapter._throwIfAborted(signal);
1578
1658
  if (!account.extendedPublicKey) {
@@ -1613,6 +1693,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1613
1693
  const method = item.methodName;
1614
1694
  const hwkChain = (0, import_hwk_adapter_core3.getAllNetworkMethodChain)(method);
1615
1695
  const path = normalizePath(item.path);
1696
+ if (!hasChainCoinType(hwkChain, path)) return void 0;
1616
1697
  if (hwkChain === "btc" && !isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1617
1698
  return void 0;
1618
1699
  }
@@ -1629,10 +1710,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1629
1710
  }
1630
1711
  }
1631
1712
  /**
1632
- * QR answers the whole bundle with one request QR and one scan. USB exports one path per
1633
- * request because the device limits that channel.
1713
+ * Picks the bundle's channel. QR answers every item with one request QR and one scan; USB items
1714
+ * each ask the device directly, like other vendors, on the session found here.
1634
1715
  */
1635
- async _prefetchAllNetworkAccounts(connectId, deviceId, params) {
1716
+ async _prepareAllNetworkBundle(connectId, deviceId, params) {
1636
1717
  return this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), async (signal) => {
1637
1718
  const target = this._resolveTarget(connectId, deviceId);
1638
1719
  let { record } = target;
@@ -1641,21 +1722,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1641
1722
  const schema = this._allNetworkSyncSchema(item);
1642
1723
  if (schema) requestedByKey.set(accountKey(schema.hwkChain, schema.path), schema);
1643
1724
  }
1644
- const book = /* @__PURE__ */ new Map();
1725
+ const scanned = /* @__PURE__ */ new Map();
1645
1726
  if (!requestedByKey.size) {
1646
- return { book };
1727
+ return { access: { channel: "qr", scanned } };
1647
1728
  }
1648
- const requestedSchemas = Array.from(requestedByKey.values());
1649
- const assertAllBooked = () => {
1650
- for (const schema of requestedSchemas) {
1651
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1652
- throw (0, import_hwk_adapter_core3.createHwkError)({
1653
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1654
- message: `Keystone did not return the requested derivation path (${schema.path})`
1655
- });
1656
- }
1657
- }
1658
- };
1659
1729
  const operation = (0, import_hwk_adapter_core3.isHardwareOperationId)(params.operationId) ? this._operations.find(params.operationId) : void 0;
1660
1730
  const operationRoute = operation ? this._operationRoutes.get(operation.connectId) : void 0;
1661
1731
  const routedToQr = operationRoute?.operationId === operation?.operationId && operationRoute?.connectionType === "qr";
@@ -1664,40 +1734,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1664
1734
  _KeystoneAdapter._throwIfAborted(signal);
1665
1735
  }
1666
1736
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1667
- const bundleSessionId = record.usbSessionId;
1668
- const assertBundleSession = () => {
1669
- if (record?.usbSessionId !== bundleSessionId) {
1670
- throw (0, import_hwk_adapter_core3.createHwkError)({
1671
- code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
1672
- message: "Keystone USB connection was lost during account export"
1673
- });
1674
- }
1737
+ return {
1738
+ access: { channel: "usb", usbSessionId: record.usbSessionId },
1739
+ masterFingerprint: record.masterFingerprint
1675
1740
  };
1676
- for (const schema of requestedSchemas) {
1677
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1678
- assertBundleSession();
1679
- const synced = await this._fetchAccount(
1680
- connectId,
1681
- deviceId,
1682
- schema.hwkChain,
1683
- schema.path,
1684
- signal,
1685
- book
1686
- );
1687
- record = synced.record;
1688
- assertBundleSession();
1689
- }
1690
- }
1691
- assertAllBooked();
1692
- return { book, masterFingerprint: record.masterFingerprint };
1693
1741
  }
1694
- if (this._forcedTransport === "usb") {
1742
+ if (this._forcedTransport === "usb" && !routedToQr) {
1695
1743
  throw (0, import_hwk_adapter_core3.createHwkError)({
1696
1744
  code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
1697
1745
  message: "USB channel is not connected for this Keystone wallet"
1698
1746
  });
1699
1747
  }
1700
- const schemas = requestedSchemas;
1748
+ const schemas = Array.from(requestedByKey.values());
1701
1749
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1702
1750
  schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1703
1751
  origin: this._origin
@@ -1711,21 +1759,50 @@ var KeystoneAdapter = class _KeystoneAdapter {
1711
1759
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1712
1760
  this._assertParsedIdentity(parsed, target);
1713
1761
  record = this._upsertDeviceRecord(parsed);
1714
- const requestedChainByPath = new Map(
1715
- schemas.map((schema) => [normalizePath(schema.path), schema.hwkChain])
1716
- );
1717
- for (const account of parsed.accounts) {
1718
- const normalizedPath = normalizePath(account.path);
1719
- const hwkChain = requestedChainByPath.get(normalizedPath) ?? inferHwkChainFromPath(normalizedPath);
1720
- if (hwkChain) {
1721
- book.set(accountKey(hwkChain, normalizedPath), { ...account, hwkChain });
1762
+ for (const schema of schemas) {
1763
+ const account = parsed.accounts.find(
1764
+ (returned) => normalizePath(returned.path) === schema.path
1765
+ );
1766
+ if (!account) {
1767
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1768
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1769
+ message: `Keystone did not return the requested derivation path (${schema.path})`
1770
+ });
1722
1771
  }
1772
+ scanned.set(accountKey(schema.hwkChain, schema.path), {
1773
+ ...account,
1774
+ hwkChain: schema.hwkChain
1775
+ });
1723
1776
  }
1724
- assertAllBooked();
1725
- return { book, masterFingerprint: record.masterFingerprint };
1777
+ return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1726
1778
  });
1727
1779
  }
1728
1780
  /** Resolve the wallet's master fingerprint from the connectId and/or deviceId the caller passed. */
1781
+ /**
1782
+ * A positional wallet id and an operation id must name the same wallet: otherwise the call
1783
+ * would run on the operation's wallet while the caller files the result under the other one.
1784
+ * Ids that do not carry a master fingerprint cannot be compared and pass through.
1785
+ */
1786
+ _resolveOperationTarget(positionalTargetId, operationId) {
1787
+ const target = (0, import_hwk_adapter_core3.resolveHardwareOperationTarget)(
1788
+ positionalTargetId,
1789
+ operationId,
1790
+ "keystone"
1791
+ );
1792
+ if (!target.success || !operationId || !positionalTargetId || (0, import_hwk_adapter_core3.isHardwareOperationId)(positionalTargetId)) {
1793
+ return target;
1794
+ }
1795
+ const operation = this._operations.find(operationId);
1796
+ const positionalMfp = keystoneMfpFromIdentifier(positionalTargetId);
1797
+ const operationMfp = operation ? keystoneMfpFromIdentifier(operation.connectId) : void 0;
1798
+ if (positionalMfp && operationMfp && positionalMfp !== operationMfp) {
1799
+ return (0, import_hwk_adapter_core3.failure)(
1800
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1801
+ "Keystone connectId and operationId name different wallets"
1802
+ );
1803
+ }
1804
+ return target;
1805
+ }
1729
1806
  _resolveTarget(connectId, deviceId) {
1730
1807
  const resolvedConnectId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? this._operations.resolve(connectId).connectId : connectId;
1731
1808
  const identifiers = [deviceId, resolvedConnectId].filter(
@@ -1913,6 +1990,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1913
1990
  }
1914
1991
  }
1915
1992
  if (!availableDevices.length) {
1993
+ const record = options?.waitForReenumeration ? this._devices.get(expectedMasterFingerprint) : void 0;
1994
+ if (record) record.hadUsbSession = false;
1916
1995
  if (this._forcedTransport === "usb" && lastSearchError) {
1917
1996
  throw lastSearchError instanceof Error ? lastSearchError : new Error(String(lastSearchError));
1918
1997
  }
@@ -1929,8 +2008,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1929
2008
  return attached.success ? this._devices.get(expectedMasterFingerprint) : void 0;
1930
2009
  }
1931
2010
  /**
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.
2011
+ * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
2012
+ * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
1934
2013
  */
1935
2014
  async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
1936
2015
  const releaseOperationRetention = (0, import_hwk_adapter_core3.isHardwareOperationId)(operationId) ? this._operations.retain(operationId) : void 0;
@@ -1961,7 +2040,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1961
2040
  }
1962
2041
  interactionRoute = route;
1963
2042
  }
1964
- if (!interactionRoute && !this._forcedTransport && record && !record.usbSessionId && this._usbConnector) {
2043
+ if (!interactionRoute && this._forcedTransport !== "qr" && record && !record.usbSessionId && this._usbConnector) {
1965
2044
  record = await this._tryUsbAttach(signal, record.masterFingerprint, {
1966
2045
  waitForReenumeration: record.hadUsbSession
1967
2046
  }) ?? record;
@@ -2058,30 +2137,35 @@ var KeystoneAdapter = class _KeystoneAdapter {
2058
2137
  });
2059
2138
  }
2060
2139
  /**
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.
2140
+ * Fetches one account's key material. An all-network QR item takes it from the bundle's scan; a
2141
+ * USB item asks the device on the bundle's session. A failed USB export ends the operation
2142
+ * without replaying or switching transports.
2063
2143
  */
2064
- async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, book) {
2144
+ async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, bundle) {
2065
2145
  const target = this._resolveTarget(connectId, deviceId);
2146
+ if (bundle?.channel === "qr") {
2147
+ const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2148
+ if (!target.record || !scanned) {
2149
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2150
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2151
+ message: `Keystone did not return the requested derivation path (${syncPath})`
2152
+ });
2153
+ }
2154
+ return { record: target.record, account: scanned };
2155
+ }
2156
+ if (bundle?.channel === "usb" && target.record?.usbSessionId !== bundle.usbSessionId) {
2157
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2158
+ code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
2159
+ message: "Keystone USB connection was lost during the bundle"
2160
+ });
2161
+ }
2066
2162
  const operationConnectionType = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? this._operations.resolve(connectId).connectionType : void 0;
2067
- const key = accountKey(hwkChain, syncPath);
2068
2163
  let existingRecord = target.record;
2069
2164
  if (!existingRecord) {
2070
2165
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2071
2166
  _KeystoneAdapter._throwIfAborted(signal);
2072
2167
  }
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);
2168
+ const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2085
2169
  const schemas = [keySchema(hwkChain, syncPath)];
2086
2170
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2087
2171
  const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
@@ -2109,20 +2193,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2109
2193
  message: `Keystone did not return the requested derivation path (${syncPath})`
2110
2194
  });
2111
2195
  }
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 };
2196
+ return { record, account: { ...account, hwkChain } };
2126
2197
  }
2127
2198
  /**
2128
2199
  * Resolves which wallet is attached, without a per-path account. `CHAIN_FINGERPRINT_PATHS.evm` is