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

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
@@ -47,6 +47,8 @@ module.exports = __toCommonJS(index_exports);
47
47
 
48
48
  // src/urEngine/KeystoneUrEngine.ts
49
49
  var import_bc_ur_registry_eth = require("@keystonehq/bc-ur-registry-eth");
50
+ var import_bc_ur_registry3 = require("@keystonehq/bc-ur-registry");
51
+ var import_ScriptExpression = require("@keystonehq/bc-ur-registry/dist/ScriptExpression.js");
50
52
  var import_keystone_sdk = require("@keystonehq/keystone-sdk");
51
53
  var import_bs58check = __toESM(require("bs58check"));
52
54
  var bitcoin = __toESM(require("bitcoinjs-lib"));
@@ -207,6 +209,35 @@ function toParsedAccount(key) {
207
209
  };
208
210
  }
209
211
  var BIP32_HARDENED_OFFSET = 2147483648;
212
+ function isExportedAccountPath(path) {
213
+ return /^m(?:\/\d+')+(?:\/\d+)*$/.test(path) && path.slice(2).split("/").every(
214
+ (segment) => Number(segment.endsWith("'") ? segment.slice(0, -1) : segment) < BIP32_HARDENED_OFFSET
215
+ );
216
+ }
217
+ function checkExportedKey(key, account, masterFingerprint, unsupportedDescriptor) {
218
+ if (unsupportedDescriptor || key.isMaster() || key.isPrivateKey()) {
219
+ return { rejected: "unusable-key" };
220
+ }
221
+ const source = key.getOrigin()?.getSourceFingerprint();
222
+ if (source && source.toString("hex") !== masterFingerprint) {
223
+ return { rejected: "different-wallet" };
224
+ }
225
+ if (!account.extendedPublicKey) {
226
+ return /^[0-9a-f]{64}$/i.test(account.publicKey) ? { identity: account.publicKey } : { rejected: "unusable-key" };
227
+ }
228
+ try {
229
+ const node = import_hdkey.default.fromExtendedKey(account.extendedPublicKey);
230
+ if (node.privateKey || !node.publicKey || !node.chainCode || node.publicKey.toString("hex") !== account.publicKey.toLowerCase()) {
231
+ return { rejected: "unusable-key" };
232
+ }
233
+ return { identity: `${account.publicKey}:${node.chainCode.toString("hex")}` };
234
+ } catch {
235
+ return { rejected: "unusable-key" };
236
+ }
237
+ }
238
+ function unexpectedQrCodeError(message, code = import_hwk_adapter_core.HardwareErrorCode.InvalidParams) {
239
+ return (0, import_hwk_adapter_core.createHwkError)({ code, message, params: { reason: "unexpected-qr-code" } });
240
+ }
210
241
  function relativeHdPath(relativeDerivePath) {
211
242
  const segments = relativeDerivePath.replace(/^m\//i, "").split("/");
212
243
  const valid = segments.every(
@@ -220,7 +251,7 @@ function relativeHdPath(relativeDerivePath) {
220
251
  }
221
252
  return `m/${segments.join("/")}`;
222
253
  }
223
- var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.]{1,20})?$/;
254
+ var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.-]{1,20})?$/;
224
255
  var DEVICE_TEXT = /^[^\p{Cc}\p{Cf}]{1,64}$/u;
