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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -105,11 +105,12 @@ var TronSignRequest = class _TronSignRequest extends import_bc_ur_registry.Regis
105
105
  static parsePath(path, xfp) {
106
106
  const segments = path.replace(/^[mM]\//, "").split("/");
107
107
  const components = segments.map((segment) => {
108
- const hardened = segment.endsWith("'");
109
- return new import_bc_ur_registry.PathComponent({
110
- index: parseInt(hardened ? segment.slice(0, -1) : segment, 10),
111
- hardened
112
- });
108
+ const match = /^(\d+)('?)$/.exec(segment);
109
+ const index = match ? Number(match[1]) : NaN;
110
+ if (!match || index >= 2147483648) {
111
+ throw new Error(`Invalid TRON derivation path segment (${segment})`);
112
+ }
113
+ return new import_bc_ur_registry.PathComponent({ index, hardened: match[2] === "'" });
113
114
  });
114
115
  return new import_bc_ur_registry.CryptoKeypath(components, Buffer.from(xfp, "hex"));
115
116
  }
@@ -167,7 +168,7 @@ var DERIVATION_CURVE = {
167
168
  ed25519: import_keystone_sdk.Curve.ed25519
168
169
  };
169
170
  function toSdkUr(ur) {
170
- return new import_keystone_sdk.UR(Buffer.from(ur.urData, "hex"), ur.urType);
171
+ return new import_keystone_sdk.UR((0, import_hwk_adapter_core.boundedCborFromHex)(ur.urData), ur.urType);
171
172
  }
172
173
  function fromSdkUr(ur) {
173
174
  return { urType: ur.type, urData: ur.cbor.toString("hex") };
@@ -219,6 +220,11 @@ function relativeHdPath(relativeDerivePath) {
219
220
  }
220
221
  return `m/${segments.join("/")}`;
221
222
  }
223
+ var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.]{1,20})?$/;
224
+ var DEVICE_TEXT = /^[^\p{Cc}\p{Cf}]{1,64}$/u;
225
+ function deviceText(value, pattern) {
226
+ return typeof value === "string" && pattern.test(value) ? value : void 0;
227
+ }
222
228
  var KeystoneUrEngine = class {
223
229
  constructor(origin = "OneKey") {
224
230
  this.sdk = new import_keystone_sdk.KeystoneSDK({ origin });
@@ -228,9 +234,9 @@ var KeystoneUrEngine = class {
228
234
  const parsed = this.sdk.parseMultiAccounts(toSdkUr(ur));
229
235
  return {
230
236
  masterFingerprint: requireBip32MasterFingerprint(parsed.masterFingerprint),
231
- device: parsed.device,
232
- deviceId: parsed.deviceId,
233
- deviceVersion: parsed.deviceVersion,
237
+ device: deviceText(parsed.device, DEVICE_TEXT),
238
+ deviceId: deviceText(parsed.deviceId, DEVICE_TEXT),
239
+ deviceVersion: deviceText(parsed.deviceVersion, FIRMWARE_VERSION),
234
240
  accounts: parsed.keys.map(toParsedAccount)
235
241
  };
236
242
  }
@@ -292,10 +298,7 @@ var KeystoneUrEngine = class {
292
298
  return (0, import_bc_ur_registry_eth.generateAddressFromXpub)(xpub, relativeHdPath(relativeDerivePath));
293
299
  }
294
300
  // --- BTC (PSBT transaction signing + plain message signing) ---
295
- /**
296
- * `CryptoHDKey` always emits mainnet xpub version bytes (`0488B21E`), so `hdkey` parses it as is.
297
- * `p2tr` needs an ECC lib for BIP-341 tweaking, not wired here.
298
- */
301
+ /** `CryptoHDKey` always emits mainnet xpub version bytes (`0488B21E`), so `hdkey` parses it as is. */
299
302
  deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType) {
300
303
  const node = import_hdkey.default.fromExtendedKey(xpub).derive(relativeHdPath(relativeDerivePath));
301
304
  if (!node.publicKey) throw new Error("HDKey derivation did not produce a public key");
@@ -341,9 +344,27 @@ var KeystoneUrEngine = class {
341
344
  const ur = this.sdk.btc.generatePSBT(Buffer.from(unsignedPsbtHex, "hex"));
342
345
  return fromSdkUr(ur);
343
346
  }
344
- /** Returns the hex-encoded (possibly still-unsigned-in-part) PSBT the device replied with. */
345
- parseBtcPsbt(ur) {
346
- return this.sdk.btc.parsePSBT(toSdkUr(ur));
347
+ /**
348
+ * Returns the hex-encoded (possibly still-unsigned-in-part) PSBT the device replied with. A PSBT
349
+ * carries no request id, so the reply is bound to the request by its unsigned transaction, which
350
+ * signing never changes (BIP-174); a scan of another PSBT's signature is refused.
351
+ */
352
+ parseBtcPsbt(ur, requestPsbtHex) {
353
+ const signedPsbtHex = this.sdk.btc.parsePSBT(toSdkUr(ur));
354
+ let sameTransaction = false;
355
+ try {
356
+ const unsignedTx = (hex) => Buffer.from(bitcoin.Psbt.fromHex(hex).data.globalMap.unsignedTx.toBuffer());
357
+ sameTransaction = unsignedTx(signedPsbtHex).equals(unsignedTx(requestPsbtHex));
358
+ } catch {
359
+ sameTransaction = false;
360
+ }
361
+ if (!sameTransaction) {
362
+ throw (0, import_hwk_adapter_core.createHwkError)({
363
+ code: import_hwk_adapter_core.HardwareErrorCode.DeviceMismatch,
364
+ message: "Keystone returned a PSBT for another transaction than the one requested"
365
+ });
366
+ }
367
+ return signedPsbtHex;
347
368
  }
348
369
  buildBtcMessageSignRequest(params) {
349
370
  const ur = this.sdk.btc.generateSignRequest({
@@ -403,7 +424,7 @@ var KeystoneUrEngine = class {
403
424
  if (ur.urType !== "tron-signature") {
404
425
  throw new Error(`Expected a tron-signature UR, got ${ur.urType}`);
405
426
  }
406
- const signature = TronSignature.fromCBOR(Buffer.from(ur.urData, "hex"));
427
+ const signature = TronSignature.fromCBOR((0, import_hwk_adapter_core.boundedCborFromHex)(ur.urData));
407
428
  const requestId = signature.getRequestId();
408
429
  return {
409
430
  requestId: requestId ? (0, import_uuid.stringify)(requestId) : void 0,
@@ -447,6 +468,14 @@ function normalizePath(path) {
447
468
  const trimmed = path.trim();
448
469
  return /^m\//i.test(trimmed) ? `m/${trimmed.slice(2)}` : `m/${trimmed}`;
449
470
  }
471
+ var BIP32_HARDENED_OFFSET2 = 2147483648;
472
+ function isBip32Path(path) {
473
+ const segments = normalizePath(path).slice(2).split("/");
474
+ return segments.every((segment) => {
475
+ const match = /^(\d+)'?$/.exec(segment);
476
+ return match !== null && Number(match[1]) < BIP32_HARDENED_OFFSET2;
477
+ });
478
+ }
450
479
  function splitAccountPath(path) {
451
480
  const normalized = normalizePath(path);
452
481
  const segments = normalized.slice(2).split("/");
@@ -583,12 +612,6 @@ function waitForKeystoneUsbReattachProbe() {
583
612
  setTimeout(resolve, KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS);
584
613
  });
585
614
  }
586
- function buildCancelledFailure(signal) {
587
- const reason = signal.reason;
588
- const code = typeof reason?.code === "number" ? reason.code : import_hwk_adapter_core3.HardwareErrorCode.UserAborted;
589
- const message = typeof reason?.message === "string" ? reason.message : "";
590
- return (0, import_hwk_adapter_core3.failure)(code, message || "All-network get-address cancelled");
591
- }
592
615
  var BIP44_COIN_TYPE_TO_CHAIN = {
593
616
  60: "evm",
594
617
  0: "btc",
@@ -599,6 +622,23 @@ function hasChainCoinType(chain, path) {
599
622
  const match = normalizePath(path).match(/^m\/\d+'\/(\d+)'/);
600
623
  return Boolean(match) && BIP44_COIN_TYPE_TO_CHAIN[Number(match?.[1])] === chain;
601
624
  }
625
+ function exactHex(value) {
626
+ const hex = value.replace(/^0x/i, "");
627
+ return /^(?:[0-9a-f]{2})*$/i.test(hex) ? hex : void 0;
628
+ }
629
+ function invalidHexFailure(field) {
630
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${field} must be an even-length hex string`);
631
+ }
632
+ function requireExportedPath(parsed, path) {
633
+ const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
634
+ if (!account) {
635
+ throw (0, import_hwk_adapter_core3.createHwkError)({
636
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
637
+ message: `Keystone did not return the requested derivation path (${path})`
638
+ });
639
+ }
640
+ return account;
641
+ }
602
642
  function coinTypeFailure(chain, path) {
603
643
  if (hasChainCoinType(chain, path)) return void 0;
604
644
  return (0, import_hwk_adapter_core3.failure)(
@@ -606,6 +646,19 @@ function coinTypeFailure(chain, path) {
606
646
  `Keystone ${chain} needs a path with its own BIP44 coin type, not ${path}`
607
647
  );
608
648
  }
649
+ function btcAccountFailure(accountPath) {
650
+ if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
651
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
652
+ }
653
+ function missingParamFailure(method, param) {
654
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${method} requires ${param}`);
655
+ }
656
+ function messageToHex(message, hex) {
657
+ return hex ? exactHex(message) : Buffer.from(message, "utf8").toString("hex");
658
+ }
659
+ function evmMessageSignature(sig) {
660
+ return { signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) };
661
+ }
609
662
  var KeystoneAdapter = class _KeystoneAdapter {
610
663
  constructor(options) {
611
664
  this.vendor = "keystone";
@@ -620,6 +673,15 @@ var KeystoneAdapter = class _KeystoneAdapter {
620
673
  const route = this._operationRoutes.get(operation.connectId);
621
674
  if (route?.operationId === operation.operationId) {
622
675
  this._operationRoutes.delete(operation.connectId);
676
+ if (route.connectionType === "qr") {
677
+ const ended = (0, import_hwk_adapter_core3.createHwkError)({
678
+ code: import_hwk_adapter_core3.HardwareErrorCode.OperationEnded,
679
+ message: "Keystone operation has ended",
680
+ params: { operationId: operation.operationId, reason }
681
+ });
682
+ this._jobQueue.cancelActiveAndPending(operation.operationId, ended);
683
+ this._uiRegistry.cancel(void 0, void 0, operation.operationId);
684
+ }
623
685
  }
624
686
  this.emitter.emit(import_hwk_adapter_core3.SDK.OPERATION_ENDED, {
625
687
  type: import_hwk_adapter_core3.SDK.OPERATION_ENDED,
@@ -696,7 +758,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
696
758
  callItem: async ({ method, item, index }) => {
697
759
  if (scope.signal.aborted) {
698
760
  cancelledIndexes.add(index);
699
- return buildCancelledFailure(scope.signal);
761
+ return (0, import_hwk_adapter_core3.buildAllNetworkCancelledFailure)(scope.signal);
700
762
  }
701
763
  const commonArgs = {
702
764
  path: item.path,
@@ -718,11 +780,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
718
780
  return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
719
781
  case "tronGetAddress":
720
782
  return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
721
- default:
722
- return (0, import_hwk_adapter_core3.failure)(
723
- import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
724
- `Unsupported method: ${String(method)}`
725
- );
726
783
  }
727
784
  },
728
785
  attachIdentity: (context) => {
@@ -763,9 +820,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
763
820
  this._usbConnector?.on("device-disconnect", this._handleUsbDisconnect);
764
821
  this._usbConnector?.on("ui-event", this._handleUsbUiEvent);
765
822
  }
766
- // ---------------------------------------------------------------------------
767
- // Lifecycle / transport
768
- // ---------------------------------------------------------------------------
769
823
  get activeTransport() {
770
824
  if (this._devices.size === 0) return null;
771
825
  const hasUsbSession = Array.from(this._devices.values()).some((r) => r.usbSessionId);
@@ -795,9 +849,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
795
849
  this._devices.clear();
796
850
  this.emitter.removeAllListeners();
797
851
  }
798
- // ---------------------------------------------------------------------------
799
- // Device table
800
- // ---------------------------------------------------------------------------
801
852
  /**
802
853
  * Returns known wallets plus USB scan results; USB entries have no mfp until `connectDevice()`
803
854
  * claims them. Explicit QR discovery returns one virtual target.
@@ -870,11 +921,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
870
921
  }
871
922
  /** Best-effort disconnect; the session is retired either way so it cannot be selected again. */
872
923
  async _retireUsbSession(sessionId) {
873
- if (this._usbConnector) {
874
- try {
875
- await this._usbConnector.disconnect(sessionId);
876
- } catch {
877
- }
924
+ try {
925
+ await this._usbConnector?.disconnect(sessionId);
926
+ } catch {
878
927
  }
879
928
  this._handleUsbDisconnect({ connectId: sessionId });
880
929
  }
@@ -893,13 +942,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
893
942
  serialNumber: device.serialNumber
894
943
  }));
895
944
  }
896
- async listConnectionTargets(options) {
897
- const targets = await this.searchDeviceTargets(options);
898
- return targets.map(({ searchTargetId, ...target }) => ({
899
- ...target,
900
- targetId: searchTargetId
901
- }));
902
- }
903
945
  async connectDevice(searchTargetId) {
904
946
  const scope = this._jobQueue.createCancelScope(searchTargetId);
905
947
  try {
@@ -908,16 +950,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
908
950
  const discoveredConnectionType = this._searchDeviceTargets.get(searchTargetId);
909
951
  if (discoveredConnectionType === "qr") {
910
952
  selectedConnectionType = "qr";
911
- const abortColdStart = () => this._jobQueue.cancelActiveAndPending(
912
- KEYSTONE_COLD_START_JOB_LABEL,
913
- scope.signal.reason
953
+ connected = await _KeystoneAdapter._untilAborted(
954
+ scope.signal,
955
+ this._importFromQr({}, searchTargetId)
914
956
  );
915
- scope.signal.addEventListener("abort", abortColdStart, { once: true });
916
- try {
917
- connected = await this.importFromQr();
918
- } finally {
919
- scope.signal.removeEventListener("abort", abortColdStart);
920
- }
921
957
  } else if (discoveredConnectionType === "usb") {
922
958
  selectedConnectionType = "usb";
923
959
  if (!this._usbConnector) {
@@ -926,7 +962,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
926
962
  "No USB connector configured for this Keystone adapter"
927
963
  );
928
964
  }
929
- connected = await this._connectUsb({}, searchTargetId, scope.signal);
965
+ connected = await this._connectUsb(this._usbConnector, {}, searchTargetId, scope.signal);
930
966
  } else if ((0, import_hwk_adapter_core3.hasHardwareRuntimeIdPrefix)(searchTargetId)) {
931
967
  return (0, import_hwk_adapter_core3.failure)(
932
968
  import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
@@ -947,7 +983,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
947
983
  );
948
984
  } else {
949
985
  selectedConnectionType = "usb";
950
- connected = await this._connectUsb(target, void 0, scope.signal);
986
+ connected = await this._connectUsb(this._usbConnector, target, void 0, scope.signal);
951
987
  }
952
988
  }
953
989
  _KeystoneAdapter._throwIfAborted(scope.signal);
@@ -1006,10 +1042,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1006
1042
  const { record } = this._resolveTarget(connectId, deviceId);
1007
1043
  if (!record) {
1008
1044
  return Promise.resolve(
1009
- (0, import_hwk_adapter_core3.failure)(
1010
- import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
1011
- `Unknown Keystone device: ${connectId || deviceId}`
1012
- )
1045
+ (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound, "Unknown Keystone device")
1013
1046
  );
1014
1047
  }
1015
1048
  return Promise.resolve((0, import_hwk_adapter_core3.success)(toDeviceInfo(record)));
@@ -1085,18 +1118,21 @@ var KeystoneAdapter = class _KeystoneAdapter {
1085
1118
  // Explicit account import: call before signing to avoid a cold sync per call.
1086
1119
  // ---------------------------------------------------------------------------
1087
1120
  async importFromQr(options = {}) {
1121
+ return this._importFromQr(options, KEYSTONE_COLD_START_JOB_LABEL);
1122
+ }
1123
+ async _importFromQr(options, jobKey) {
1088
1124
  try {
1089
- return await this._jobQueue.enqueue(KEYSTONE_COLD_START_JOB_LABEL, async (signal) => {
1125
+ return await this._jobQueue.enqueue(jobKey, async (signal) => {
1090
1126
  const displayDevice = placeholderDeviceInfo();
1091
1127
  let responseUr;
1092
1128
  if (options.mode === "scan") {
1093
- responseUr = await this._requestQrScanAndAwaitResponse(displayDevice, signal);
1129
+ responseUr = await this._requestQrAndAwaitResponse(displayDevice, void 0, signal);
1094
1130
  } else {
1095
1131
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1096
1132
  schemas: [keySchema("evm", KEYSTONE_COLD_START_PATH)],
1097
1133
  origin: this._origin
1098
1134
  });
1099
- responseUr = await this._requestQrDisplayAndAwaitResponse(
1135
+ responseUr = await this._requestQrAndAwaitResponse(
1100
1136
  displayDevice,
1101
1137
  { ...requestUr, animated: false },
1102
1138
  signal
@@ -1104,6 +1140,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1104
1140
  }
1105
1141
  _KeystoneAdapter._throwIfAborted(signal);
1106
1142
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1143
+ if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1107
1144
  const record = this._upsertDeviceRecord(parsed);
1108
1145
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
1109
1146
  });
@@ -1111,163 +1148,103 @@ var KeystoneAdapter = class _KeystoneAdapter {
1111
1148
  return this._errorToFailure(err);
1112
1149
  }
1113
1150
  }
1114
- // ---------------------------------------------------------------------------
1115
- // EVM
1116
- // ---------------------------------------------------------------------------
1117
- async evmGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1118
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1119
- if (!operationTarget.success) return operationTarget;
1120
- const connectId = operationTarget.payload.targetId;
1121
- const deviceId = deviceIdArg ?? void 0;
1122
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmGetAddress requires params");
1123
- if (!params.path)
1124
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmGetAddress requires params.path");
1151
+ async evmGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1152
+ const call = this._beginCall("evmGetAddress", connectIdArg, deviceIdArg, paramsArg);
1153
+ if (!call.success) return call;
1154
+ const { params } = call.payload;
1155
+ if (!params.path) return missingParamFailure("evmGetAddress", "params.path");
1125
1156
  const evmCoinTypeFailure = coinTypeFailure("evm", params.path);
1126
1157
  if (evmCoinTypeFailure) return evmCoinTypeFailure;
1127
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1128
- if (!relativeDerivePath) {
1129
- return (0, import_hwk_adapter_core3.failure)(
1130
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1131
- "evmGetAddress requires a full leaf path, e.g. m/44'/60'/0'/0/0"
1132
- );
1133
- }
1134
- return this._runJob(connectId, deviceId, async (signal) => {
1135
- const xpub = await this._fetchAccountXpub(
1136
- connectId,
1137
- deviceId,
1138
- "evm",
1139
- accountPath,
1140
- signal,
1141
- bundle
1142
- );
1143
- const address = this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath);
1144
- return (0, import_hwk_adapter_core3.success)({ address, path: normalizePath(params.path) });
1145
- });
1158
+ return this._addressFromAccountXpub(
1159
+ "evmGetAddress",
1160
+ "evm",
1161
+ call.payload,
1162
+ params.path,
1163
+ "m/44'/60'/0'/0/0",
1164
+ bundle,
1165
+ (xpub, relativeDerivePath) => this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath)
1166
+ );
1146
1167
  }
1147
- async evmSignTransaction(connectIdArg, deviceIdArg, params) {
1148
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1149
- if (!operationTarget.success) return operationTarget;
1150
- const connectId = operationTarget.payload.targetId;
1151
- const deviceId = deviceIdArg ?? void 0;
1152
- if (!params)
1153
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTransaction requires params");
1154
- if (!params.path) {
1155
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTransaction requires params.path");
1156
- }
1168
+ async evmSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1169
+ const call = this._beginCall("evmSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1170
+ if (!call.success) return call;
1171
+ const { params } = call.payload;
1172
+ if (!params.path) return missingParamFailure("evmSignTransaction", "params.path");
1157
1173
  if (!("serializedTx" in params) || typeof params.serializedTx !== "string" || !params.serializedTx) {
1158
1174
  return (0, import_hwk_adapter_core3.failure)(
1159
1175
  import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1160
1176
  "Keystone only signs a fully RLP-serialized transaction (params.serializedTx) \u2014 structured-field signing is not supported"
1161
1177
  );
1162
1178
  }
1163
- const rawTxHex = (0, import_hwk_adapter_core3.stripHex)(params.serializedTx);
1164
- const path = normalizePath(params.path);
1179
+ const rawTxHex = exactHex(params.serializedTx);
1180
+ if (rawTxHex === void 0) return invalidHexFailure("serializedTx");
1165
1181
  const dataType = parseInt(rawTxHex.slice(0, 2), 16) < 192 ? "typedTransaction" : "transaction";
1166
- return this._signWithWallet({
1167
- connectId,
1168
- deviceId,
1169
- chain: "evm",
1170
- operationName: "evmSignTransaction",
1171
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1172
- requestId,
1173
- unsignedTxHex: rawTxHex,
1174
- dataType,
1175
- path,
1176
- xfp,
1177
- chainId: params.chainId,
1178
- origin: this._origin
1179
- }),
1180
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1181
- toPayload: (sig) => ({
1182
- v: (0, import_hwk_adapter_core3.ensure0x)(sig.v),
1183
- r: (0, import_hwk_adapter_core3.ensure0x)(sig.r),
1184
- s: (0, import_hwk_adapter_core3.ensure0x)(sig.s)
1185
- })
1186
- });
1182
+ return this._evmSign(
1183
+ "evmSignTransaction",
1184
+ call.payload,
1185
+ params.path,
1186
+ params.chainId,
1187
+ rawTxHex,
1188
+ dataType,
1189
+ (sig) => ({ v: (0, import_hwk_adapter_core3.ensure0x)(sig.v), r: (0, import_hwk_adapter_core3.ensure0x)(sig.r), s: (0, import_hwk_adapter_core3.ensure0x)(sig.s) })
1190
+ );
1187
1191
  }
1188
- async evmSignMessage(connectIdArg, deviceIdArg, params) {
1189
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1190
- if (!operationTarget.success) return operationTarget;
1191
- const connectId = operationTarget.payload.targetId;
1192
- const deviceId = deviceIdArg ?? void 0;
1193
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignMessage requires params");
1192
+ async evmSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1193
+ const call = this._beginCall("evmSignMessage", connectIdArg, deviceIdArg, paramsArg);
1194
+ if (!call.success) return call;
1195
+ const { params } = call.payload;
1194
1196
  if (!params.path || params.message === void 0) {
1195
- return (0, import_hwk_adapter_core3.failure)(
1196
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1197
- "evmSignMessage requires params.path and params.message"
1198
- );
1199
- }
1200
- const messageHex = params.hex ? (0, import_hwk_adapter_core3.stripHex)(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1201
- const path = normalizePath(params.path);
1202
- return this._signWithWallet({
1203
- connectId,
1204
- deviceId,
1205
- chain: "evm",
1206
- operationName: "evmSignMessage",
1207
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1208
- requestId,
1209
- unsignedTxHex: messageHex,
1210
- dataType: "personalMessage",
1211
- path,
1212
- xfp,
1213
- chainId: params.chainId,
1214
- origin: this._origin
1215
- }),
1216
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1217
- toPayload: (sig) => ({ signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) })
1218
- });
1197
+ return missingParamFailure("evmSignMessage", "params.path and params.message");
1198
+ }
1199
+ const messageHex = messageToHex(params.message, params.hex);
1200
+ if (messageHex === void 0) return invalidHexFailure("message");
1201
+ return this._evmSign(
1202
+ "evmSignMessage",
1203
+ call.payload,
1204
+ params.path,
1205
+ params.chainId,
1206
+ messageHex,
1207
+ "personalMessage",
1208
+ evmMessageSignature
1209
+ );
1219
1210
  }
1220
- async evmSignTypedData(connectIdArg, deviceIdArg, params) {
1221
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1222
- if (!operationTarget.success) return operationTarget;
1223
- const connectId = operationTarget.payload.targetId;
1224
- const deviceId = deviceIdArg ?? void 0;
1225
- if (!params)
1226
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTypedData requires params");
1227
- if (!params.path) {
1228
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTypedData requires params.path");
1229
- }
1211
+ async evmSignTypedData(connectIdArg, deviceIdArg, paramsArg) {
1212
+ const call = this._beginCall("evmSignTypedData", connectIdArg, deviceIdArg, paramsArg);
1213
+ if (!call.success) return call;
1214
+ const { params } = call.payload;
1215
+ if (!params.path) return missingParamFailure("evmSignTypedData", "params.path");
1230
1216
  if (params.mode === "hash") {
1231
1217
  return (0, import_hwk_adapter_core3.failure)(
1232
1218
  import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1233
1219
  "Keystone always displays the full EIP-712 payload for on-device review \u2014 pre-hashed signing is not supported"
1234
1220
  );
1235
1221
  }
1236
- const signDataHex = Buffer.from(
1237
- params.dataJson ?? JSON.stringify(params.data),
1238
- "utf8"
1239
- ).toString("hex");
1240
- const path = normalizePath(params.path);
1241
- return this._signWithWallet({
1242
- connectId,
1243
- deviceId,
1244
- chain: "evm",
1245
- operationName: "evmSignTypedData",
1246
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1247
- requestId,
1248
- unsignedTxHex: signDataHex,
1249
- dataType: "typedData",
1250
- path,
1251
- xfp,
1252
- chainId: params.chainId,
1253
- origin: this._origin
1254
- }),
1255
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1256
- toPayload: (sig) => ({ signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) })
1257
- });
1222
+ if (typeof params.dataJson !== "string" || !params.dataJson) {
1223
+ return (0, import_hwk_adapter_core3.failure)(
1224
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1225
+ "Keystone evmSignTypedData requires params.dataJson, the original typed-data JSON text"
1226
+ );
1227
+ }
1228
+ const signDataHex = Buffer.from(params.dataJson, "utf8").toString("hex");
1229
+ return this._evmSign(
1230
+ "evmSignTypedData",
1231
+ call.payload,
1232
+ params.path,
1233
+ params.chainId,
1234
+ signDataHex,
1235
+ "typedData",
1236
+ evmMessageSignature
1237
+ );
1258
1238
  }
1259
1239
  // ---------------------------------------------------------------------------
1260
1240
  // BTC: 44'/49'/84' addresses derive offline from the account xpub; P2TR addresses
1261
1241
  // and structured-field tx signing are unsupported (the host builds a PSBT instead).
1262
1242
  // ---------------------------------------------------------------------------
1263
- async btcGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1264
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1265
- if (!operationTarget.success) return operationTarget;
1266
- const connectId = operationTarget.payload.targetId;
1267
- const deviceId = deviceIdArg ?? void 0;
1268
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetAddress requires params");
1269
- if (!params.path)
1270
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetAddress requires params.path");
1243
+ async btcGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1244
+ const call = this._beginCall("btcGetAddress", connectIdArg, deviceIdArg, paramsArg);
1245
+ if (!call.success) return call;
1246
+ const { params } = call.payload;
1247
+ if (!params.path) return missingParamFailure("btcGetAddress", "params.path");
1271
1248
  const btcParamsFailure = keystoneBtcParamsFailure(params);
1272
1249
  if (btcParamsFailure) return btcParamsFailure;
1273
1250
  const scriptType = btcScriptTypeFromPath(params.path);
@@ -1283,42 +1260,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
1283
1260
  "P2TR (purpose 86') needs an elliptic-curve library for BIP-341 tweaking, not yet wired in \u2014 44'/49'/84' work"
1284
1261
  );
1285
1262
  }
1286
- const normalizedPath = normalizePath(params.path);
1287
- const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1288
- if (!relativeDerivePath) {
1289
- return (0, import_hwk_adapter_core3.failure)(
1290
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1291
- "btcGetAddress requires a full leaf path, e.g. m/84'/0'/0'/0/0"
1292
- );
1293
- }
1294
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1295
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1296
- }
1297
- return this._runJob(connectId, deviceId, async (signal) => {
1298
- const xpub = await this._fetchAccountXpub(
1299
- connectId,
1300
- deviceId,
1301
- "btc",
1302
- accountPath,
1303
- signal,
1304
- bundle
1305
- );
1306
- const address = this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType);
1307
- return (0, import_hwk_adapter_core3.success)({ address, path: normalizedPath });
1308
- });
1263
+ return this._addressFromAccountXpub(
1264
+ "btcGetAddress",
1265
+ "btc",
1266
+ call.payload,
1267
+ params.path,
1268
+ "m/84'/0'/0'/0/0",
1269
+ bundle,
1270
+ (xpub, relativeDerivePath) => this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType)
1271
+ );
1309
1272
  }
