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

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,6 +476,14 @@ 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("/");
@@ -590,12 +620,6 @@ function waitForKeystoneUsbReattachProbe() {
590
620
  setTimeout(resolve, KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS);
591
621
  });
592
622
  }
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
623
  var BIP44_COIN_TYPE_TO_CHAIN = {
600
624
  60: "evm",
601
625
  0: "btc",
@@ -606,6 +630,23 @@ function hasChainCoinType(chain, path) {
606
630
  const match = normalizePath(path).match(/^m\/\d+'\/(\d+)'/);
607
631
  return Boolean(match) && BIP44_COIN_TYPE_TO_CHAIN[Number(match?.[1])] === chain;
608
632
  }
633
+ function exactHex(value) {
634
+ const hex = value.replace(/^0x/i, "");
635
+ return /^(?:[0-9a-f]{2})*$/i.test(hex) ? hex : void 0;
636
+ }
637
+ function invalidHexFailure(field) {
638
+ return failure(HardwareErrorCode2.InvalidParams, `${field} must be an even-length hex string`);
639
+ }
640
+ function requireExportedPath(parsed, path) {
641
+ const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
642
+ if (!account) {
643
+ throw createHwkError2({
644
+ code: HardwareErrorCode2.DeviceMismatch,
645
+ message: `Keystone did not return the requested derivation path (${path})`
646
+ });
647
+ }
648
+ return account;
649
+ }
609
650
  function coinTypeFailure(chain, path) {
610
651
  if (hasChainCoinType(chain, path)) return void 0;
611
652
  return failure(
@@ -613,6 +654,19 @@ function coinTypeFailure(chain, path) {
613
654
  `Keystone ${chain} needs a path with its own BIP44 coin type, not ${path}`
614
655
  );
615
656
  }
657
+ function btcAccountFailure(accountPath) {
658
+ if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
659
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
660
+ }
661
+ function missingParamFailure(method, param) {
662
+ return failure(HardwareErrorCode2.InvalidParams, `${method} requires ${param}`);
663
+ }
664
+ function messageToHex(message, hex) {
665
+ return hex ? exactHex(message) : Buffer.from(message, "utf8").toString("hex");
666
+ }
667
+ function evmMessageSignature(sig) {
668
+ return { signature: ensure0x(sig.r + sig.s + sig.v) };
669
+ }
616
670
  var KeystoneAdapter = class _KeystoneAdapter {
617
671
  constructor(options) {
618
672
  this.vendor = "keystone";
@@ -627,6 +681,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
627
681
  const route = this._operationRoutes.get(operation.connectId);
628
682
  if (route?.operationId === operation.operationId) {
629
683
  this._operationRoutes.delete(operation.connectId);
684
+ if (route.connectionType === "qr") {
685
+ const ended = createHwkError2({
686
+ code: HardwareErrorCode2.OperationEnded,
687
+ message: "Keystone operation has ended",
688
+ params: { operationId: operation.operationId, reason }
689
+ });
690
+ const queueKey = keystoneQueueKey(operation.operationId);
691
+ const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
692
+ this._jobQueue.cancelActiveAndPending(queueKey, ended);
693
+ if (ownsRunningCall) {
694
+ this._uiRegistry.cancel(void 0, void 0, operation.operationId);
695
+ }
696
+ }
630
697
  }
631
698
  this.emitter.emit(SDK.OPERATION_ENDED, {
632
699
  type: SDK.OPERATION_ENDED,
@@ -703,7 +770,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
703
770
  callItem: async ({ method, item, index }) => {
704
771
  if (scope.signal.aborted) {
705
772
  cancelledIndexes.add(index);
706
- return buildCancelledFailure(scope.signal);
773
+ return buildAllNetworkCancelledFailure(scope.signal);
707
774
  }
708
775
  const commonArgs = {
709
776
  path: item.path,
@@ -725,11 +792,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
725
792
  return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
726
793
  case "tronGetAddress":
727
794
  return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
728
- default:
729
- return failure(
730
- HardwareErrorCode2.MethodNotSupported,
731
- `Unsupported method: ${String(method)}`
732
- );
733
795
  }
734
796
  },
735
797
  attachIdentity: (context) => {
@@ -770,9 +832,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
770
832
  this._usbConnector?.on("device-disconnect", this._handleUsbDisconnect);
771
833
  this._usbConnector?.on("ui-event", this._handleUsbUiEvent);
772
834
  }
773
- // ---------------------------------------------------------------------------
774
- // Lifecycle / transport
775
- // ---------------------------------------------------------------------------
776
835
  get activeTransport() {
777
836
  if (this._devices.size === 0) return null;
778
837
  const hasUsbSession = Array.from(this._devices.values()).some((r) => r.usbSessionId);
@@ -802,9 +861,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
802
861
  this._devices.clear();
803
862
  this.emitter.removeAllListeners();
804
863
  }
805
- // ---------------------------------------------------------------------------
806
- // Device table
807
- // ---------------------------------------------------------------------------
808
864
  /**
809
865
  * Returns known wallets plus USB scan results; USB entries have no mfp until `connectDevice()`
810
866
  * claims them. Explicit QR discovery returns one virtual target.
@@ -877,11 +933,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
877
933
  }
878
934
  /** Best-effort disconnect; the session is retired either way so it cannot be selected again. */
879
935
  async _retireUsbSession(sessionId) {
880
- if (this._usbConnector) {
881
- try {
882
- await this._usbConnector.disconnect(sessionId);
883
- } catch {
884
- }
936
+ try {
937
+ await this._usbConnector?.disconnect(sessionId);
938
+ } catch {
885
939
  }
886
940
  this._handleUsbDisconnect({ connectId: sessionId });
887
941
  }
@@ -900,13 +954,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
900
954
  serialNumber: device.serialNumber
901
955
  }));
902
956
  }
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
957
  async connectDevice(searchTargetId) {
911
958
  const scope = this._jobQueue.createCancelScope(searchTargetId);
912
959
  try {
@@ -915,16 +962,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
915
962
  const discoveredConnectionType = this._searchDeviceTargets.get(searchTargetId);
916
963
  if (discoveredConnectionType === "qr") {
917
964
  selectedConnectionType = "qr";
918
- const abortColdStart = () => this._jobQueue.cancelActiveAndPending(
919
- KEYSTONE_COLD_START_JOB_LABEL,
920
- scope.signal.reason
965
+ connected = await _KeystoneAdapter._untilAborted(
966
+ scope.signal,
967
+ this._importFromQr({}, searchTargetId)
921
968
  );
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
969
  } else if (discoveredConnectionType === "usb") {
929
970
  selectedConnectionType = "usb";
930
971
  if (!this._usbConnector) {
@@ -933,7 +974,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
933
974
  "No USB connector configured for this Keystone adapter"
934
975
  );
935
976
  }
936
- connected = await this._connectUsb({}, searchTargetId, scope.signal);
977
+ connected = await this._connectUsb(this._usbConnector, {}, searchTargetId, scope.signal);
937
978
  } else if (hasHardwareRuntimeIdPrefix(searchTargetId)) {
938
979
  return failure(
939
980
  HardwareErrorCode2.DeviceNotFound,
@@ -954,7 +995,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
954
995
  );
955
996
  } else {
956
997
  selectedConnectionType = "usb";
957
- connected = await this._connectUsb(target, void 0, scope.signal);
998
+ connected = await this._connectUsb(this._usbConnector, target, void 0, scope.signal);
958
999
  }
959
1000
  }
960
1001
  _KeystoneAdapter._throwIfAborted(scope.signal);
@@ -1013,10 +1054,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1013
1054
  const { record } = this._resolveTarget(connectId, deviceId);
1014
1055
  if (!record) {
1015
1056
  return Promise.resolve(
1016
- failure(
1017
- HardwareErrorCode2.DeviceNotFound,
1018
- `Unknown Keystone device: ${connectId || deviceId}`
1019
- )
1057
+ failure(HardwareErrorCode2.DeviceNotFound, "Unknown Keystone device")
1020
1058
  );
1021
1059
  }
1022
1060
  return Promise.resolve(success(toDeviceInfo(record)));
@@ -1092,18 +1130,21 @@ var KeystoneAdapter = class _KeystoneAdapter {
1092
1130
  // Explicit account import: call before signing to avoid a cold sync per call.
1093
1131
  // ---------------------------------------------------------------------------
1094
1132
  async importFromQr(options = {}) {
1133
+ return this._importFromQr(options, KEYSTONE_COLD_START_JOB_LABEL);
1134
+ }
1135
+ async _importFromQr(options, jobKey) {
1095
1136
  try {
1096
- return await this._jobQueue.enqueue(KEYSTONE_COLD_START_JOB_LABEL, async (signal) => {
1137
+ return await this._jobQueue.enqueue(jobKey, async (signal) => {
1097
1138
  const displayDevice = placeholderDeviceInfo();
1098
1139
  let responseUr;
1099
1140
  if (options.mode === "scan") {
1100
- responseUr = await this._requestQrScanAndAwaitResponse(displayDevice, signal);
1141
+ responseUr = await this._requestQrAndAwaitResponse(displayDevice, void 0, signal);
1101
1142
  } else {
1102
1143
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1103
1144
  schemas: [keySchema("evm", KEYSTONE_COLD_START_PATH)],
1104
1145
  origin: this._origin
1105
1146
  });
1106
- responseUr = await this._requestQrDisplayAndAwaitResponse(
1147
+ responseUr = await this._requestQrAndAwaitResponse(
1107
1148
  displayDevice,
1108
1149
  { ...requestUr, animated: false },
1109
1150
  signal
@@ -1111,6 +1152,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1111
1152
  }
1112
1153
  _KeystoneAdapter._throwIfAborted(signal);
1113
1154
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1155
+ if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1114
1156
  const record = this._upsertDeviceRecord(parsed);
1115
1157
  return success(toDeviceInfo(record));
1116
1158
  });
@@ -1118,163 +1160,103 @@ var KeystoneAdapter = class _KeystoneAdapter {
1118
1160
  return this._errorToFailure(err);
1119
1161
  }
1120
1162
  }
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");
1163
+ async evmGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1164
+ const call = this._beginCall("evmGetAddress", connectIdArg, deviceIdArg, paramsArg);
1165
+ if (!call.success) return call;
1166
+ const { params } = call.payload;
1167
+ if (!params.path) return missingParamFailure("evmGetAddress", "params.path");
1132
1168
  const evmCoinTypeFailure = coinTypeFailure("evm", params.path);
1133
1169
  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
- });
1170
+ return this._addressFromAccountXpub(
1171
+ "evmGetAddress",
1172
+ "evm",
1173
+ call.payload,
1174
+ params.path,
1175
+ "m/44'/60'/0'/0/0",
1176
+ bundle,
1177
+ (xpub, relativeDerivePath) => this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath)
1178
+ );
1153
1179
  }
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
- }
1180
+ async evmSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1181
+ const call = this._beginCall("evmSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1182
+ if (!call.success) return call;
1183
+ const { params } = call.payload;
1184
+ if (!params.path) return missingParamFailure("evmSignTransaction", "params.path");
1164
1185
  if (!("serializedTx" in params) || typeof params.serializedTx !== "string" || !params.serializedTx) {
1165
1186
  return failure(
1166
1187
  HardwareErrorCode2.MethodNotSupported,
1167
1188
  "Keystone only signs a fully RLP-serialized transaction (params.serializedTx) \u2014 structured-field signing is not supported"
1168
1189
  );
1169
1190
  }
1170
- const rawTxHex = stripHex(params.serializedTx);
1171
- const path = normalizePath(params.path);
1191
+ const rawTxHex = exactHex(params.serializedTx);
1192
+ if (rawTxHex === void 0) return invalidHexFailure("serializedTx");
1172
1193
  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
- });
1194
+ return this._evmSign(
1195
+ "evmSignTransaction",
1196
+ call.payload,
1197
+ params.path,
1198
+ params.chainId,
1199
+ rawTxHex,
1200
+ dataType,
1201
+ (sig) => ({ v: ensure0x(sig.v), r: ensure0x(sig.r), s: ensure0x(sig.s) })
1202
+ );
1194
1203
  }
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");
1204
+ async evmSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1205
+ const call = this._beginCall("evmSignMessage", connectIdArg, deviceIdArg, paramsArg);
1206
+ if (!call.success) return call;
1207
+ const { params } = call.payload;
1201
1208
  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
- });
1209
+ return missingParamFailure("evmSignMessage", "params.path and params.message");
1210
+ }
1211
+ const messageHex = messageToHex(params.message, params.hex);
1212
+ if (messageHex === void 0) return invalidHexFailure("message");
1213
+ return this._evmSign(
1214
+ "evmSignMessage",
1215
+ call.payload,
1216
+ params.path,
1217
+ params.chainId,
1218
+ messageHex,
1219
+ "personalMessage",
1220
+ evmMessageSignature
1221
+ );
1226
1222
  }
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
- }
1223
+ async evmSignTypedData(connectIdArg, deviceIdArg, paramsArg) {
1224
+ const call = this._beginCall("evmSignTypedData", connectIdArg, deviceIdArg, paramsArg);
1225
+ if (!call.success) return call;
1226
+ const { params } = call.payload;
1227
+ if (!params.path) return missingParamFailure("evmSignTypedData", "params.path");
1237
1228
  if (params.mode === "hash") {
1238
1229
  return failure(
1239
1230
  HardwareErrorCode2.MethodNotSupported,
1240
1231
  "Keystone always displays the full EIP-712 payload for on-device review \u2014 pre-hashed signing is not supported"
1241
1232
  );
1242
1233
  }
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
- });
1234
+ if (typeof params.dataJson !== "string" || !params.dataJson) {
1235
+ return failure(
1236
+ HardwareErrorCode2.InvalidParams,
1237
+ "Keystone evmSignTypedData requires params.dataJson, the original typed-data JSON text"
1238
+ );
1239
+ }
1240
+ const signDataHex = Buffer.from(params.dataJson, "utf8").toString("hex");
1241
+ return this._evmSign(
1242
+ "evmSignTypedData",
1243
+ call.payload,
1244
+ params.path,
1245
+ params.chainId,
1246
+ signDataHex,
1247
+ "typedData",
1248
+ evmMessageSignature
1249
+ );
1265
1250
  }