225
256
  function deviceText(value, pattern) {
226
257
  return typeof value === "string" && pattern.test(value) ? value : void 0;
@@ -251,7 +282,8 @@ var KeystoneUrEngine = class {
251
282
  const ur = this.sdk.generateKeyDerivationCall({
252
283
  schemas: input.schemas.map((schema) => ({
253
284
  path: schema.path,
254
- curve: DERIVATION_CURVE[schema.curve ?? "secp256k1"]
285
+ curve: DERIVATION_CURVE[schema.curve ?? "secp256k1"],
286
+ chainType: schema.chainType
255
287
  })),
256
288
  origin: input.origin,
257
289
  version: import_keystone_sdk.QRHardwareCallVersion.V1
@@ -275,6 +307,90 @@ var KeystoneUrEngine = class {
275
307
  }
276
308
  return this.parseMultiAccounts(ur);
277
309
  }
310
+ /**
311
+ * Device exports are opt-in: request responses retain their existing format/path checks. An
312
+ * export carries whatever the device syncs to other wallets, so each key is checked on its own: a
313
+ * key that fails lands in `rejectedPaths` instead of discarding the whole export.
314
+ */
315
+ parseAccountExport(ur) {
316
+ let parsed;
317
+ let keys;
318
+ const unsupportedDescriptors = /* @__PURE__ */ new Set();
319
+ try {
320
+ const { cbor } = toSdkUr(ur);
321
+ if (ur.urType === "crypto-account") {
322
+ if (!Object.values(import_bc_ur_registry3.ScriptExpressions).some((script) => script.getTag() === 409)) {
323
+ Object.assign(import_bc_ur_registry3.ScriptExpressions, { TAPROOT: new import_ScriptExpression.ScriptExpression(409, "tr") });
324
+ }
325
+ import_bc_ur_registry3.extend.cbor.patchTags([409]);
326
+ const account = import_bc_ur_registry3.CryptoAccount.fromCBOR(cbor);
327
+ keys = account.getOutputDescriptors().map((output, index) => {
328
+ const key = output.getHDKey();
329
+ const path = key?.getOrigin()?.getPath();
330
+ const script = output.getScriptExpressions().map((item) => item.getExpression()).join("/");
331
+ const validScript = path?.startsWith("44'/0'/") && script === "pkh" || path?.startsWith("49'/0'/") && script === "sh/wpkh" || path?.startsWith("84'/0'/") && script === "wpkh" || path?.startsWith("86'/0'/") && script === "tr";
332
+ const children = key?.getChildren();
333
+ if (!key) throw new Error("Unsupported account descriptor");
334
+ if (!validScript || children && children.getPath() !== "0/*") {
335
+ unsupportedDescriptors.add(index);
336
+ }
337
+ return key;
338
+ });
339
+ const result = this.sdk.parseAccount(toSdkUr(ur));
340
+ parsed = {
341
+ masterFingerprint: requireBip32MasterFingerprint(result.masterFingerprint),
342
+ accounts: result.keys.map(toParsedAccount)
343
+ };
344
+ } else if (ur.urType === "crypto-multi-accounts") {
345
+ keys = import_bc_ur_registry3.CryptoMultiAccounts.fromCBOR(cbor).getKeys();
346
+ parsed = this.parseMultiAccounts(ur);
347
+ } else if (ur.urType === "crypto-hdkey") {
348
+ keys = [import_bc_ur_registry3.CryptoHDKey.fromCBOR(cbor)];
349
+ parsed = this.parseAccountResponse(ur);
350
+ } else {
351
+ throw new Error("Unsupported account export type");
352
+ }
353
+ if (!keys.length || keys.length !== parsed.accounts.length) {
354
+ throw new Error("Empty account export");
355
+ }
356
+ } catch {
357
+ throw unexpectedQrCodeError(
358
+ "Unable to read account export; scan a supported Keystone account export code"
359
+ );
360
+ }
361
+ const byPath = /* @__PURE__ */ new Map();
362
+ parsed.accounts.forEach((account, index) => {
363
+ if (!isExportedAccountPath(account.path)) return;
364
+ const entry = byPath.get(account.path) ?? {};
365
+ byPath.set(account.path, entry);
366
+ const check = checkExportedKey(
367
+ keys[index],
368
+ account,
369
+ parsed.masterFingerprint,
370
+ unsupportedDescriptors.has(index)
371
+ );
372
+ if (check.rejected === "different-wallet") {
373
+ entry.rejected = check.rejected;
374
+ } else if (check.identity === void 0) {
375
+ entry.rejected ?? (entry.rejected = check.rejected);
376
+ } else if (entry.identity === void 0) {
377
+ entry.account = account;
378
+ entry.identity = check.identity;
379
+ } else if (entry.identity !== check.identity && entry.rejected !== "different-wallet") {
380
+ entry.rejected = "conflicting-keys";
381
+ }
382
+ });
383
+ const accounts = [];
384
+ const rejectedPaths = [];
385
+ byPath.forEach((entry, path) => {
386
+ if (entry.account && entry.rejected !== "different-wallet" && entry.rejected !== "conflicting-keys") {
387
+ accounts.push(entry.account);
388
+ } else if (entry.rejected) {
389
+ rejectedPaths.push({ path, reason: entry.rejected });
390
+ }
391
+ });
392
+ return { ...parsed, accounts, rejectedPaths };
393
+ }
278
394
  // --- EVM ---
279
395
  buildEthSignRequest(input) {
280
396
  const ur = this.sdk.eth.generateSignRequest({
@@ -359,10 +475,10 @@ var KeystoneUrEngine = class {
359
475
  sameTransaction = false;
360
476
  }
361
477
  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
- });
478
+ throw unexpectedQrCodeError(
479
+ "Keystone returned a PSBT for another transaction than the one requested",
480
+ import_hwk_adapter_core.HardwareErrorCode.DeviceMismatch
481
+ );
366
482
  }
367
483
  return signedPsbtHex;
368
484
  }
@@ -479,11 +595,15 @@ function isBip32Path(path) {
479
595
  function splitAccountPath(path) {
480
596
  const normalized = normalizePath(path);
481
597
  const segments = normalized.slice(2).split("/");
482
- if (segments.length <= 3) {
598
+ let accountLength = 0;
599
+ segments.forEach((segment, index) => {
600
+ if (segment.endsWith("'")) accountLength = index + 1;
601
+ });
602
+ if (segments.length <= 3 || accountLength === 0 || accountLength === segments.length) {
483
603
  return { accountPath: normalized, relativeDerivePath: "" };
484
604
  }
485
- const accountSegments = segments.slice(0, segments.length - 2);
486
- const relativeSegments = segments.slice(segments.length - 2);
605
+ const accountSegments = segments.slice(0, accountLength);
606
+ const relativeSegments = segments.slice(accountLength);
487
607
  return {
488
608
  accountPath: `m/${accountSegments.join("/")}`,
489
609
  relativeDerivePath: relativeSegments.join("/")
@@ -525,12 +645,15 @@ function accountKey(hwkChain, path) {
525
645
  function createDeviceRecord(masterFingerprint) {
526
646
  return {
527
647
  masterFingerprint,
528
- connectId: walletConnectId(masterFingerprint),
529
- importedAt: Date.now()
648
+ connectId: walletConnectId(masterFingerprint)
530
649
  };
531
650
  }
532
651
  var CAPABILITIES = { persistentDeviceIdentity: true };
533
652
  function toDeviceInfo(record) {
653
+ return toDeviceInfoForConnection(record, record.usbSessionId ? "usb" : "qr");
654
+ }
655
+ function toDeviceInfoForConnection(record, connectionType) {
656
+ const firmwareVersion = connectionType === "usb" ? record.usbFirmwareVersion : record.deviceVersion;
534
657
  let availableChannels = ["qr"];
535
658
  if (record.usbSessionId) {
536
659
  availableChannels = record.qrSynced ? ["qr", "usb"] : ["usb"];
@@ -539,11 +662,13 @@ function toDeviceInfo(record) {
539
662
  vendor: "keystone",
540
663
  model: record.model ?? "unknown",
541
664
  modelName: record.model,
542
- firmwareVersion: record.deviceVersion ?? "0.0.0",
665
+ firmwareVersion: firmwareVersion ?? "0.0.0",
543
666
  deviceId: record.masterFingerprint,
544
667
  connectId: record.connectId,
545
- connectionType: record.usbSessionId ? "usb" : "qr",
546
- capabilities: CAPABILITIES,
668
+ connectionType,
669
+ capabilities: {
670
+ ...CAPABILITIES
671
+ },
547
672
  raw: {
548
673
  availableChannels,
549
674
  masterFingerprint: record.masterFingerprint,
@@ -563,6 +688,31 @@ function placeholderDeviceInfo() {
563
688
  };
564
689
  }
565
690
 
691
+ // src/adapter/firmwareCapabilities.ts
692
+ var MULTI_COIN = {
693
+ variant: "multi-coin",
694
+ supportedChains: ["btc", "evm", "sol", "tron"]
695
+ };
696
+ var BITCOIN_ONLY = {
697
+ variant: "bitcoin-only",
698
+ supportedChains: ["btc"]
699
+ };
700
+ var CYPHERPUNK = {
701
+ variant: "cypherpunk",
702
+ // Firmware support alone is insufficient: this adapter has no Zcash/Monero methods yet.
703
+ supportedChains: ["btc"]
704
+ };
705
+ function getKeystoneFirmwareProfile(firmwareVersion) {
706
+ if (!firmwareVersion || firmwareVersion === "0.0.0") return void 0;
707
+ const version = /^\d{1,4}(?:\.\d{1,4}){1,3}(?:-([a-z0-9.-]{1,40}))?$/i.exec(firmwareVersion);
708
+ if (!version) return void 0;
709
+ const suffix = version[1]?.toUpperCase();
710
+ if (!suffix) return MULTI_COIN;
711
+ if (suffix === "C" || suffix === "CYPHERPUNK" || suffix === "CYPHERPUNK-B") return CYPHERPUNK;
712
+ if (suffix === "B" || suffix === "BTC" || suffix === "BTC-ONLY") return BITCOIN_ONLY;
713
+ return void 0;
714
+ }
715
+
566
716
  // src/utils/queueKey.ts
567
717
  var import_hwk_adapter_core2 = require("@onekeyfe/hwk-adapter-core");
568
718
  var KEYSTONE_COLD_START_JOB_LABEL = "keystone-cold-start";
@@ -602,10 +752,36 @@ function keystoneBtcParamsFailure(params) {
602
752
  }
603
753
  return void 0;
604
754
  }
755
+ var USB_ATTACH_FAILURE_REASONS = {
756
+ [import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch]: "wallet-mismatch",
757
+ [import_hwk_adapter_core3.HardwareErrorCode.DeviceNotInitialized]: "wallet-mismatch",
758
+ [import_hwk_adapter_core3.HardwareErrorCode.DeviceLocked]: "device-locked"
759
+ };
760
+ var KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS = 24;
605
761
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
606
762
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
763
+ var CHAIN_TYPE_BY_CHAIN = {
764
+ evm: "ETH",
765
+ sol: "SOL",
766
+ tron: "TRX"
767
+ };
768
+ var BTC_CHAIN_TYPE_BY_PURPOSE = {
769
+ 44: "BTC_LEGACY",
770
+ 49: "BTC",
771
+ 84: "BTC_NATIVE_SEGWIT",
772
+ 86: "BTC_TAPROOT"
773
+ };
774
+ function hardwareCallChainType(chain, path) {
775
+ if (chain !== "btc") return CHAIN_TYPE_BY_CHAIN[chain];
776
+ const purpose = normalizePath(path).match(/^m\/(\d+)'/)?.[1];
777
+ return purpose ? BTC_CHAIN_TYPE_BY_PURPOSE[Number(purpose)] : void 0;
778
+ }
607
779
  function keySchema(chain, path) {
608
- return { path, curve: chain === "sol" ? "ed25519" : "secp256k1" };
780
+ return {
781
+ path,
782
+ curve: chain === "sol" ? "ed25519" : "secp256k1",
783
+ chainType: hardwareCallChainType(chain, path)
784
+ };
609
785
  }
610
786
  function waitForKeystoneUsbReattachProbe() {
611
787
  return new Promise((resolve) => {
@@ -629,12 +805,42 @@ function exactHex(value) {
629
805
  function invalidHexFailure(field) {
630
806
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${field} must be an even-length hex string`);
631
807
  }
632
- function requireExportedPath(parsed, path) {
633
- const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
808
+ function exportedAccountAt(parsed, path) {
809
+ const rejected = parsed.rejectedPaths?.find((entry) => normalizePath(entry.path) === path);
810
+ switch (rejected?.reason) {
811
+ case "different-wallet":
812
+ throw (0, import_hwk_adapter_core3.createHwkError)({
813
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
814
+ message: "Account export contains a different wallet fingerprint"
815
+ });
816
+ case "conflicting-keys":
817
+ throw (0, import_hwk_adapter_core3.createHwkError)({
818
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
819
+ message: "Account export contains conflicting keys for the same path"
820
+ });
821
+ case "unusable-key":
822
+ throw unexpectedQrCodeError(`Account export key at ${path} is not usable`);
823
+ default:
824
+ return parsed.accounts.find((returned) => normalizePath(returned.path) === path);
825
+ }
826
+ }
827
+ function parseScannedAnswer(parse) {
828
+ try {
829
+ return parse();
830
+ } catch (error) {
831
+ if (typeof error?.code === "number") throw error;
832
+ throw unexpectedQrCodeError(
833
+ `Scanned code is not this request's answer: ${error instanceof Error ? error.message : ""}`
834
+ );
835
+ }
836
+ }
837
+ function requireExportedPath(parsed, path, accountExport = false) {
838
+ const account = exportedAccountAt(parsed, path);
634
839
  if (!account) {
635
840
  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})`
841
+ code: accountExport ? import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden : import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
842
+ message: `Keystone did not return the requested derivation path (${path})`,
843
+ ...accountExport ? { params: { reason: "account-not-exported" } } : {}
638
844
  });
639
845
  }
640
846
  return account;
@@ -648,7 +854,9 @@ function coinTypeFailure(chain, path) {
648
854
  }
649
855
  function btcAccountFailure(accountPath) {
650
856
  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);
857
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE, {
858
+ reason: "btc-account-limit"
859
+ });
652
860
  }
653
861
  function missingParamFailure(method, param) {
654
862
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${method} requires ${param}`);
@@ -660,6 +868,10 @@ function evmMessageSignature(sig) {
660
868
  return { signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) };
661
869
  }
662
870
  var KeystoneAdapter = class _KeystoneAdapter {
871
+ /**
872
+ * `qrKeyRequestLimit` caps the account paths one QR key request may ask for, below the firmware's
873
+ * own limit: a host with no USB to fall back on can refuse a large request before the device does.
874
+ */
663
875
  constructor(options) {
664
876
  this.vendor = "keystone";
665
877
  // No protocol-level cancel exists over Keystone USB, and QR has no transport
@@ -679,7 +891,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
679
891
  message: "Keystone operation has ended",
680
892
  params: { operationId: operation.operationId, reason }
681
893
  });
682
- this._jobQueue.cancelActiveAndPending(operation.operationId, ended);
894
+ const queueKey = keystoneQueueKey(operation.operationId);
895
+ this._jobQueue.cancelActiveAndPending(queueKey, ended);
683
896
  this._uiRegistry.cancel(void 0, void 0, operation.operationId);
684
897
  }
685
898
  }
@@ -707,6 +920,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
707
920
  if (!record) return;
708
921
  this._operations.endByConnectionKey(connectId, "disconnect");
709
922
  record.usbSessionId = void 0;
923
+ record.usbFirmwareVersion = void 0;
710
924
  const info = toDeviceInfo(record);
711
925
  if (record.qrSynced) {
712
926
  this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: info });
@@ -716,7 +930,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
716
930
  }
717
931
  };
718
932
  this._handleUsbUiEvent = (event) => {
719
- this.emitter.emit("ui-event", event);
933
+ const operationId = this._activeOperationId();
934
+ this.emitter.emit("ui-event", operationId ? { ...event, operationId } : event);
720
935
  };
721
936
  // ---------------------------------------------------------------------------
722
937
  // All-network bundle, dispatched to the per-chain methods below.
@@ -789,6 +1004,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
789
1004
  success: true,
790
1005
  payload: {
791
1006
  ...context.payload,
1007
+ ...access?.channel === "qr" && access.accountExport ? { accountExport: true } : {},
792
1008
  rootFingerprint: record ? Number.parseInt(record.masterFingerprint, 16) : void 0,
793
1009
  deviceIdentity: record ? {
794
1010
  vendor: "keystone",
@@ -814,6 +1030,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
814
1030
  };
815
1031
  this._origin = options?.origin ?? "OneKey";
816
1032
  this._qrTimeoutMs = options?.qrTimeoutMs;
1033
+ const limit = options?.qrKeyRequestLimit;
1034
+ this._qrKeyRequestLimit = limit !== void 0 && Number.isInteger(limit) && limit > 0 ? Math.min(limit, KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS) : KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS;
817
1035
  this.urEngine = new KeystoneUrEngine(this._origin);
818
1036
  this._jobQueue = new import_hwk_adapter_core3.DeviceJobQueue();
819
1037
  this._usbConnector = options?.usbConnector;
@@ -1038,23 +1256,24 @@ var KeystoneAdapter = class _KeystoneAdapter {
1038
1256
  }
1039
1257
  getDeviceInfo(connectIdOrOperationId, deviceId) {
1040
1258
  try {
1041
- const connectId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1259
+ const operation = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId) : void 0;
1260
+ const connectId = operation?.connectId ?? connectIdOrOperationId;
1042
1261
  const { record } = this._resolveTarget(connectId, deviceId);
1043
1262
  if (!record) {
1044
1263
  return Promise.resolve(
1045
1264
  (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound, "Unknown Keystone device")
1046
1265
  );
1047
1266
  }
1048
- return Promise.resolve((0, import_hwk_adapter_core3.success)(toDeviceInfo(record)));
1267
+ const info = operation ? toDeviceInfoForConnection(record, operation.connectionType === "qr" ? "qr" : "usb") : toDeviceInfo(record);
1268
+ return Promise.resolve((0, import_hwk_adapter_core3.success)(info));
1049
1269
  } catch (err) {
1050
1270
  return Promise.resolve(this._errorToFailure(err));
1051
1271
  }
1052
1272
  }
1053
1273
  cancel(connectId) {
1054
- let namedOperationConnectId;
1055
1274
  if ((0, import_hwk_adapter_core3.isHardwareOperationId)(connectId)) {
1056
1275
  try {
1057
- namedOperationConnectId = this._operations.resolve(connectId).connectId;
1276
+ this._operations.resolve(connectId);
1058
1277
  } catch {
1059
1278
  return;
1060
1279
  }
@@ -1064,15 +1283,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1064
1283
  message: "User aborted operation"
1065
1284
  });
1066
1285
  if (connectId) {
1286
+ const scopedOperationId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1067
1287
  const queueKeys = keystoneCancelQueueKeys([
1068
1288
  connectId,
1069
- this._operationRoutes.get(connectId)?.operationId,
1070
- namedOperationConnectId
1289
+ this._operationRoutes.get(connectId)?.operationId
1071
1290
  ]);
1072
1291
  for (const key of queueKeys) {
1073
1292
  this._jobQueue.cancelActiveAndPending(key, reason);
1074
1293
  }
1075
- const scopedOperationId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1076
1294
  if (scopedOperationId) {
1077
1295
  this._uiRegistry.cancel(void 0, void 0, scopedOperationId);
1078
1296
  }
@@ -1134,13 +1352,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1134
1352
  });
1135
1353
  responseUr = await this._requestQrAndAwaitResponse(
1136
1354
  displayDevice,
1137
- { ...requestUr, animated: false },
1355
+ { ...requestUr, animated: false, allowAccountExport: true },
1138
1356
  signal
1139
1357
  );
1140
1358
  }
1141
1359
  _KeystoneAdapter._throwIfAborted(signal);
1142
- const parsed = this.urEngine.parseAccountResponse(responseUr);
1143
- if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1360
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1361
+ if (!responseUr.accountExport) requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1144
1362
  const record = this._upsertDeviceRecord(parsed);
1145
1363
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
1146
1364
  });
@@ -1340,7 +1558,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
1340
1558
  "btcSignPsbt"
1341
1559
  );
