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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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,14 +468,26 @@ 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("/");
453
- if (segments.length <= 3) {
482
+ let accountLength = 0;
483
+ segments.forEach((segment, index) => {
484
+ if (segment.endsWith("'")) accountLength = index + 1;
485
+ });
486
+ if (segments.length <= 3 || accountLength === 0 || accountLength === segments.length) {
454
487
  return { accountPath: normalized, relativeDerivePath: "" };
455
488
  }
456
- const accountSegments = segments.slice(0, segments.length - 2);
457
- const relativeSegments = segments.slice(segments.length - 2);
489
+ const accountSegments = segments.slice(0, accountLength);
490
+ const relativeSegments = segments.slice(accountLength);
458
491
  return {
459
492
  accountPath: `m/${accountSegments.join("/")}`,
460
493
  relativeDerivePath: relativeSegments.join("/")
@@ -583,12 +616,6 @@ function waitForKeystoneUsbReattachProbe() {
583
616
  setTimeout(resolve, KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS);
584
617
  });
585
618
  }
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
619
  var BIP44_COIN_TYPE_TO_CHAIN = {
593
620
  60: "evm",
594
621
  0: "btc",
@@ -599,6 +626,23 @@ function hasChainCoinType(chain, path) {
599
626
  const match = normalizePath(path).match(/^m\/\d+'\/(\d+)'/);
600
627
  return Boolean(match) && BIP44_COIN_TYPE_TO_CHAIN[Number(match?.[1])] === chain;
601
628
  }
629
+ function exactHex(value) {
630
+ const hex = value.replace(/^0x/i, "");
631
+ return /^(?:[0-9a-f]{2})*$/i.test(hex) ? hex : void 0;
632
+ }
633
+ function invalidHexFailure(field) {
634
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${field} must be an even-length hex string`);
635
+ }
636
+ function requireExportedPath(parsed, path) {
637
+ const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
638
+ if (!account) {
639
+ throw (0, import_hwk_adapter_core3.createHwkError)({
640
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
641
+ message: `Keystone did not return the requested derivation path (${path})`
642
+ });
643
+ }
644
+ return account;
645
+ }
602
646
  function coinTypeFailure(chain, path) {
603
647
  if (hasChainCoinType(chain, path)) return void 0;
604
648
  return (0, import_hwk_adapter_core3.failure)(
@@ -606,6 +650,19 @@ function coinTypeFailure(chain, path) {
606
650
  `Keystone ${chain} needs a path with its own BIP44 coin type, not ${path}`
607
651
  );
608
652
  }
653
+ function btcAccountFailure(accountPath) {
654
+ if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
655
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
656
+ }
657
+ function missingParamFailure(method, param) {
658
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${method} requires ${param}`);
659
+ }
660
+ function messageToHex(message, hex) {
661
+ return hex ? exactHex(message) : Buffer.from(message, "utf8").toString("hex");
662
+ }
663
+ function evmMessageSignature(sig) {
664
+ return { signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) };
665
+ }
609
666
  var KeystoneAdapter = class _KeystoneAdapter {
610
667
  constructor(options) {
611
668
  this.vendor = "keystone";
@@ -620,6 +677,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
620
677
  const route = this._operationRoutes.get(operation.connectId);
621
678
  if (route?.operationId === operation.operationId) {
622
679
  this._operationRoutes.delete(operation.connectId);
680
+ if (route.connectionType === "qr") {
681
+ const ended = (0, import_hwk_adapter_core3.createHwkError)({
682
+ code: import_hwk_adapter_core3.HardwareErrorCode.OperationEnded,
683
+ message: "Keystone operation has ended",
684
+ params: { operationId: operation.operationId, reason }
685
+ });
686
+ const queueKey = keystoneQueueKey(operation.operationId);
687
+ const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
688
+ this._jobQueue.cancelActiveAndPending(queueKey, ended);
689
+ if (ownsRunningCall) {
690
+ this._uiRegistry.cancel(void 0, void 0, operation.operationId);
691
+ }
692
+ }
623
693
  }
624
694
  this.emitter.emit(import_hwk_adapter_core3.SDK.OPERATION_ENDED, {
625
695
  type: import_hwk_adapter_core3.SDK.OPERATION_ENDED,
@@ -696,7 +766,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
696
766
  callItem: async ({ method, item, index }) => {
697
767
  if (scope.signal.aborted) {
698
768
  cancelledIndexes.add(index);
699
- return buildCancelledFailure(scope.signal);
769
+ return (0, import_hwk_adapter_core3.buildAllNetworkCancelledFailure)(scope.signal);
700
770
  }
701
771
  const commonArgs = {
702
772
  path: item.path,
@@ -718,11 +788,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
718
788
  return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
719
789
  case "tronGetAddress":
720
790
  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
791
  }
727
792
  },
728
793
  attachIdentity: (context) => {
@@ -763,9 +828,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
763
828
  this._usbConnector?.on("device-disconnect", this._handleUsbDisconnect);
764
829
  this._usbConnector?.on("ui-event", this._handleUsbUiEvent);
765
830
  }
766
- // ---------------------------------------------------------------------------
767
- // Lifecycle / transport
768
- // ---------------------------------------------------------------------------
769
831
  get activeTransport() {
770
832
  if (this._devices.size === 0) return null;
771
833
  const hasUsbSession = Array.from(this._devices.values()).some((r) => r.usbSessionId);
@@ -795,9 +857,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
795
857
  this._devices.clear();
796
858
  this.emitter.removeAllListeners();
797
859
  }
798
- // ---------------------------------------------------------------------------
799
- // Device table
800
- // ---------------------------------------------------------------------------
801
860
  /**
802
861
  * Returns known wallets plus USB scan results; USB entries have no mfp until `connectDevice()`
803
862
  * claims them. Explicit QR discovery returns one virtual target.
@@ -870,11 +929,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
870
929
  }
871
930
  /** Best-effort disconnect; the session is retired either way so it cannot be selected again. */
872
931
  async _retireUsbSession(sessionId) {
873
- if (this._usbConnector) {
874
- try {
875
- await this._usbConnector.disconnect(sessionId);
876
- } catch {
877
- }
932
+ try {
933
+ await this._usbConnector?.disconnect(sessionId);
934
+ } catch {
878
935
  }
879
936
  this._handleUsbDisconnect({ connectId: sessionId });
880
937
  }
@@ -893,13 +950,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
893
950
  serialNumber: device.serialNumber
894
951
  }));
895
952
  }
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
953
  async connectDevice(searchTargetId) {
904
954
  const scope = this._jobQueue.createCancelScope(searchTargetId);
905
955
  try {
@@ -908,16 +958,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
908
958
  const discoveredConnectionType = this._searchDeviceTargets.get(searchTargetId);
909
959
  if (discoveredConnectionType === "qr") {
910
960
  selectedConnectionType = "qr";
911
- const abortColdStart = () => this._jobQueue.cancelActiveAndPending(
912
- KEYSTONE_COLD_START_JOB_LABEL,
913
- scope.signal.reason
961
+ connected = await _KeystoneAdapter._untilAborted(
962
+ scope.signal,
963
+ this._importFromQr({}, searchTargetId)
914
964
  );
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
965
  } else if (discoveredConnectionType === "usb") {
922
966
  selectedConnectionType = "usb";
923
967
  if (!this._usbConnector) {
@@ -926,7 +970,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
926
970
  "No USB connector configured for this Keystone adapter"
927
971
  );
928
972
  }
929
- connected = await this._connectUsb({}, searchTargetId, scope.signal);
973
+ connected = await this._connectUsb(this._usbConnector, {}, searchTargetId, scope.signal);
930
974
  } else if ((0, import_hwk_adapter_core3.hasHardwareRuntimeIdPrefix)(searchTargetId)) {
931
975
  return (0, import_hwk_adapter_core3.failure)(
932
976
  import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
@@ -947,7 +991,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
947
991
  );
948
992
  } else {
949
993
  selectedConnectionType = "usb";
950
- connected = await this._connectUsb(target, void 0, scope.signal);
994
+ connected = await this._connectUsb(this._usbConnector, target, void 0, scope.signal);
951
995
  }
952
996
  }
953
997
  _KeystoneAdapter._throwIfAborted(scope.signal);
@@ -1006,10 +1050,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1006
1050
  const { record } = this._resolveTarget(connectId, deviceId);
1007
1051
  if (!record) {
1008
1052
  return Promise.resolve(
1009
- (0, import_hwk_adapter_core3.failure)(
1010
- import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
1011
- `Unknown Keystone device: ${connectId || deviceId}`
1012
- )
1053
+ (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound, "Unknown Keystone device")
1013
1054
  );
1014
1055
  }
1015
1056
  return Promise.resolve((0, import_hwk_adapter_core3.success)(toDeviceInfo(record)));
@@ -1085,18 +1126,21 @@ var KeystoneAdapter = class _KeystoneAdapter {
1085
1126
  // Explicit account import: call before signing to avoid a cold sync per call.
1086
1127
  // ---------------------------------------------------------------------------
1087
1128
  async importFromQr(options = {}) {
1129
+ return this._importFromQr(options, KEYSTONE_COLD_START_JOB_LABEL);
1130
+ }
1131
+ async _importFromQr(options, jobKey) {
1088
1132
  try {
1089
- return await this._jobQueue.enqueue(KEYSTONE_COLD_START_JOB_LABEL, async (signal) => {
1133
+ return await this._jobQueue.enqueue(jobKey, async (signal) => {
1090
1134
  const displayDevice = placeholderDeviceInfo();
1091
1135
  let responseUr;
1092
1136
  if (options.mode === "scan") {
1093
- responseUr = await this._requestQrScanAndAwaitResponse(displayDevice, signal);
1137
+ responseUr = await this._requestQrAndAwaitResponse(displayDevice, void 0, signal);
1094
1138
  } else {
1095
1139
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1096
1140
  schemas: [keySchema("evm", KEYSTONE_COLD_START_PATH)],
1097
1141
  origin: this._origin
1098
1142
  });
1099
- responseUr = await this._requestQrDisplayAndAwaitResponse(
1143
+ responseUr = await this._requestQrAndAwaitResponse(
1100
1144
  displayDevice,
1101
1145
  { ...requestUr, animated: false },
1102
1146
  signal
@@ -1104,6 +1148,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1104
1148
  }
1105
1149
  _KeystoneAdapter._throwIfAborted(signal);
1106
1150
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1151
+ if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1107
1152
  const record = this._upsertDeviceRecord(parsed);
1108
1153
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
1109
1154
  });
@@ -1111,163 +1156,103 @@ var KeystoneAdapter = class _KeystoneAdapter {
1111
1156
  return this._errorToFailure(err);
1112
1157
  }
1113
1158
  }
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");
1159
+ async evmGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1160
+ const call = this._beginCall("evmGetAddress", connectIdArg, deviceIdArg, paramsArg);
1161
+ if (!call.success) return call;
1162
+ const { params } = call.payload;
1163
+ if (!params.path) return missingParamFailure("evmGetAddress", "params.path");
1125
1164
  const evmCoinTypeFailure = coinTypeFailure("evm", params.path);
1126
1165
  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
- });
1166
+ return this._addressFromAccountXpub(
1167
+ "evmGetAddress",
1168
+ "evm",
1169
+ call.payload,
1170
+ params.path,
1171
+ "m/44'/60'/0'/0/0",
1172
+ bundle,
1173
+ (xpub, relativeDerivePath) => this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath)
1174
+ );
1146
1175
  }
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
- }
1176
+ async evmSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1177
+ const call = this._beginCall("evmSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1178
+ if (!call.success) return call;
1179
+ const { params } = call.payload;
1180
+ if (!params.path) return missingParamFailure("evmSignTransaction", "params.path");
1157
1181
  if (!("serializedTx" in params) || typeof params.serializedTx !== "string" || !params.serializedTx) {
1158
1182
  return (0, import_hwk_adapter_core3.failure)(
1159
1183
  import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1160
1184
  "Keystone only signs a fully RLP-serialized transaction (params.serializedTx) \u2014 structured-field signing is not supported"
1161
1185
  );
1162
1186
  }
1163
- const rawTxHex = (0, import_hwk_adapter_core3.stripHex)(params.serializedTx);
1164
- const path = normalizePath(params.path);
1187
+ const rawTxHex = exactHex(params.serializedTx);
1188
+ if (rawTxHex === void 0) return invalidHexFailure("serializedTx");
1165
1189
  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
- });
1190
+ return this._evmSign(
1191
+ "evmSignTransaction",
1192
+ call.payload,
1193
+ params.path,
1194
+ params.chainId,
1195
+ rawTxHex,
1196
+ dataType,
1197
+ (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) })
1198
+ );
1187
1199
  }
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");
1200
+ async evmSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1201
+ const call = this._beginCall("evmSignMessage", connectIdArg, deviceIdArg, paramsArg);
1202
+ if (!call.success) return call;
1203
+ const { params } = call.payload;
1194
1204
  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