1266
1251
  // ---------------------------------------------------------------------------
1267
1252
  // BTC: 44'/49'/84' addresses derive offline from the account xpub; P2TR addresses
1268
1253
  // and structured-field tx signing are unsupported (the host builds a PSBT instead).
1269
1254
  // ---------------------------------------------------------------------------
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");
1255
+ async btcGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1256
+ const call = this._beginCall("btcGetAddress", connectIdArg, deviceIdArg, paramsArg);
1257
+ if (!call.success) return call;
1258
+ const { params } = call.payload;
1259
+ if (!params.path) return missingParamFailure("btcGetAddress", "params.path");
1278
1260
  const btcParamsFailure = keystoneBtcParamsFailure(params);
1279
1261
  if (btcParamsFailure) return btcParamsFailure;
1280
1262
  const scriptType = btcScriptTypeFromPath(params.path);
@@ -1290,42 +1272,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
1290
1272
  "P2TR (purpose 86') needs an elliptic-curve library for BIP-341 tweaking, not yet wired in \u2014 44'/49'/84' work"
1291
1273
  );
1292
1274
  }
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
- });
1275
+ return this._addressFromAccountXpub(
1276
+ "btcGetAddress",
1277
+ "btc",
1278
+ call.payload,
1279
+ params.path,
1280
+ "m/84'/0'/0'/0/0",
1281
+ bundle,
1282
+ (xpub, relativeDerivePath) => this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType)
1283
+ );
1316
1284
  }