1342
1560
  _KeystoneAdapter._throwIfAborted(signal);
1343
- const signedPsbt = this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex);
1561
+ const signedPsbt = parseScannedAnswer(
1562
+ () => this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex)
1563
+ );
1344
1564
  return (0, import_hwk_adapter_core3.success)({ signedPsbt });
1345
1565
  });
1346
1566
  }
@@ -1687,7 +1907,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1687
1907
  args.operationName
1688
1908
  );
1689
1909
  _KeystoneAdapter._throwIfAborted(signal);
1690
- const signature = args.parseResponse(responseUr);
1910
+ const signature = parseScannedAnswer(() => args.parseResponse(responseUr));
1691
1911
  _KeystoneAdapter._assertRequestIdMatches(requestId, signature.requestId);
1692
1912
  return (0, import_hwk_adapter_core3.success)(args.toPayload(signature));
1693
1913
  });
@@ -1737,7 +1957,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1737
1957
  }
1738
1958
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1739
1959
  return {
1740
- access: { channel: "usb", usbSessionId: record.usbSessionId },
1960
+ access: { channel: "usb", usbSessionId: record.usbSessionId, qrFallback: {} },
1741
1961
  masterFingerprint: record.masterFingerprint
1742
1962
  };
1743
1963
  }