- });
1205
+ return missingParamFailure("evmSignMessage", "params.path and params.message");
1206
+ }
1207
+ const messageHex = messageToHex(params.message, params.hex);
1208
+ if (messageHex === void 0) return invalidHexFailure("message");
1209
+ return this._evmSign(
1210
+ "evmSignMessage",
1211
+ call.payload,
1212
+ params.path,
1213
+ params.chainId,
1214
+ messageHex,
1215
+ "personalMessage",
1216
+ evmMessageSignature
1217
+ );
1219
1218
  }
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
- }
1219
+ async evmSignTypedData(connectIdArg, deviceIdArg, paramsArg) {
1220
+ const call = this._beginCall("evmSignTypedData", connectIdArg, deviceIdArg, paramsArg);
1221
+ if (!call.success) return call;
1222
+ const { params } = call.payload;
1223
+ if (!params.path) return missingParamFailure("evmSignTypedData", "params.path");
1230
1224
  if (params.mode === "hash") {
1231
1225
  return (0, import_hwk_adapter_core3.failure)(
1232
1226
  import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1233
1227
  "Keystone always displays the full EIP-712 payload for on-device review \u2014 pre-hashed signing is not supported"
1234
1228
  );
1235
1229
  }
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
- });
1230
+ if (typeof params.dataJson !== "string" || !params.dataJson) {
1231
+ return (0, import_hwk_adapter_core3.failure)(
1232
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1233
+ "Keystone evmSignTypedData requires params.dataJson, the original typed-data JSON text"
1234
+ );
1235
+ }
1236
+ const signDataHex = Buffer.from(params.dataJson, "utf8").toString("hex");
1237
+ return this._evmSign(
1238
+ "evmSignTypedData",
1239
+ call.payload,
1240
+ params.path,
1241
+ params.chainId,
1242
+ signDataHex,
1243
+ "typedData",
1244
+ evmMessageSignature
1245
+ );
1258
1246
  }
