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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -7,6 +7,7 @@ import HDKey from "hdkey";
7
7
  import { parse as uuidParse, stringify as uuidStringify } from "uuid";
8
8
  import {
9
9
  HardwareErrorCode,
10
+ boundedCborFromHex,
10
11
  createHwkError,
11
12
  parseWalletMasterFingerprint
12
13
  } from "@onekeyfe/hwk-adapter-core";
@@ -70,11 +71,12 @@ var TronSignRequest = class _TronSignRequest extends RegistryItem {
70
71
  static parsePath(path, xfp) {
71
72
  const segments = path.replace(/^[mM]\//, "").split("/");
72
73
  const components = segments.map((segment) => {
73
- const hardened = segment.endsWith("'");
74
- return new PathComponent({
75
- index: parseInt(hardened ? segment.slice(0, -1) : segment, 10),
76
- hardened
77
- });
74
+ const match = /^(\d+)('?)$/.exec(segment);
75
+ const index = match ? Number(match[1]) : NaN;
76
+ if (!match || index >= 2147483648) {
77
+ throw new Error(`Invalid TRON derivation path segment (${segment})`);
78
+ }
79
+ return new PathComponent({ index, hardened: match[2] === "'" });
78
80
  });
79
81
  return new CryptoKeypath(components, Buffer.from(xfp, "hex"));
80
82
  }
@@ -138,7 +140,7 @@ var DERIVATION_CURVE = {
138
140
  ed25519: Curve.ed25519
139
141
  };
140
142
  function toSdkUr(ur) {
141
- return new UR(Buffer.from(ur.urData, "hex"), ur.urType);
143
+ return new UR(boundedCborFromHex(ur.urData), ur.urType);
142
144
  }
143
145
  function fromSdkUr(ur) {
144
146
  return { urType: ur.type, urData: ur.cbor.toString("hex") };
@@ -190,6 +192,11 @@ function relativeHdPath(relativeDerivePath) {
190
192
  }
191
193
  return `m/${segments.join("/")}`;
192
194
  }
195
+ var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.]{1,20})?$/;
196
+ var DEVICE_TEXT = /^[^\p{Cc}\p{Cf}]{1,64}$/u;
197
+ function deviceText(value, pattern) {
198
+ return typeof value === "string" && pattern.test(value) ? value : void 0;
199
+ }
193
200
  var KeystoneUrEngine = class {
194
201
  constructor(origin = "OneKey") {
195
202
  this.sdk = new KeystoneSDK({ origin });
@@ -199,9 +206,9 @@ var KeystoneUrEngine = class {
199
206
  const parsed = this.sdk.parseMultiAccounts(toSdkUr(ur));
200
207
  return {
201
208
  masterFingerprint: requireBip32MasterFingerprint(parsed.masterFingerprint),
202
- device: parsed.device,
203
- deviceId: parsed.deviceId,
204
- deviceVersion: parsed.deviceVersion,
209
+ device: deviceText(parsed.device, DEVICE_TEXT),
210
+ deviceId: deviceText(parsed.deviceId, DEVICE_TEXT),
211
+ deviceVersion: deviceText(parsed.deviceVersion, FIRMWARE_VERSION),
205
212
  accounts: parsed.keys.map(toParsedAccount)
206
213
  };
207
214
  }
@@ -263,10 +270,7 @@ var KeystoneUrEngine = class {
263
270
  return generateAddressFromXpub(xpub, relativeHdPath(relativeDerivePath));
264
271
  }
265
272
  // --- BTC (PSBT transaction signing + plain message signing) ---
266
- /**
267
- * `CryptoHDKey` always emits mainnet xpub version bytes (`0488B21E`), so `hdkey` parses it as is.
268
- * `p2tr` needs an ECC lib for BIP-341 tweaking, not wired here.
269
- */
273
+ /** `CryptoHDKey` always emits mainnet xpub version bytes (`0488B21E`), so `hdkey` parses it as is. */
270
274
  deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType) {
271
275
  const node = HDKey.fromExtendedKey(xpub).derive(relativeHdPath(relativeDerivePath));
272
276
  if (!node.publicKey) throw new Error("HDKey derivation did not produce a public key");
@@ -312,9 +316,27 @@ var KeystoneUrEngine = class {
312
316
  const ur = this.sdk.btc.generatePSBT(Buffer.from(unsignedPsbtHex, "hex"));
313
317
  return fromSdkUr(ur);
314
318
  }
315
- /** Returns the hex-encoded (possibly still-unsigned-in-part) PSBT the device replied with. */
316
- parseBtcPsbt(ur) {
317
- return this.sdk.btc.parsePSBT(toSdkUr(ur));
319
+ /**
320
+ * Returns the hex-encoded (possibly still-unsigned-in-part) PSBT the device replied with. A PSBT
321
+ * carries no request id, so the reply is bound to the request by its unsigned transaction, which
322
+ * signing never changes (BIP-174); a scan of another PSBT's signature is refused.
323
+ */
324
+ parseBtcPsbt(ur, requestPsbtHex) {
325
+ const signedPsbtHex = this.sdk.btc.parsePSBT(toSdkUr(ur));
326
+ let sameTransaction = false;
327
+ try {
328
+ const unsignedTx = (hex) => Buffer.from(bitcoin.Psbt.fromHex(hex).data.globalMap.unsignedTx.toBuffer());
329
+ sameTransaction = unsignedTx(signedPsbtHex).equals(unsignedTx(requestPsbtHex));
330
+ } catch {
331
+ sameTransaction = false;
332
+ }
333
+ if (!sameTransaction) {
334
+ throw createHwkError({
335
+ code: HardwareErrorCode.DeviceMismatch,
336
+ message: "Keystone returned a PSBT for another transaction than the one requested"
337
+ });
338
+ }
339
+ return signedPsbtHex;
318
340
  }
319
341
  buildBtcMessageSignRequest(params) {
320
342
  const ur = this.sdk.btc.generateSignRequest({
@@ -374,7 +396,7 @@ var KeystoneUrEngine = class {
374
396
  if (ur.urType !== "tron-signature") {
375
397
  throw new Error(`Expected a tron-signature UR, got ${ur.urType}`);
376
398
  }
377
- const signature = TronSignature.fromCBOR(Buffer.from(ur.urData, "hex"));
399
+ const signature = TronSignature.fromCBOR(boundedCborFromHex(ur.urData));
378
400
  const requestId = signature.getRequestId();
379
401
  return {
380
402
  requestId: requestId ? uuidStringify(requestId) : void 0,
@@ -426,6 +448,7 @@ import {
426
448
  UI_REQUEST_TIMEOUT_TAG,
427
449
  UI_RESPONSE,
428
450
  UiRequestRegistry,
451
+ buildAllNetworkCancelledFailure,
429
452
  createHardwareSearchTargetId,
430
453
  createHwkError as createHwkError2,
431
454
  deriveDeviceFingerprint,
@@ -445,7 +468,6 @@ import {
445
468
  rehydrateConnectorError,
446
469
  resolveHardwareOperationTarget as resolveGenericHardwareOperationTarget,
447
470
  runAllNetworkGetAddress,
448
- stripHex,
449
471
  success
450
472
  } from "@onekeyfe/hwk-adapter-core";
451
473
 
@@ -454,14 +476,26 @@ function normalizePath(path) {
454
476
  const trimmed = path.trim();
455
477
  return /^m\//i.test(trimmed) ? `m/${trimmed.slice(2)}` : `m/${trimmed}`;
456
478
  }
479
+ var BIP32_HARDENED_OFFSET2 = 2147483648;
480
+ function isBip32Path(path) {
481
+ const segments = normalizePath(path).slice(2).split("/");
482
+ return segments.every((segment) => {
483
+ const match = /^(\d+)'?$/.exec(segment);
484
+ return match !== null && Number(match[1]) < BIP32_HARDENED_OFFSET2;
485
+ });
486
+ }
457
487
  function splitAccountPath(path) {
458
488
  const normalized = normalizePath(path);
459
489
  const segments = normalized.slice(2).split("/");
460
- if (segments.length <= 3) {
490
+ let accountLength = 0;
491
+ segments.forEach((segment, index) => {
492
+ if (segment.endsWith("'")) accountLength = index + 1;
493
+ });
494
+ if (segments.length <= 3 || accountLength === 0 || accountLength === segments.length) {
461
495
  return { accountPath: normalized, relativeDerivePath: "" };
462
496
  }
463
- const accountSegments = segments.slice(0, segments.length - 2);
464
- const relativeSegments = segments.slice(segments.length - 2);
497
+ const accountSegments = segments.slice(0, accountLength);
498
+ const relativeSegments = segments.slice(accountLength);
465
499
  return {
466
500
  accountPath: `m/${accountSegments.join("/")}`,
467
501
  relativeDerivePath: relativeSegments.join("/")
@@ -590,12 +624,6 @@ function waitForKeystoneUsbReattachProbe() {
590
624
  setTimeout(resolve, KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS);
591
625
  });
592
626
  }
593
- function buildCancelledFailure(signal) {
594
- const reason = signal.reason;
595
- const code = typeof reason?.code === "number" ? reason.code : HardwareErrorCode2.UserAborted;
596
- const message = typeof reason?.message === "string" ? reason.message : "";
597
- return failure(code, message || "All-network get-address cancelled");
598
- }
599
627
  var BIP44_COIN_TYPE_TO_CHAIN = {
600
628
  60: "evm",
601
629
  0: "btc",
@@ -606,6 +634,23 @@ function hasChainCoinType(chain, path) {
606
634
  const match = normalizePath(path).match(/^m\/\d+'\/(\d+)'/);
607
635
  return Boolean(match) && BIP44_COIN_TYPE_TO_CHAIN[Number(match?.[1])] === chain;
608
636
  }
637
+ function exactHex(value) {
638
+ const hex = value.replace(/^0x/i, "");
639
+ return /^(?:[0-9a-f]{2})*$/i.test(hex) ? hex : void 0;
640
+ }
641
+ function invalidHexFailure(field) {
642
+ return failure(HardwareErrorCode2.InvalidParams, `${field} must be an even-length hex string`);
643
+ }
644
+ function requireExportedPath(parsed, path) {
645
+ const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
646
+ if (!account) {
647
+ throw createHwkError2({
648
+ code: HardwareErrorCode2.DeviceMismatch,
649
+ message: `Keystone did not return the requested derivation path (${path})`
650
+ });
651
+ }
652
+ return account;
653
+ }
609
654
  function coinTypeFailure(chain, path) {
610
655
  if (hasChainCoinType(chain, path)) return void 0;
611
656
  return failure(
@@ -613,6 +658,19 @@ function coinTypeFailure(chain, path) {
613
658
  `Keystone ${chain} needs a path with its own BIP44 coin type, not ${path}`
614
659
  );
615
660
  }
661
+ function btcAccountFailure(accountPath) {
662
+ if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
663
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
664
+ }
665
+ function missingParamFailure(method, param) {
666
+ return failure(HardwareErrorCode2.InvalidParams, `${method} requires ${param}`);
667
+ }
668
+ function messageToHex(message, hex) {
669
+ return hex ? exactHex(message) : Buffer.from(message, "utf8").toString("hex");
670
+ }
671
+ function evmMessageSignature(sig) {
672
+ return { signature: ensure0x(sig.r + sig.s + sig.v) };
673
+ }
616
674
  var KeystoneAdapter = class _KeystoneAdapter {
617
675
  constructor(options) {
618
676
  this.vendor = "keystone";
@@ -627,6 +685,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
627
685
  const route = this._operationRoutes.get(operation.connectId);
628
686
  if (route?.operationId === operation.operationId) {
629
687
  this._operationRoutes.delete(operation.connectId);
688
+ if (route.connectionType === "qr") {
689
+ const ended = createHwkError2({
690
+ code: HardwareErrorCode2.OperationEnded,
691
+ message: "Keystone operation has ended",
692
+ params: { operationId: operation.operationId, reason }
693
+ });
694
+ const queueKey = keystoneQueueKey(operation.operationId);
695
+ const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
696
+ this._jobQueue.cancelActiveAndPending(queueKey, ended);
697
+ if (ownsRunningCall) {
698
+ this._uiRegistry.cancel(void 0, void 0, operation.operationId);
699
+ }
700
+ }
630
701
  }
631
702
  this.emitter.emit(SDK.OPERATION_ENDED, {
632
703
  type: SDK.OPERATION_ENDED,
@@ -703,7 +774,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
703
774
  callItem: async ({ method, item, index }) => {
704
775
  if (scope.signal.aborted) {
705
776
  cancelledIndexes.add(index);
706
- return buildCancelledFailure(scope.signal);
777
+ return buildAllNetworkCancelledFailure(scope.signal);
707
778
  }
708
779
  const commonArgs = {
709
780
  path: item.path,
@@ -725,11 +796,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
725
796
  return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
726
797
  case "tronGetAddress":
727
798
  return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
728
- default:
729
- return failure(
730
- HardwareErrorCode2.MethodNotSupported,
731
- `Unsupported method: ${String(method)}`
732
- );
733
799
  }
734
800
  },
735
801
  attachIdentity: (context) => {
@@ -770,9 +836,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
770
836
  this._usbConnector?.on("device-disconnect", this._handleUsbDisconnect);
771
837
  this._usbConnector?.on("ui-event", this._handleUsbUiEvent);
772
838
  }
773
- // ---------------------------------------------------------------------------
774
- // Lifecycle / transport
775
- // ---------------------------------------------------------------------------
776
839
  get activeTransport() {
777
840
  if (this._devices.size === 0) return null;
778
841
  const hasUsbSession = Array.from(this._devices.values()).some((r) => r.usbSessionId);
@@ -802,9 +865,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
802
865
  this._devices.clear();
803
866
  this.emitter.removeAllListeners();
804
867
  }
805
- // ---------------------------------------------------------------------------
806
- // Device table
807
- // ---------------------------------------------------------------------------
808
868
  /**
809
869
  * Returns known wallets plus USB scan results; USB entries have no mfp until `connectDevice()`
810
870
  * claims them. Explicit QR discovery returns one virtual target.
@@ -877,11 +937,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
877
937
  }
878
938
  /** Best-effort disconnect; the session is retired either way so it cannot be selected again. */
879
939
  async _retireUsbSession(sessionId) {
880
- if (this._usbConnector) {
881
- try {
882
- await this._usbConnector.disconnect(sessionId);
883
- } catch {
884
- }
940
+ try {
941
+ await this._usbConnector?.disconnect(sessionId);
942
+ } catch {
885
943
  }
886
944
  this._handleUsbDisconnect({ connectId: sessionId });
887
945
  }
@@ -900,13 +958,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
900
958
  serialNumber: device.serialNumber
901
959
  }));
902
960
  }
903
- async listConnectionTargets(options) {
904
- const targets = await this.searchDeviceTargets(options);
905
- return targets.map(({ searchTargetId, ...target }) => ({
906
- ...target,
907
- targetId: searchTargetId
908
- }));
909
- }
910
961
  async connectDevice(searchTargetId) {
911
962
  const scope = this._jobQueue.createCancelScope(searchTargetId);
912
963
  try {
@@ -915,16 +966,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
915
966
  const discoveredConnectionType = this._searchDeviceTargets.get(searchTargetId);
916
967
  if (discoveredConnectionType === "qr") {
917
968
  selectedConnectionType = "qr";
918
- const abortColdStart = () => this._jobQueue.cancelActiveAndPending(
919
- KEYSTONE_COLD_START_JOB_LABEL,
920
- scope.signal.reason
969
+ connected = await _KeystoneAdapter._untilAborted(
970
+ scope.signal,
971
+ this._importFromQr({}, searchTargetId)
921
972
  );
922
- scope.signal.addEventListener("abort", abortColdStart, { once: true });
923
- try {
924
- connected = await this.importFromQr();
925
- } finally {
926
- scope.signal.removeEventListener("abort", abortColdStart);
927
- }
928
973
  } else if (discoveredConnectionType === "usb") {
929
974
  selectedConnectionType = "usb";
930
975
  if (!this._usbConnector) {
@@ -933,7 +978,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
933
978
  "No USB connector configured for this Keystone adapter"
934
979
  );
935
980
  }
936
- connected = await this._connectUsb({}, searchTargetId, scope.signal);
981
+ connected = await this._connectUsb(this._usbConnector, {}, searchTargetId, scope.signal);
937
982
  } else if (hasHardwareRuntimeIdPrefix(searchTargetId)) {
938
983
  return failure(
939
984
  HardwareErrorCode2.DeviceNotFound,
@@ -954,7 +999,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
954
999
  );
955
1000
  } else {
956
1001
  selectedConnectionType = "usb";
957
- connected = await this._connectUsb(target, void 0, scope.signal);
1002
+ connected = await this._connectUsb(this._usbConnector, target, void 0, scope.signal);
958
1003
  }
959
1004
  }
960
1005
  _KeystoneAdapter._throwIfAborted(scope.signal);
@@ -1013,10 +1058,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1013
1058
  const { record } = this._resolveTarget(connectId, deviceId);
1014
1059
  if (!record) {
1015
1060
  return Promise.resolve(
1016
- failure(
1017
- HardwareErrorCode2.DeviceNotFound,
1018
- `Unknown Keystone device: ${connectId || deviceId}`
1019
- )
1061
+ failure(HardwareErrorCode2.DeviceNotFound, "Unknown Keystone device")
1020
1062
  );
1021
1063
  }
1022
1064
  return Promise.resolve(success(toDeviceInfo(record)));
@@ -1092,18 +1134,21 @@ var KeystoneAdapter = class _KeystoneAdapter {
1092
1134
  // Explicit account import: call before signing to avoid a cold sync per call.
1093
1135
  // ---------------------------------------------------------------------------
1094
1136
  async importFromQr(options = {}) {
1137
+ return this._importFromQr(options, KEYSTONE_COLD_START_JOB_LABEL);
1138
+ }
1139
+ async _importFromQr(options, jobKey) {
1095
1140
  try {
1096
- return await this._jobQueue.enqueue(KEYSTONE_COLD_START_JOB_LABEL, async (signal) => {
1141
+ return await this._jobQueue.enqueue(jobKey, async (signal) => {
1097
1142
  const displayDevice = placeholderDeviceInfo();
1098
1143
  let responseUr;
1099
1144
  if (options.mode === "scan") {
1100
- responseUr = await this._requestQrScanAndAwaitResponse(displayDevice, signal);
1145
+ responseUr = await this._requestQrAndAwaitResponse(displayDevice, void 0, signal);
1101
1146
  } else {
1102
1147
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1103
1148
  schemas: [keySchema("evm", KEYSTONE_COLD_START_PATH)],
1104
1149
  origin: this._origin
1105
1150
  });
1106
- responseUr = await this._requestQrDisplayAndAwaitResponse(
1151
+ responseUr = await this._requestQrAndAwaitResponse(
1107
1152
  displayDevice,
1108
1153
  { ...requestUr, animated: false },
1109
1154
  signal
@@ -1111,6 +1156,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1111
1156
  }
1112
1157
  _KeystoneAdapter._throwIfAborted(signal);
1113
1158
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1159
+ if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1114
1160
  const record = this._upsertDeviceRecord(parsed);
1115
1161
  return success(toDeviceInfo(record));
1116
1162
  });
@@ -1118,163 +1164,103 @@ var KeystoneAdapter = class _KeystoneAdapter {
1118
1164
  return this._errorToFailure(err);
1119
1165
  }
1120
1166
  }
1121
- // ---------------------------------------------------------------------------
1122
- // EVM
1123
- // ---------------------------------------------------------------------------
1124
- async evmGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1125
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1126
- if (!operationTarget.success) return operationTarget;
1127
- const connectId = operationTarget.payload.targetId;
1128
- const deviceId = deviceIdArg ?? void 0;
1129
- if (!params) return failure(HardwareErrorCode2.InvalidParams, "evmGetAddress requires params");
1130
- if (!params.path)
1131
- return failure(HardwareErrorCode2.InvalidParams, "evmGetAddress requires params.path");
1167
+ async evmGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1168
+ const call = this._beginCall("evmGetAddress", connectIdArg, deviceIdArg, paramsArg);
1169
+ if (!call.success) return call;
1170
+ const { params } = call.payload;
1171
+ if (!params.path) return missingParamFailure("evmGetAddress", "params.path");
1132
1172
  const evmCoinTypeFailure = coinTypeFailure("evm", params.path);
1133
1173
  if (evmCoinTypeFailure) return evmCoinTypeFailure;
1134
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1135
- if (!relativeDerivePath) {
1136
- return failure(
1137
- HardwareErrorCode2.InvalidParams,
1138
- "evmGetAddress requires a full leaf path, e.g. m/44'/60'/0'/0/0"
1139
- );
1140
- }
1141
- return this._runJob(connectId, deviceId, async (signal) => {
1142
- const xpub = await this._fetchAccountXpub(
1143
- connectId,
1144
- deviceId,
1145
- "evm",
1146
- accountPath,
1147
- signal,
1148
- bundle
1149
- );
1150
- const address = this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath);
1151
- return success({ address, path: normalizePath(params.path) });
1152
- });
1174
+ return this._addressFromAccountXpub(
1175
+ "evmGetAddress",
1176
+ "evm",
1177
+ call.payload,
1178
+ params.path,
1179
+ "m/44'/60'/0'/0/0",
1180
+ bundle,
1181
+ (xpub, relativeDerivePath) => this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath)
1182
+ );
1153
1183
  }
1154
- async evmSignTransaction(connectIdArg, deviceIdArg, params) {
1155
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1156
- if (!operationTarget.success) return operationTarget;
1157
- const connectId = operationTarget.payload.targetId;
1158
- const deviceId = deviceIdArg ?? void 0;
1159
- if (!params)
1160
- return failure(HardwareErrorCode2.InvalidParams, "evmSignTransaction requires params");
1161
- if (!params.path) {
1162
- return failure(HardwareErrorCode2.InvalidParams, "evmSignTransaction requires params.path");
1163
- }
1184
+ async evmSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1185
+ const call = this._beginCall("evmSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1186
+ if (!call.success) return call;
1187
+ const { params } = call.payload;
1188
+ if (!params.path) return missingParamFailure("evmSignTransaction", "params.path");
1164
1189
  if (!("serializedTx" in params) || typeof params.serializedTx !== "string" || !params.serializedTx) {
1165
1190
  return failure(
1166
1191
  HardwareErrorCode2.MethodNotSupported,
1167
1192
  "Keystone only signs a fully RLP-serialized transaction (params.serializedTx) \u2014 structured-field signing is not supported"
1168
1193
  );
1169
1194
  }
1170
- const rawTxHex = stripHex(params.serializedTx);
1171
- const path = normalizePath(params.path);
1195
+ const rawTxHex = exactHex(params.serializedTx);
1196
+ if (rawTxHex === void 0) return invalidHexFailure("serializedTx");
1172
1197
  const dataType = parseInt(rawTxHex.slice(0, 2), 16) < 192 ? "typedTransaction" : "transaction";
1173
- return this._signWithWallet({
1174
- connectId,
1175
- deviceId,
1176
- chain: "evm",
1177
- operationName: "evmSignTransaction",
1178
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1179
- requestId,
1180
- unsignedTxHex: rawTxHex,
1181
- dataType,
1182
- path,
1183
- xfp,
1184
- chainId: params.chainId,
1185
- origin: this._origin
1186
- }),
1187
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1188
- toPayload: (sig) => ({
1189
- v: ensure0x(sig.v),
1190
- r: ensure0x(sig.r),
1191
- s: ensure0x(sig.s)
1192
- })
1193
- });
1198
+ return this._evmSign(
1199
+ "evmSignTransaction",
1200
+ call.payload,
1201
+ params.path,
1202
+ params.chainId,
1203
+ rawTxHex,
1204
+ dataType,
1205
+ (sig) => ({ v: ensure0x(sig.v), r: ensure0x(sig.r), s: ensure0x(sig.s) })
1206
+ );
1194
1207
  }
1195
- async evmSignMessage(connectIdArg, deviceIdArg, params) {
1196
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1197
- if (!operationTarget.success) return operationTarget;
1198
- const connectId = operationTarget.payload.targetId;
1199
- const deviceId = deviceIdArg ?? void 0;
1200
- if (!params) return failure(HardwareErrorCode2.InvalidParams, "evmSignMessage requires params");
1208
+ async evmSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1209
+ const call = this._beginCall("evmSignMessage", connectIdArg, deviceIdArg, paramsArg);
1210
+ if (!call.success) return call;
1211
+ const { params } = call.payload;
1201
1212
  if (!params.path || params.message === void 0) {
1202
- return failure(
1203
- HardwareErrorCode2.InvalidParams,
1204
- "evmSignMessage requires params.path and params.message"
1205
- );
1206
- }
1207
- const messageHex = params.hex ? stripHex(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1208
- const path = normalizePath(params.path);
1209
- return this._signWithWallet({
1210
- connectId,
1211
- deviceId,
1212
- chain: "evm",
1213
- operationName: "evmSignMessage",
1214
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1215
- requestId,
1216
- unsignedTxHex: messageHex,
1217
- dataType: "personalMessage",
1218
- path,
1219
- xfp,
1220
- chainId: params.chainId,
1221
- origin: this._origin
1222
- }),
1223
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1224
- toPayload: (sig) => ({ signature: ensure0x(sig.r + sig.s + sig.v) })
1225
- });
1213
+ return missingParamFailure("evmSignMessage", "params.path and params.message");
1214
+ }
1215
+ const messageHex = messageToHex(params.message, params.hex);
1216
+ if (messageHex === void 0) return invalidHexFailure("message");
1217
+ return this._evmSign(
1218
+ "evmSignMessage",
1219
+ call.payload,
1220
+ params.path,
1221
+ params.chainId,
1222
+ messageHex,
1223
+ "personalMessage",
1224
+ evmMessageSignature
1225
+ );
1226
1226
  }
1227
- async evmSignTypedData(connectIdArg, deviceIdArg, params) {
1228
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1229
- if (!operationTarget.success) return operationTarget;
1230
- const connectId = operationTarget.payload.targetId;
1231
- const deviceId = deviceIdArg ?? void 0;
1232
- if (!params)
1233
- return failure(HardwareErrorCode2.InvalidParams, "evmSignTypedData requires params");
1234
- if (!params.path) {
1235
- return failure(HardwareErrorCode2.InvalidParams, "evmSignTypedData requires params.path");
1236
- }
1227
+ async evmSignTypedData(connectIdArg, deviceIdArg, paramsArg) {
1228
+ const call = this._beginCall("evmSignTypedData", connectIdArg, deviceIdArg, paramsArg);
1229
+ if (!call.success) return call;
1230
+ const { params } = call.payload;
1231
+ if (!params.path) return missingParamFailure("evmSignTypedData", "params.path");
1237
1232
  if (params.mode === "hash") {
1238
1233
  return failure(
1239
1234
  HardwareErrorCode2.MethodNotSupported,
1240
1235
  "Keystone always displays the full EIP-712 payload for on-device review \u2014 pre-hashed signing is not supported"
1241
1236
  );
1242
1237
  }
1243
- const signDataHex = Buffer.from(
1244
- params.dataJson ?? JSON.stringify(params.data),
1245
- "utf8"
1246
- ).toString("hex");
1247
- const path = normalizePath(params.path);
1248
- return this._signWithWallet({
1249
- connectId,
1250
- deviceId,
1251
- chain: "evm",
1252
- operationName: "evmSignTypedData",
1253
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1254
- requestId,
1255
- unsignedTxHex: signDataHex,
1256
- dataType: "typedData",
1257
- path,
1258
- xfp,
1259
- chainId: params.chainId,
1260
- origin: this._origin
1261
- }),
1262
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1263
- toPayload: (sig) => ({ signature: ensure0x(sig.r + sig.s + sig.v) })
1264
- });
1238
+ if (typeof params.dataJson !== "string" || !params.dataJson) {
1239
+ return failure(
1240
+ HardwareErrorCode2.InvalidParams,
1241
+ "Keystone evmSignTypedData requires params.dataJson, the original typed-data JSON text"
1242
+ );
1243
+ }
1244
+ const signDataHex = Buffer.from(params.dataJson, "utf8").toString("hex");
1245
+ return this._evmSign(
1246
+ "evmSignTypedData",
1247
+ call.payload,
1248
+ params.path,
1249
+ params.chainId,
1250
+ signDataHex,
1251
+ "typedData",
1252
+ evmMessageSignature
1253
+ );
1265
1254
  }
1266
1255
  // ---------------------------------------------------------------------------
1267
1256
  // BTC: 44'/49'/84' addresses derive offline from the account xpub; P2TR addresses
1268
1257
  // and structured-field tx signing are unsupported (the host builds a PSBT instead).
1269
1258
  // ---------------------------------------------------------------------------
1270
- async btcGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1271
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1272
- if (!operationTarget.success) return operationTarget;
1273
- const connectId = operationTarget.payload.targetId;
1274
- const deviceId = deviceIdArg ?? void 0;
1275
- if (!params) return failure(HardwareErrorCode2.InvalidParams, "btcGetAddress requires params");
1276
- if (!params.path)
1277
- return failure(HardwareErrorCode2.InvalidParams, "btcGetAddress requires params.path");
1259
+ async btcGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1260
+ const call = this._beginCall("btcGetAddress", connectIdArg, deviceIdArg, paramsArg);
1261
+ if (!call.success) return call;
1262
+ const { params } = call.payload;
1263
+ if (!params.path) return missingParamFailure("btcGetAddress", "params.path");
1278
1264
  const btcParamsFailure = keystoneBtcParamsFailure(params);
1279
1265
  if (btcParamsFailure) return btcParamsFailure;
1280
1266
  const scriptType = btcScriptTypeFromPath(params.path);
@@ -1290,42 +1276,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
1290
1276
  "P2TR (purpose 86') needs an elliptic-curve library for BIP-341 tweaking, not yet wired in \u2014 44'/49'/84' work"
1291
1277
  );
1292
1278
  }
1293
- const normalizedPath = normalizePath(params.path);
1294
- const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1295
- if (!relativeDerivePath) {
1296
- return failure(
1297
- HardwareErrorCode2.InvalidParams,
1298
- "btcGetAddress requires a full leaf path, e.g. m/84'/0'/0'/0/0"
1299
- );
1300
- }
1301
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1302
- return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1303
- }
1304
- return this._runJob(connectId, deviceId, async (signal) => {
1305
- const xpub = await this._fetchAccountXpub(
1306
- connectId,
1307
- deviceId,
1308
- "btc",
1309
- accountPath,
1310
- signal,
1311
- bundle
1312
- );
1313
- const address = this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType);
1314
- return success({ address, path: normalizedPath });
1315
- });
1279
+ return this._addressFromAccountXpub(
1280
+ "btcGetAddress",
1281
+ "btc",
1282
+ call.payload,
1283
+ params.path,
1284
+ "m/84'/0'/0'/0/0",
1285
+ bundle,
1286
+ (xpub, relativeDerivePath) => this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType)
1287
+ );
1316
1288
  }
1317
1289
  /**
1318
1290
  * `params.path` must be an account path (`m/84'/0'/0'`), the level Keystone syncs. An xpub is
1319
1291
  * script-type agnostic, so `86'` works here even though `btcGetAddress` rejects it.
1320
1292
  */
1321
- async btcGetPublicKey(connectIdArg, deviceIdArg, params, bundle) {
1322
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1323
- if (!operationTarget.success) return operationTarget;
1324
- const connectId = operationTarget.payload.targetId;
1325
- const deviceId = deviceIdArg ?? void 0;
1326
- if (!params) return failure(HardwareErrorCode2.InvalidParams, "btcGetPublicKey requires params");
1327
- if (!params.path)
1328
- return failure(HardwareErrorCode2.InvalidParams, "btcGetPublicKey requires params.path");
1293
+ async btcGetPublicKey(connectIdArg, deviceIdArg, paramsArg, bundle) {
1294
+ const call = this._beginCall("btcGetPublicKey", connectIdArg, deviceIdArg, paramsArg);
1295
+ if (!call.success) return call;
1296
+ const { connectId, deviceId, params } = call.payload;
1297
+ if (!params.path) return missingParamFailure("btcGetPublicKey", "params.path");
1329
1298
  const btcParamsFailure = keystoneBtcParamsFailure(params);
1330
1299
  if (btcParamsFailure) return btcParamsFailure;
1331
1300
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
@@ -1335,9 +1304,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1335
1304
  "btcGetPublicKey requires an account path, e.g. m/84'/0'/0' (not a leaf path)"
1336
1305
  );
1337
1306
  }
1338
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1339
- return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1340
- }
1307
+ const accountFailure = btcAccountFailure(accountPath);
1308
+ if (accountFailure) return accountFailure;
1341
1309
  return this._runJob(connectId, deviceId, async (signal) => {
1342
1310
  const xpub = await this._fetchAccountXpub(
1343
1311
  connectId,
@@ -1354,7 +1322,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1354
1322
  chainCode: meta.chainCode,
1355
1323
  depth: meta.depth,
1356
1324
  fingerprint: meta.parentFingerprint,
1357
- path: normalizePath(accountPath)
1325
+ path: normalizePath(accountPath),
1326
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1358
1327
  });
1359
1328
  });
1360
1329
  }
@@ -1364,23 +1333,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1364
1333
  "use btcSignPsbt \u2014 structured input/output signing needs host-side PSBT construction, not yet wired in"
1365
1334
  );
1366
1335
  }
1367
- async btcSignPsbt(connectIdArg, deviceIdArg, params) {
1368
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1369
- if (!operationTarget.success) return operationTarget;
1370
- const connectId = operationTarget.payload.targetId;
1371
- const deviceId = deviceIdArg ?? void 0;
1372
- if (!params) return failure(HardwareErrorCode2.InvalidParams, "btcSignPsbt requires params");
1373
- if (!params.psbt)
1374
- return failure(HardwareErrorCode2.InvalidParams, "btcSignPsbt requires params.psbt");
1375
- if (!params.path)
1376
- return failure(HardwareErrorCode2.InvalidParams, "btcSignPsbt requires params.path");
1377
- if (!isKeystoneSignableBtcAccountPath(splitAccountPath(params.path).accountPath)) {
1378
- return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1379
- }
1336
+ async btcSignPsbt(connectIdArg, deviceIdArg, paramsArg) {
1337
+ const call = this._beginCall("btcSignPsbt", connectIdArg, deviceIdArg, paramsArg);
1338
+ if (!call.success) return call;
1339
+ const { connectId, deviceId, params } = call.payload;
1340
+ if (!params.psbt) return missingParamFailure("btcSignPsbt", "params.psbt");
1341
+ if (!params.path) return missingParamFailure("btcSignPsbt", "params.path");
1342
+ const accountFailure = btcAccountFailure(splitAccountPath(params.path).accountPath);
1343
+ if (accountFailure) return accountFailure;
1344
+ const requestPsbtHex = exactHex(params.psbt);
1345
+ if (requestPsbtHex === void 0) return invalidHexFailure("psbt");
1380
1346
  return this._runJob(connectId, deviceId, async (signal) => {
1381
1347
  const { record } = await this._ensureWalletKnown(connectId, deviceId, "btc", signal);
1382
1348
  _KeystoneAdapter._throwIfAborted(signal);
1383
- const requestUr = this.urEngine.buildBtcPsbtRequest(stripHex(params.psbt));
1349
+ const requestUr = this.urEngine.buildBtcPsbtRequest(requestPsbtHex);
1384
1350
  const responseUr = await this._resolveUr(
1385
1351
  record,
1386
1352
  requestUr,
@@ -1390,30 +1356,26 @@ var KeystoneAdapter = class _KeystoneAdapter {
1390
1356
  "btcSignPsbt"
1391
1357
  );
1392
1358
  _KeystoneAdapter._throwIfAborted(signal);
1393
- const signedPsbt = this.urEngine.parseBtcPsbt(responseUr);
1359
+ const signedPsbt = this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex);
1394
1360
  return success({ signedPsbt });
1395
1361
  });
1396
1362
  }
1397
- async btcSignMessage(connectIdArg, deviceIdArg, params) {
1398
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1399
- if (!operationTarget.success) return operationTarget;
1400
- const connectId = operationTarget.payload.targetId;
1401
- const deviceId = deviceIdArg ?? void 0;
1402
- if (!params) return failure(HardwareErrorCode2.InvalidParams, "btcSignMessage requires params");
1363
+ async btcSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1364
+ const call = this._beginCall("btcSignMessage", connectIdArg, deviceIdArg, paramsArg);
1365
+ if (!call.success) return call;
1366
+ const { connectId, deviceId, params } = call.payload;
1403
1367
  if (!params.path || params.message === void 0) {
1404
- return failure(
1405
- HardwareErrorCode2.InvalidParams,
1406
- "btcSignMessage requires params.path and params.message"
1407
- );
1368
+ return missingParamFailure("btcSignMessage", "params.path and params.message");
1408
1369
  }
1409
- const messageHex = params.hex ? stripHex(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1370
+ const messageHex = messageToHex(params.message, params.hex);
1371
+ if (messageHex === void 0) return invalidHexFailure("message");
1410
1372
  const path = normalizePath(params.path);
1411
- if (!isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1412
- return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1413
- }
1373
+ const accountFailure = btcAccountFailure(splitAccountPath(path).accountPath);
1374
+ if (accountFailure) return accountFailure;
1414
1375
  return this._signWithWallet({
1415
1376
  connectId,
1416
1377
  deviceId,
1378
+ path,
1417
1379
  chain: "btc",
1418
1380
  operationName: "btcSignMessage",
1419
1381
  buildRequest: (requestId, xfp) => this.urEngine.buildBtcMessageSignRequest({
@@ -1441,17 +1403,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1441
1403
  return success({ masterFingerprint: record.masterFingerprint });
1442
1404
  });
1443
1405
  }
1444
- // ---------------------------------------------------------------------------
1445
- // SOL
1446
- // ---------------------------------------------------------------------------
1447
- async solGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1448
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1449
- if (!operationTarget.success) return operationTarget;
1450
- const connectId = operationTarget.payload.targetId;
1451
- const deviceId = deviceIdArg ?? void 0;
1452
- if (!params) return failure(HardwareErrorCode2.InvalidParams, "solGetAddress requires params");
1453
- if (!params.path)
1454
- return failure(HardwareErrorCode2.InvalidParams, "solGetAddress requires params.path");
1406
+ async solGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1407
+ const call = this._beginCall("solGetAddress", connectIdArg, deviceIdArg, paramsArg);
1408
+ if (!call.success) return call;
1409
+ const { connectId, deviceId, params } = call.payload;
1410
+ if (!params.path) return missingParamFailure("solGetAddress", "params.path");
1455
1411
  const solCoinTypeFailure = coinTypeFailure("sol", params.path);
1456
1412
  if (solCoinTypeFailure) return solCoinTypeFailure;
1457
1413
  const path = normalizePath(params.path);
@@ -1471,180 +1427,218 @@ var KeystoneAdapter = class _KeystoneAdapter {
1471
1427
  bundle
1472
1428
  );
1473
1429
  _KeystoneAdapter._throwIfAborted(signal);
1430
+ if (!/^[0-9a-f]{64}$/i.test(account.publicKey)) {
1431
+ throw createHwkError2({
1432
+ code: HardwareErrorCode2.DeviceMismatch,
1433
+ message: "Keystone returned a Solana key that is not a 32-byte Ed25519 public key"
1434
+ });
1435
+ }
1474
1436
  const address = bs58.encode(Buffer.from(account.publicKey, "hex"));
1475
- return success({ address, path });
1437
+ return success({
1438
+ address,
1439
+ path,
1440
+ accountKey: { path, publicKey: account.publicKey }
1441
+ });
1476
1442
  });
1477
1443
  }
1478
- async solSignTransaction(connectIdArg, deviceIdArg, params) {
1479
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1480
- if (!operationTarget.success) return operationTarget;
1481
- const connectId = operationTarget.payload.targetId;
1482
- const deviceId = deviceIdArg ?? void 0;
1483
- if (!params)
1484
- return failure(HardwareErrorCode2.InvalidParams, "solSignTransaction requires params");
1444
+ async solSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1445
+ const call = this._beginCall("solSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1446
+ if (!call.success) return call;
1447
+ const { params } = call.payload;
1485
1448
  if (!params.path || !params.serializedTx) {
1486
- return failure(
1487
- HardwareErrorCode2.InvalidParams,
1488
- "solSignTransaction requires params.path and params.serializedTx"
1489
- );
1490
- }
1491
- const path = normalizePath(params.path);
1492
- return this._signWithWallet({
1493
- connectId,
1494
- deviceId,
1495
- chain: "sol",
1496
- operationName: "solSignTransaction",
1497
- buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1498
- requestId,
1499
- unsignedPayloadHex: stripHex(params.serializedTx),
1500
- dataType: "transaction",
1501
- path,
1502
- xfp,
1503
- origin: this._origin
1504
- }),
1505
- parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1506
- toPayload: (sig) => ({ signature: sig.signature })
1507
- });
1449
+ return missingParamFailure("solSignTransaction", "params.path and params.serializedTx");
1450
+ }
1451
+ const unsignedPayloadHex = exactHex(params.serializedTx);
1452
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("serializedTx");
1453
+ return this._solSign(
1454
+ "solSignTransaction",
1455
+ call.payload,
1456
+ params.path,
1457
+ unsignedPayloadHex,
1458
+ "transaction"
1459
+ );
1508
1460
  }