@@ -1748,26 +1968,67 @@ var KeystoneAdapter = class _KeystoneAdapter {
1748
1968
  });
1749
1969
  }
1750
1970
  const schemas = Array.from(requestedByKey.values());
1751
- const requestUr = this.urEngine.buildKeyDerivationRequest({
1752
- schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1753
- origin: this._origin
1754
- });
1971
+ if (schemas.length > this._qrKeyRequestLimit) {
1972
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1973
+ code: import_hwk_adapter_core3.HardwareErrorCode.QrRequestTooLarge,
1974
+ message: `Keystone QR requests take at most ${this._qrKeyRequestLimit} account paths here; this one needs ${schemas.length}`,
1975
+ params: { limit: this._qrKeyRequestLimit, requested: schemas.length }
1976
+ });
1977
+ }
1978
+ const request = {
1979
+ ...this.urEngine.buildKeyDerivationRequest({
1980
+ schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1981
+ origin: this._origin
1982
+ }),
1983
+ animated: false,
1984
+ allowAccountExport: true
1985
+ };
1755
1986
  const responseUr = await this._requestQrAndAwaitResponse(
1756
1987
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1757
- { ...requestUr, animated: false },
1988
+ request,
1758
1989
  signal
1759
1990
  );
1760
1991
  _KeystoneAdapter._throwIfAborted(signal);