1317
1285
  /**
1318
1286
  * `params.path` must be an account path (`m/84'/0'/0'`), the level Keystone syncs. An xpub is
1319
1287
  * script-type agnostic, so `86'` works here even though `btcGetAddress` rejects it.
1320
1288
  */
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");
1289
+ async btcGetPublicKey(connectIdArg, deviceIdArg, paramsArg, bundle) {
1290
+ const call = this._beginCall("btcGetPublicKey", connectIdArg, deviceIdArg, paramsArg);
1291
+ if (!call.success) return call;
1292
+ const { connectId, deviceId, params } = call.payload;
1293
+ if (!params.path) return missingParamFailure("btcGetPublicKey", "params.path");
1329
1294
  const btcParamsFailure = keystoneBtcParamsFailure(params);
1330
1295
  if (btcParamsFailure) return btcParamsFailure;
1331
1296
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
@@ -1335,9 +1300,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1335
1300
  "btcGetPublicKey requires an account path, e.g. m/84'/0'/0' (not a leaf path)"
1336
1301
  );
1337
1302
  }
1338
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1339
- return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1340
- }
1303
+ const accountFailure = btcAccountFailure(accountPath);
1304
+ if (accountFailure) return accountFailure;
1341
1305
  return this._runJob(connectId, deviceId, async (signal) => {
1342
1306
  const xpub = await this._fetchAccountXpub(
1343
1307
  connectId,
@@ -1354,7 +1318,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1354
1318
  chainCode: meta.chainCode,
1355
1319
  depth: meta.depth,
1356
1320
  fingerprint: meta.parentFingerprint,
1357
- path: normalizePath(accountPath)
1321
+ path: normalizePath(accountPath),
1322
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1358
1323
  });
1359
1324
  });
1360
1325
  }
@@ -1364,23 +1329,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1364
1329
  "use btcSignPsbt \u2014 structured input/output signing needs host-side PSBT construction, not yet wired in"
1365
1330
  );