1509
- async solSignMessage(connectIdArg, deviceIdArg, params) {
1510
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1511
- if (!operationTarget.success) return operationTarget;
1512
- const connectId = operationTarget.payload.targetId;
1513
- const deviceId = deviceIdArg ?? void 0;
1514
- if (!params) return failure(HardwareErrorCode2.InvalidParams, "solSignMessage requires params");
1461
+ async solSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1462
+ const call = this._beginCall("solSignMessage", connectIdArg, deviceIdArg, paramsArg);
1463
+ if (!call.success) return call;
1464
+ const { params } = call.payload;
1515
1465
  if (!params.path || !params.message) {
1466
+ return missingParamFailure("solSignMessage", "params.path and params.message");
1467
+ }
1468
+ if (params.messageVersion !== void 0) {
1516
1469
  return failure(
1517
- HardwareErrorCode2.InvalidParams,
1518
- "solSignMessage requires params.path and params.message"
1470
+ HardwareErrorCode2.MethodNotSupported,
1471
+ "Keystone signs Solana messages as raw bytes only; off-chain message format is not supported"
1519
1472
  );
1520
1473
  }
1521
- const path = normalizePath(params.path);
1522
- return this._signWithWallet({
1523
- connectId,
1524
- deviceId,
1525
- chain: "sol",
1526
- operationName: "solSignMessage",
1527
- buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1528
- requestId,
1529
- unsignedPayloadHex: stripHex(params.message),
1530
- dataType: "message",
1531
- path,
1532
- xfp,
1533
- origin: this._origin
1534
- }),
1535
- parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1536
- toPayload: (sig) => ({ signature: sig.signature })
1537
- });
1474
+ const unsignedPayloadHex = exactHex(params.message);
1475
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("message");
1476
+ return this._solSign(
1477
+ "solSignMessage",
1478
+ call.payload,
1479
+ params.path,
1480
+ unsignedPayloadHex,
1481
+ "message"
1482
+ );
1538
1483
  }