1310
1273
  /**
1311
1274
  * `params.path` must be an account path (`m/84'/0'/0'`), the level Keystone syncs. An xpub is
1312
1275
  * script-type agnostic, so `86'` works here even though `btcGetAddress` rejects it.
1313
1276
  */
1314
- async btcGetPublicKey(connectIdArg, deviceIdArg, params, bundle) {
1315
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1316
- if (!operationTarget.success) return operationTarget;
1317
- const connectId = operationTarget.payload.targetId;
1318
- const deviceId = deviceIdArg ?? void 0;
1319
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params");
1320
- if (!params.path)
1321
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params.path");
1277
+ async btcGetPublicKey(connectIdArg, deviceIdArg, paramsArg, bundle) {
1278
+ const call = this._beginCall("btcGetPublicKey", connectIdArg, deviceIdArg, paramsArg);
1279
+ if (!call.success) return call;
1280
+ const { connectId, deviceId, params } = call.payload;
1281
+ if (!params.path) return missingParamFailure("btcGetPublicKey", "params.path");
1322
1282
  const btcParamsFailure = keystoneBtcParamsFailure(params);
1323
1283
  if (btcParamsFailure) return btcParamsFailure;
1324
1284
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
@@ -1328,9 +1288,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1328
1288
  "btcGetPublicKey requires an account path, e.g. m/84'/0'/0' (not a leaf path)"
1329
1289
  );
1330
1290
  }
