@onekeyfe/hwk-keystone-adapter 1.2.8-alpha.54 → 1.2.9

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
  }
@@ -529,12 +645,15 @@ function accountKey(hwkChain, path) {
529
645
  function createDeviceRecord(masterFingerprint) {
530
646
  return {
531
647
  masterFingerprint,
532
- connectId: walletConnectId(masterFingerprint),
533
- importedAt: Date.now()
648
+ connectId: walletConnectId(masterFingerprint)
534
649
  };
535
650
  }
536
651
  var CAPABILITIES = { persistentDeviceIdentity: true };
537
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;
538
657
  let availableChannels = ["qr"];
539
658
  if (record.usbSessionId) {
540
659
  availableChannels = record.qrSynced ? ["qr", "usb"] : ["usb"];
@@ -543,11 +662,13 @@ function toDeviceInfo(record) {
543
662
  vendor: "keystone",
544
663
  model: record.model ?? "unknown",
545
664
  modelName: record.model,
546
- firmwareVersion: record.deviceVersion ?? "0.0.0",
665
+ firmwareVersion: firmwareVersion ?? "0.0.0",
547
666
  deviceId: record.masterFingerprint,
548
667
  connectId: record.connectId,
549
- connectionType: record.usbSessionId ? "usb" : "qr",
550
- capabilities: CAPABILITIES,
668
+ connectionType,
669
+ capabilities: {
670
+ ...CAPABILITIES
671
+ },
551
672
  raw: {
552
673
  availableChannels,
553
674
  masterFingerprint: record.masterFingerprint,
@@ -567,6 +688,31 @@ function placeholderDeviceInfo() {
567
688
  };
568
689
  }
569
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
+
570
716
  // src/utils/queueKey.ts
571
717
  var import_hwk_adapter_core2 = require("@onekeyfe/hwk-adapter-core");
572
718
  var KEYSTONE_COLD_START_JOB_LABEL = "keystone-cold-start";
@@ -606,10 +752,36 @@ function keystoneBtcParamsFailure(params) {
606
752
  }
607
753
  return void 0;
608
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;
609
761
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
610
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
+ }
611
779
  function keySchema(chain, path) {
612
- return { path, curve: chain === "sol" ? "ed25519" : "secp256k1" };
780
+ return {
781
+ path,
782
+ curve: chain === "sol" ? "ed25519" : "secp256k1",
783
+ chainType: hardwareCallChainType(chain, path)
784
+ };
613
785
  }
614
786
  function waitForKeystoneUsbReattachProbe() {
615
787
  return new Promise((resolve) => {
@@ -633,12 +805,42 @@ function exactHex(value) {
633
805
  function invalidHexFailure(field) {
634
806
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${field} must be an even-length hex string`);
635
807
  }
636
- function requireExportedPath(parsed, path) {
637
- 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);
638
839
  if (!account) {
639
840
  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})`
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" } } : {}
642
844
  });
643
845
  }
644
846
  return account;
@@ -652,7 +854,9 @@ function coinTypeFailure(chain, path) {
652
854
  }
653
855
  function btcAccountFailure(accountPath) {
654
856
  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);
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
+ });
656
860
  }
657
861
  function missingParamFailure(method, param) {
658
862
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${method} requires ${param}`);
@@ -664,6 +868,10 @@ function evmMessageSignature(sig) {
664
868
  return { signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) };
665
869
  }
666
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
+ */
667
875
  constructor(options) {
668
876
  this.vendor = "keystone";
669
877
  // No protocol-level cancel exists over Keystone USB, and QR has no transport
@@ -684,11 +892,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
684
892
  params: { operationId: operation.operationId, reason }
685
893
  });
686
894
  const queueKey = keystoneQueueKey(operation.operationId);
687
- const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
688
895
  this._jobQueue.cancelActiveAndPending(queueKey, ended);
689
- if (ownsRunningCall) {
690
- this._uiRegistry.cancel(void 0, void 0, operation.operationId);
691
- }
896
+ this._uiRegistry.cancel(void 0, void 0, operation.operationId);
692
897
  }
693
898
  }
694
899
  this.emitter.emit(import_hwk_adapter_core3.SDK.OPERATION_ENDED, {
@@ -715,6 +920,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
715
920
  if (!record) return;
716
921
  this._operations.endByConnectionKey(connectId, "disconnect");
717
922
  record.usbSessionId = void 0;
923
+ record.usbFirmwareVersion = void 0;
718
924
  const info = toDeviceInfo(record);
719
925
  if (record.qrSynced) {
720
926
  this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: info });
@@ -724,7 +930,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
724
930
  }
725
931
  };
726
932
  this._handleUsbUiEvent = (event) => {
727
- this.emitter.emit("ui-event", event);
933
+ const operationId = this._activeOperationId();
934
+ this.emitter.emit("ui-event", operationId ? { ...event, operationId } : event);
728
935
  };
729
936
  // ---------------------------------------------------------------------------
730
937
  // All-network bundle, dispatched to the per-chain methods below.
@@ -797,6 +1004,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
797
1004
  success: true,
798
1005
  payload: {
799
1006
  ...context.payload,
1007
+ ...access?.channel === "qr" && access.accountExport ? { accountExport: true } : {},
800
1008
  rootFingerprint: record ? Number.parseInt(record.masterFingerprint, 16) : void 0,
801
1009
  deviceIdentity: record ? {
802
1010
  vendor: "keystone",
@@ -822,6 +1030,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
822
1030
  };
823
1031
  this._origin = options?.origin ?? "OneKey";
824
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;
825
1035
  this.urEngine = new KeystoneUrEngine(this._origin);
826
1036
  this._jobQueue = new import_hwk_adapter_core3.DeviceJobQueue();
827
1037
  this._usbConnector = options?.usbConnector;
@@ -1046,23 +1256,24 @@ var KeystoneAdapter = class _KeystoneAdapter {
1046
1256
  }
1047
1257
  getDeviceInfo(connectIdOrOperationId, deviceId) {
1048
1258
  try {
1049
- 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;
1050
1261
  const { record } = this._resolveTarget(connectId, deviceId);
1051
1262
  if (!record) {
1052
1263
  return Promise.resolve(
1053
1264
  (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound, "Unknown Keystone device")
1054
1265
  );
1055
1266
  }
1056
- 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));
1057
1269
  } catch (err) {
1058
1270
  return Promise.resolve(this._errorToFailure(err));
1059
1271
  }
1060
1272
  }
1061
1273
  cancel(connectId) {
1062
- let namedOperationConnectId;
1063
1274
  if ((0, import_hwk_adapter_core3.isHardwareOperationId)(connectId)) {
1064
1275
  try {
1065
- namedOperationConnectId = this._operations.resolve(connectId).connectId;
1276
+ this._operations.resolve(connectId);
1066
1277
  } catch {
1067
1278
  return;
1068
1279
  }
@@ -1072,15 +1283,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1072
1283
  message: "User aborted operation"
1073
1284
  });
1074
1285
  if (connectId) {
1286
+ const scopedOperationId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1075
1287
  const queueKeys = keystoneCancelQueueKeys([
1076
1288
  connectId,
1077
- this._operationRoutes.get(connectId)?.operationId,
1078
- namedOperationConnectId
1289
+ this._operationRoutes.get(connectId)?.operationId
1079
1290
  ]);
1080
1291
  for (const key of queueKeys) {
1081
1292
  this._jobQueue.cancelActiveAndPending(key, reason);
1082
1293
  }
1083
- const scopedOperationId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1084
1294
  if (scopedOperationId) {
1085
1295
  this._uiRegistry.cancel(void 0, void 0, scopedOperationId);
1086
1296
  }
@@ -1142,13 +1352,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1142
1352
  });
1143
1353
  responseUr = await this._requestQrAndAwaitResponse(
1144
1354
  displayDevice,
1145
- { ...requestUr, animated: false },
1355
+ { ...requestUr, animated: false, allowAccountExport: true },
1146
1356
  signal
1147
1357
  );
1148
1358
  }
1149
1359
  _KeystoneAdapter._throwIfAborted(signal);
1150
- const parsed = this.urEngine.parseAccountResponse(responseUr);
1151
- 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);
1152
1362
  const record = this._upsertDeviceRecord(parsed);
1153
1363
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
1154
1364
  });
@@ -1348,7 +1558,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
1348
1558
  "btcSignPsbt"
1349
1559
  );
1350
1560
  _KeystoneAdapter._throwIfAborted(signal);
1351
- const signedPsbt = this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex);
1561
+ const signedPsbt = parseScannedAnswer(
1562
+ () => this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex)
1563
+ );
1352
1564
  return (0, import_hwk_adapter_core3.success)({ signedPsbt });
1353
1565
  });
1354
1566
  }
@@ -1695,7 +1907,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1695
1907
  args.operationName
1696
1908
  );
1697
1909
  _KeystoneAdapter._throwIfAborted(signal);
1698
- const signature = args.parseResponse(responseUr);
1910
+ const signature = parseScannedAnswer(() => args.parseResponse(responseUr));
1699
1911
  _KeystoneAdapter._assertRequestIdMatches(requestId, signature.requestId);
1700
1912
  return (0, import_hwk_adapter_core3.success)(args.toPayload(signature));
1701
1913
  });
@@ -1745,7 +1957,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1745
1957
  }
1746
1958
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1747
1959
  return {
1748
- access: { channel: "usb", usbSessionId: record.usbSessionId },
1960
+ access: { channel: "usb", usbSessionId: record.usbSessionId, qrFallback: {} },
1749
1961
  masterFingerprint: record.masterFingerprint
1750
1962
  };
1751
1963
  }
@@ -1756,26 +1968,67 @@ var KeystoneAdapter = class _KeystoneAdapter {
1756
1968
  });
1757
1969
  }
1758
1970
  const schemas = Array.from(requestedByKey.values());
1759
- const requestUr = this.urEngine.buildKeyDerivationRequest({
1760
- schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1761
- origin: this._origin
1762
- });
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
+ };
1763
1986
  const responseUr = await this._requestQrAndAwaitResponse(
1764
1987
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1765
- { ...requestUr, animated: false },
1988
+ request,
1766
1989
  signal
1767
1990
  );
1768
1991
  _KeystoneAdapter._throwIfAborted(signal);
1769
- const parsed = this.urEngine.parseAccountResponse(responseUr);
1992
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1770
1993
  this._assertParsedIdentity(parsed, target);
1771
- for (const schema of schemas) {
1772
- scanned.set(accountKey(schema.hwkChain, schema.path), {
1773
- ...requireExportedPath(parsed, schema.path),
1774
- 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" }
1775
2020
  });
1776
2021
  }
1777
2022
  record = this._upsertDeviceRecord(parsed);
1778
- 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
+ };
1779
2032
  });
1780
2033
  }
1781
2034
  /**
@@ -1849,11 +2102,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
1849
2102
  record = createDeviceRecord(masterFingerprint);
1850
2103
  this._devices.set(masterFingerprint, record);
1851
2104
  }
1852
- record.model = parsed.device ?? record.model;
1853
- record.deviceVersion = parsed.deviceVersion ?? record.deviceVersion;
1854
- record.hardwareDeviceId = parsed.deviceId ?? record.hardwareDeviceId;
1855
- record.usbSessionId = options?.usbSessionId ?? record.usbSessionId;
1856
- 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
+ }
1857
2116
  const info = toDeviceInfo(record);
1858
2117
  const eventType = isNew ? import_hwk_adapter_core3.DEVICE.CONNECT : import_hwk_adapter_core3.DEVICE.CHANGED;
1859
2118
  this.emitter.emit(eventType, { type: eventType, payload: info });
@@ -1937,16 +2196,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1937
2196
  }
1938
2197
  _KeystoneAdapter._throwIfAborted(signal);
1939
2198
  const record = this._upsertDeviceRecord(
1940
- { masterFingerprint, accounts: [] },
2199
+ {
2200
+ masterFingerprint,
2201
+ accounts: [],
2202
+ device: session.deviceInfo.modelName ?? session.deviceInfo.model
2203
+ },
1941
2204
  {
1942
2205
  viaUsb: true,
1943
- usbSessionId: session.sessionId
2206
+ usbSessionId: session.sessionId,
2207
+ usbFirmwareVersion: session.deviceInfo.firmwareVersion
1944
2208
  }
1945
2209
  );
1946
2210
  _KeystoneAdapter._throwIfAborted(signal);
1947
- record.hadUsbSession = true;
1948
- record.model = session.deviceInfo.modelName ?? session.deviceInfo.model ?? record.model;
1949
- record.deviceVersion = session.deviceInfo.firmwareVersion ?? record.deviceVersion;
1950
2211
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
1951
2212
  } catch (err) {
1952
2213
  if (sessionId) {
@@ -1960,7 +2221,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1960
2221
  }
1961
2222
  /**
1962
2223
  * Probes already-authorized USB devices without a permission picker, then attaches and verifies
1963
- * the requested wallet if present.
2224
+ * the requested wallet if present. Undefined means use QR: no device, or the user chose QR.
1964
2225
  */
1965
2226
  async _tryUsbAttach(signal, expectedMasterFingerprint, options) {
1966
2227
  _KeystoneAdapter._throwIfAborted(signal);
@@ -2004,19 +2265,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
2004
2265
  signal
2005
2266
  );
2006
2267
  _KeystoneAdapter._throwIfAborted(signal);
2007
- 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) {
2008
2271
  throw (0, import_hwk_adapter_core3.createHwkError)({
2009
2272
  ...attached.payload,
2010
2273
  message: attached.payload.error
2011
2274
  });
2012
2275
  }
2013
- 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;
2014
2289
  }
2015
2290
  /**
2016
2291
  * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
2017
2292
  * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
2018
2293
  */
2019
- async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
2294
+ async _resolveUr(record, requestUr, animated, operationId, signal, operationName, qrFallback) {
2020
2295
  const releaseOperationRetention = (0, import_hwk_adapter_core3.isHardwareOperationId)(operationId) ? this._operations.retain(operationId) : void 0;
2021
2296
  try {
2022
2297
  return await this._resolveUrWithRoute(
@@ -2025,13 +2300,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
2025
2300
  animated,
2026
2301
  operationId,
2027
2302
  signal,
2028
- operationName
2303
+ operationName,
2304
+ qrFallback
2029
2305
  );
2030
2306
  } finally {
2031
2307
  releaseOperationRetention?.();
2032
2308
  }
2033
2309
  }
2034
- async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName) {
2310
+ async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName, qrFallback) {
2035
2311
  let record = callerRecord;
2036
2312
  let interactionRoute;
2037
2313
  if ((0, import_hwk_adapter_core3.isHardwareOperationId)(operationId)) {
@@ -2070,13 +2346,31 @@ var KeystoneAdapter = class _KeystoneAdapter {
2070
2346
  requestUr,
2071
2347
  signal
2072
2348
  );
2073
- 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
+ }
2074
2353
  const usbError = (0, import_hwk_adapter_core3.rehydrateConnectorError)(result.error);
2075
2354
  const { origin: usbErrorOrigin, code: usbErrorCode } = usbError;
2076
2355
  if (usbErrorCode === import_hwk_adapter_core3.HardwareErrorCode.PayloadTooLarge && usbErrorOrigin !== "device") {
2077
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
+ }
2078
2363
  const displayDevice2 = toDeviceInfo(record);
2079
- 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" };
2080
2374
  }
2081
2375
  throw usbError;
2082
2376
  }
@@ -2087,6 +2381,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2087
2381
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2088
2382
  }
2089
2383
  record.usbSessionId = void 0;
2384
+ record.usbFirmwareVersion = void 0;
2090
2385
  this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: toDeviceInfo(record) });
2091
2386
  if (interactionRoute) {
2092
2387
  throw this._endDisconnectedOperation(
@@ -2118,11 +2413,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2118
2413
  }
2119
2414
  const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
2120
2415
  try {
2121
- return await this._requestQrAndAwaitResponse(
2416
+ const responseUr = await this._requestQrAndAwaitResponse(
2122
2417
  displayDevice,
2123
- { ...requestUr, animated },
2418
+ { ...requestUr, animated, ...!operationName ? { allowAccountExport: true } : {} },
2124
2419
  signal
2125
2420
  );
2421
+ return { ...responseUr, channel: "qr" };
2126
2422
  } catch (error) {
2127
2423
  const { code, _tag: tag } = error;
2128
2424
  if (operationName && (code === import_hwk_adapter_core3.HardwareErrorCode.OperationTimeout || tag === import_hwk_adapter_core3.UI_REQUEST_TIMEOUT_TAG)) {
@@ -2156,6 +2452,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
2156
2452
  const target = this._resolveTarget(connectId, deviceId);
2157
2453
  if (bundle?.channel === "qr") {
2158
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);
2159
2463
  if (!target.record || !scanned) {
2160
2464
  throw (0, import_hwk_adapter_core3.createHwkError)({
2161
2465
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
@@ -2170,19 +2474,27 @@ var KeystoneAdapter = class _KeystoneAdapter {
2170
2474
  message: "Keystone USB connection was lost during the bundle"
2171
2475
  });
2172
2476
  }
2173
- const operationConnectionType = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? this._operations.resolve(connectId).connectionType : void 0;
2174
2477
  let existingRecord = target.record;
2175
2478
  if (!existingRecord) {
2176
2479
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2177
2480
  _KeystoneAdapter._throwIfAborted(signal);
2178
2481
  }
2179
- const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2180
2482
  const schemas = [keySchema(hwkChain, syncPath)];
2181
2483
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2182
- 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
+ );
2183
2493
  _KeystoneAdapter._throwIfAborted(signal);
2184
- const parsed = this.urEngine.parseAccountResponse(responseUr);
2185
- 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";
2186
2498
  let record;
2187
2499
  if (useSinglePathUsbExport && existingRecord) {
2188
2500
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2193,23 +2505,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
2193
2505
  }
2194
2506
  record = existingRecord;
2195
2507
  } else {
2196
- this._assertParsedIdentity(parsed, target);
2197
- record = this._upsertDeviceRecord(parsed, {
2198
- viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2199
- });
2508
+ this._assertQrChainSupported(parsed.deviceVersion, hwkChain);
2509
+ record = this._upsertDeviceRecord(parsed);
2200
2510
  }
2201
2511
  return { record, account: { ...account, hwkChain } };
2202
2512
  }
2203
2513
  /**
2204
- * Resolves which wallet is attached, without a per-path account. `CHAIN_FINGERPRINT_PATHS.evm` is
2205
- * 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.
2206
2516
  */
2207
2517
  async _ensureWalletKnown(connectId, deviceId, chain, signal) {
2208
2518
  const target = this._resolveTarget(connectId, deviceId);
2209
2519
  if (target.record) return { record: target.record };
2210
- const attached = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2211
- _KeystoneAdapter._throwIfAborted(signal);
2212
- if (attached) return { record: attached };
2213
2520
  if (target.expectedMasterFingerprint) {
2214
2521
  return { record: createDeviceRecord(target.expectedMasterFingerprint) };
2215
2522
  }
@@ -2220,19 +2527,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
2220
2527
  });
2221
2528
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2222
2529
  _KeystoneAdapter._throwIfAborted(signal);
2223
- const parsed = this.urEngine.parseAccountResponse(responseUr);
2224
- requireExportedPath(parsed, normalizePath(accountPath));
2225
- 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
+ }
2226
2545
  }
2227
- /**
2228
- * The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
2229
- * through the operation route; a cold start returns undefined.
2230
- */
2546
+ /** Only an operation id supplied to the running call owns its UI prompts. */
2231
2547
  _activeOperationId() {
2232
- const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
2233
- if (!activeJobId) return void 0;
2234
- if ((0, import_hwk_adapter_core3.isHardwareOperationId)(activeJobId)) return activeJobId;
2235
- return this._operationRouteForIdentifier(activeJobId)?.operationId;
2548
+ return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
2236
2549
  }
2237
2550
  /** Routes are keyed by connectId; a job key may be the bare master fingerprint. */
2238
2551
  _operationRouteForIdentifier(identifier) {
@@ -2265,6 +2578,43 @@ var KeystoneAdapter = class _KeystoneAdapter {
2265
2578
  signal.removeEventListener("abort", onAbort);
2266
2579
  }
2267
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
+ }
2268
2618
  /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2269
2619
  async _requestQrAndAwaitResponse(device, data, signal) {
2270
2620
  const requestType = data ? import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY : import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN;
@@ -2287,7 +2637,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
2287
2637
  });
2288
2638
  }
2289
2639
  const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2290
- 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
+ };
2291
2648
  } finally {
2292
2649
  release?.();
2293
2650
  }
@@ -2393,10 +2750,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
2393
2750
  /** A response without the request's id is as unrelated as one with another id. */
2394
2751
  static _assertRequestIdMatches(expected, actual) {
2395
2752
  if (!actual || actual.toLowerCase() !== expected.toLowerCase()) {
2396
- throw (0, import_hwk_adapter_core3.createHwkError)({
2397
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2398
- 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"
2399
- });
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
+ );
2400
2757
  }
2401
2758
  }
2402
2759
  _unsupported(method, reason) {