1539
1484
  // ---------------------------------------------------------------------------
1540
1485
  // TRON: keystone-sdk-rust layout (tags 5201/5202, firmware >= 2.5.0), not sdk.tron's
1541
1486
  // protobuf module; OneKey Pro's encoding under the same tag is rejected by the firmware.
1542
1487
  // ---------------------------------------------------------------------------
1543
- async tronGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1544
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1545
- if (!operationTarget.success) return operationTarget;
1546
- const connectId = operationTarget.payload.targetId;
1547
- const deviceId = deviceIdArg ?? void 0;
1548
- if (!params) return failure(HardwareErrorCode2.InvalidParams, "tronGetAddress requires params");
1549
- if (!params.path)
1550
- return failure(HardwareErrorCode2.InvalidParams, "tronGetAddress requires params.path");
1488
+ async tronGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1489
+ const call = this._beginCall("tronGetAddress", connectIdArg, deviceIdArg, paramsArg);
1490
+ if (!call.success) return call;
1491
+ const { params } = call.payload;
1492
+ if (!params.path) return missingParamFailure("tronGetAddress", "params.path");
1551
1493
  const tronCoinTypeFailure = coinTypeFailure("tron", params.path);
1552
1494
  if (tronCoinTypeFailure) return tronCoinTypeFailure;