1761
- const parsed = this.urEngine.parseAccountResponse(responseUr);
1992
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1762
1993
  this._assertParsedIdentity(parsed, target);
1763
- for (const schema of schemas) {
1764
- scanned.set(accountKey(schema.hwkChain, schema.path), {
1765
- ...requireExportedPath(parsed, schema.path),
1766
- hwkChain: schema.hwkChain
1994
+ const firmware = getKeystoneFirmwareProfile(parsed.deviceVersion);
1995
+ const usableSchemas = schemas.filter(
1996
+ (schema) => !firmware || firmware.supportedChains.includes(schema.hwkChain)
1997
+ );
1998
+ const isColdStart = !target.expectedMasterFingerprint;
1999
+ if (firmware && isColdStart && !responseUr.accountExport && !usableSchemas.length) {
2000
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2001
+ code: import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
2002
+ message: `Keystone ${firmware.variant} firmware cannot use any requested chain`,
2003
+ params: { firmwareVariant: firmware.variant }
2004
+ });
2005
+ }
2006
+ for (const schema of usableSchemas) {
2007
+ const exported = responseUr.accountExport ? exportedAccountAt(parsed, schema.path) : requireExportedPath(parsed, schema.path);
2008
+ if (exported) {
2009
+ scanned.set(accountKey(schema.hwkChain, schema.path), {
2010
+ ...exported,
2011
+ hwkChain: schema.hwkChain
2012
+ });
2013
+ }
2014
+ }
2015
+ if (responseUr.accountExport && !scanned.size) {
2016
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2017
+ code: import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden,
2018
+ message: "Account export contains none of the requested supported account paths",
2019
+ params: { reason: "account-not-exported" }
1767
2020
  });
1768
2021
  }
1769
2022
  record = this._upsertDeviceRecord(parsed);
1770
- return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
2023
+ return {
2024
+ access: {
2025
+ channel: "qr",
2026
+ scanned,
2027
+ firmwareVersion: parsed.deviceVersion,
2028
+ ...responseUr.accountExport ? { accountExport: true } : {}
2029
+ },
2030
+ masterFingerprint: record.masterFingerprint
2031
+ };
1771
2032
  });
1772
2033
  }