1331
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1332
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1333
- }
1291
+ const accountFailure = btcAccountFailure(accountPath);
1292
+ if (accountFailure) return accountFailure;
1334
1293
  return this._runJob(connectId, deviceId, async (signal) => {
1335
1294
  const xpub = await this._fetchAccountXpub(
1336
1295
  connectId,
@@ -1347,7 +1306,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1347
1306
  chainCode: meta.chainCode,
1348
1307
  depth: meta.depth,
1349
1308
  fingerprint: meta.parentFingerprint,
1350
- path: normalizePath(accountPath)
1309
+ path: normalizePath(accountPath),
1310
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1351
1311
  });
1352
1312
  });
1353
1313
  }
@@ -1357,23 +1317,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1357
1317
  "use btcSignPsbt \u2014 structured input/output signing needs host-side PSBT construction, not yet wired in"
1358
1318
  );
1359
1319
  }
1360
- async btcSignPsbt(connectIdArg, deviceIdArg, params) {
1361
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1362
- if (!operationTarget.success) return operationTarget;
1363
- const connectId = operationTarget.payload.targetId;
1364
- const deviceId = deviceIdArg ?? void 0;
1365
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignPsbt requires params");
1366
- if (!params.psbt)
1367
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.psbt");
1368
- if (!params.path)
1369
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.path");
1370
- if (!isKeystoneSignableBtcAccountPath(splitAccountPath(params.path).accountPath)) {
1371
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1372
- }
1320
+ async btcSignPsbt(connectIdArg, deviceIdArg, paramsArg) {
1321
+ const call = this._beginCall("btcSignPsbt", connectIdArg, deviceIdArg, paramsArg);
1322
+ if (!call.success) return call;
1323
+ const { connectId, deviceId, params } = call.payload;
1324
+ if (!params.psbt) return missingParamFailure("btcSignPsbt", "params.psbt");
1325
+ if (!params.path) return missingParamFailure("btcSignPsbt", "params.path");
1326
+ const accountFailure = btcAccountFailure(splitAccountPath(params.path).accountPath);
1327
+ if (accountFailure) return accountFailure;
1328
+ const requestPsbtHex = exactHex(params.psbt);
1329
+ if (requestPsbtHex === void 0) return invalidHexFailure("psbt");
1373
1330
  return this._runJob(connectId, deviceId, async (signal) => {
1374
1331
  const { record } = await this._ensureWalletKnown(connectId, deviceId, "btc", signal);
1375
1332
  _KeystoneAdapter._throwIfAborted(signal);
1376
- const requestUr = this.urEngine.buildBtcPsbtRequest((0, import_hwk_adapter_core3.stripHex)(params.psbt));
1333
+ const requestUr = this.urEngine.buildBtcPsbtRequest(requestPsbtHex);
1377
1334
  const responseUr = await this._resolveUr(
1378
1335
  record,
1379
1336
  requestUr,
@@ -1383,30 +1340,26 @@ var KeystoneAdapter = class _KeystoneAdapter {
1383
1340
  "btcSignPsbt"
1384
1341
  );
1385
1342
  _KeystoneAdapter._throwIfAborted(signal);
1386
- const signedPsbt = this.urEngine.parseBtcPsbt(responseUr);
1343
+ const signedPsbt = this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex);
1387
1344
  return (0, import_hwk_adapter_core3.success)({ signedPsbt });
1388
1345
  });
1389
1346
  }
1390
- async btcSignMessage(connectIdArg, deviceIdArg, params) {
1391
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1392
- if (!operationTarget.success) return operationTarget;
1393
- const connectId = operationTarget.payload.targetId;
1394
- const deviceId = deviceIdArg ?? void 0;
1395
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignMessage requires params");
1347
+ async btcSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1348
+ const call = this._beginCall("btcSignMessage", connectIdArg, deviceIdArg, paramsArg);
1349
+ if (!call.success) return call;
1350
+ const { connectId, deviceId, params } = call.payload;
1396
1351
  if (!params.path || params.message === void 0) {
1397
- return (0, import_hwk_adapter_core3.failure)(
1398
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1399
- "btcSignMessage requires params.path and params.message"
1400
- );
1352
+ return missingParamFailure("btcSignMessage", "params.path and params.message");
1401
1353
  }
1402
- const messageHex = params.hex ? (0, import_hwk_adapter_core3.stripHex)(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1354
+ const messageHex = messageToHex(params.message, params.hex);
1355
+ if (messageHex === void 0) return invalidHexFailure("message");
1403
1356
  const path = normalizePath(params.path);
1404
- if (!isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1405
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1406
- }
1357
+ const accountFailure = btcAccountFailure(splitAccountPath(path).accountPath);
1358
+ if (accountFailure) return accountFailure;
1407
1359
  return this._signWithWallet({
1408
1360
  connectId,
1409
1361
  deviceId,
1362
+ path,
1410
1363
  chain: "btc",
1411
1364
  operationName: "btcSignMessage",
1412
1365
  buildRequest: (requestId, xfp) => this.urEngine.buildBtcMessageSignRequest({
@@ -1434,17 +1387,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1434
1387
  return (0, import_hwk_adapter_core3.success)({ masterFingerprint: record.masterFingerprint });
1435
1388
  });
1436
1389
  }
1437
- // ---------------------------------------------------------------------------
1438
- // SOL
1439
- // ---------------------------------------------------------------------------
1440
- async solGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1441
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1442
- if (!operationTarget.success) return operationTarget;
1443
- const connectId = operationTarget.payload.targetId;
1444
- const deviceId = deviceIdArg ?? void 0;
1445
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solGetAddress requires params");
1446
- if (!params.path)
1447
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solGetAddress requires params.path");
1390
+ async solGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1391
+ const call = this._beginCall("solGetAddress", connectIdArg, deviceIdArg, paramsArg);
1392
+ if (!call.success) return call;
1393
+ const { connectId, deviceId, params } = call.payload;
1394
+ if (!params.path) return missingParamFailure("solGetAddress", "params.path");
1448
1395
  const solCoinTypeFailure = coinTypeFailure("sol", params.path);
1449
1396
  if (solCoinTypeFailure) return solCoinTypeFailure;
1450
1397
  const path = normalizePath(params.path);
@@ -1464,180 +1411,218 @@ var KeystoneAdapter = class _KeystoneAdapter {
1464
1411
  bundle
1465
1412
  );
1466
1413
  _KeystoneAdapter._throwIfAborted(signal);
1414
+ if (!/^[0-9a-f]{64}$/i.test(account.publicKey)) {
1415
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1416
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1417
+ message: "Keystone returned a Solana key that is not a 32-byte Ed25519 public key"
1418
+ });
1419
+ }
1467
1420
  const address = import_bs58.default.encode(Buffer.from(account.publicKey, "hex"));
1468
- return (0, import_hwk_adapter_core3.success)({ address, path });
1421
+ return (0, import_hwk_adapter_core3.success)({
1422
+ address,
1423
+ path,
1424
+ accountKey: { path, publicKey: account.publicKey }
1425
+ });
1469
1426
  });