1553
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1495
+ return this._addressFromAccountXpub(
1496
+ "tronGetAddress",
1497
+ "tron",
1498
+ call.payload,
1499
+ params.path,
1500
+ "m/44'/195'/0'/0/0",
1501
+ bundle,
1502
+ (xpub, relativeDerivePath) => this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath)
1503
+ );
1504
+ }
1505
+ async tronSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1506
+ const call = this._beginCall("tronSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1507
+ if (!call.success) return call;
1508
+ const { params } = call.payload;
1509
+ if (!params.path) return missingParamFailure("tronSignTransaction", "params.path");
1510
+ if (!params.rawTxHex) {
1511
+ return failure(
1512
+ HardwareErrorCode2.InvalidParams,
1513
+ "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1514
+ );
1515
+ }
1516
+ const rawTxHex = exactHex(params.rawTxHex);
1517
+ if (rawTxHex === void 0) return invalidHexFailure("rawTxHex");
1518
+ return this._tronSign("tronSignTransaction", call.payload, params.path, rawTxHex);
1519
+ }
1520
+ async tronSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1521
+ const call = this._beginCall("tronSignMessage", connectIdArg, deviceIdArg, paramsArg);
1522
+ if (!call.success) return call;
1523
+ const { params } = call.payload;
1524
+ if (!params.path) return missingParamFailure("tronSignMessage", "params.path");
1525
+ if (!params.messageHex) return missingParamFailure("tronSignMessage", "params.messageHex");
1526
+ if (params.messageType !== "V2") {
1527
+ return failure(
1528
+ HardwareErrorCode2.MethodNotSupported,
1529
+ 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1530
+ );
1531
+ }
1532
+ const messageHex = exactHex(params.messageHex);
1533
+ if (messageHex === void 0) return invalidHexFailure("messageHex");
1534
+ return this._tronSign(
1535
+ "tronSignMessage",
1536
+ call.payload,
1537
+ params.path,
1538
+ messageHex,
1539
+ 2 /* PersonalMessage */
1540
+ );
1541
+ }
1542
+ /** Resolves the call's target and requires params, before any method-specific check. */
1543
+ _beginCall(method, connectIdArg, deviceIdArg, params) {
1544
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1545
+ if (!operationTarget.success) return operationTarget;
1546
+ if (!params) return missingParamFailure(method, "params");
1547
+ return success({
1548
+ connectId: operationTarget.payload.targetId,
1549
+ deviceId: deviceIdArg ?? void 0,
1550
+ params
1551
+ });
1552
+ }
1553
+ /** Derives a leaf address offline from its account xpub. */
1554
+ async _addressFromAccountXpub(method, chain, { connectId, deviceId }, path, leafExample, bundle, derive) {
1555
+ const normalizedPath = normalizePath(path);
1556
+ const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1554
1557
  if (!relativeDerivePath) {
1555
1558
  return failure(
1556
1559
  HardwareErrorCode2.InvalidParams,
1557
- "tronGetAddress requires a full leaf path, e.g. m/44'/195'/0'/0/0"
1560
+ `${method} requires a full leaf path, e.g. ${leafExample}`
1558
1561
  );
1559
1562
  }
1563
+ const accountFailure = chain === "btc" ? btcAccountFailure(accountPath) : void 0;
1564
+ if (accountFailure) return accountFailure;
1560
1565
  return this._runJob(connectId, deviceId, async (signal) => {
1561
1566
  const xpub = await this._fetchAccountXpub(
1562
1567
  connectId,
1563
1568
  deviceId,
1564
- "tron",
1569
+ chain,
1565
1570
  accountPath,
1566
1571
  signal,
1567
1572
  bundle
1568
1573
  );
1569
- const address = this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath);
1570
- return success({ address, path: normalizePath(params.path) });
1574
+ return success({
1575
+ address: derive(xpub, relativeDerivePath),
1576
+ path: normalizedPath,
1577
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1578
+ });
1571
1579
  });