1366
1331
  }
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
- }
1332
+ async btcSignPsbt(connectIdArg, deviceIdArg, paramsArg) {
1333
+ const call = this._beginCall("btcSignPsbt", connectIdArg, deviceIdArg, paramsArg);
1334
+ if (!call.success) return call;
1335
+ const { connectId, deviceId, params } = call.payload;
1336
+ if (!params.psbt) return missingParamFailure("btcSignPsbt", "params.psbt");
1337
+ if (!params.path) return missingParamFailure("btcSignPsbt", "params.path");
1338
+ const accountFailure = btcAccountFailure(splitAccountPath(params.path).accountPath);
1339
+ if (accountFailure) return accountFailure;
1340
+ const requestPsbtHex = exactHex(params.psbt);
1341
+ if (requestPsbtHex === void 0) return invalidHexFailure("psbt");
1380
1342
  return this._runJob(connectId, deviceId, async (signal) => {
1381
1343
  const { record } = await this._ensureWalletKnown(connectId, deviceId, "btc", signal);
1382
1344
  _KeystoneAdapter._throwIfAborted(signal);
1383
- const requestUr = this.urEngine.buildBtcPsbtRequest(stripHex(params.psbt));
1345
+ const requestUr = this.urEngine.buildBtcPsbtRequest(requestPsbtHex);
1384
1346
  const responseUr = await this._resolveUr(
1385
1347
  record,
1386
1348
  requestUr,
@@ -1390,30 +1352,26 @@ var KeystoneAdapter = class _KeystoneAdapter {
1390
1352
  "btcSignPsbt"
1391
1353
  );
1392
1354
  _KeystoneAdapter._throwIfAborted(signal);
1393
- const signedPsbt = this.urEngine.parseBtcPsbt(responseUr);
1355
+ const signedPsbt = this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex);
1394
1356
  return success({ signedPsbt });
1395
1357
  });
1396
1358
  }
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");
1359
+ async btcSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1360
+ const call = this._beginCall("btcSignMessage", connectIdArg, deviceIdArg, paramsArg);
1361
+ if (!call.success) return call;
1362
+ const { connectId, deviceId, params } = call.payload;
1403
1363
  if (!params.path || params.message === void 0) {
1404
- return failure(
1405
- HardwareErrorCode2.InvalidParams,
1406
- "btcSignMessage requires params.path and params.message"
1407
- );
1364
+ return missingParamFailure("btcSignMessage", "params.path and params.message");
1408
1365
  }
1409
- const messageHex = params.hex ? stripHex(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1366
+ const messageHex = messageToHex(params.message, params.hex);
1367
+ if (messageHex === void 0) return invalidHexFailure("message");
1410
1368
  const path = normalizePath(params.path);
1411
- if (!isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1412
- return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1413
- }
1369
+ const accountFailure = btcAccountFailure(splitAccountPath(path).accountPath);
1370
+ if (accountFailure) return accountFailure;
1414
1371
  return this._signWithWallet({
1415
1372
  connectId,
1416
1373
  deviceId,
1374
+ path,
1417
1375
  chain: "btc",
1418
1376
  operationName: "btcSignMessage",
1419
1377
  buildRequest: (requestId, xfp) => this.urEngine.buildBtcMessageSignRequest({
@@ -1441,17 +1399,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1441
1399
  return success({ masterFingerprint: record.masterFingerprint });
1442
1400
  });
1443
1401
  }
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");
1402
+ async solGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1403
+ const call = this._beginCall("solGetAddress", connectIdArg, deviceIdArg, paramsArg);
1404
+ if (!call.success) return call;
1405
+ const { connectId, deviceId, params } = call.payload;
1406
+ if (!params.path) return missingParamFailure("solGetAddress", "params.path");
1455
1407
  const solCoinTypeFailure = coinTypeFailure("sol", params.path);
1456
1408
  if (solCoinTypeFailure) return solCoinTypeFailure;
1457
1409
  const path = normalizePath(params.path);
@@ -1471,180 +1423,218 @@ var KeystoneAdapter = class _KeystoneAdapter {
1471
1423
  bundle
1472
1424
  );
1473
1425
  _KeystoneAdapter._throwIfAborted(signal);
1426
+ if (!/^[0-9a-f]{64}$/i.test(account.publicKey)) {
1427
+ throw createHwkError2({
1428
+ code: HardwareErrorCode2.DeviceMismatch,
1429
+ message: "Keystone returned a Solana key that is not a 32-byte Ed25519 public key"
1430
+ });
1431
+ }
1474
1432
  const address = bs58.encode(Buffer.from(account.publicKey, "hex"));
1475
- return success({ address, path });
1433
+ return success({
1434
+ address,
1435
+ path,
1436
+ accountKey: { path, publicKey: account.publicKey }
1437
+ });
1476
1438
  });
1477
1439
  }
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");
1440
+ async solSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1441
+ const call = this._beginCall("solSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1442
+ if (!call.success) return call;
1443
+ const { params } = call.payload;
1485
1444
  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
- });
1445
+ return missingParamFailure("solSignTransaction", "params.path and params.serializedTx");
1446
+ }
1447
+ const unsignedPayloadHex = exactHex(params.serializedTx);
1448
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("serializedTx");
1449
+ return this._solSign(
1450
+ "solSignTransaction",
1451
+ call.payload,
1452
+ params.path,
1453
+ unsignedPayloadHex,
1454
+ "transaction"
1455
+ );
1508
1456
  }
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");
1457
+ async solSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1458
+ const call = this._beginCall("solSignMessage", connectIdArg, deviceIdArg, paramsArg);
1459
+ if (!call.success) return call;
1460
+ const { params } = call.payload;
1515
1461
  if (!params.path || !params.message) {
1462
+ return missingParamFailure("solSignMessage", "params.path and params.message");
1463
+ }
1464
+ if (params.messageVersion !== void 0) {
1516
1465
  return failure(
1517
- HardwareErrorCode2.InvalidParams,
1518
- "solSignMessage requires params.path and params.message"
1466
+ HardwareErrorCode2.MethodNotSupported,
1467
+ "Keystone signs Solana messages as raw bytes only; off-chain message format is not supported"
1519
1468
  );
1520
1469
  }
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
- });
1470
+ const unsignedPayloadHex = exactHex(params.message);
1471
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("message");
1472
+ return this._solSign(
1473
+ "solSignMessage",
1474
+ call.payload,
1475
+ params.path,
1476
+ unsignedPayloadHex,
1477
+ "message"
1478
+ );
1538
1479
  }