1259
1247
  // ---------------------------------------------------------------------------
1260
1248
  // BTC: 44'/49'/84' addresses derive offline from the account xpub; P2TR addresses
1261
1249
  // and structured-field tx signing are unsupported (the host builds a PSBT instead).
1262
1250
  // ---------------------------------------------------------------------------
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");
1251
+ async btcGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1252
+ const call = this._beginCall("btcGetAddress", connectIdArg, deviceIdArg, paramsArg);
1253
+ if (!call.success) return call;
1254
+ const { params } = call.payload;
1255
+ if (!params.path) return missingParamFailure("btcGetAddress", "params.path");
1271
1256
  const btcParamsFailure = keystoneBtcParamsFailure(params);
1272
1257
  if (btcParamsFailure) return btcParamsFailure;
1273
1258
  const scriptType = btcScriptTypeFromPath(params.path);
@@ -1283,42 +1268,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
1283
1268
  "P2TR (purpose 86') needs an elliptic-curve library for BIP-341 tweaking, not yet wired in \u2014 44'/49'/84' work"
1284
1269
  );
1285
1270
  }
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
- });
1271
+ return this._addressFromAccountXpub(
1272
+ "btcGetAddress",
1273
+ "btc",
1274
+ call.payload,
1275
+ params.path,
1276
+ "m/84'/0'/0'/0/0",
1277
+ bundle,
1278
+ (xpub, relativeDerivePath) => this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType)
1279
+ );
1309
1280
  }
1310
1281
  /**
1311
1282
  * `params.path` must be an account path (`m/84'/0'/0'`), the level Keystone syncs. An xpub is
1312
1283
  * script-type agnostic, so `86'` works here even though `btcGetAddress` rejects it.
1313
1284
  */
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");
1285
+ async btcGetPublicKey(connectIdArg, deviceIdArg, paramsArg, bundle) {
1286
+ const call = this._beginCall("btcGetPublicKey", connectIdArg, deviceIdArg, paramsArg);
1287
+ if (!call.success) return call;
1288
+ const { connectId, deviceId, params } = call.payload;
1289
+ if (!params.path) return missingParamFailure("btcGetPublicKey", "params.path");
1322
1290
  const btcParamsFailure = keystoneBtcParamsFailure(params);
1323
1291
  if (btcParamsFailure) return btcParamsFailure;
1324
1292
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
@@ -1328,9 +1296,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1328
1296
  "btcGetPublicKey requires an account path, e.g. m/84'/0'/0' (not a leaf path)"
1329
1297
  );
1330
1298
  }
1331
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1332
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1333
- }
1299
+ const accountFailure = btcAccountFailure(accountPath);
1300
+ if (accountFailure) return accountFailure;
1334
1301
  return this._runJob(connectId, deviceId, async (signal) => {
1335
1302
  const xpub = await this._fetchAccountXpub(
1336
1303
  connectId,
@@ -1347,7 +1314,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1347
1314
  chainCode: meta.chainCode,
1348
1315
  depth: meta.depth,
1349
1316
  fingerprint: meta.parentFingerprint,
1350
- path: normalizePath(accountPath)
1317
+ path: normalizePath(accountPath),
1318
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1351
1319
  });
1352
1320
  });
1353
1321
  }
@@ -1357,23 +1325,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1357
1325
  "use btcSignPsbt \u2014 structured input/output signing needs host-side PSBT construction, not yet wired in"