1572
1580
  }
1573
- async tronSignTransaction(connectIdArg, deviceIdArg, params) {
1574
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1575
- if (!operationTarget.success) return operationTarget;
1576
- const connectId = operationTarget.payload.targetId;
1577
- const deviceId = deviceIdArg ?? void 0;
1578
- if (!params)
1579
- return failure(HardwareErrorCode2.InvalidParams, "tronSignTransaction requires params");
1580
- if (!params.path) {
1581
- return failure(HardwareErrorCode2.InvalidParams, "tronSignTransaction requires params.path");
1582
- }
1583
- if (!params.rawTxHex) {
1584
- return failure(
1585
- HardwareErrorCode2.InvalidParams,
1586
- "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1587
- );
1588
- }
1589
- const rawTxHex = stripHex(params.rawTxHex);
1590
- const path = normalizePath(params.path);
1581
+ _evmSign(method, target, rawPath, chainId, signDataHex, dataType, toPayload) {
1582
+ const path = normalizePath(rawPath);
1591
1583
  return this._signWithWallet({
1592
- connectId,
1593
- deviceId,
1594
- chain: "tron",
1595
- operationName: "tronSignTransaction",
1596
- buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1584
+ connectId: target.connectId,
1585
+ deviceId: target.deviceId,
1586
+ path,
1587
+ chain: "evm",
1588
+ operationName: method,
1589
+ buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1597
1590
  requestId,
1598
- rawTxHex,
1591
+ unsignedTxHex: signDataHex,
1592
+ dataType,
1599
1593
  path,
1600
1594
  xfp,
1595
+ chainId,
1601
1596
  origin: this._origin
1602
1597
  }),
1603
- parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1604
- // Keystone signs rawTxHex as given and returns only the signature, so no serializedTx.
1598
+ parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1599
+ toPayload
1600
+ });
1601
+ }
1602
+ _solSign(method, target, rawPath, unsignedPayloadHex, dataType) {
1603
+ const path = normalizePath(rawPath);
1604
+ return this._signWithWallet({
1605
+ connectId: target.connectId,
1606
+ deviceId: target.deviceId,
1607
+ path,
1608
+ chain: "sol",
1609
+ operationName: method,
1610
+ buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1611
+ requestId,
1612
+ unsignedPayloadHex,
1613
+ dataType,
1614
+ path,
1615
+ xfp,
1616
+ origin: this._origin
1617
+ }),
1618
+ parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1605
1619
  toPayload: (sig) => ({ signature: sig.signature })
1606
1620
  });