1539
1480
  // ---------------------------------------------------------------------------
1540
1481
  // TRON: keystone-sdk-rust layout (tags 5201/5202, firmware >= 2.5.0), not sdk.tron's
1541
1482
  // protobuf module; OneKey Pro's encoding under the same tag is rejected by the firmware.
1542
1483
  // ---------------------------------------------------------------------------
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");
1484
+ async tronGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1485
+ const call = this._beginCall("tronGetAddress", connectIdArg, deviceIdArg, paramsArg);
1486
+ if (!call.success) return call;
1487
+ const { params } = call.payload;
1488
+ if (!params.path) return missingParamFailure("tronGetAddress", "params.path");
1551
1489
  const tronCoinTypeFailure = coinTypeFailure("tron", params.path);
1552
1490
  if (tronCoinTypeFailure) return tronCoinTypeFailure;
1553
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1491
+ return this._addressFromAccountXpub(
1492
+ "tronGetAddress",
1493
+ "tron",
1494
+ call.payload,
1495
+ params.path,
1496
+ "m/44'/195'/0'/0/0",
1497
+ bundle,
1498
+ (xpub, relativeDerivePath) => this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath)
1499
+ );
1500
+ }
1501
+ async tronSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1502
+ const call = this._beginCall("tronSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1503
+ if (!call.success) return call;
1504
+ const { params } = call.payload;
1505
+ if (!params.path) return missingParamFailure("tronSignTransaction", "params.path");
1506
+ if (!params.rawTxHex) {
1507
+ return failure(
1508
+ HardwareErrorCode2.InvalidParams,
1509
+ "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1510
+ );
1511
+ }
1512
+ const rawTxHex = exactHex(params.rawTxHex);
1513
+ if (rawTxHex === void 0) return invalidHexFailure("rawTxHex");
1514
+ return this._tronSign("tronSignTransaction", call.payload, params.path, rawTxHex);
1515
+ }
1516
+ async tronSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1517
+ const call = this._beginCall("tronSignMessage", connectIdArg, deviceIdArg, paramsArg);
1518
+ if (!call.success) return call;
1519
+ const { params } = call.payload;
1520
+ if (!params.path) return missingParamFailure("tronSignMessage", "params.path");
1521
+ if (!params.messageHex) return missingParamFailure("tronSignMessage", "params.messageHex");
1522
+ if (params.messageType !== "V2") {
1523
+ return failure(
1524
+ HardwareErrorCode2.MethodNotSupported,
1525
+ 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1526
+ );
1527
+ }
1528
+ const messageHex = exactHex(params.messageHex);
1529
+ if (messageHex === void 0) return invalidHexFailure("messageHex");
1530
+ return this._tronSign(
1531
+ "tronSignMessage",
1532
+ call.payload,
1533
+ params.path,
1534
+ messageHex,
1535
+ 2 /* PersonalMessage */
1536
+ );
1537
+ }
1538
+ /** Resolves the call's target and requires params, before any method-specific check. */
1539
+ _beginCall(method, connectIdArg, deviceIdArg, params) {
1540
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1541
+ if (!operationTarget.success) return operationTarget;
1542
+ if (!params) return missingParamFailure(method, "params");
1543
+ return success({
1544
+ connectId: operationTarget.payload.targetId,
1545
+ deviceId: deviceIdArg ?? void 0,
1546
+ params
1547
+ });
1548
+ }
1549
+ /** Derives a leaf address offline from its account xpub. */
1550
+ async _addressFromAccountXpub(method, chain, { connectId, deviceId }, path, leafExample, bundle, derive) {
1551
+ const normalizedPath = normalizePath(path);
1552
+ const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1554
1553
  if (!relativeDerivePath) {
1555
1554
  return failure(
1556
1555
  HardwareErrorCode2.InvalidParams,
1557
- "tronGetAddress requires a full leaf path, e.g. m/44'/195'/0'/0/0"
1556
+ `${method} requires a full leaf path, e.g. ${leafExample}`
1558
1557
  );
1559
1558
  }
1559
+ const accountFailure = chain === "btc" ? btcAccountFailure(accountPath) : void 0;
1560
+ if (accountFailure) return accountFailure;
1560
1561
  return this._runJob(connectId, deviceId, async (signal) => {
1561
1562
  const xpub = await this._fetchAccountXpub(
1562
1563
  connectId,
1563
1564
  deviceId,
1564
- "tron",
1565
+ chain,
1565
1566
  accountPath,
1566
1567
  signal,
1567
1568
  bundle
1568
1569
  );
1569
- const address = this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath);
1570
- return success({ address, path: normalizePath(params.path) });
1570
+ return success({
1571
+ address: derive(xpub, relativeDerivePath),
1572
+ path: normalizedPath,
1573
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1574
+ });
1571
1575
  });
1572
1576
  }
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);
1577
+ _evmSign(method, target, rawPath, chainId, signDataHex, dataType, toPayload) {
1578
+ const path = normalizePath(rawPath);
1591
1579
  return this._signWithWallet({
1592
- connectId,
1593
- deviceId,
1594
- chain: "tron",
1595
- operationName: "tronSignTransaction",
1596
- buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1580
+ connectId: target.connectId,
1581
+ deviceId: target.deviceId,
1582
+ path,
1583
+ chain: "evm",
1584
+ operationName: method,
1585
+ buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1586
+ requestId,
1587
+ unsignedTxHex: signDataHex,
1588
+ dataType,
1589
+ path,
1590
+ xfp,
1591
+ chainId,
1592
+ origin: this._origin
1593
+ }),
1594
+ parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1595
+ toPayload
1596
+ });
1597
+ }
1598
+ _solSign(method, target, rawPath, unsignedPayloadHex, dataType) {
1599
+ const path = normalizePath(rawPath);
1600
+ return this._signWithWallet({
1601
+ connectId: target.connectId,
1602
+ deviceId: target.deviceId,
1603
+ path,
1604
+ chain: "sol",
1605
+ operationName: method,
1606
+ buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1597
1607
  requestId,
1598
- rawTxHex,
1608
+ unsignedPayloadHex,
1609
+ dataType,
1599
1610
  path,
1600
1611
  xfp,
1601
1612
  origin: this._origin
1602
1613
  }),
1603
- parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1604
- // Keystone signs rawTxHex as given and returns only the signature, so no serializedTx.
1614
+ parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1605
1615
  toPayload: (sig) => ({ signature: sig.signature })
1606
1616
  });