1358
1326
  );
1359
1327
  }
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
- }
1328
+ async btcSignPsbt(connectIdArg, deviceIdArg, paramsArg) {
1329
+ const call = this._beginCall("btcSignPsbt", connectIdArg, deviceIdArg, paramsArg);
1330
+ if (!call.success) return call;
1331
+ const { connectId, deviceId, params } = call.payload;
1332
+ if (!params.psbt) return missingParamFailure("btcSignPsbt", "params.psbt");
1333
+ if (!params.path) return missingParamFailure("btcSignPsbt", "params.path");
1334
+ const accountFailure = btcAccountFailure(splitAccountPath(params.path).accountPath);
1335
+ if (accountFailure) return accountFailure;
1336
+ const requestPsbtHex = exactHex(params.psbt);
1337
+ if (requestPsbtHex === void 0) return invalidHexFailure("psbt");
1373
1338
  return this._runJob(connectId, deviceId, async (signal) => {
1374
1339
  const { record } = await this._ensureWalletKnown(connectId, deviceId, "btc", signal);
1375
1340
  _KeystoneAdapter._throwIfAborted(signal);
1376
- const requestUr = this.urEngine.buildBtcPsbtRequest((0, import_hwk_adapter_core3.stripHex)(params.psbt));
1341
+ const requestUr = this.urEngine.buildBtcPsbtRequest(requestPsbtHex);
1377
1342
  const responseUr = await this._resolveUr(
1378
1343
  record,
1379
1344
  requestUr,
@@ -1383,30 +1348,26 @@ var KeystoneAdapter = class _KeystoneAdapter {
1383
1348
  "btcSignPsbt"
1384
1349
  );
1385
1350
  _KeystoneAdapter._throwIfAborted(signal);
1386
- const signedPsbt = this.urEngine.parseBtcPsbt(responseUr);
1351
+ const signedPsbt = this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex);
1387
1352
  return (0, import_hwk_adapter_core3.success)({ signedPsbt });
1388
1353
  });
1389
1354
  }
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");
1355
+ async btcSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1356
+ const call = this._beginCall("btcSignMessage", connectIdArg, deviceIdArg, paramsArg);
1357
+ if (!call.success) return call;
1358
+ const { connectId, deviceId, params } = call.payload;
1396
1359
  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
- );
1360
+ return missingParamFailure("btcSignMessage", "params.path and params.message");
1401
1361
  }
1402
- const messageHex = params.hex ? (0, import_hwk_adapter_core3.stripHex)(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1362
+ const messageHex = messageToHex(params.message, params.hex);
1363
+ if (messageHex === void 0) return invalidHexFailure("message");
1403
1364
  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
- }
1365
+ const accountFailure = btcAccountFailure(splitAccountPath(path).accountPath);
1366
+ if (accountFailure) return accountFailure;
1407
1367
  return this._signWithWallet({
1408
1368
  connectId,
1409
1369
  deviceId,
1370
+ path,
1410
1371
  chain: "btc",
1411
1372
  operationName: "btcSignMessage",
1412
1373
  buildRequest: (requestId, xfp) => this.urEngine.buildBtcMessageSignRequest({
@@ -1434,17 +1395,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1434
1395
  return (0, import_hwk_adapter_core3.success)({ masterFingerprint: record.masterFingerprint });
1435
1396
  });
1436
1397
  }
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");
1398
+ async solGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1399
+ const call = this._beginCall("solGetAddress", connectIdArg, deviceIdArg, paramsArg);
1400
+ if (!call.success) return call;
1401
+ const { connectId, deviceId, params } = call.payload;
1402
+ if (!params.path) return missingParamFailure("solGetAddress", "params.path");
1448
1403
  const solCoinTypeFailure = coinTypeFailure("sol", params.path);
1449
1404
  if (solCoinTypeFailure) return solCoinTypeFailure;
1450
1405
  const path = normalizePath(params.path);
@@ -1464,180 +1419,218 @@ var KeystoneAdapter = class _KeystoneAdapter {
1464
1419
  bundle
1465
1420
  );
1466
1421
  _KeystoneAdapter._throwIfAborted(signal);
1422
+ if (!/^[0-9a-f]{64}$/i.test(account.publicKey)) {
1423
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1424
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1425
+ message: "Keystone returned a Solana key that is not a 32-byte Ed25519 public key"
1426
+ });
1427
+ }
1467
1428
  const address = import_bs58.default.encode(Buffer.from(account.publicKey, "hex"));
1468
- return (0, import_hwk_adapter_core3.success)({ address, path });
1429
+ return (0, import_hwk_adapter_core3.success)({
1430
+ address,
1431
+ path,
1432
+ accountKey: { path, publicKey: account.publicKey }
1433
+ });
1469
1434
  });
1470
1435
  }
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");
1436
+ async solSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1437
+ const call = this._beginCall("solSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1438
+ if (!call.success) return call;
1439
+ const { params } = call.payload;
1478
1440
  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
- });
1441
+ return missingParamFailure("solSignTransaction", "params.path and params.serializedTx");
1442
+ }
1443
+ const unsignedPayloadHex = exactHex(params.serializedTx);
1444
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("serializedTx");
1445
+ return this._solSign(
1446
+ "solSignTransaction",
1447
+ call.payload,
1448
+ params.path,
1449
+ unsignedPayloadHex,
1450
+ "transaction"
1451
+ );
1501
1452
  }
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");
1453
+ async solSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1454
+ const call = this._beginCall("solSignMessage", connectIdArg, deviceIdArg, paramsArg);
1455
+ if (!call.success) return call;
1456
+ const { params } = call.payload;
1508
1457
  if (!params.path || !params.message) {
1458
+ return missingParamFailure("solSignMessage", "params.path and params.message");
1459
+ }
1460
+ if (params.messageVersion !== void 0) {
1509
1461
  return (0, import_hwk_adapter_core3.failure)(
1510
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1511
- "solSignMessage requires params.path and params.message"
1462
+ import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1463
+ "Keystone signs Solana messages as raw bytes only; off-chain message format is not supported"
1512
1464
  );
1513
1465
  }
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
- });
1466
+ const unsignedPayloadHex = exactHex(params.message);
1467
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("message");
1468
+ return this._solSign(
1469
+ "solSignMessage",
1470
+ call.payload,
1471
+ params.path,
1472
+ unsignedPayloadHex,
1473
+ "message"
1474
+ );
1531
1475
  }