1773
2034
  /**
@@ -1841,11 +2102,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
1841
2102
  record = createDeviceRecord(masterFingerprint);
1842
2103
  this._devices.set(masterFingerprint, record);
1843
2104
  }
1844
- record.model = parsed.device ?? record.model;
1845
- record.deviceVersion = parsed.deviceVersion ?? record.deviceVersion;
1846
- record.hardwareDeviceId = parsed.deviceId ?? record.hardwareDeviceId;
1847
- record.usbSessionId = options?.usbSessionId ?? record.usbSessionId;
1848
- if (!options?.viaUsb) record.qrSynced = true;
2105
+ record.model = parsed.device;
2106
+ record.hardwareDeviceId = parsed.deviceId;
2107
+ if (options?.usbSessionId) {
2108
+ record.usbSessionId = options.usbSessionId;
2109
+ record.usbFirmwareVersion = options.usbFirmwareVersion;
2110
+ record.hadUsbSession = true;
2111
+ }
2112
+ if (!options?.viaUsb) {
2113
+ record.deviceVersion = parsed.deviceVersion;
2114
+ record.qrSynced = true;
2115
+ }
1849
2116
  const info = toDeviceInfo(record);
1850
2117
  const eventType = isNew ? import_hwk_adapter_core3.DEVICE.CONNECT : import_hwk_adapter_core3.DEVICE.CHANGED;
1851
2118
  this.emitter.emit(eventType, { type: eventType, payload: info });
@@ -1871,7 +2138,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1871
2138
  signal.addEventListener("abort", onAbort, { once: true });
1872
2139
  const pending = this._usbConnectTail.then(async () => {
1873
2140
  _KeystoneAdapter._throwIfAborted(signal);
1874
- return this._connectUsbExclusive(connector, expected, searchTargetId, signal);
2141
+ if (this._unsettledUsbOperations.size > 0) {
2142
+ return (0, import_hwk_adapter_core3.failure)(
2143
+ import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal,
2144
+ "Keystone USB is still finishing an earlier request"
2145
+ );
2146
+ }
2147
+ const releaseConnect = this._retainUsbOperation("connect");
2148
+ try {
2149
+ return await this._connectUsbExclusive(connector, expected, searchTargetId, signal);
2150
+ } finally {
2151
+ releaseConnect();
2152
+ }
1875
2153
  });
1876
2154
  const settled = pending.finally(() => {
1877
2155
  signal.removeEventListener("abort", onAbort);
@@ -1918,16 +2196,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1918
2196
  }
1919
2197
  _KeystoneAdapter._throwIfAborted(signal);
1920
2198
  const record = this._upsertDeviceRecord(
1921
- { masterFingerprint, accounts: [] },
2199
+ {
2200
+ masterFingerprint,
2201
+ accounts: [],
2202
+ device: session.deviceInfo.modelName ?? session.deviceInfo.model
2203
+ },
1922
2204
  {
1923
2205
  viaUsb: true,
1924
- usbSessionId: session.sessionId
2206
+ usbSessionId: session.sessionId,
2207
+ usbFirmwareVersion: session.deviceInfo.firmwareVersion
1925
2208
  }
1926
2209
  );
1927
2210
  _KeystoneAdapter._throwIfAborted(signal);
1928
- record.hadUsbSession = true;
1929
- record.model = session.deviceInfo.modelName ?? session.deviceInfo.model ?? record.model;
1930
- record.deviceVersion = session.deviceInfo.firmwareVersion ?? record.deviceVersion;
1931
2211
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
1932
2212
  } catch (err) {
1933
2213
  if (sessionId) {
@@ -1941,7 +2221,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1941
2221
  }
1942
2222
  /**
1943
2223
  * Probes already-authorized USB devices without a permission picker, then attaches and verifies
1944
- * the requested wallet if present.
2224
+ * the requested wallet if present. Undefined means use QR: no device, or the user chose QR.
1945
2225
  */
1946
2226
  async _tryUsbAttach(signal, expectedMasterFingerprint, options) {
1947
2227
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1985,19 +2265,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
1985
2265
  signal
1986
2266
  );
1987
2267
  _KeystoneAdapter._throwIfAborted(signal);
1988
- if (!attached.success && (attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal || attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceOneDeviceOnly)) {
2268
+ if (attached.success) return this._devices.get(expectedMasterFingerprint);
2269
+ const { code } = attached.payload;
2270
+ if (code === import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal || code === import_hwk_adapter_core3.HardwareErrorCode.DeviceOneDeviceOnly) {
1989
2271
  throw (0, import_hwk_adapter_core3.createHwkError)({
1990
2272
  ...attached.payload,
1991
2273
  message: attached.payload.error
1992
2274
  });
1993
2275
  }
1994
- return attached.success ? this._devices.get(expectedMasterFingerprint) : void 0;
2276
+ if (code === import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound || this._forcedTransport) return void 0;
2277
+ const answer = await this._askQrFallback(
2278
+ signal,
2279
+ USB_ATTACH_FAILURE_REASONS[code] ?? "usb-unavailable"
2280
+ );
2281
+ if (answer === "retry") return this._tryUsbAttach(signal, expectedMasterFingerprint);
2282
+ if (answer === "cancel") {
2283
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2284
+ code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
2285
+ message: "User declined to continue by QR while the connected Keystone was unusable"
2286
+ });
2287
+ }
2288
+ return void 0;
1995
2289
  }
1996
2290
  /**
1997
2291
  * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
1998
2292
  * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
1999
2293
  */
2000
- async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
2294
+ async _resolveUr(record, requestUr, animated, operationId, signal, operationName, qrFallback) {
2001
2295
  const releaseOperationRetention = (0, import_hwk_adapter_core3.isHardwareOperationId)(operationId) ? this._operations.retain(operationId) : void 0;
2002
2296
  try {
2003
2297
  return await this._resolveUrWithRoute(
@@ -2006,13 +2300,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
2006
2300
  animated,
2007
2301
  operationId,
2008
2302
  signal,
2009
- operationName
2303
+ operationName,
2304
+ qrFallback
2010
2305
  );
2011
2306
  } finally {
2012
2307
  releaseOperationRetention?.();
2013
2308
  }
2014
2309
  }