1607
1617
  }
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);
1618
+ _tronSign(method, target, rawPath, signDataHex, signType) {
1619
+ const path = normalizePath(rawPath);
1628
1620
  return this._signWithWallet({
1629
- connectId,
1630
- deviceId,
1621
+ connectId: target.connectId,
1622
+ deviceId: target.deviceId,
1623
+ path,
1631
1624
  chain: "tron",
1632
- operationName: "tronSignMessage",
1625
+ operationName: method,
1633
1626
  buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1634
1627
  requestId,
1635
- rawTxHex: messageHex,
1628
+ rawTxHex: signDataHex,
1636
1629
  path,
1637
1630
  xfp,
1638
- signType: 2 /* PersonalMessage */,
1631
+ signType,
1639
1632
  origin: this._origin
1640
1633
  }),
1641
1634
  parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1642
1635
  toPayload: (sig) => ({ signature: sig.signature })
1643
1636
  });
1644
1637
  }
1645
- // ---------------------------------------------------------------------------
1646
- // Internals
1647
- // ---------------------------------------------------------------------------
1648
1638
  async _runJob(connectId, deviceId, job) {
1649
1639
  try {
1650
1640
  return await this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), job);
@@ -1668,14 +1658,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
1668
1658
  message: "Keystone did not return an extended public key for this account path"
1669
1659
  });
1670
1660
  }
1661
+ const { publicKey } = this.urEngine.parseXpubMeta(account.extendedPublicKey);
1662
+ if (!/^0[23]/.test(publicKey)) {
1663
+ throw createHwkError2({
1664
+ code: HardwareErrorCode2.DeviceMismatch,
1665
+ message: "Keystone returned an account key that is not a public key"
1666
+ });
1667
+ }
1671
1668
  return account.extendedPublicKey;
1672
1669
  }
1670
+ /** The exported key behind an address, reduced to the fields that identify it. */
1671
+ _exportedAccountKey(accountPath, xpub) {
1672
+ const { publicKey, chainCode } = this.urEngine.parseXpubMeta(xpub);
1673
+ return { path: normalizePath(accountPath), publicKey, chainCode, xpub };
1674
+ }
1673
1675
  /**
1674
1676
  * Signing needs only the wallet's mfp: the device re-derives the key from path+xfp, so no
1675
1677
  * per-path account lookup happens here.
1676
1678
  */
1677
1679
  _signWithWallet(args) {
1678
1680
  const { connectId, deviceId } = args;
1681
+ if (!isBip32Path(args.path)) {
1682
+ return Promise.resolve(
1683
+ failure(HardwareErrorCode2.InvalidParams, `Invalid derivation path (${args.path})`)
1684
+ );
1685
+ }
1686
+ const chainCoinTypeFailure = coinTypeFailure(args.chain, args.path);
1687
+ if (chainCoinTypeFailure) return Promise.resolve(chainCoinTypeFailure);
1679
1688
  return this._runJob(connectId, deviceId, async (signal) => {
1680
1689
  const { record } = await this._ensureWalletKnown(connectId, deviceId, args.chain, signal);
1681
1690
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1712,8 +1721,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1712
1721
  case "btcGetPublicKey":
1713
1722
  case "solGetAddress":
1714
1723
  return { hwkChain, path };
1715
- default:
1716
- return void 0;
1717
1724
  }
1718
1725
  }
1719
1726
  /**
@@ -1757,7 +1764,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1757
1764
  schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1758
1765
  origin: this._origin
1759
1766
  });
1760
- const responseUr = await this._requestQrDisplayAndAwaitResponse(
1767
+ const responseUr = await this._requestQrAndAwaitResponse(
1761
1768
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1762
1769
  { ...requestUr, animated: false },
1763
1770
  signal
@@ -1765,26 +1772,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
1765
1772
  _KeystoneAdapter._throwIfAborted(signal);
1766
1773
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1767
1774
  this._assertParsedIdentity(parsed, target);
1768
- record = this._upsertDeviceRecord(parsed);
1769
1775
  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
1776
  scanned.set(accountKey(schema.hwkChain, schema.path), {
1780
- ...account,
1777
+ ...requireExportedPath(parsed, schema.path),
1781
1778
  hwkChain: schema.hwkChain
1782
1779
  });
1783
1780
  }
1781
+ record = this._upsertDeviceRecord(parsed);
1784
1782
  return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1785
1783
  });
1786
1784
  }
1787
- /** Resolve the wallet's master fingerprint from the connectId and/or deviceId the caller passed. */
1788
1785
  /**
1789
1786
  * A positional wallet id and an operation id must name the same wallet: otherwise the call
1790
1787
  * would run on the operation's wallet while the caller files the result under the other one.
@@ -1839,7 +1836,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1839
1836
  if (expected.expectedMasterFingerprint && parsed.masterFingerprint !== expected.expectedMasterFingerprint) {
1840
1837
  throw createHwkError2({
1841
1838
  code: HardwareErrorCode2.DeviceMismatch,
1842
- message: `Connected Keystone wallet (mfp ${parsed.masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1839
+ // The master fingerprint identifies the wallet; keep it out of messages that reach logs.
1840
+ message: "Connected Keystone wallet does not match the requested wallet"
1843
1841
  });
1844
1842
  }
1845
1843
  }
@@ -1869,7 +1867,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1869
1867
  * Opens a permitted USB Keystone and takes its mfp as the wallet identity. A known wallet gains
1870
1868
  * USB in place (`device-changed`); an unseen one becomes USB-only.
1871
1869
  */
1872
- async _connectUsb(expected, searchTargetId, signal) {
1870
+ async _connectUsb(connector, expected, searchTargetId, signal) {
1873
1871
  if (this._pendingUsbTeardowns > 0 || this._abandonedUsbConnects > 0) {
1874
1872
  return failure(
1875
1873
  HardwareErrorCode2.DeviceBusyInternal,
@@ -1882,28 +1880,22 @@ var KeystoneAdapter = class _KeystoneAdapter {
1882
1880
  abandoned = true;
1883
1881
  this._abandonedUsbConnects += 1;
1884
1882
  };
1885
- signal?.addEventListener("abort", onAbort, { once: true });
1883
+ signal.addEventListener("abort", onAbort, { once: true });
1886
1884
  const pending = this._usbConnectTail.then(async () => {
1887
1885
  _KeystoneAdapter._throwIfAborted(signal);
1888
- return this._connectUsbExclusive(expected, searchTargetId, signal);
1886
+ return this._connectUsbExclusive(connector, expected, searchTargetId, signal);
1889
1887
  });
1890
1888
  const settled = pending.finally(() => {
1891
- signal?.removeEventListener("abort", onAbort);
1889
+ signal.removeEventListener("abort", onAbort);
1892
1890
  if (abandoned) this._abandonedUsbConnects -= 1;
1893
1891
  });
1894
1892
  this._usbConnectTail = settled.then(
1895
1893
  () => void 0,
1896
1894
  () => void 0
1897
1895
  );
1898
- return signal ? _KeystoneAdapter._abortable(signal, settled) : settled;
1896
+ return _KeystoneAdapter._abortable(signal, settled);
1899
1897
  }
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
- }
1898
+ async _connectUsbExclusive(connector, expected, searchTargetId, signal) {
1907
1899
  let sessionId;
1908
1900
  try {
1909
1901
  let connectTarget = { type: "default" };
@@ -1915,7 +1907,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1915
1907
  deviceIdentity: expected.expectedMasterFingerprint
1916
1908
  };
1917
1909
  }
1918
- const connector = this._usbConnector;
1919
1910
  const session = await (connector.connectTarget ? connector.connectTarget(connectTarget) : connector.connect(searchTargetId ?? expected.expectedMasterFingerprint));
1920
1911
  sessionId = session.sessionId;
1921
1912
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1929,16 +1920,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1929
1920
  });
1930
1921
  }