1532
1476
  // ---------------------------------------------------------------------------
1533
1477
  // TRON: keystone-sdk-rust layout (tags 5201/5202, firmware >= 2.5.0), not sdk.tron's
1534
1478
  // protobuf module; OneKey Pro's encoding under the same tag is rejected by the firmware.
1535
1479
  // ---------------------------------------------------------------------------
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");
1480
+ async tronGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1481
+ const call = this._beginCall("tronGetAddress", connectIdArg, deviceIdArg, paramsArg);
1482
+ if (!call.success) return call;
1483
+ const { params } = call.payload;
1484
+ if (!params.path) return missingParamFailure("tronGetAddress", "params.path");
1544
1485
  const tronCoinTypeFailure = coinTypeFailure("tron", params.path);
1545
1486
  if (tronCoinTypeFailure) return tronCoinTypeFailure;
1546
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1487
+ return this._addressFromAccountXpub(
1488
+ "tronGetAddress",
1489
+ "tron",
1490
+ call.payload,
1491
+ params.path,
1492
+ "m/44'/195'/0'/0/0",
1493
+ bundle,
1494
+ (xpub, relativeDerivePath) => this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath)
1495
+ );
1496
+ }
1497
+ async tronSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1498
+ const call = this._beginCall("tronSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1499
+ if (!call.success) return call;
1500
+ const { params } = call.payload;
1501
+ if (!params.path) return missingParamFailure("tronSignTransaction", "params.path");
1502
+ if (!params.rawTxHex) {
1503
+ return (0, import_hwk_adapter_core3.failure)(
1504
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1505
+ "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1506
+ );
1507
+ }
1508
+ const rawTxHex = exactHex(params.rawTxHex);
1509
+ if (rawTxHex === void 0) return invalidHexFailure("rawTxHex");
1510
+ return this._tronSign("tronSignTransaction", call.payload, params.path, rawTxHex);
1511
+ }
1512
+ async tronSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1513
+ const call = this._beginCall("tronSignMessage", connectIdArg, deviceIdArg, paramsArg);
1514
+ if (!call.success) return call;
1515
+ const { params } = call.payload;
1516
+ if (!params.path) return missingParamFailure("tronSignMessage", "params.path");
1517
+ if (!params.messageHex) return missingParamFailure("tronSignMessage", "params.messageHex");
1518
+ if (params.messageType !== "V2") {
1519
+ return (0, import_hwk_adapter_core3.failure)(
1520
+ import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1521
+ 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1522
+ );
1523
+ }
1524
+ const messageHex = exactHex(params.messageHex);
1525
+ if (messageHex === void 0) return invalidHexFailure("messageHex");
1526
+ return this._tronSign(
1527
+ "tronSignMessage",
1528
+ call.payload,
1529
+ params.path,
1530
+ messageHex,
1531
+ 2 /* PersonalMessage */
1532
+ );
1533
+ }
1534
+ /** Resolves the call's target and requires params, before any method-specific check. */
1535
+ _beginCall(method, connectIdArg, deviceIdArg, params) {
1536
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1537
+ if (!operationTarget.success) return operationTarget;
1538
+ if (!params) return missingParamFailure(method, "params");
1539
+ return (0, import_hwk_adapter_core3.success)({
1540
+ connectId: operationTarget.payload.targetId,
1541
+ deviceId: deviceIdArg ?? void 0,
1542
+ params
1543
+ });
1544
+ }
1545
+ /** Derives a leaf address offline from its account xpub. */
1546
+ async _addressFromAccountXpub(method, chain, { connectId, deviceId }, path, leafExample, bundle, derive) {
1547
+ const normalizedPath = normalizePath(path);
1548
+ const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1547
1549
  if (!relativeDerivePath) {
1548
1550
  return (0, import_hwk_adapter_core3.failure)(
1549
1551
  import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1550
- "tronGetAddress requires a full leaf path, e.g. m/44'/195'/0'/0/0"
1552
+ `${method} requires a full leaf path, e.g. ${leafExample}`
1551
1553
  );
1552
1554
  }
1555
+ const accountFailure = chain === "btc" ? btcAccountFailure(accountPath) : void 0;
1556
+ if (accountFailure) return accountFailure;
1553
1557
  return this._runJob(connectId, deviceId, async (signal) => {
1554
1558
  const xpub = await this._fetchAccountXpub(
1555
1559
  connectId,
1556
1560
  deviceId,
1557
- "tron",
1561
+ chain,
1558
1562
  accountPath,
1559
1563
  signal,
1560
1564
  bundle
1561
1565
  );
1562
- const address = this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath);
1563
- return (0, import_hwk_adapter_core3.success)({ address, path: normalizePath(params.path) });
1566
+ return (0, import_hwk_adapter_core3.success)({
1567
+ address: derive(xpub, relativeDerivePath),
1568
+ path: normalizedPath,
1569
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1570
+ });
1564
1571
  });
1565
1572
  }
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);
1573
+ _evmSign(method, target, rawPath, chainId, signDataHex, dataType, toPayload) {
1574
+ const path = normalizePath(rawPath);
1584
1575
  return this._signWithWallet({
1585
- connectId,
1586
- deviceId,
1587
- chain: "tron",
1588
- operationName: "tronSignTransaction",
1589
- buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1576
+ connectId: target.connectId,
1577
+ deviceId: target.deviceId,
1578
+ path,
1579
+ chain: "evm",
1580
+ operationName: method,
1581
+ buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1590
1582
  requestId,
1591
- rawTxHex,
1583
+ unsignedTxHex: signDataHex,
1584
+ dataType,
1592
1585
  path,
1593
1586
  xfp,
1587
+ chainId,
1594
1588
  origin: this._origin
1595
1589
  }),
1596
- parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1597
- // Keystone signs rawTxHex as given and returns only the signature, so no serializedTx.
1590
+ parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1591
+ toPayload
1592
+ });
1593
+ }
1594
+ _solSign(method, target, rawPath, unsignedPayloadHex, dataType) {
1595
+ const path = normalizePath(rawPath);
1596
+ return this._signWithWallet({
1597
+ connectId: target.connectId,
1598
+ deviceId: target.deviceId,
1599
+ path,
1600
+ chain: "sol",
1601
+ operationName: method,
1602
+ buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1603
+ requestId,
1604
+ unsignedPayloadHex,
1605
+ dataType,
1606
+ path,
1607
+ xfp,
1608
+ origin: this._origin
1609
+ }),
1610
+ parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1598
1611
  toPayload: (sig) => ({ signature: sig.signature })
1599
1612
  });