1470
1427
  }
1471
- async solSignTransaction(connectIdArg, deviceIdArg, params) {
1472
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1473
- if (!operationTarget.success) return operationTarget;
1474
- const connectId = operationTarget.payload.targetId;
1475
- const deviceId = deviceIdArg ?? void 0;
1476
- if (!params)
1477
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solSignTransaction requires params");
1428
+ async solSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1429
+ const call = this._beginCall("solSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1430
+ if (!call.success) return call;
1431
+ const { params } = call.payload;
1478
1432
  if (!params.path || !params.serializedTx) {
1479
- return (0, import_hwk_adapter_core3.failure)(
1480
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1481
- "solSignTransaction requires params.path and params.serializedTx"
1482
- );
1483
- }
1484
- const path = normalizePath(params.path);
1485
- return this._signWithWallet({
1486
- connectId,
1487
- deviceId,
1488
- chain: "sol",
1489
- operationName: "solSignTransaction",
1490
- buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1491
- requestId,
1492
- unsignedPayloadHex: (0, import_hwk_adapter_core3.stripHex)(params.serializedTx),
1493
- dataType: "transaction",
1494
- path,
1495
- xfp,
1496
- origin: this._origin
1497
- }),
1498
- parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1499
- toPayload: (sig) => ({ signature: sig.signature })
1500
- });
1433
+ return missingParamFailure("solSignTransaction", "params.path and params.serializedTx");
1434
+ }
1435
+ const unsignedPayloadHex = exactHex(params.serializedTx);
1436
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("serializedTx");
1437
+ return this._solSign(
1438
+ "solSignTransaction",
1439
+ call.payload,
1440
+ params.path,
1441
+ unsignedPayloadHex,
1442
+ "transaction"
1443
+ );
1501
1444
  }