1931
1922
  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
- }
1923
+ this._assertParsedIdentity({ masterFingerprint, accounts: [] }, expected);
1938
1924
  const previousUsbSessionId = this._devices.get(masterFingerprint)?.usbSessionId;
1939
1925
  if (previousUsbSessionId && previousUsbSessionId !== session.sessionId) {
1940
1926
  try {
1941
- await this._usbConnector.disconnect(previousUsbSessionId);
1927
+ await connector.disconnect(previousUsbSessionId);
1942
1928
  } catch {
1943
1929
  }
1944
1930
  }
@@ -1958,7 +1944,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1958
1944
  } catch (err) {
1959
1945
  if (sessionId) {
1960
1946
  try {
1961
- await this._usbConnector.disconnect(sessionId);
1947
+ await connector.disconnect(sessionId);
1962
1948
  } catch {
1963
1949
  }
1964
1950
  }
@@ -2004,9 +1990,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
2004
1990
  }
2005
1991
  return void 0;
2006
1992
  }
2007
- const attached = await this._connectUsb({ expectedMasterFingerprint }, void 0, signal);
1993
+ const attached = await this._connectUsb(
1994
+ this._usbConnector,
1995
+ { expectedMasterFingerprint },
1996
+ void 0,
1997
+ signal
1998
+ );
2008
1999
  _KeystoneAdapter._throwIfAborted(signal);
2009
- if (!attached.success && attached.payload.code === HardwareErrorCode2.DeviceBusyInternal) {
2000
+ if (!attached.success && (attached.payload.code === HardwareErrorCode2.DeviceBusyInternal || attached.payload.code === HardwareErrorCode2.DeviceOneDeviceOnly)) {
2010
2001
  throw createHwkError2({
2011
2002
  ...attached.payload,
2012
2003
  message: attached.payload.error
@@ -2066,9 +2057,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2066
2057
  message: "USB channel is not connected for this Keystone wallet"
2067
2058
  });
2068
2059
  }
2069
- const result = await this._callUsbConnector(
2060
+ const result = await this._callUsbResolveUr(
2061
+ this._usbConnector,
2070
2062
  record.usbSessionId,
2071
- "resolveUr",
2072
2063
  requestUr,
2073
2064
  signal
2074
2065
  );
@@ -2078,11 +2069,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2078
2069
  if (usbErrorCode === HardwareErrorCode2.PayloadTooLarge && usbErrorOrigin !== "device") {
2079
2070
  if (!interactionRoute && !this._forcedTransport) {
2080
2071
  const displayDevice2 = toDeviceInfo(record);
2081
- return this._requestQrDisplayAndAwaitResponse(
2082
- displayDevice2,
2083
- { ...requestUr, animated },
2084
- signal
2085
- );
2072
+ return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2086
2073
  }
2087
2074
  throw usbError;
2088
2075
  }
@@ -2093,6 +2080,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2093
2080
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2094
2081
  }
2095
2082
  record.usbSessionId = void 0;
2083
+ this.emitter.emit(DEVICE.CHANGED, { type: DEVICE.CHANGED, payload: toDeviceInfo(record) });
2096
2084
  if (interactionRoute) {
2097
2085
  throw this._endDisconnectedOperation(
2098
2086
  interactionRoute.operationId,
@@ -2110,11 +2098,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2110
2098
  });
2111
2099
  }
2112
2100
  }
2101
+ if (operationName && usbError.replyUnreadable === true) {
2102
+ throw createHwkError2({
2103
+ code: usbErrorCode ?? HardwareErrorCode2.UnknownError,
2104
+ message: `Keystone ${operationName} may have completed but its reply could not be read`,
2105
+ origin: "device",
2106
+ recovery: { scope: "unknown" },
2107
+ params: operationMayHaveCompletedParams(operationName)
2108
+ });
2109
+ }
2113
2110
  throw usbError;
2114
2111
  }
2115
2112
  const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