1607
1621
  }
1608
- async tronSignMessage(connectIdArg, deviceIdArg, params) {
1609
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1610
- if (!operationTarget.success) return operationTarget;
1611
- const connectId = operationTarget.payload.targetId;
1612
- const deviceId = deviceIdArg ?? void 0;
1613
- if (!params) return failure(HardwareErrorCode2.InvalidParams, "tronSignMessage requires params");
1614
- if (!params.path) {
1615
- return failure(HardwareErrorCode2.InvalidParams, "tronSignMessage requires params.path");
1616
- }
1617
- if (!params.messageHex) {
1618
- return failure(HardwareErrorCode2.InvalidParams, "tronSignMessage requires params.messageHex");
1619
- }
1620
- if (params.messageType !== "V2") {
1621
- return failure(
1622
- HardwareErrorCode2.MethodNotSupported,
1623
- 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1624
- );
1625
- }
1626
- const messageHex = stripHex(params.messageHex);
1627
- const path = normalizePath(params.path);
1622
+ _tronSign(method, target, rawPath, signDataHex, signType) {
1623
+ const path = normalizePath(rawPath);
1628
1624
  return this._signWithWallet({
1629
- connectId,
1630
- deviceId,
1625
+ connectId: target.connectId,
1626
+ deviceId: target.deviceId,
1627
+ path,
1631
1628
  chain: "tron",
1632
- operationName: "tronSignMessage",
1629
+ operationName: method,
1633
1630
  buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1634
1631
  requestId,
1635
- rawTxHex: messageHex,
1632
+ rawTxHex: signDataHex,
1636
1633
  path,
1637
1634
  xfp,
1638
- signType: 2 /* PersonalMessage */,
1635
+ signType,
1639
1636
  origin: this._origin
1640
1637
  }),
1641
1638
  parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1642
1639
  toPayload: (sig) => ({ signature: sig.signature })
1643
1640
  });
1644
1641
  }
1645
- // ---------------------------------------------------------------------------
1646
- // Internals
1647
- // ---------------------------------------------------------------------------
1648
1642
  async _runJob(connectId, deviceId, job) {
1649
1643
  try {
1650
1644
  return await this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), job);
@@ -1668,14 +1662,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
1668
1662
  message: "Keystone did not return an extended public key for this account path"
1669
1663
  });
1670
1664
  }
1665
+ const { publicKey } = this.urEngine.parseXpubMeta(account.extendedPublicKey);
1666
+ if (!/^0[23]/.test(publicKey)) {
1667
+ throw createHwkError2({
1668
+ code: HardwareErrorCode2.DeviceMismatch,
1669
+ message: "Keystone returned an account key that is not a public key"
1670
+ });
1671
+ }
1671
1672
  return account.extendedPublicKey;
1672
1673
  }
1674
+ /** The exported key behind an address, reduced to the fields that identify it. */
1675
+ _exportedAccountKey(accountPath, xpub) {
1676
+ const { publicKey, chainCode } = this.urEngine.parseXpubMeta(xpub);
1677
+ return { path: normalizePath(accountPath), publicKey, chainCode, xpub };
1678
+ }
1673
1679
  /**
1674
1680
  * Signing needs only the wallet's mfp: the device re-derives the key from path+xfp, so no
1675
1681
  * per-path account lookup happens here.
1676
1682
  */