1600
1613
  }
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);
1614
+ _tronSign(method, target, rawPath, signDataHex, signType) {
1615
+ const path = normalizePath(rawPath);
1621
1616
  return this._signWithWallet({
1622
- connectId,
1623
- deviceId,
1617
+ connectId: target.connectId,
1618
+ deviceId: target.deviceId,
1619
+ path,
1624
1620
  chain: "tron",
1625
- operationName: "tronSignMessage",
1621
+ operationName: method,
1626
1622
  buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1627
1623
  requestId,
1628
- rawTxHex: messageHex,
1624
+ rawTxHex: signDataHex,
1629
1625
  path,
1630
1626
  xfp,
1631
- signType: 2 /* PersonalMessage */,
1627
+ signType,
1632
1628
  origin: this._origin
1633
1629
  }),
1634
1630
  parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1635
1631
  toPayload: (sig) => ({ signature: sig.signature })
1636
1632
  });
1637
1633
  }
1638
- // ---------------------------------------------------------------------------
1639
- // Internals
1640
- // ---------------------------------------------------------------------------
1641
1634
  async _runJob(connectId, deviceId, job) {
1642
1635
  try {
1643
1636
  return await this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), job);
@@ -1661,14 +1654,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
1661
1654
  message: "Keystone did not return an extended public key for this account path"
1662
1655
  });
1663
1656
  }
1657
+ const { publicKey } = this.urEngine.parseXpubMeta(account.extendedPublicKey);
1658
+ if (!/^0[23]/.test(publicKey)) {
1659
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1660
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1661
+ message: "Keystone returned an account key that is not a public key"
1662
+ });
1663
+ }
1664
1664
  return account.extendedPublicKey;
1665
1665
  }
1666
+ /** The exported key behind an address, reduced to the fields that identify it. */
1667
+ _exportedAccountKey(accountPath, xpub) {
1668
+ const { publicKey, chainCode } = this.urEngine.parseXpubMeta(xpub);
1669
+ return { path: normalizePath(accountPath), publicKey, chainCode, xpub };
1670
+ }
1666
1671
  /**
1667
1672
  * Signing needs only the wallet's mfp: the device re-derives the key from path+xfp, so no
1668
1673
  * per-path account lookup happens here.
1669
1674
  */
1670
1675
  _signWithWallet(args) {
1671
1676
  const { connectId, deviceId } = args;
1677
+ if (!isBip32Path(args.path)) {
1678
+ return Promise.resolve(
1679
+ (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `Invalid derivation path (${args.path})`)
1680
+ );
1681
+ }
1682
+ const chainCoinTypeFailure = coinTypeFailure(args.chain, args.path);
1683
+ if (chainCoinTypeFailure) return Promise.resolve(chainCoinTypeFailure);
1672
1684
  return this._runJob(connectId, deviceId, async (signal) => {
1673
1685
  const { record } = await this._ensureWalletKnown(connectId, deviceId, args.chain, signal);
1674
1686
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1705,8 +1717,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1705
1717
  case "btcGetPublicKey":
1706
1718
  case "solGetAddress":
1707
1719
  return { hwkChain, path };
1708
- default:
1709
- return void 0;
1710
1720
  }
1711
1721
  }
1712
1722
  /**
@@ -1750,7 +1760,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1750
1760
  schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1751
1761
  origin: this._origin
1752
1762
  });
1753
- const responseUr = await this._requestQrDisplayAndAwaitResponse(
1763
+ const responseUr = await this._requestQrAndAwaitResponse(
1754
1764
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1755
1765
  { ...requestUr, animated: false },
1756
1766
  signal
@@ -1758,26 +1768,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
1758
1768
  _KeystoneAdapter._throwIfAborted(signal);
1759
1769
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1760
1770
  this._assertParsedIdentity(parsed, target);
1761
- record = this._upsertDeviceRecord(parsed);
1762
1771
  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
1772
  scanned.set(accountKey(schema.hwkChain, schema.path), {
1773
- ...account,
1773
+ ...requireExportedPath(parsed, schema.path),
1774
1774
  hwkChain: schema.hwkChain
1775
1775
  });
1776
1776
  }
1777
+ record = this._upsertDeviceRecord(parsed);
1777
1778
  return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1778
1779
  });
1779
1780
  }
1780
- /** Resolve the wallet's master fingerprint from the connectId and/or deviceId the caller passed. */
1781
1781
  /**
1782
1782
  * A positional wallet id and an operation id must name the same wallet: otherwise the call
1783
1783
  * would run on the operation's wallet while the caller files the result under the other one.
@@ -1832,7 +1832,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1832
1832
  if (expected.expectedMasterFingerprint && parsed.masterFingerprint !== expected.expectedMasterFingerprint) {
1833
1833
  throw (0, import_hwk_adapter_core3.createHwkError)({
1834
1834
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1835
- message: `Connected Keystone wallet (mfp ${parsed.masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1835
+ // The master fingerprint identifies the wallet; keep it out of messages that reach logs.
1836
+ message: "Connected Keystone wallet does not match the requested wallet"
1836
1837
  });
1837
1838
  }
1838
1839
  }
@@ -1862,7 +1863,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1862
1863
  * Opens a permitted USB Keystone and takes its mfp as the wallet identity. A known wallet gains
1863
1864
  * USB in place (`device-changed`); an unseen one becomes USB-only.
1864
1865
  */
1865
- async _connectUsb(expected, searchTargetId, signal) {
1866
+ async _connectUsb(connector, expected, searchTargetId, signal) {
1866
1867
  if (this._pendingUsbTeardowns > 0 || this._abandonedUsbConnects > 0) {
1867
1868
  return (0, import_hwk_adapter_core3.failure)(
1868
1869
  import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal,
@@ -1875,28 +1876,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
1875
1876
  abandoned = true;
1876
1877
  this._abandonedUsbConnects += 1;
1877
1878
  };
1878
- signal?.addEventListener("abort", onAbort, { once: true });
1879
+ signal.addEventListener("abort", onAbort, { once: true });
1879
1880
  const pending = this._usbConnectTail.then(async () => {
1880
1881
  _KeystoneAdapter._throwIfAborted(signal);
1881
- return this._connectUsbExclusive(expected, searchTargetId, signal);
1882
+ if (this._unsettledUsbOperations.size > 0) {
1883
+ return (0, import_hwk_adapter_core3.failure)(
1884
+ import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal,
1885
+ "Keystone USB is still finishing an earlier request"
1886
+ );
1887
+ }
1888
+ const releaseConnect = this._retainUsbOperation("connect");
1889
+ try {
1890
+ return await this._connectUsbExclusive(connector, expected, searchTargetId, signal);
1891
+ } finally {
1892
+ releaseConnect();
1893
+ }
1882
1894
  });
1883
1895
  const settled = pending.finally(() => {
1884
- signal?.removeEventListener("abort", onAbort);
1896
+ signal.removeEventListener("abort", onAbort);
1885
1897
  if (abandoned) this._abandonedUsbConnects -= 1;
1886
1898
  });
1887
1899
  this._usbConnectTail = settled.then(
1888
1900
  () => void 0,
1889
1901
  () => void 0
1890
1902
  );
1891
- return signal ? _KeystoneAdapter._abortable(signal, settled) : settled;
1903
+ return _KeystoneAdapter._abortable(signal, settled);
1892
1904
  }
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
- }
1905
+ async _connectUsbExclusive(connector, expected, searchTargetId, signal) {
1900
1906
  let sessionId;
1901
1907
  try {
1902
1908
  let connectTarget = { type: "default" };
@@ -1908,7 +1914,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1908
1914
  deviceIdentity: expected.expectedMasterFingerprint
1909
1915
  };
1910
1916
  }
1911
- const connector = this._usbConnector;
1912
1917
  const session = await (connector.connectTarget ? connector.connectTarget(connectTarget) : connector.connect(searchTargetId ?? expected.expectedMasterFingerprint));
1913
1918
  sessionId = session.sessionId;
1914
1919
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1922,16 +1927,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1922
1927
  });