1502
- async solSignMessage(connectIdArg, deviceIdArg, params) {
1503
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1504
- if (!operationTarget.success) return operationTarget;
1505
- const connectId = operationTarget.payload.targetId;
1506
- const deviceId = deviceIdArg ?? void 0;
1507
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solSignMessage requires params");
1445
+ async solSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1446
+ const call = this._beginCall("solSignMessage", connectIdArg, deviceIdArg, paramsArg);
1447
+ if (!call.success) return call;
1448
+ const { params } = call.payload;
1508
1449
  if (!params.path || !params.message) {
1450
+ return missingParamFailure("solSignMessage", "params.path and params.message");
1451
+ }
1452
+ if (params.messageVersion !== void 0) {
1509
1453
  return (0, import_hwk_adapter_core3.failure)(
1510
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1511
- "solSignMessage requires params.path and params.message"
1454
+ import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1455
+ "Keystone signs Solana messages as raw bytes only; off-chain message format is not supported"
1512
1456
  );
1513
1457
  }
1514
- const path = normalizePath(params.path);
1515
- return this._signWithWallet({
1516
- connectId,
1517
- deviceId,
1518
- chain: "sol",
1519
- operationName: "solSignMessage",
1520
- buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1521
- requestId,
1522
- unsignedPayloadHex: (0, import_hwk_adapter_core3.stripHex)(params.message),
1523
- dataType: "message",
1524
- path,
1525
- xfp,
1526
- origin: this._origin
1527
- }),
1528
- parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1529
- toPayload: (sig) => ({ signature: sig.signature })
1530
- });
1458
+ const unsignedPayloadHex = exactHex(params.message);
1459
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("message");
1460
+ return this._solSign(
1461
+ "solSignMessage",
1462
+ call.payload,
1463
+ params.path,
1464
+ unsignedPayloadHex,
1465
+ "message"
1466
+ );
1531
1467
  }
1532
1468
  // ---------------------------------------------------------------------------
1533
1469
  // TRON: keystone-sdk-rust layout (tags 5201/5202, firmware >= 2.5.0), not sdk.tron's
1534
1470
  // protobuf module; OneKey Pro's encoding under the same tag is rejected by the firmware.
1535
1471
  // ---------------------------------------------------------------------------
1536
- async tronGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1537
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1538
- if (!operationTarget.success) return operationTarget;
1539
- const connectId = operationTarget.payload.targetId;
1540
- const deviceId = deviceIdArg ?? void 0;
1541
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronGetAddress requires params");
1542
- if (!params.path)
1543
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronGetAddress requires params.path");
1472
+ async tronGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1473
+ const call = this._beginCall("tronGetAddress", connectIdArg, deviceIdArg, paramsArg);
1474
+ if (!call.success) return call;
1475
+ const { params } = call.payload;
1476
+ if (!params.path) return missingParamFailure("tronGetAddress", "params.path");
1544
1477
  const tronCoinTypeFailure = coinTypeFailure("tron", params.path);
1545
1478
  if (tronCoinTypeFailure) return tronCoinTypeFailure;