2015
- async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName) {
2310
+ async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName, qrFallback) {
2016
2311
  let record = callerRecord;
2017
2312
  let interactionRoute;
2018
2313
  if ((0, import_hwk_adapter_core3.isHardwareOperationId)(operationId)) {
@@ -2051,13 +2346,31 @@ var KeystoneAdapter = class _KeystoneAdapter {
2051
2346
  requestUr,
2052
2347
  signal
2053
2348
  );
2054
- if (result.success) return result.payload;
2349
+ if (result.success) {
2350
+ const ur = result.payload;
2351
+ return { urType: ur.urType, urData: ur.urData, channel: "usb" };
2352
+ }
2055
2353
  const usbError = (0, import_hwk_adapter_core3.rehydrateConnectorError)(result.error);
2056
2354
  const { origin: usbErrorOrigin, code: usbErrorCode } = usbError;
2057
2355
  if (usbErrorCode === import_hwk_adapter_core3.HardwareErrorCode.PayloadTooLarge && usbErrorOrigin !== "device") {
2058
2356
  if (!interactionRoute && !this._forcedTransport) {
2357
+ if (!await this._confirmQrFallback(signal, qrFallback)) {
2358
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2359
+ code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
2360
+ message: "User declined to show the request too large for USB as a QR code"
2361
+ });
2362
+ }
2059
2363
  const displayDevice2 = toDeviceInfo(record);
2060
- return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2364
+ const responseUr = await this._requestQrAndAwaitResponse(
2365
+ displayDevice2,
2366
+ {
2367
+ ...requestUr,
2368
+ animated,
2369
+ ...!operationName ? { allowAccountExport: true } : {}
2370
+ },
2371
+ signal
2372
+ );
2373
+ return { ...responseUr, channel: "qr" };
2061
2374
  }
2062
2375
  throw usbError;
2063
2376
  }
@@ -2068,6 +2381,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2068
2381
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2069
2382
  }
2070
2383
  record.usbSessionId = void 0;
2384
+ record.usbFirmwareVersion = void 0;
2071
2385
  this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: toDeviceInfo(record) });
2072
2386
  if (interactionRoute) {
2073
2387
  throw this._endDisconnectedOperation(
@@ -2099,11 +2413,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2099
2413
  }
2100
2414
  const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
2101
2415
  try {
2102
- return await this._requestQrAndAwaitResponse(
2416
+ const responseUr = await this._requestQrAndAwaitResponse(
2103
2417
  displayDevice,
2104
- { ...requestUr, animated },
2418
+ { ...requestUr, animated, ...!operationName ? { allowAccountExport: true } : {} },
2105
2419
  signal
2106
2420
  );
2421
+ return { ...responseUr, channel: "qr" };
2107
2422
  } catch (error) {
2108
2423
  const { code, _tag: tag } = error;
2109
2424
  if (operationName && (code === import_hwk_adapter_core3.HardwareErrorCode.OperationTimeout || tag === import_hwk_adapter_core3.UI_REQUEST_TIMEOUT_TAG)) {
@@ -2137,6 +2452,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
2137
2452
  const target = this._resolveTarget(connectId, deviceId);
2138
2453
  if (bundle?.channel === "qr") {
2139
2454
  const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2455
+ if (target.record && !scanned && bundle.accountExport) {
2456
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2457
+ code: import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden,
2458
+ message: "Scanned account export does not include this account path",
2459
+ params: { reason: "account-not-exported" }
2460
+ });
2461
+ }
2462
+ this._assertQrChainSupported(bundle.firmwareVersion, hwkChain);
2140
2463
  if (!target.record || !scanned) {
2141
2464
  throw (0, import_hwk_adapter_core3.createHwkError)({
2142
2465
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
@@ -2151,19 +2474,27 @@ var KeystoneAdapter = class _KeystoneAdapter {
2151
2474
  message: "Keystone USB connection was lost during the bundle"
2152
2475
  });
2153
2476
  }
2154
- const operationConnectionType = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? this._operations.resolve(connectId).connectionType : void 0;
2155
2477
  let existingRecord = target.record;
2156
2478
  if (!existingRecord) {
2157
2479
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2158
2480
  _KeystoneAdapter._throwIfAborted(signal);
2159
2481
  }
2160
- const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2161
2482
  const schemas = [keySchema(hwkChain, syncPath)];
2162
2483
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2163
- const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2484
+ const responseUr = await this._resolveUr(
2485
+ existingRecord,
2486
+ requestUr,
2487
+ false,
2488
+ connectId,
2489
+ signal,
2490
+ void 0,
2491
+ bundle?.channel === "usb" ? bundle.qrFallback : void 0
2492
+ );
2164
2493
  _KeystoneAdapter._throwIfAborted(signal);
2165
- const parsed = this.urEngine.parseAccountResponse(responseUr);
2166
- const account = requireExportedPath(parsed, syncPath);
2494
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2495
+ this._assertParsedIdentity(parsed, target);
2496
+ const account = requireExportedPath(parsed, syncPath, responseUr.accountExport);
2497
+ const useSinglePathUsbExport = !responseUr.accountExport && responseUr.channel === "usb";
2167
2498
  let record;
2168
2499
  if (useSinglePathUsbExport && existingRecord) {
2169
2500
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2174,23 +2505,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
2174
2505
  }
2175
2506
  record = existingRecord;
2176
2507
  } else {
2177
- this._assertParsedIdentity(parsed, target);
2178
- record = this._upsertDeviceRecord(parsed, {
2179
- viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2180
- });
2508
+ this._assertQrChainSupported(parsed.deviceVersion, hwkChain);
2509
+ record = this._upsertDeviceRecord(parsed);
2181
2510
  }
2182
2511
  return { record, account: { ...account, hwkChain } };
2183
2512
  }
2184
2513
  /**
2185
- * Resolves which wallet is attached, without a per-path account. `CHAIN_FINGERPRINT_PATHS.evm` is
2186
- * a leaf path, so it is cut to the account path Keystone expects.
2514
+ * Resolves wallet identity without a per-path account. A caller-supplied fingerprint needs no
2515
+ * device round trip; otherwise request the account path from the device.
2187
2516
  */
2188
2517
  async _ensureWalletKnown(connectId, deviceId, chain, signal) {
2189
2518
  const target = this._resolveTarget(connectId, deviceId);
2190
2519
  if (target.record) return { record: target.record };
2191
- const attached = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2192
- _KeystoneAdapter._throwIfAborted(signal);
2193
- if (attached) return { record: attached };
2194
2520
  if (target.expectedMasterFingerprint) {
2195
2521
  return { record: createDeviceRecord(target.expectedMasterFingerprint) };
2196
2522
  }
@@ -2201,19 +2527,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
2201
2527
  });
2202
2528
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2203
2529
  _KeystoneAdapter._throwIfAborted(signal);
2204
- const parsed = this.urEngine.parseAccountResponse(responseUr);
2205
- requireExportedPath(parsed, normalizePath(accountPath));
2206
- return { record: this._upsertDeviceRecord(parsed) };
2530
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2531
+ if (!responseUr.accountExport) requireExportedPath(parsed, normalizePath(accountPath));
2532
+ this._assertQrChainSupported(parsed.deviceVersion, chain);
2533
+ const record = this._upsertDeviceRecord(parsed);
2534
+ return { record };
2535
+ }
2536
+ _assertQrChainSupported(firmwareVersion, chain) {
2537
+ const firmware = getKeystoneFirmwareProfile(firmwareVersion);
2538
+ if (firmware && !firmware.supportedChains.includes(chain)) {
2539
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2540
+ code: import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
2541
+ message: `Keystone ${firmware.variant} firmware cannot use ${chain} through this adapter`,
2542
+ params: { firmwareVariant: firmware.variant, chain }
2543
+ });
2544
+ }
2207
2545
  }