1923
1928
  }
1924
1929
  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
- }
1930
+ this._assertParsedIdentity({ masterFingerprint, accounts: [] }, expected);
1931
1931
  const previousUsbSessionId = this._devices.get(masterFingerprint)?.usbSessionId;
1932
1932
  if (previousUsbSessionId && previousUsbSessionId !== session.sessionId) {
1933
1933
  try {
1934
- await this._usbConnector.disconnect(previousUsbSessionId);
1934
+ await connector.disconnect(previousUsbSessionId);
1935
1935
  } catch {
1936
1936
  }
1937
1937
  }
@@ -1951,7 +1951,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1951
1951
  } catch (err) {
1952
1952
  if (sessionId) {
1953
1953
  try {
1954
- await this._usbConnector.disconnect(sessionId);
1954
+ await connector.disconnect(sessionId);
1955
1955
  } catch {
1956
1956
  }
1957
1957
  }
@@ -1997,9 +1997,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1997
1997
  }
1998
1998
  return void 0;
1999
1999
  }
2000
- const attached = await this._connectUsb({ expectedMasterFingerprint }, void 0, signal);
2000
+ const attached = await this._connectUsb(
2001
+ this._usbConnector,
2002
+ { expectedMasterFingerprint },
2003
+ void 0,
2004
+ signal
2005
+ );
2001
2006
  _KeystoneAdapter._throwIfAborted(signal);
2002
- if (!attached.success && attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal) {
2007
+ if (!attached.success && (attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal || attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceOneDeviceOnly)) {
2003
2008
  throw (0, import_hwk_adapter_core3.createHwkError)({
2004
2009
  ...attached.payload,
2005
2010
  message: attached.payload.error
@@ -2059,9 +2064,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2059
2064
  message: "USB channel is not connected for this Keystone wallet"
2060
2065
  });
2061
2066
  }
2062
- const result = await this._callUsbConnector(
2067
+ const result = await this._callUsbResolveUr(
2068
+ this._usbConnector,
2063
2069
  record.usbSessionId,
2064
- "resolveUr",
2065
2070
  requestUr,
2066
2071
  signal
2067
2072
  );
@@ -2071,11 +2076,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2071
2076
  if (usbErrorCode === import_hwk_adapter_core3.HardwareErrorCode.PayloadTooLarge && usbErrorOrigin !== "device") {
2072
2077
  if (!interactionRoute && !this._forcedTransport) {
2073
2078
  const displayDevice2 = toDeviceInfo(record);
2074
- return this._requestQrDisplayAndAwaitResponse(
2075
- displayDevice2,
2076
- { ...requestUr, animated },
2077
- signal
2078
- );
2079
+ return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2079
2080
  }
2080
2081
  throw usbError;
2081
2082
  }
@@ -2086,6 +2087,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2086
2087
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2087
2088
  }
2088
2089
  record.usbSessionId = void 0;
2090
+ this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: toDeviceInfo(record) });
2089
2091
  if (interactionRoute) {
2090
2092
  throw this._endDisconnectedOperation(
2091
2093
  interactionRoute.operationId,
@@ -2103,11 +2105,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2103
2105
  });
2104
2106
  }
2105
2107
  }