1546
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1479
+ return this._addressFromAccountXpub(
1480
+ "tronGetAddress",
1481
+ "tron",
1482
+ call.payload,
1483
+ params.path,
1484
+ "m/44'/195'/0'/0/0",
1485
+ bundle,
1486
+ (xpub, relativeDerivePath) => this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath)
1487
+ );
1488
+ }
1489
+ async tronSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1490
+ const call = this._beginCall("tronSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1491
+ if (!call.success) return call;
1492
+ const { params } = call.payload;
1493
+ if (!params.path) return missingParamFailure("tronSignTransaction", "params.path");
1494
+ if (!params.rawTxHex) {
1495
+ return (0, import_hwk_adapter_core3.failure)(
1496
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1497
+ "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1498
+ );
1499
+ }
1500
+ const rawTxHex = exactHex(params.rawTxHex);
1501
+ if (rawTxHex === void 0) return invalidHexFailure("rawTxHex");
1502
+ return this._tronSign("tronSignTransaction", call.payload, params.path, rawTxHex);
1503
+ }
1504
+ async tronSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1505
+ const call = this._beginCall("tronSignMessage", connectIdArg, deviceIdArg, paramsArg);
1506
+ if (!call.success) return call;
1507
+ const { params } = call.payload;
1508
+ if (!params.path) return missingParamFailure("tronSignMessage", "params.path");
1509
+ if (!params.messageHex) return missingParamFailure("tronSignMessage", "params.messageHex");
1510
+ if (params.messageType !== "V2") {
1511
+ return (0, import_hwk_adapter_core3.failure)(
1512
+ import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1513
+ 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1514
+ );
1515
+ }
1516
+ const messageHex = exactHex(params.messageHex);
1517
+ if (messageHex === void 0) return invalidHexFailure("messageHex");
1518
+ return this._tronSign(
1519
+ "tronSignMessage",
1520
+ call.payload,
1521
+ params.path,
1522
+ messageHex,
1523
+ 2 /* PersonalMessage */
1524
+ );
1525
+ }
1526
+ /** Resolves the call's target and requires params, before any method-specific check. */
1527
+ _beginCall(method, connectIdArg, deviceIdArg, params) {
1528
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1529
+ if (!operationTarget.success) return operationTarget;
1530
+ if (!params) return missingParamFailure(method, "params");
1531
+ return (0, import_hwk_adapter_core3.success)({
1532
+ connectId: operationTarget.payload.targetId,
1533
+ deviceId: deviceIdArg ?? void 0,
1534
+ params
1535
+ });
1536
+ }
1537
+ /** Derives a leaf address offline from its account xpub. */
1538
+ async _addressFromAccountXpub(method, chain, { connectId, deviceId }, path, leafExample, bundle, derive) {
1539
+ const normalizedPath = normalizePath(path);
1540
+ const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1547
1541
  if (!relativeDerivePath) {
1548
1542
  return (0, import_hwk_adapter_core3.failure)(
1549
1543
  import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1550
- "tronGetAddress requires a full leaf path, e.g. m/44'/195'/0'/0/0"
1544
+ `${method} requires a full leaf path, e.g. ${leafExample}`
1551
1545
  );
1552
1546
  }
1547
+ const accountFailure = chain === "btc" ? btcAccountFailure(accountPath) : void 0;
1548
+ if (accountFailure) return accountFailure;
1553
1549
  return this._runJob(connectId, deviceId, async (signal) => {
1554
1550
  const xpub = await this._fetchAccountXpub(
1555
1551
  connectId,
1556
1552
  deviceId,
1557
- "tron",
1553
+ chain,
1558
1554
  accountPath,
1559
1555
  signal,
1560
1556
  bundle
1561
1557
  );
1562
- const address = this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath);
1563
- return (0, import_hwk_adapter_core3.success)({ address, path: normalizePath(params.path) });
1558
+ return (0, import_hwk_adapter_core3.success)({
1559
+ address: derive(xpub, relativeDerivePath),
1560
+ path: normalizedPath,
1561
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1562
+ });
1564
1563
  });
1565
1564
  }
1566
- async tronSignTransaction(connectIdArg, deviceIdArg, params) {
1567
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1568
- if (!operationTarget.success) return operationTarget;
1569
- const connectId = operationTarget.payload.targetId;
1570
- const deviceId = deviceIdArg ?? void 0;
1571
- if (!params)
1572
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignTransaction requires params");
1573
- if (!params.path) {
1574
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignTransaction requires params.path");
1575
- }
1576
- if (!params.rawTxHex) {
1577
- return (0, import_hwk_adapter_core3.failure)(
1578
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1579
- "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1580
- );
1581
- }
1582
- const rawTxHex = (0, import_hwk_adapter_core3.stripHex)(params.rawTxHex);
1583
- const path = normalizePath(params.path);
1565
+ _evmSign(method, target, rawPath, chainId, signDataHex, dataType, toPayload) {
1566
+ const path = normalizePath(rawPath);
1584
1567
  return this._signWithWallet({
1585
- connectId,
1586
- deviceId,
1587
- chain: "tron",
1588
- operationName: "tronSignTransaction",
1589
- buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1568
+ connectId: target.connectId,
1569
+ deviceId: target.deviceId,
1570
+ path,
1571
+ chain: "evm",
1572
+ operationName: method,
1573
+ buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1574
+ requestId,
1575
+ unsignedTxHex: signDataHex,
1576
+ dataType,
1577
+ path,
1578
+ xfp,
1579
+ chainId,
1580
+ origin: this._origin
1581
+ }),
1582
+ parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1583
+ toPayload
1584
+ });
1585
+ }
1586
+ _solSign(method, target, rawPath, unsignedPayloadHex, dataType) {
1587
+ const path = normalizePath(rawPath);
1588
+ return this._signWithWallet({
1589
+ connectId: target.connectId,
1590
+ deviceId: target.deviceId,
1591
+ path,
1592
+ chain: "sol",
1593
+ operationName: method,
1594
+ buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1590
1595
  requestId,
1591
- rawTxHex,
1596
+ unsignedPayloadHex,
1597
+ dataType,
1592
1598
  path,
1593
1599
  xfp,
1594
1600
  origin: this._origin
1595
1601
  }),
1596
- parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1597
- // Keystone signs rawTxHex as given and returns only the signature, so no serializedTx.
1602
+ parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1598
1603
  toPayload: (sig) => ({ signature: sig.signature })
1599
1604
  });
1600
1605
  }
1601
- async tronSignMessage(connectIdArg, deviceIdArg, params) {
1602
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1603
- if (!operationTarget.success) return operationTarget;
1604
- const connectId = operationTarget.payload.targetId;
1605
- const deviceId = deviceIdArg ?? void 0;
1606
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignMessage requires params");
1607
- if (!params.path) {
1608
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignMessage requires params.path");
1609
- }
1610
- if (!params.messageHex) {
1611
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignMessage requires params.messageHex");
1612
- }
1613
- if (params.messageType !== "V2") {
1614
- return (0, import_hwk_adapter_core3.failure)(
1615
- import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1616
- 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1617
- );
1618
- }
1619
- const messageHex = (0, import_hwk_adapter_core3.stripHex)(params.messageHex);
1620
- const path = normalizePath(params.path);
1606
+ _tronSign(method, target, rawPath, signDataHex, signType) {
1607
+ const path = normalizePath(rawPath);
1621
1608
  return this._signWithWallet({
1622
- connectId,
1623
- deviceId,
1609
+ connectId: target.connectId,
1610
+ deviceId: target.deviceId,
1611
+ path,
1624
1612
  chain: "tron",
1625
- operationName: "tronSignMessage",
1613
+ operationName: method,
1626
1614
  buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1627
1615
  requestId,
1628
- rawTxHex: messageHex,
1616
+ rawTxHex: signDataHex,
1629
1617
  path,
1630
1618
  xfp,
1631
- signType: 2 /* PersonalMessage */,
1619
+ signType,
1632
1620
  origin: this._origin
1633
1621
  }),
1634
1622
  parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1635
1623
  toPayload: (sig) => ({ signature: sig.signature })
1636
1624
  });
1637
1625
  }
1638
- // ---------------------------------------------------------------------------
1639
- // Internals
1640
- // ---------------------------------------------------------------------------
1641
1626
  async _runJob(connectId, deviceId, job) {
1642
1627
  try {
1643
1628
  return await this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), job);
@@ -1661,14 +1646,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
1661
1646
  message: "Keystone did not return an extended public key for this account path"
1662
1647
  });
1663
1648
  }
1649
+ const { publicKey } = this.urEngine.parseXpubMeta(account.extendedPublicKey);
1650
+ if (!/^0[23]/.test(publicKey)) {
1651
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1652
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1653
+ message: "Keystone returned an account key that is not a public key"
1654
+ });
1655
+ }
1664
1656
  return account.extendedPublicKey;
1665
1657
  }
1658
+ /** The exported key behind an address, reduced to the fields that identify it. */
1659
+ _exportedAccountKey(accountPath, xpub) {
1660
+ const { publicKey, chainCode } = this.urEngine.parseXpubMeta(xpub);
1661
+ return { path: normalizePath(accountPath), publicKey, chainCode, xpub };
1662
+ }
1666
1663
  /**
1667
1664
  * Signing needs only the wallet's mfp: the device re-derives the key from path+xfp, so no
1668
1665
  * per-path account lookup happens here.
1669
1666
  */