2208
- /**
2209
- * The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
2210
- * through the operation route; a cold start returns undefined.
2211
- */
2546
+ /** Only an operation id supplied to the running call owns its UI prompts. */
2212
2547
  _activeOperationId() {
2213
- const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
2214
- if (!activeJobId) return void 0;
2215
- if ((0, import_hwk_adapter_core3.isHardwareOperationId)(activeJobId)) return activeJobId;
2216
- return this._operationRouteForIdentifier(activeJobId)?.operationId;
2548
+ return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
2217
2549
  }
2218
2550
  /** Routes are keyed by connectId; a job key may be the bare master fingerprint. */
2219
2551
  _operationRouteForIdentifier(identifier) {
@@ -2246,6 +2578,43 @@ var KeystoneAdapter = class _KeystoneAdapter {
2246
2578
  signal.removeEventListener("abort", onAbort);
2247
2579
  }
2248
2580
  }
2581
+ /**
2582
+ * Asks whether a request too large for USB may be shown as a QR. A timeout or an unanswered
2583
+ * prompt reads as no; a cancelled call keeps its own error.
2584
+ */
2585
+ async _confirmQrFallback(signal, choice) {
2586
+ if (choice?.confirmed !== void 0) return choice.confirmed;
2587
+ const confirmed = await this._askQrFallback(signal, "payload-too-large") === "qr";
2588
+ if (choice) choice.confirmed = confirmed;
2589
+ return confirmed;
2590
+ }
2591
+ /** A timeout or an unanswered prompt reads as cancel; a cancelled call keeps its own error. */
2592
+ async _askQrFallback(signal, reason) {
2593
+ const requestType = import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_FALLBACK_CONFIRM;
2594
+ const requestId = this._uiRegistry.createRequestId();
2595
+ const operationId = this._activeOperationId();
2596
+ const release = operationId ? this._operations.retain(operationId) : void 0;
2597
+ try {
2598
+ const waitPromise = this._uiRegistry.wait(
2599
+ requestType,
2600
+ { requestId, operationId }
2601
+ );
2602
+ this.emitter.emit(requestType, {
2603
+ type: requestType,
2604
+ payload: { vendor: "keystone", requestId, operationId, reason }
2605
+ });
2606
+ let answer;
2607
+ try {
2608
+ answer = await this._awaitQrResponse(requestType, waitPromise, signal);
2609
+ } catch (error) {
2610
+ if (signal.aborted) throw error;
2611
+ }
2612
+ if (answer?.retry && reason !== "payload-too-large") return "retry";
2613
+ return answer?.confirmed ? "qr" : "cancel";
2614
+ } finally {
2615
+ release?.();
2616
+ }
2617
+ }
2249
2618
  /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2250
2619
  async _requestQrAndAwaitResponse(device, data, signal) {
2251
2620
  const requestType = data ? import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY : import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN;
@@ -2268,7 +2637,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
2268
2637
  });
2269
2638
  }
2270
2639
  const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2271
- return { urType: response.urType, urData: response.urData };
2640
+ if (response.accountExport && data && !data.allowAccountExport) {
2641
+ throw unexpectedQrCodeError("This request cannot be answered with an account export");
2642
+ }
2643
+ return {
2644
+ urType: response.urType,
2645
+ urData: response.urData,
2646
+ ...!data || response.accountExport ? { accountExport: true } : {}
2647
+ };
2272
2648
  } finally {
2273
2649
  release?.();
2274
2650
  }
@@ -2374,10 +2750,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
2374
2750
  /** A response without the request's id is as unrelated as one with another id. */
2375
2751
  static _assertRequestIdMatches(expected, actual) {
2376
2752
  if (!actual || actual.toLowerCase() !== expected.toLowerCase()) {
2377
- throw (0, import_hwk_adapter_core3.createHwkError)({
2378
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2379
- message: actual ? "Keystone response requestId does not match the pending request \u2014 discarding a stale or unrelated scan" : "Keystone response carries no requestId \u2014 discarding a stale or unrelated scan"
2380
- });
2753
+ throw unexpectedQrCodeError(
2754
+ actual ? "Keystone response requestId does not match the pending request \u2014 discarding a stale or unrelated scan" : "Keystone response carries no requestId \u2014 discarding a stale or unrelated scan",
2755
+ import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
2756
+ );
2381
2757
  }
2382
2758
  }
2383
2759
  _unsupported(method, reason) {