1677
1683
  _signWithWallet(args) {
1678
1684
  const { connectId, deviceId } = args;
1685
+ if (!isBip32Path(args.path)) {
1686
+ return Promise.resolve(
1687
+ failure(HardwareErrorCode2.InvalidParams, `Invalid derivation path (${args.path})`)
1688
+ );
1689
+ }
1690
+ const chainCoinTypeFailure = coinTypeFailure(args.chain, args.path);
1691
+ if (chainCoinTypeFailure) return Promise.resolve(chainCoinTypeFailure);
1679
1692
  return this._runJob(connectId, deviceId, async (signal) => {
1680
1693
  const { record } = await this._ensureWalletKnown(connectId, deviceId, args.chain, signal);
1681
1694
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1712,8 +1725,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1712
1725
  case "btcGetPublicKey":
1713
1726
  case "solGetAddress":
1714
1727
  return { hwkChain, path };
1715
- default:
1716
- return void 0;
1717
1728
  }
1718
1729
  }
1719
1730
  /**
@@ -1757,7 +1768,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1757
1768
  schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1758
1769
  origin: this._origin
1759
1770
  });
1760
- const responseUr = await this._requestQrDisplayAndAwaitResponse(
1771
+ const responseUr = await this._requestQrAndAwaitResponse(
1761
1772
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1762
1773
  { ...requestUr, animated: false },
1763
1774
  signal
@@ -1765,26 +1776,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
1765
1776
  _KeystoneAdapter._throwIfAborted(signal);
1766
1777
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1767
1778
  this._assertParsedIdentity(parsed, target);
1768
- record = this._upsertDeviceRecord(parsed);
1769
1779
  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
- });
1778
- }
1779
1780
  scanned.set(accountKey(schema.hwkChain, schema.path), {
1780
- ...account,
1781
+ ...requireExportedPath(parsed, schema.path),
1781
1782
  hwkChain: schema.hwkChain
1782
1783
  });
1783
1784
  }
1785
+ record = this._upsertDeviceRecord(parsed);
1784
1786
  return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1785
1787
  });
1786
1788
  }
1787
- /** Resolve the wallet's master fingerprint from the connectId and/or deviceId the caller passed. */
1788
1789
  /**
1789
1790
  * A positional wallet id and an operation id must name the same wallet: otherwise the call
1790
1791
  * would run on the operation's wallet while the caller files the result under the other one.
@@ -1839,7 +1840,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1839
1840
  if (expected.expectedMasterFingerprint && parsed.masterFingerprint !== expected.expectedMasterFingerprint) {
1840
1841
  throw createHwkError2({
1841
1842
  code: HardwareErrorCode2.DeviceMismatch,
1842
- message: `Connected Keystone wallet (mfp ${parsed.masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1843
+ // The master fingerprint identifies the wallet; keep it out of messages that reach logs.
1844
+ message: "Connected Keystone wallet does not match the requested wallet"
1843
1845
  });
1844
1846
  }
1845
1847
  }
@@ -1869,7 +1871,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1869
1871
  * Opens a permitted USB Keystone and takes its mfp as the wallet identity. A known wallet gains
1870
1872
  * USB in place (`device-changed`); an unseen one becomes USB-only.
1871
1873
  */
1872
- async _connectUsb(expected, searchTargetId, signal) {
1874
+ async _connectUsb(connector, expected, searchTargetId, signal) {
1873
1875
  if (this._pendingUsbTeardowns > 0 || this._abandonedUsbConnects > 0) {
1874
1876
  return failure(
1875
1877
  HardwareErrorCode2.DeviceBusyInternal,
@@ -1882,28 +1884,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
1882
1884
  abandoned = true;
1883
1885
  this._abandonedUsbConnects += 1;
1884
1886
  };
1885
- signal?.addEventListener("abort", onAbort, { once: true });
1887
+ signal.addEventListener("abort", onAbort, { once: true });
1886
1888
  const pending = this._usbConnectTail.then(async () => {
1887
1889
  _KeystoneAdapter._throwIfAborted(signal);
1888
- return this._connectUsbExclusive(expected, searchTargetId, signal);
1890
+ if (this._unsettledUsbOperations.size > 0) {
1891
+ return failure(
1892
+ HardwareErrorCode2.DeviceBusyInternal,
1893
+ "Keystone USB is still finishing an earlier request"
1894
+ );
1895
+ }
1896
+ const releaseConnect = this._retainUsbOperation("connect");
1897
+ try {
1898
+ return await this._connectUsbExclusive(connector, expected, searchTargetId, signal);
1899
+ } finally {
1900
+ releaseConnect();
1901
+ }
1889
1902
  });
1890
1903
  const settled = pending.finally(() => {
1891
- signal?.removeEventListener("abort", onAbort);
1904
+ signal.removeEventListener("abort", onAbort);
1892
1905
  if (abandoned) this._abandonedUsbConnects -= 1;
1893
1906
  });
1894
1907
  this._usbConnectTail = settled.then(
1895
1908
  () => void 0,
1896
1909
  () => void 0
1897
1910
  );
1898
- return signal ? _KeystoneAdapter._abortable(signal, settled) : settled;
1911
+ return _KeystoneAdapter._abortable(signal, settled);
1899
1912
  }
1900
- async _connectUsbExclusive(expected, searchTargetId, signal) {
1901
- if (!this._usbConnector) {
1902
- return failure(
1903
- HardwareErrorCode2.TransportNotAvailable,
1904
- "No USB connector configured for this Keystone adapter"
1905
- );
1906
- }
1913
+ async _connectUsbExclusive(connector, expected, searchTargetId, signal) {
1907
1914
  let sessionId;
1908
1915
  try {
1909
1916
  let connectTarget = { type: "default" };
@@ -1915,7 +1922,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1915
1922
  deviceIdentity: expected.expectedMasterFingerprint
1916
1923
  };
1917
1924
  }
1918
- const connector = this._usbConnector;
1919
1925
  const session = await (connector.connectTarget ? connector.connectTarget(connectTarget) : connector.connect(searchTargetId ?? expected.expectedMasterFingerprint));
1920
1926
  sessionId = session.sessionId;
1921
1927
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1929,16 +1935,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1929
1935
  });
1930
1936
  }
1931
1937
  const masterFingerprint = mfpValue.toLowerCase();
1932
- if (expected.expectedMasterFingerprint && masterFingerprint !== expected.expectedMasterFingerprint) {
1933
- throw createHwkError2({
1934
- code: HardwareErrorCode2.DeviceMismatch,
1935
- message: `Connected Keystone wallet (mfp ${masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1936
- });
1937
- }
1938
+ this._assertParsedIdentity({ masterFingerprint, accounts: [] }, expected);
1938
1939
  const previousUsbSessionId = this._devices.get(masterFingerprint)?.usbSessionId;
1939
1940
  if (previousUsbSessionId && previousUsbSessionId !== session.sessionId) {
1940
1941
  try {
1941
- await this._usbConnector.disconnect(previousUsbSessionId);
1942
+ await connector.disconnect(previousUsbSessionId);
1942
1943
  } catch {
1943
1944
  }
1944
1945
  }
@@ -1958,7 +1959,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1958
1959
  } catch (err) {
1959
1960
  if (sessionId) {
1960
1961
  try {
1961
- await this._usbConnector.disconnect(sessionId);
1962
+ await connector.disconnect(sessionId);
1962
1963
  } catch {
1963
1964
  }
1964
1965
  }
@@ -2004,9 +2005,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
2004
2005
  }
2005
2006
  return void 0;
2006
2007
  }
2007
- const attached = await this._connectUsb({ expectedMasterFingerprint }, void 0, signal);
2008
+ const attached = await this._connectUsb(
2009
+ this._usbConnector,
2010
+ { expectedMasterFingerprint },
2011
+ void 0,
2012
+ signal
2013
+ );
2008
2014
  _KeystoneAdapter._throwIfAborted(signal);
2009
- if (!attached.success && attached.payload.code === HardwareErrorCode2.DeviceBusyInternal) {
2015
+ if (!attached.success && (attached.payload.code === HardwareErrorCode2.DeviceBusyInternal || attached.payload.code === HardwareErrorCode2.DeviceOneDeviceOnly)) {
2010
2016
  throw createHwkError2({
2011
2017
  ...attached.payload,
2012
2018
  message: attached.payload.error
@@ -2066,9 +2072,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2066
2072
  message: "USB channel is not connected for this Keystone wallet"
2067
2073
  });
2068
2074
  }
2069
- const result = await this._callUsbConnector(
2075
+ const result = await this._callUsbResolveUr(
2076
+ this._usbConnector,
2070
2077
  record.usbSessionId,
2071
- "resolveUr",
2072
2078
  requestUr,
2073
2079
  signal
2074
2080
  );
@@ -2078,11 +2084,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2078
2084
  if (usbErrorCode === HardwareErrorCode2.PayloadTooLarge && usbErrorOrigin !== "device") {
2079
2085
  if (!interactionRoute && !this._forcedTransport) {
2080
2086
  const displayDevice2 = toDeviceInfo(record);
2081
- return this._requestQrDisplayAndAwaitResponse(
2082
- displayDevice2,
2083
- { ...requestUr, animated },
2084
- signal
2085
- );
2087
+ return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2086
2088
  }
2087
2089
  throw usbError;
2088
2090
  }
@@ -2093,6 +2095,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2093
2095
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2094
2096
  }
2095
2097
  record.usbSessionId = void 0;
2098
+ this.emitter.emit(DEVICE.CHANGED, { type: DEVICE.CHANGED, payload: toDeviceInfo(record) });
2096
2099
  if (interactionRoute) {
2097
2100
  throw this._endDisconnectedOperation(
2098
2101
  interactionRoute.operationId,
@@ -2110,11 +2113,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2110
2113
  });
2111
2114
  }
2112
2115
  }
2116
+ if (operationName && usbError.replyUnreadable === true) {
2117
+ throw createHwkError2({
2118
+ code: usbErrorCode ?? HardwareErrorCode2.UnknownError,
2119
+ message: `Keystone ${operationName} may have completed but its reply could not be read`,
2120
+ origin: "device",
2121
+ recovery: { scope: "unknown" },
2122
+ params: operationMayHaveCompletedParams(operationName)
2123
+ });
2124
+ }
2113
2125
  throw usbError;
2114
2126
  }
2115
2127
  const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
2116
2128
  try {
2117
- return await this._requestQrDisplayAndAwaitResponse(
2129
+ return await this._requestQrAndAwaitResponse(
2118
2130
  displayDevice,
2119
2131
  { ...requestUr, animated },
2120
2132
  signal
@@ -2178,6 +2190,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2178
2190
  const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2179
2191
  _KeystoneAdapter._throwIfAborted(signal);
2180
2192
  const parsed = this.urEngine.parseAccountResponse(responseUr);
2193
+ const account = requireExportedPath(parsed, syncPath);
2181
2194
  let record;
2182
2195
  if (useSinglePathUsbExport && existingRecord) {
2183
2196
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2193,13 +2206,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2193
2206
  viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2194
2207
  });
2195
2208
  }
2196
- const account = parsed.accounts.find((a) => normalizePath(a.path) === syncPath);
2197
- if (!account) {
2198
- throw createHwkError2({
2199
- code: HardwareErrorCode2.DeviceMismatch,
2200
- message: `Keystone did not return the requested derivation path (${syncPath})`
2201
- });
2202
- }
2203
2209
  return { record, account: { ...account, hwkChain } };
2204
2210
  }
2205
2211
  /**
@@ -2222,7 +2228,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2222
2228
  });
2223
2229
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2224
2230
  _KeystoneAdapter._throwIfAborted(signal);
2225
- return { record: this._upsertDeviceRecord(this.urEngine.parseAccountResponse(responseUr)) };
2231
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
2232
+ requireExportedPath(parsed, normalizePath(accountPath));
2233
+ return { record: this._upsertDeviceRecord(parsed) };
2226
2234
  }
2227
2235
  /**
2228
2236
  * The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
@@ -2248,7 +2256,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2248
2256
  * a cancel reach the wait before the QR timeout.
2249
2257
  */
2250
2258
  async _awaitQrResponse(requestType, pending, signal) {
2251
- if (!signal) return pending;
2252
2259
  let settled = false;
2253
2260
  const onAbort = () => {
2254
2261
  if (!settled) this._uiRegistry.cancel(requestType);
@@ -2257,55 +2264,50 @@ var KeystoneAdapter = class _KeystoneAdapter {
2257
2264
  else signal.addEventListener("abort", onAbort, { once: true });
2258
2265
  try {
2259
2266
  return await pending;
2267
+ } catch (error) {
2268
+ const reason = signal.reason;
2269
+ if (signal.aborted && reason?.code === HardwareErrorCode2.OperationEnded) throw signal.reason;
2270
+ throw error;
2260
2271
  } finally {
2261
2272
  settled = true;
2262
2273
  signal.removeEventListener("abort", onAbort);
2263
2274
  }
2264
2275
  }
2265
- async _requestQrDisplayAndAwaitResponse(device, data, signal) {
2276
+ /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2277
+ async _requestQrAndAwaitResponse(device, data, signal) {
2278
+ const requestType = data ? UI_REQUEST.REQUEST_QR_DISPLAY : UI_REQUEST.REQUEST_QR_SCAN;
2266
2279
  const operationId = this._activeOperationId();
2267
- const waitPromise = this._uiRegistry.wait(
2268
- UI_REQUEST.REQUEST_QR_DISPLAY,
2269
- { timeoutMs: this._qrTimeoutMs, operationId }
2270
- );
2271
- this.emitter.emit(UI_REQUEST.REQUEST_QR_DISPLAY, {
2272
- type: UI_REQUEST.REQUEST_QR_DISPLAY,
2273
- payload: { device, data, operationId }
2274
- });
2275
- const response = await this._awaitQrResponse(
2276
- UI_REQUEST.REQUEST_QR_DISPLAY,
2277
- waitPromise,
2278
- signal
2279
- );
2280
- return { urType: response.urType, urData: response.urData };
2281
- }
2282
- async _requestQrScanAndAwaitResponse(device, signal) {
2283
- const operationId = this._activeOperationId();
2284
- const waitPromise = this._uiRegistry.wait(
2285
- UI_REQUEST.REQUEST_QR_SCAN,
2286
- { timeoutMs: this._qrTimeoutMs, operationId }
2287
- );
2288
- this.emitter.emit(UI_REQUEST.REQUEST_QR_SCAN, {
2289
- type: UI_REQUEST.REQUEST_QR_SCAN,
2290
- payload: { device, operationId }
2291
- });
2292
- const response = await this._awaitQrResponse(UI_REQUEST.REQUEST_QR_SCAN, waitPromise, signal);
2293
- return { urType: response.urType, urData: response.urData };
2294
- }
2295
- async _callUsbConnector(sessionId, method, params, signal) {
2296
- if (!this._usbConnector) {
2297
- throw createHwkError2({
2298
- code: HardwareErrorCode2.TransportNotAvailable,
2299
- message: "No USB connector configured for this Keystone adapter"
2280
+ const release = operationId ? this._operations.retain(operationId) : void 0;
2281
+ try {
2282
+ const waitPromise = this._uiRegistry.wait(requestType, {
2283
+ timeoutMs: this._qrTimeoutMs,
2284
+ operationId
2300
2285
  });
2286
+ if (data) {
2287
+ this.emitter.emit(UI_REQUEST.REQUEST_QR_DISPLAY, {
2288
+ type: UI_REQUEST.REQUEST_QR_DISPLAY,
2289
+ payload: { device, data, operationId }
2290
+ });
2291
+ } else {
2292
+ this.emitter.emit(UI_REQUEST.REQUEST_QR_SCAN, {
2293
+ type: UI_REQUEST.REQUEST_QR_SCAN,
2294
+ payload: { device, operationId }
2295
+ });
2296
+ }
2297
+ const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2298
+ return { urType: response.urType, urData: response.urData };
2299
+ } finally {
2300
+ release?.();
2301
2301
  }
2302
+ }
2303
+ async _callUsbResolveUr(connector, sessionId, requestUr, signal) {
2302
2304
  if (this._pendingUsbTeardowns > 0 || this._unsettledUsbOperations.size > 0) {
2303
2305
  throw createHwkError2({
2304
2306
  code: HardwareErrorCode2.DeviceBusyInternal,
2305
- message: `Keystone USB is busy while calling ${method}`
2307
+ message: "Keystone USB is busy while calling resolveUr"
2306
2308
  });
2307
2309
  }
2308
- if (signal?.aborted) {
2310
+ if (signal.aborted) {
2309
2311
  throw signal.reason instanceof Error ? signal.reason : createHwkError2({
2310
2312
  code: HardwareErrorCode2.UserAborted,
2311
2313
  message: "User aborted operation"
@@ -2314,12 +2316,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2314
2316
  const releaseOperation = this._retainUsbOperation(`call:${sessionId}`);
2315
2317
  let rawCall;
2316
2318
  try {
2317
- rawCall = this._usbConnector.call(sessionId, method, params).finally(releaseOperation);
2319
+ rawCall = connector.call(sessionId, "resolveUr", requestUr).finally(releaseOperation);
2318
2320
  } catch (error) {
2319
2321
  releaseOperation();
2320
2322
  throw error;
2321
2323
  }
2322
- return signal ? _KeystoneAdapter._abortable(signal, rawCall) : rawCall;
2324
+ return _KeystoneAdapter._abortable(signal, rawCall);
2323
2325
  }
2324
2326
  _runUsbTeardown(task) {
2325
2327
  const previous = this._usbTeardownTail;
@@ -2381,6 +2383,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
2381
2383
  );
2382
2384
  });
2383
2385
  }
2386
+ /** Settles with `signal`'s reason once it aborts; a later outcome of `promise` is dropped. */
2387
+ static _untilAborted(signal, promise) {
2388
+ promise.catch(() => void 0);
2389
+ if (signal.aborted) return Promise.reject(signal.reason);
2390
+ return new Promise((resolve, reject) => {
2391
+ const onAbort = () => reject(signal.reason);
2392
+ signal.addEventListener("abort", onAbort, { once: true });
2393
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort)).catch(() => void 0);
2394
+ });
2395
+ }
2384
2396
  static _throwIfAborted(signal) {
2385
2397
  if (signal?.aborted) {
2386
2398
  throw signal.reason instanceof Error ? signal.reason : new Error("Operation aborted");