2108
+ if (operationName && usbError.replyUnreadable === true) {
2109
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2110
+ code: usbErrorCode ?? import_hwk_adapter_core3.HardwareErrorCode.UnknownError,
2111
+ message: `Keystone ${operationName} may have completed but its reply could not be read`,
2112
+ origin: "device",
2113
+ recovery: { scope: "unknown" },
2114
+ params: (0, import_hwk_adapter_core3.operationMayHaveCompletedParams)(operationName)
2115
+ });
2116
+ }
2106
2117
  throw usbError;
2107
2118
  }
2108
2119
  const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
2109
2120
  try {
2110
- return await this._requestQrDisplayAndAwaitResponse(
2121
+ return await this._requestQrAndAwaitResponse(
2111
2122
  displayDevice,
2112
2123
  { ...requestUr, animated },
2113
2124
  signal
@@ -2171,6 +2182,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2171
2182
  const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2172
2183
  _KeystoneAdapter._throwIfAborted(signal);
2173
2184
  const parsed = this.urEngine.parseAccountResponse(responseUr);
2185
+ const account = requireExportedPath(parsed, syncPath);
2174
2186
  let record;
2175
2187
  if (useSinglePathUsbExport && existingRecord) {
2176
2188
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2186,13 +2198,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2186
2198
  viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2187
2199
  });
2188
2200
  }
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
2201
  return { record, account: { ...account, hwkChain } };
2197
2202
  }
2198
2203
  /**
@@ -2215,7 +2220,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2215
2220
  });
2216
2221
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2217
2222
  _KeystoneAdapter._throwIfAborted(signal);
2218
- return { record: this._upsertDeviceRecord(this.urEngine.parseAccountResponse(responseUr)) };
2223
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
2224
+ requireExportedPath(parsed, normalizePath(accountPath));
2225
+ return { record: this._upsertDeviceRecord(parsed) };
2219
2226
  }
2220
2227
  /**
2221
2228
  * The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
@@ -2241,7 +2248,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2241
2248
  * a cancel reach the wait before the QR timeout.
2242
2249
  */
2243
2250
  async _awaitQrResponse(requestType, pending, signal) {
2244
- if (!signal) return pending;
2245
2251
  let settled = false;
2246
2252
  const onAbort = () => {
2247
2253
  if (!settled) this._uiRegistry.cancel(requestType);
@@ -2250,55 +2256,50 @@ var KeystoneAdapter = class _KeystoneAdapter {
2250
2256
  else signal.addEventListener("abort", onAbort, { once: true });
2251
2257
  try {
2252
2258
  return await pending;
2259
+ } catch (error) {
2260
+ const reason = signal.reason;
2261
+ if (signal.aborted && reason?.code === import_hwk_adapter_core3.HardwareErrorCode.OperationEnded) throw signal.reason;
2262
+ throw error;
2253
2263
  } finally {
2254
2264
  settled = true;
2255
2265
  signal.removeEventListener("abort", onAbort);
2256
2266
  }
2257
2267
  }
2258
- async _requestQrDisplayAndAwaitResponse(device, data, signal) {
2268
+ /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2269
+ async _requestQrAndAwaitResponse(device, data, signal) {
2270
+ const requestType = data ? import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY : import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN;
2259
2271
  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"
2272
+ const release = operationId ? this._operations.retain(operationId) : void 0;
2273
+ try {
2274
+ const waitPromise = this._uiRegistry.wait(requestType, {
2275
+ timeoutMs: this._qrTimeoutMs,
2276
+ operationId
2293
2277
  });
2278
+ if (data) {
2279
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY, {
2280
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2281
+ payload: { device, data, operationId }
2282
+ });
2283
+ } else {
2284
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN, {
2285
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN,
2286
+ payload: { device, operationId }
2287
+ });
2288
+ }
2289
+ const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2290
+ return { urType: response.urType, urData: response.urData };
2291
+ } finally {
2292
+ release?.();
2294
2293
  }
2294
+ }
2295
+ async _callUsbResolveUr(connector, sessionId, requestUr, signal) {
2295
2296
  if (this._pendingUsbTeardowns > 0 || this._unsettledUsbOperations.size > 0) {
2296
2297
  throw (0, import_hwk_adapter_core3.createHwkError)({
2297
2298
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal,
2298
- message: `Keystone USB is busy while calling ${method}`
2299
+ message: "Keystone USB is busy while calling resolveUr"
2299
2300
  });
2300
2301
  }
2301
- if (signal?.aborted) {
2302
+ if (signal.aborted) {
2302
2303
  throw signal.reason instanceof Error ? signal.reason : (0, import_hwk_adapter_core3.createHwkError)({
2303
2304
  code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
2304
2305
  message: "User aborted operation"
@@ -2307,12 +2308,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2307
2308
  const releaseOperation = this._retainUsbOperation(`call:${sessionId}`);
2308
2309
  let rawCall;
2309
2310
  try {
2310
- rawCall = this._usbConnector.call(sessionId, method, params).finally(releaseOperation);
2311
+ rawCall = connector.call(sessionId, "resolveUr", requestUr).finally(releaseOperation);
2311
2312
  } catch (error) {
2312
2313
  releaseOperation();
2313
2314
  throw error;
2314
2315
  }
2315
- return signal ? _KeystoneAdapter._abortable(signal, rawCall) : rawCall;
2316
+ return _KeystoneAdapter._abortable(signal, rawCall);
2316
2317
  }
2317
2318
  _runUsbTeardown(task) {
2318
2319
  const previous = this._usbTeardownTail;
@@ -2374,6 +2375,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
2374
2375
  );
2375
2376
  });
2376
2377
  }
2378
+ /** Settles with `signal`'s reason once it aborts; a later outcome of `promise` is dropped. */
2379
+ static _untilAborted(signal, promise) {
2380
+ promise.catch(() => void 0);
2381
+ if (signal.aborted) return Promise.reject(signal.reason);
2382
+ return new Promise((resolve, reject) => {
2383
+ const onAbort = () => reject(signal.reason);
2384
+ signal.addEventListener("abort", onAbort, { once: true });
2385
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort)).catch(() => void 0);
2386
+ });
2387
+ }
2377
2388
  static _throwIfAborted(signal) {
2378
2389
  if (signal?.aborted) {
2379
2390
  throw signal.reason instanceof Error ? signal.reason : new Error("Operation aborted");