2116
2113
  try {
2117
- return await this._requestQrDisplayAndAwaitResponse(
2114
+ return await this._requestQrAndAwaitResponse(
2118
2115
  displayDevice,
2119
2116
  { ...requestUr, animated },
2120
2117
  signal
@@ -2178,6 +2175,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2178
2175
  const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2179
2176
  _KeystoneAdapter._throwIfAborted(signal);
2180
2177
  const parsed = this.urEngine.parseAccountResponse(responseUr);
2178
+ const account = requireExportedPath(parsed, syncPath);
2181
2179
  let record;
2182
2180
  if (useSinglePathUsbExport && existingRecord) {
2183
2181
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2193,13 +2191,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2193
2191
  viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2194
2192
  });
2195
2193
  }
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
2194
  return { record, account: { ...account, hwkChain } };
2204
2195
  }
2205
2196
  /**
@@ -2222,7 +2213,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2222
2213
  });
2223
2214
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2224
2215
  _KeystoneAdapter._throwIfAborted(signal);
2225
- return { record: this._upsertDeviceRecord(this.urEngine.parseAccountResponse(responseUr)) };
2216
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
2217
+ requireExportedPath(parsed, normalizePath(accountPath));
2218
+ return { record: this._upsertDeviceRecord(parsed) };
2226
2219
  }
2227
2220
  /**
2228
2221
  * The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
@@ -2248,7 +2241,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2248
2241
  * a cancel reach the wait before the QR timeout.
2249
2242
  */
2250
2243
  async _awaitQrResponse(requestType, pending, signal) {
2251
- if (!signal) return pending;
2252
2244
  let settled = false;
2253
2245
  const onAbort = () => {
2254
2246
  if (!settled) this._uiRegistry.cancel(requestType);
@@ -2257,55 +2249,50 @@ var KeystoneAdapter = class _KeystoneAdapter {
2257
2249
  else signal.addEventListener("abort", onAbort, { once: true });
2258
2250
  try {
2259
2251
  return await pending;
2252
+ } catch (error) {
2253
+ const reason = signal.reason;
2254
+ if (signal.aborted && reason?.code === HardwareErrorCode2.OperationEnded) throw signal.reason;
2255
+ throw error;
2260
2256
  } finally {
2261
2257
  settled = true;
2262
2258
  signal.removeEventListener("abort", onAbort);
2263
2259
  }
2264
2260
  }
2265
- async _requestQrDisplayAndAwaitResponse(device, data, signal) {
2261
+ /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2262
+ async _requestQrAndAwaitResponse(device, data, signal) {
2263
+ const requestType = data ? UI_REQUEST.REQUEST_QR_DISPLAY : UI_REQUEST.REQUEST_QR_SCAN;
2266
2264
  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"
2265
+ const release = operationId ? this._operations.retain(operationId) : void 0;
2266
+ try {
2267
+ const waitPromise = this._uiRegistry.wait(requestType, {
2268
+ timeoutMs: this._qrTimeoutMs,
2269
+ operationId
2300
2270
  });
2271
+ if (data) {
2272
+ this.emitter.emit(UI_REQUEST.REQUEST_QR_DISPLAY, {
2273
+ type: UI_REQUEST.REQUEST_QR_DISPLAY,
2274
+ payload: { device, data, operationId }
2275
+ });
2276
+ } else {
2277
+ this.emitter.emit(UI_REQUEST.REQUEST_QR_SCAN, {
2278
+ type: UI_REQUEST.REQUEST_QR_SCAN,
2279
+ payload: { device, operationId }
2280
+ });
2281
+ }
2282
+ const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2283
+ return { urType: response.urType, urData: response.urData };
2284
+ } finally {
2285
+ release?.();
2301
2286
  }
2287
+ }
2288
+ async _callUsbResolveUr(connector, sessionId, requestUr, signal) {
2302
2289
  if (this._pendingUsbTeardowns > 0 || this._unsettledUsbOperations.size > 0) {
2303
2290
  throw createHwkError2({
2304
2291
  code: HardwareErrorCode2.DeviceBusyInternal,
2305
- message: `Keystone USB is busy while calling ${method}`
2292
+ message: "Keystone USB is busy while calling resolveUr"
2306
2293
  });
2307
2294
  }
2308
- if (signal?.aborted) {
2295
+ if (signal.aborted) {
2309
2296
  throw signal.reason instanceof Error ? signal.reason : createHwkError2({
2310
2297
  code: HardwareErrorCode2.UserAborted,
2311
2298
  message: "User aborted operation"
@@ -2314,12 +2301,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2314
2301
  const releaseOperation = this._retainUsbOperation(`call:${sessionId}`);
2315
2302
  let rawCall;
2316
2303
  try {
2317
- rawCall = this._usbConnector.call(sessionId, method, params).finally(releaseOperation);
2304
+ rawCall = connector.call(sessionId, "resolveUr", requestUr).finally(releaseOperation);
2318
2305
  } catch (error) {
2319
2306
  releaseOperation();
2320
2307
  throw error;
2321
2308
  }
2322
- return signal ? _KeystoneAdapter._abortable(signal, rawCall) : rawCall;
2309
+ return _KeystoneAdapter._abortable(signal, rawCall);
2323
2310
  }
2324
2311
  _runUsbTeardown(task) {
2325
2312
  const previous = this._usbTeardownTail;
@@ -2381,6 +2368,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
2381
2368
  );
2382
2369
  });
2383
2370
  }
2371
+ /** Settles with `signal`'s reason once it aborts; a later outcome of `promise` is dropped. */
2372
+ static _untilAborted(signal, promise) {
2373
+ promise.catch(() => void 0);
2374
+ if (signal.aborted) return Promise.reject(signal.reason);
2375
+ return new Promise((resolve, reject) => {
2376
+ const onAbort = () => reject(signal.reason);
2377
+ signal.addEventListener("abort", onAbort, { once: true });
2378
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort)).catch(() => void 0);
2379
+ });
2380
+ }
2384
2381
  static _throwIfAborted(signal) {
2385
2382
  if (signal?.aborted) {
2386
2383
  throw signal.reason instanceof Error ? signal.reason : new Error("Operation aborted");