1670
1667
  _signWithWallet(args) {
1671
1668
  const { connectId, deviceId } = args;
1669
+ if (!isBip32Path(args.path)) {
1670
+ return Promise.resolve(
1671
+ (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `Invalid derivation path (${args.path})`)
1672
+ );
1673
+ }
1674
+ const chainCoinTypeFailure = coinTypeFailure(args.chain, args.path);
1675
+ if (chainCoinTypeFailure) return Promise.resolve(chainCoinTypeFailure);
1672
1676
  return this._runJob(connectId, deviceId, async (signal) => {
1673
1677
  const { record } = await this._ensureWalletKnown(connectId, deviceId, args.chain, signal);
1674
1678
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1705,8 +1709,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1705
1709
  case "btcGetPublicKey":
1706
1710
  case "solGetAddress":
1707
1711
  return { hwkChain, path };
1708
- default:
1709
- return void 0;
1710
1712
  }
1711
1713
  }
1712
1714
  /**
@@ -1750,7 +1752,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1750
1752
  schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1751
1753
  origin: this._origin
1752
1754
  });
1753
- const responseUr = await this._requestQrDisplayAndAwaitResponse(
1755
+ const responseUr = await this._requestQrAndAwaitResponse(
1754
1756
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1755
1757
  { ...requestUr, animated: false },
1756
1758
  signal
@@ -1758,26 +1760,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
1758
1760
  _KeystoneAdapter._throwIfAborted(signal);
1759
1761
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1760
1762
  this._assertParsedIdentity(parsed, target);
1761
- record = this._upsertDeviceRecord(parsed);
1762
1763
  for (const schema of schemas) {
1763
- const account = parsed.accounts.find(
1764
- (returned) => normalizePath(returned.path) === schema.path
1765
- );
1766
- if (!account) {
1767
- throw (0, import_hwk_adapter_core3.createHwkError)({
1768
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1769
- message: `Keystone did not return the requested derivation path (${schema.path})`
1770
- });
1771
- }
1772
1764
  scanned.set(accountKey(schema.hwkChain, schema.path), {
1773
- ...account,
1765
+ ...requireExportedPath(parsed, schema.path),
1774
1766
  hwkChain: schema.hwkChain
1775
1767
  });
1776
1768
  }
1769
+ record = this._upsertDeviceRecord(parsed);
1777
1770
  return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1778
1771
  });
1779
1772
  }
1780
- /** Resolve the wallet's master fingerprint from the connectId and/or deviceId the caller passed. */
1781
1773
  /**
1782
1774
  * A positional wallet id and an operation id must name the same wallet: otherwise the call
1783
1775
  * would run on the operation's wallet while the caller files the result under the other one.
@@ -1832,7 +1824,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1832
1824
  if (expected.expectedMasterFingerprint && parsed.masterFingerprint !== expected.expectedMasterFingerprint) {
1833
1825
  throw (0, import_hwk_adapter_core3.createHwkError)({
1834
1826
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1835
- message: `Connected Keystone wallet (mfp ${parsed.masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1827
+ // The master fingerprint identifies the wallet; keep it out of messages that reach logs.
1828
+ message: "Connected Keystone wallet does not match the requested wallet"
1836
1829
  });
1837
1830
  }
1838
1831
  }
@@ -1862,7 +1855,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1862
1855
  * Opens a permitted USB Keystone and takes its mfp as the wallet identity. A known wallet gains
1863
1856
  * USB in place (`device-changed`); an unseen one becomes USB-only.
1864
1857
  */
1865
- async _connectUsb(expected, searchTargetId, signal) {
1858
+ async _connectUsb(connector, expected, searchTargetId, signal) {
1866
1859
  if (this._pendingUsbTeardowns > 0 || this._abandonedUsbConnects > 0) {
1867
1860
  return (0, import_hwk_adapter_core3.failure)(
1868
1861
  import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal,
@@ -1875,28 +1868,22 @@ var KeystoneAdapter = class _KeystoneAdapter {
1875
1868
  abandoned = true;
1876
1869
  this._abandonedUsbConnects += 1;
1877
1870
  };
1878
- signal?.addEventListener("abort", onAbort, { once: true });
1871
+ signal.addEventListener("abort", onAbort, { once: true });
1879
1872
  const pending = this._usbConnectTail.then(async () => {
1880
1873
  _KeystoneAdapter._throwIfAborted(signal);
1881
- return this._connectUsbExclusive(expected, searchTargetId, signal);
1874
+ return this._connectUsbExclusive(connector, expected, searchTargetId, signal);
1882
1875
  });
1883
1876
  const settled = pending.finally(() => {
1884
- signal?.removeEventListener("abort", onAbort);
1877
+ signal.removeEventListener("abort", onAbort);
1885
1878
  if (abandoned) this._abandonedUsbConnects -= 1;
1886
1879
  });
1887
1880
  this._usbConnectTail = settled.then(
1888
1881
  () => void 0,
1889
1882
  () => void 0
1890
1883
  );
1891
- return signal ? _KeystoneAdapter._abortable(signal, settled) : settled;
1884
+ return _KeystoneAdapter._abortable(signal, settled);
1892
1885
  }
1893
- async _connectUsbExclusive(expected, searchTargetId, signal) {
1894
- if (!this._usbConnector) {
1895
- return (0, import_hwk_adapter_core3.failure)(
1896
- import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
1897
- "No USB connector configured for this Keystone adapter"
1898
- );
1899
- }
1886
+ async _connectUsbExclusive(connector, expected, searchTargetId, signal) {
1900
1887
  let sessionId;
1901
1888
  try {
1902
1889
  let connectTarget = { type: "default" };
@@ -1908,7 +1895,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1908
1895
  deviceIdentity: expected.expectedMasterFingerprint
1909
1896
  };
1910
1897
  }
1911
- const connector = this._usbConnector;
1912
1898
  const session = await (connector.connectTarget ? connector.connectTarget(connectTarget) : connector.connect(searchTargetId ?? expected.expectedMasterFingerprint));
1913
1899
  sessionId = session.sessionId;
1914
1900
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1922,16 +1908,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1922
1908
  });
1923
1909
  }
1924
1910
  const masterFingerprint = mfpValue.toLowerCase();
1925
- if (expected.expectedMasterFingerprint && masterFingerprint !== expected.expectedMasterFingerprint) {
1926
- throw (0, import_hwk_adapter_core3.createHwkError)({
1927
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1928
- message: `Connected Keystone wallet (mfp ${masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1929
- });
1930
- }
1911
+ this._assertParsedIdentity({ masterFingerprint, accounts: [] }, expected);
1931
1912
  const previousUsbSessionId = this._devices.get(masterFingerprint)?.usbSessionId;
1932
1913
  if (previousUsbSessionId && previousUsbSessionId !== session.sessionId) {
1933
1914
  try {
1934
- await this._usbConnector.disconnect(previousUsbSessionId);
1915
+ await connector.disconnect(previousUsbSessionId);
1935
1916
  } catch {
1936
1917
  }
1937
1918
  }
@@ -1951,7 +1932,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1951
1932
  } catch (err) {
1952
1933
  if (sessionId) {
1953
1934
  try {
1954
- await this._usbConnector.disconnect(sessionId);
1935
+ await connector.disconnect(sessionId);
1955
1936
  } catch {
1956
1937
  }
1957
1938
  }
@@ -1997,9 +1978,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1997
1978
  }
1998
1979
  return void 0;
1999
1980
  }
2000
- const attached = await this._connectUsb({ expectedMasterFingerprint }, void 0, signal);
1981
+ const attached = await this._connectUsb(
1982
+ this._usbConnector,
1983
+ { expectedMasterFingerprint },
1984
+ void 0,
1985
+ signal
1986
+ );
2001
1987
  _KeystoneAdapter._throwIfAborted(signal);
2002
- if (!attached.success && attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal) {
1988
+ if (!attached.success && (attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal || attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceOneDeviceOnly)) {
2003
1989
  throw (0, import_hwk_adapter_core3.createHwkError)({
2004
1990
  ...attached.payload,
2005
1991
  message: attached.payload.error
@@ -2059,9 +2045,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2059
2045
  message: "USB channel is not connected for this Keystone wallet"
2060
2046
  });
2061
2047
  }
2062
- const result = await this._callUsbConnector(
2048
+ const result = await this._callUsbResolveUr(
2049
+ this._usbConnector,
2063
2050
  record.usbSessionId,
2064
- "resolveUr",
2065
2051
  requestUr,
2066
2052
  signal
2067
2053
  );
@@ -2071,11 +2057,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2071
2057
  if (usbErrorCode === import_hwk_adapter_core3.HardwareErrorCode.PayloadTooLarge && usbErrorOrigin !== "device") {
2072
2058
  if (!interactionRoute && !this._forcedTransport) {
2073
2059
  const displayDevice2 = toDeviceInfo(record);
2074
- return this._requestQrDisplayAndAwaitResponse(
2075
- displayDevice2,
2076
- { ...requestUr, animated },
2077
- signal
2078
- );
2060
+ return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2079
2061
  }
2080
2062
  throw usbError;
2081
2063
  }
@@ -2086,6 +2068,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2086
2068
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2087
2069
  }
2088
2070
  record.usbSessionId = void 0;
2071
+ this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: toDeviceInfo(record) });
2089
2072
  if (interactionRoute) {
2090
2073
  throw this._endDisconnectedOperation(
2091
2074
  interactionRoute.operationId,
@@ -2103,11 +2086,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2103
2086
  });
2104
2087
  }
2105
2088
  }
2089
+ if (operationName && usbError.replyUnreadable === true) {
2090
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2091
+ code: usbErrorCode ?? import_hwk_adapter_core3.HardwareErrorCode.UnknownError,
2092
+ message: `Keystone ${operationName} may have completed but its reply could not be read`,
2093
+ origin: "device",
2094
+ recovery: { scope: "unknown" },
2095
+ params: (0, import_hwk_adapter_core3.operationMayHaveCompletedParams)(operationName)
2096
+ });
2097
+ }
2106
2098
  throw usbError;
2107
2099
  }
2108
2100
  const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
2109
2101
  try {
2110
- return await this._requestQrDisplayAndAwaitResponse(
2102
+ return await this._requestQrAndAwaitResponse(
2111
2103
  displayDevice,
2112
2104
  { ...requestUr, animated },
2113
2105
  signal
@@ -2171,6 +2163,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2171
2163
  const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2172
2164
  _KeystoneAdapter._throwIfAborted(signal);
2173
2165
  const parsed = this.urEngine.parseAccountResponse(responseUr);
2166
+ const account = requireExportedPath(parsed, syncPath);
2174
2167
  let record;
2175
2168
  if (useSinglePathUsbExport && existingRecord) {
2176
2169
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2186,13 +2179,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2186
2179
  viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2187
2180
  });
2188
2181
  }
2189
- const account = parsed.accounts.find((a) => normalizePath(a.path) === syncPath);
2190
- if (!account) {
2191
- throw (0, import_hwk_adapter_core3.createHwkError)({
2192
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2193
- message: `Keystone did not return the requested derivation path (${syncPath})`
2194
- });
2195
- }
2196
2182
  return { record, account: { ...account, hwkChain } };
2197
2183
  }
2198
2184
  /**
@@ -2215,7 +2201,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2215
2201
  });
2216
2202
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2217
2203
  _KeystoneAdapter._throwIfAborted(signal);
2218
- return { record: this._upsertDeviceRecord(this.urEngine.parseAccountResponse(responseUr)) };
2204
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
2205
+ requireExportedPath(parsed, normalizePath(accountPath));
2206
+ return { record: this._upsertDeviceRecord(parsed) };
2219
2207
  }
2220
2208
  /**
2221
2209
  * The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
@@ -2241,7 +2229,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2241
2229
  * a cancel reach the wait before the QR timeout.
2242
2230
  */
2243
2231
  async _awaitQrResponse(requestType, pending, signal) {
2244
- if (!signal) return pending;
2245
2232
  let settled = false;
2246
2233
  const onAbort = () => {
2247
2234
  if (!settled) this._uiRegistry.cancel(requestType);
@@ -2250,55 +2237,50 @@ var KeystoneAdapter = class _KeystoneAdapter {
2250
2237
  else signal.addEventListener("abort", onAbort, { once: true });
2251
2238
  try {
2252
2239
  return await pending;
2240
+ } catch (error) {
2241
+ const reason = signal.reason;
2242
+ if (signal.aborted && reason?.code === import_hwk_adapter_core3.HardwareErrorCode.OperationEnded) throw signal.reason;
2243
+ throw error;
2253
2244
  } finally {
2254
2245
  settled = true;
2255
2246
  signal.removeEventListener("abort", onAbort);
2256
2247
  }
2257
2248
  }
2258
- async _requestQrDisplayAndAwaitResponse(device, data, signal) {
2249
+ /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2250
+ async _requestQrAndAwaitResponse(device, data, signal) {
2251
+ const requestType = data ? import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY : import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN;
2259
2252
  const operationId = this._activeOperationId();
2260
- const waitPromise = this._uiRegistry.wait(
2261
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2262
- { timeoutMs: this._qrTimeoutMs, operationId }
2263
- );
2264
- this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY, {
2265
- type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2266
- payload: { device, data, operationId }
2267
- });
2268
- const response = await this._awaitQrResponse(
2269
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2270
- waitPromise,
2271
- signal
2272
- );
2273
- return { urType: response.urType, urData: response.urData };
2274
- }
2275
- async _requestQrScanAndAwaitResponse(device, signal) {
2276
- const operationId = this._activeOperationId();
2277
- const waitPromise = this._uiRegistry.wait(
2278
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN,
2279
- { timeoutMs: this._qrTimeoutMs, operationId }
2280
- );
2281
- this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN, {
2282
- type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN,
2283
- payload: { device, operationId }
2284
- });
2285
- const response = await this._awaitQrResponse(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN, waitPromise, signal);
2286
- return { urType: response.urType, urData: response.urData };
2287
- }
2288
- async _callUsbConnector(sessionId, method, params, signal) {
2289
- if (!this._usbConnector) {
2290
- throw (0, import_hwk_adapter_core3.createHwkError)({
2291
- code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
2292
- message: "No USB connector configured for this Keystone adapter"
2253
+ const release = operationId ? this._operations.retain(operationId) : void 0;
2254
+ try {
2255
+ const waitPromise = this._uiRegistry.wait(requestType, {
2256
+ timeoutMs: this._qrTimeoutMs,
2257
+ operationId
2293
2258
  });
2259
+ if (data) {
2260
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY, {
2261
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2262
+ payload: { device, data, operationId }
2263
+ });
2264
+ } else {
2265
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN, {
2266
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN,
2267
+ payload: { device, operationId }
2268
+ });
2269
+ }
2270
+ const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2271
+ return { urType: response.urType, urData: response.urData };
2272
+ } finally {
2273
+ release?.();
2294
2274
  }
2275
+ }
2276
+ async _callUsbResolveUr(connector, sessionId, requestUr, signal) {
2295
2277
  if (this._pendingUsbTeardowns > 0 || this._unsettledUsbOperations.size > 0) {
2296
2278
  throw (0, import_hwk_adapter_core3.createHwkError)({
2297
2279
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal,
2298
- message: `Keystone USB is busy while calling ${method}`
2280
+ message: "Keystone USB is busy while calling resolveUr"
2299
2281
  });
2300
2282
  }
2301
- if (signal?.aborted) {
2283
+ if (signal.aborted) {
2302
2284
  throw signal.reason instanceof Error ? signal.reason : (0, import_hwk_adapter_core3.createHwkError)({
2303
2285
  code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
2304
2286
  message: "User aborted operation"
@@ -2307,12 +2289,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2307
2289
  const releaseOperation = this._retainUsbOperation(`call:${sessionId}`);
2308
2290
  let rawCall;
2309
2291
  try {
2310
- rawCall = this._usbConnector.call(sessionId, method, params).finally(releaseOperation);
2292
+ rawCall = connector.call(sessionId, "resolveUr", requestUr).finally(releaseOperation);
2311
2293
  } catch (error) {
2312
2294
  releaseOperation();
2313
2295
  throw error;
2314
2296
  }
2315
- return signal ? _KeystoneAdapter._abortable(signal, rawCall) : rawCall;
2297
+ return _KeystoneAdapter._abortable(signal, rawCall);
2316
2298
  }
2317
2299
  _runUsbTeardown(task) {
2318
2300
  const previous = this._usbTeardownTail;
@@ -2374,6 +2356,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
2374
2356
  );
2375
2357
  });
2376
2358
  }
2359
+ /** Settles with `signal`'s reason once it aborts; a later outcome of `promise` is dropped. */
2360
+ static _untilAborted(signal, promise) {
2361
+ promise.catch(() => void 0);
2362
+ if (signal.aborted) return Promise.reject(signal.reason);
2363
+ return new Promise((resolve, reject) => {
2364
+ const onAbort = () => reject(signal.reason);
2365
+ signal.addEventListener("abort", onAbort, { once: true });
2366
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort)).catch(() => void 0);
2367
+ });
2368
+ }
2377
2369
  static _throwIfAborted(signal) {
2378
2370
  if (signal?.aborted) {
2379
2371
  throw signal.reason instanceof Error ? signal.reason : new Error("Operation aborted");