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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,13 @@
1
1
  // src/urEngine/KeystoneUrEngine.ts
2
2
  import { generateAddressFromXpub } from "@keystonehq/bc-ur-registry-eth";
3
+ import {
4
+ CryptoAccount,
5
+ CryptoHDKey,
6
+ CryptoMultiAccounts,
7
+ ScriptExpressions,
8
+ extend as extend3
9
+ } from "@keystonehq/bc-ur-registry";
10
+ import { ScriptExpression } from "@keystonehq/bc-ur-registry/dist/ScriptExpression.js";
3
11
  import { Curve, KeystoneSDK, QRHardwareCallVersion, UR } from "@keystonehq/keystone-sdk";
4
12
  import bs58check from "bs58check";
5
13
  import * as bitcoin from "bitcoinjs-lib";
@@ -179,6 +187,35 @@ function toParsedAccount(key) {
179
187
  };
180
188
  }
181
189
  var BIP32_HARDENED_OFFSET = 2147483648;
190
+ function isExportedAccountPath(path) {
191
+ return /^m(?:\/\d+')+(?:\/\d+)*$/.test(path) && path.slice(2).split("/").every(
192
+ (segment) => Number(segment.endsWith("'") ? segment.slice(0, -1) : segment) < BIP32_HARDENED_OFFSET
193
+ );
194
+ }
195
+ function checkExportedKey(key, account, masterFingerprint, unsupportedDescriptor) {
196
+ if (unsupportedDescriptor || key.isMaster() || key.isPrivateKey()) {
197
+ return { rejected: "unusable-key" };
198
+ }
199
+ const source = key.getOrigin()?.getSourceFingerprint();
200
+ if (source && source.toString("hex") !== masterFingerprint) {
201
+ return { rejected: "different-wallet" };
202
+ }
203
+ if (!account.extendedPublicKey) {
204
+ return /^[0-9a-f]{64}$/i.test(account.publicKey) ? { identity: account.publicKey } : { rejected: "unusable-key" };
205
+ }
206
+ try {
207
+ const node = HDKey.fromExtendedKey(account.extendedPublicKey);
208
+ if (node.privateKey || !node.publicKey || !node.chainCode || node.publicKey.toString("hex") !== account.publicKey.toLowerCase()) {
209
+ return { rejected: "unusable-key" };
210
+ }
211
+ return { identity: `${account.publicKey}:${node.chainCode.toString("hex")}` };
212
+ } catch {
213
+ return { rejected: "unusable-key" };
214
+ }
215
+ }
216
+ function unexpectedQrCodeError(message, code = HardwareErrorCode.InvalidParams) {
217
+ return createHwkError({ code, message, params: { reason: "unexpected-qr-code" } });
218
+ }
182
219
  function relativeHdPath(relativeDerivePath) {
183
220
  const segments = relativeDerivePath.replace(/^m\//i, "").split("/");
184
221
  const valid = segments.every(
@@ -192,7 +229,7 @@ function relativeHdPath(relativeDerivePath) {
192
229
  }
193
230
  return `m/${segments.join("/")}`;
194
231
  }
195
- var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.]{1,20})?$/;
232
+ var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.-]{1,20})?$/;
196
233
  var DEVICE_TEXT = /^[^\p{Cc}\p{Cf}]{1,64}$/u;
197
234
  function deviceText(value, pattern) {
198
235
  return typeof value === "string" && pattern.test(value) ? value : void 0;
@@ -223,7 +260,8 @@ var KeystoneUrEngine = class {
223
260
  const ur = this.sdk.generateKeyDerivationCall({
224
261
  schemas: input.schemas.map((schema) => ({
225
262
  path: schema.path,
226
- curve: DERIVATION_CURVE[schema.curve ?? "secp256k1"]
263
+ curve: DERIVATION_CURVE[schema.curve ?? "secp256k1"],
264
+ chainType: schema.chainType
227
265
  })),
228
266
  origin: input.origin,
229
267
  version: QRHardwareCallVersion.V1
@@ -247,6 +285,90 @@ var KeystoneUrEngine = class {
247
285
  }
248
286
  return this.parseMultiAccounts(ur);
249
287
  }
288
+ /**
289
+ * Device exports are opt-in: request responses retain their existing format/path checks. An
290
+ * export carries whatever the device syncs to other wallets, so each key is checked on its own: a
291
+ * key that fails lands in `rejectedPaths` instead of discarding the whole export.
292
+ */
293
+ parseAccountExport(ur) {
294
+ let parsed;
295
+ let keys;
296
+ const unsupportedDescriptors = /* @__PURE__ */ new Set();
297
+ try {
298
+ const { cbor } = toSdkUr(ur);
299
+ if (ur.urType === "crypto-account") {
300
+ if (!Object.values(ScriptExpressions).some((script) => script.getTag() === 409)) {
301
+ Object.assign(ScriptExpressions, { TAPROOT: new ScriptExpression(409, "tr") });
302
+ }
303
+ extend3.cbor.patchTags([409]);
304
+ const account = CryptoAccount.fromCBOR(cbor);
305
+ keys = account.getOutputDescriptors().map((output, index) => {
306
+ const key = output.getHDKey();
307
+ const path = key?.getOrigin()?.getPath();
308
+ const script = output.getScriptExpressions().map((item) => item.getExpression()).join("/");
309
+ 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";
310
+ const children = key?.getChildren();
311
+ if (!key) throw new Error("Unsupported account descriptor");
312
+ if (!validScript || children && children.getPath() !== "0/*") {
313
+ unsupportedDescriptors.add(index);
314
+ }
315
+ return key;
316
+ });
317
+ const result = this.sdk.parseAccount(toSdkUr(ur));
318
+ parsed = {
319
+ masterFingerprint: requireBip32MasterFingerprint(result.masterFingerprint),
320
+ accounts: result.keys.map(toParsedAccount)
321
+ };
322
+ } else if (ur.urType === "crypto-multi-accounts") {
323
+ keys = CryptoMultiAccounts.fromCBOR(cbor).getKeys();
324
+ parsed = this.parseMultiAccounts(ur);
325
+ } else if (ur.urType === "crypto-hdkey") {
326
+ keys = [CryptoHDKey.fromCBOR(cbor)];
327
+ parsed = this.parseAccountResponse(ur);
328
+ } else {
329
+ throw new Error("Unsupported account export type");
330
+ }
331
+ if (!keys.length || keys.length !== parsed.accounts.length) {
332
+ throw new Error("Empty account export");
333
+ }
334
+ } catch {
335
+ throw unexpectedQrCodeError(
336
+ "Unable to read account export; scan a supported Keystone account export code"
337
+ );
338
+ }
339
+ const byPath = /* @__PURE__ */ new Map();
340
+ parsed.accounts.forEach((account, index) => {
341
+ if (!isExportedAccountPath(account.path)) return;
342
+ const entry = byPath.get(account.path) ?? {};
343
+ byPath.set(account.path, entry);
344
+ const check = checkExportedKey(
345
+ keys[index],
346
+ account,
347
+ parsed.masterFingerprint,
348
+ unsupportedDescriptors.has(index)
349
+ );
350
+ if (check.rejected === "different-wallet") {
351
+ entry.rejected = check.rejected;
352
+ } else if (check.identity === void 0) {
353
+ entry.rejected ?? (entry.rejected = check.rejected);
354
+ } else if (entry.identity === void 0) {
355
+ entry.account = account;
356
+ entry.identity = check.identity;
357
+ } else if (entry.identity !== check.identity && entry.rejected !== "different-wallet") {
358
+ entry.rejected = "conflicting-keys";
359
+ }
360
+ });
361
+ const accounts = [];
362
+ const rejectedPaths = [];
363
+ byPath.forEach((entry, path) => {
364
+ if (entry.account && entry.rejected !== "different-wallet" && entry.rejected !== "conflicting-keys") {
365
+ accounts.push(entry.account);
366
+ } else if (entry.rejected) {
367
+ rejectedPaths.push({ path, reason: entry.rejected });
368
+ }
369
+ });
370
+ return { ...parsed, accounts, rejectedPaths };
371
+ }
250
372
  // --- EVM ---
251
373
  buildEthSignRequest(input) {
252
374
  const ur = this.sdk.eth.generateSignRequest({
@@ -331,10 +453,10 @@ var KeystoneUrEngine = class {
331
453
  sameTransaction = false;
332
454
  }
333
455
  if (!sameTransaction) {
334
- throw createHwkError({
335
- code: HardwareErrorCode.DeviceMismatch,
336
- message: "Keystone returned a PSBT for another transaction than the one requested"
337
- });
456
+ throw unexpectedQrCodeError(
457
+ "Keystone returned a PSBT for another transaction than the one requested",
458
+ HardwareErrorCode.DeviceMismatch
459
+ );
338
460
  }
339
461
  return signedPsbtHex;
340
462
  }
@@ -487,11 +609,15 @@ function isBip32Path(path) {
487
609
  function splitAccountPath(path) {
488
610
  const normalized = normalizePath(path);
489
611
  const segments = normalized.slice(2).split("/");
490
- if (segments.length <= 3) {
612
+ let accountLength = 0;
613
+ segments.forEach((segment, index) => {
614
+ if (segment.endsWith("'")) accountLength = index + 1;
615
+ });
616
+ if (segments.length <= 3 || accountLength === 0 || accountLength === segments.length) {
491
617
  return { accountPath: normalized, relativeDerivePath: "" };
492
618
  }
493
- const accountSegments = segments.slice(0, segments.length - 2);
494
- const relativeSegments = segments.slice(segments.length - 2);
619
+ const accountSegments = segments.slice(0, accountLength);
620
+ const relativeSegments = segments.slice(accountLength);
495
621
  return {
496
622
  accountPath: `m/${accountSegments.join("/")}`,
497
623
  relativeDerivePath: relativeSegments.join("/")
@@ -533,12 +659,15 @@ function accountKey(hwkChain, path) {
533
659
  function createDeviceRecord(masterFingerprint) {
534
660
  return {
535
661
  masterFingerprint,
536
- connectId: walletConnectId(masterFingerprint),
537
- importedAt: Date.now()
662
+ connectId: walletConnectId(masterFingerprint)
538
663
  };
539
664
  }
540
665
  var CAPABILITIES = { persistentDeviceIdentity: true };
541
666
  function toDeviceInfo(record) {
667
+ return toDeviceInfoForConnection(record, record.usbSessionId ? "usb" : "qr");
668
+ }
669
+ function toDeviceInfoForConnection(record, connectionType) {
670
+ const firmwareVersion = connectionType === "usb" ? record.usbFirmwareVersion : record.deviceVersion;
542
671
  let availableChannels = ["qr"];
543
672
  if (record.usbSessionId) {
544
673
  availableChannels = record.qrSynced ? ["qr", "usb"] : ["usb"];
@@ -547,11 +676,13 @@ function toDeviceInfo(record) {
547
676
  vendor: "keystone",
548
677
  model: record.model ?? "unknown",
549
678
  modelName: record.model,
550
- firmwareVersion: record.deviceVersion ?? "0.0.0",
679
+ firmwareVersion: firmwareVersion ?? "0.0.0",
551
680
  deviceId: record.masterFingerprint,
552
681
  connectId: record.connectId,
553
- connectionType: record.usbSessionId ? "usb" : "qr",
554
- capabilities: CAPABILITIES,
682
+ connectionType,
683
+ capabilities: {
684
+ ...CAPABILITIES
685
+ },
555
686
  raw: {
556
687
  availableChannels,
557
688
  masterFingerprint: record.masterFingerprint,
@@ -571,6 +702,31 @@ function placeholderDeviceInfo() {
571
702
  };
572
703
  }
573
704
 
705
+ // src/adapter/firmwareCapabilities.ts
706
+ var MULTI_COIN = {
707
+ variant: "multi-coin",
708
+ supportedChains: ["btc", "evm", "sol", "tron"]
709
+ };
710
+ var BITCOIN_ONLY = {
711
+ variant: "bitcoin-only",
712
+ supportedChains: ["btc"]
713
+ };
714
+ var CYPHERPUNK = {
715
+ variant: "cypherpunk",
716
+ // Firmware support alone is insufficient: this adapter has no Zcash/Monero methods yet.
717
+ supportedChains: ["btc"]
718
+ };
719
+ function getKeystoneFirmwareProfile(firmwareVersion) {
720
+ if (!firmwareVersion || firmwareVersion === "0.0.0") return void 0;
721
+ const version = /^\d{1,4}(?:\.\d{1,4}){1,3}(?:-([a-z0-9.-]{1,40}))?$/i.exec(firmwareVersion);
722
+ if (!version) return void 0;
723
+ const suffix = version[1]?.toUpperCase();
724
+ if (!suffix) return MULTI_COIN;
725
+ if (suffix === "C" || suffix === "CYPHERPUNK" || suffix === "CYPHERPUNK-B") return CYPHERPUNK;
726
+ if (suffix === "B" || suffix === "BTC" || suffix === "BTC-ONLY") return BITCOIN_ONLY;
727
+ return void 0;
728
+ }
729
+
574
730
  // src/utils/queueKey.ts
575
731
  import { isHardwareOperationId, parseWalletMasterFingerprint as parseWalletMasterFingerprint2 } from "@onekeyfe/hwk-adapter-core";
576
732
  var KEYSTONE_COLD_START_JOB_LABEL = "keystone-cold-start";
@@ -610,10 +766,36 @@ function keystoneBtcParamsFailure(params) {
610
766
  }
611
767
  return void 0;
612
768
  }
769
+ var USB_ATTACH_FAILURE_REASONS = {
770
+ [HardwareErrorCode2.DeviceMismatch]: "wallet-mismatch",
771
+ [HardwareErrorCode2.DeviceNotInitialized]: "wallet-mismatch",
772
+ [HardwareErrorCode2.DeviceLocked]: "device-locked"
773
+ };
774
+ var KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS = 24;
613
775
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
614
776
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
777
+ var CHAIN_TYPE_BY_CHAIN = {
778
+ evm: "ETH",
779
+ sol: "SOL",
780
+ tron: "TRX"
781
+ };
782
+ var BTC_CHAIN_TYPE_BY_PURPOSE = {
783
+ 44: "BTC_LEGACY",
784
+ 49: "BTC",
785
+ 84: "BTC_NATIVE_SEGWIT",
786
+ 86: "BTC_TAPROOT"
787
+ };
788
+ function hardwareCallChainType(chain, path) {
789
+ if (chain !== "btc") return CHAIN_TYPE_BY_CHAIN[chain];
790
+ const purpose = normalizePath(path).match(/^m\/(\d+)'/)?.[1];
791
+ return purpose ? BTC_CHAIN_TYPE_BY_PURPOSE[Number(purpose)] : void 0;
792
+ }
615
793
  function keySchema(chain, path) {
616
- return { path, curve: chain === "sol" ? "ed25519" : "secp256k1" };
794
+ return {
795
+ path,
796
+ curve: chain === "sol" ? "ed25519" : "secp256k1",
797
+ chainType: hardwareCallChainType(chain, path)
798
+ };
617
799
  }
618
800
  function waitForKeystoneUsbReattachProbe() {
619
801
  return new Promise((resolve) => {
@@ -637,12 +819,42 @@ function exactHex(value) {
637
819
  function invalidHexFailure(field) {
638
820
  return failure(HardwareErrorCode2.InvalidParams, `${field} must be an even-length hex string`);
639
821
  }
640
- function requireExportedPath(parsed, path) {
641
- const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
822
+ function exportedAccountAt(parsed, path) {
823
+ const rejected = parsed.rejectedPaths?.find((entry) => normalizePath(entry.path) === path);
824
+ switch (rejected?.reason) {
825
+ case "different-wallet":
826
+ throw createHwkError2({
827
+ code: HardwareErrorCode2.DeviceMismatch,
828
+ message: "Account export contains a different wallet fingerprint"
829
+ });
830
+ case "conflicting-keys":
831
+ throw createHwkError2({
832
+ code: HardwareErrorCode2.DeviceMismatch,
833
+ message: "Account export contains conflicting keys for the same path"
834
+ });
835
+ case "unusable-key":
836
+ throw unexpectedQrCodeError(`Account export key at ${path} is not usable`);
837
+ default:
838
+ return parsed.accounts.find((returned) => normalizePath(returned.path) === path);
839
+ }
840
+ }
841
+ function parseScannedAnswer(parse) {
842
+ try {
843
+ return parse();
844
+ } catch (error) {
845
+ if (typeof error?.code === "number") throw error;
846
+ throw unexpectedQrCodeError(
847
+ `Scanned code is not this request's answer: ${error instanceof Error ? error.message : ""}`
848
+ );
849
+ }
850
+ }
851
+ function requireExportedPath(parsed, path, accountExport = false) {
852
+ const account = exportedAccountAt(parsed, path);
642
853
  if (!account) {
643
854
  throw createHwkError2({
644
- code: HardwareErrorCode2.DeviceMismatch,
645
- message: `Keystone did not return the requested derivation path (${path})`
855
+ code: accountExport ? HardwareErrorCode2.DevicePathForbidden : HardwareErrorCode2.DeviceMismatch,
856
+ message: `Keystone did not return the requested derivation path (${path})`,
857
+ ...accountExport ? { params: { reason: "account-not-exported" } } : {}
646
858
  });
647
859
  }
648
860
  return account;
@@ -656,7 +868,9 @@ function coinTypeFailure(chain, path) {
656
868
  }
657
869
  function btcAccountFailure(accountPath) {
658
870
  if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
659
- return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
871
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE, {
872
+ reason: "btc-account-limit"
873
+ });
660
874
  }
661
875
  function missingParamFailure(method, param) {
662
876
  return failure(HardwareErrorCode2.InvalidParams, `${method} requires ${param}`);
@@ -668,6 +882,10 @@ function evmMessageSignature(sig) {
668
882
  return { signature: ensure0x(sig.r + sig.s + sig.v) };
669
883
  }
670
884
  var KeystoneAdapter = class _KeystoneAdapter {
885
+ /**
886
+ * `qrKeyRequestLimit` caps the account paths one QR key request may ask for, below the firmware's
887
+ * own limit: a host with no USB to fall back on can refuse a large request before the device does.
888
+ */
671
889
  constructor(options) {
672
890
  this.vendor = "keystone";
673
891
  // No protocol-level cancel exists over Keystone USB, and QR has no transport
@@ -687,7 +905,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
687
905
  message: "Keystone operation has ended",
688
906
  params: { operationId: operation.operationId, reason }
689
907
  });
690
- this._jobQueue.cancelActiveAndPending(operation.operationId, ended);
908
+ const queueKey = keystoneQueueKey(operation.operationId);
909
+ this._jobQueue.cancelActiveAndPending(queueKey, ended);
691
910
  this._uiRegistry.cancel(void 0, void 0, operation.operationId);
692
911
  }
693
912
  }
@@ -715,6 +934,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
715
934
  if (!record) return;
716
935
  this._operations.endByConnectionKey(connectId, "disconnect");
717
936
  record.usbSessionId = void 0;
937
+ record.usbFirmwareVersion = void 0;
718
938
  const info = toDeviceInfo(record);
719
939
  if (record.qrSynced) {
720
940
  this.emitter.emit(DEVICE.CHANGED, { type: DEVICE.CHANGED, payload: info });
@@ -724,7 +944,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
724
944
  }
725
945
  };
726
946
  this._handleUsbUiEvent = (event) => {
727
- this.emitter.emit("ui-event", event);
947
+ const operationId = this._activeOperationId();
948
+ this.emitter.emit("ui-event", operationId ? { ...event, operationId } : event);
728
949
  };
729
950
  // ---------------------------------------------------------------------------
730
951
  // All-network bundle, dispatched to the per-chain methods below.
@@ -797,6 +1018,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
797
1018
  success: true,
798
1019
  payload: {
799
1020
  ...context.payload,
1021
+ ...access?.channel === "qr" && access.accountExport ? { accountExport: true } : {},
800
1022
  rootFingerprint: record ? Number.parseInt(record.masterFingerprint, 16) : void 0,
801
1023
  deviceIdentity: record ? {
802
1024
  vendor: "keystone",
@@ -822,6 +1044,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
822
1044
  };
823
1045
  this._origin = options?.origin ?? "OneKey";
824
1046
  this._qrTimeoutMs = options?.qrTimeoutMs;
1047
+ const limit = options?.qrKeyRequestLimit;
1048
+ this._qrKeyRequestLimit = limit !== void 0 && Number.isInteger(limit) && limit > 0 ? Math.min(limit, KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS) : KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS;
825
1049
  this.urEngine = new KeystoneUrEngine(this._origin);
826
1050
  this._jobQueue = new DeviceJobQueue();
827
1051
  this._usbConnector = options?.usbConnector;
@@ -1046,23 +1270,24 @@ var KeystoneAdapter = class _KeystoneAdapter {
1046
1270
  }
1047
1271
  getDeviceInfo(connectIdOrOperationId, deviceId) {
1048
1272
  try {
1049
- const connectId = isHardwareOperationId2(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1273
+ const operation = isHardwareOperationId2(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId) : void 0;
1274
+ const connectId = operation?.connectId ?? connectIdOrOperationId;
1050
1275
  const { record } = this._resolveTarget(connectId, deviceId);
1051
1276
  if (!record) {
1052
1277
  return Promise.resolve(
1053
1278
  failure(HardwareErrorCode2.DeviceNotFound, "Unknown Keystone device")
1054
1279
  );
1055
1280
  }
1056
- return Promise.resolve(success(toDeviceInfo(record)));
1281
+ const info = operation ? toDeviceInfoForConnection(record, operation.connectionType === "qr" ? "qr" : "usb") : toDeviceInfo(record);
1282
+ return Promise.resolve(success(info));
1057
1283
  } catch (err) {
1058
1284
  return Promise.resolve(this._errorToFailure(err));
1059
1285
  }
1060
1286
  }
1061
1287
  cancel(connectId) {
1062
- let namedOperationConnectId;
1063
1288
  if (isHardwareOperationId2(connectId)) {
1064
1289
  try {
1065
- namedOperationConnectId = this._operations.resolve(connectId).connectId;
1290
+ this._operations.resolve(connectId);
1066
1291
  } catch {
1067
1292
  return;
1068
1293
  }
@@ -1072,15 +1297,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1072
1297
  message: "User aborted operation"
1073
1298
  });
1074
1299
  if (connectId) {
1300
+ const scopedOperationId = isHardwareOperationId2(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1075
1301
  const queueKeys = keystoneCancelQueueKeys([
1076
1302
  connectId,
1077
- this._operationRoutes.get(connectId)?.operationId,
1078
- namedOperationConnectId
1303
+ this._operationRoutes.get(connectId)?.operationId
1079
1304
  ]);
1080
1305
  for (const key of queueKeys) {
1081
1306
  this._jobQueue.cancelActiveAndPending(key, reason);
1082
1307
  }
1083
- const scopedOperationId = isHardwareOperationId2(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1084
1308
  if (scopedOperationId) {
1085
1309
  this._uiRegistry.cancel(void 0, void 0, scopedOperationId);
1086
1310
  }
@@ -1142,13 +1366,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1142
1366
  });
1143
1367
  responseUr = await this._requestQrAndAwaitResponse(
1144
1368
  displayDevice,
1145
- { ...requestUr, animated: false },
1369
+ { ...requestUr, animated: false, allowAccountExport: true },
1146
1370
  signal
1147
1371
  );
1148
1372
  }
1149
1373
  _KeystoneAdapter._throwIfAborted(signal);
1150
- const parsed = this.urEngine.parseAccountResponse(responseUr);
1151
- if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1374
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1375
+ if (!responseUr.accountExport) requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1152
1376
  const record = this._upsertDeviceRecord(parsed);
1153
1377
  return success(toDeviceInfo(record));
1154
1378
  });
@@ -1348,7 +1572,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
1348
1572
  "btcSignPsbt"
1349
1573
  );
1350
1574
  _KeystoneAdapter._throwIfAborted(signal);
1351
- const signedPsbt = this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex);
1575
+ const signedPsbt = parseScannedAnswer(
1576
+ () => this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex)
1577
+ );
1352
1578
  return success({ signedPsbt });
1353
1579
  });
1354
1580
  }
@@ -1695,7 +1921,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1695
1921
  args.operationName
1696
1922
  );
1697
1923
  _KeystoneAdapter._throwIfAborted(signal);
1698
- const signature = args.parseResponse(responseUr);
1924
+ const signature = parseScannedAnswer(() => args.parseResponse(responseUr));
1699
1925
  _KeystoneAdapter._assertRequestIdMatches(requestId, signature.requestId);
1700
1926
  return success(args.toPayload(signature));
1701
1927
  });
@@ -1745,7 +1971,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1745
1971
  }
1746
1972
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1747
1973
  return {
1748
- access: { channel: "usb", usbSessionId: record.usbSessionId },
1974
+ access: { channel: "usb", usbSessionId: record.usbSessionId, qrFallback: {} },
1749
1975
  masterFingerprint: record.masterFingerprint
1750
1976
  };
1751
1977
  }
@@ -1756,26 +1982,67 @@ var KeystoneAdapter = class _KeystoneAdapter {
1756
1982
  });
1757
1983
  }
1758
1984
  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
- });
1985
+ if (schemas.length > this._qrKeyRequestLimit) {
1986
+ throw createHwkError2({
1987
+ code: HardwareErrorCode2.QrRequestTooLarge,
1988
+ message: `Keystone QR requests take at most ${this._qrKeyRequestLimit} account paths here; this one needs ${schemas.length}`,
1989
+ params: { limit: this._qrKeyRequestLimit, requested: schemas.length }
1990
+ });
1991
+ }
1992
+ const request = {
1993
+ ...this.urEngine.buildKeyDerivationRequest({
1994
+ schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1995
+ origin: this._origin
1996
+ }),
1997
+ animated: false,
1998
+ allowAccountExport: true
1999
+ };
1763
2000
  const responseUr = await this._requestQrAndAwaitResponse(
1764
2001
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1765
- { ...requestUr, animated: false },
2002
+ request,
1766
2003
  signal
1767
2004
  );
1768
2005
  _KeystoneAdapter._throwIfAborted(signal);
1769
- const parsed = this.urEngine.parseAccountResponse(responseUr);
2006
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1770
2007
  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
2008
+ const firmware = getKeystoneFirmwareProfile(parsed.deviceVersion);
2009
+ const usableSchemas = schemas.filter(
2010
+ (schema) => !firmware || firmware.supportedChains.includes(schema.hwkChain)
2011
+ );
2012
+ const isColdStart = !target.expectedMasterFingerprint;
2013
+ if (firmware && isColdStart && !responseUr.accountExport && !usableSchemas.length) {
2014
+ throw createHwkError2({
2015
+ code: HardwareErrorCode2.ChainNotSupported,
2016
+ message: `Keystone ${firmware.variant} firmware cannot use any requested chain`,
2017
+ params: { firmwareVariant: firmware.variant }
2018
+ });
2019
+ }
2020
+ for (const schema of usableSchemas) {
2021
+ const exported = responseUr.accountExport ? exportedAccountAt(parsed, schema.path) : requireExportedPath(parsed, schema.path);
2022
+ if (exported) {
2023
+ scanned.set(accountKey(schema.hwkChain, schema.path), {
2024
+ ...exported,
2025
+ hwkChain: schema.hwkChain
2026
+ });
2027
+ }
2028
+ }
2029
+ if (responseUr.accountExport && !scanned.size) {
2030
+ throw createHwkError2({
2031
+ code: HardwareErrorCode2.DevicePathForbidden,
2032
+ message: "Account export contains none of the requested supported account paths",
2033
+ params: { reason: "account-not-exported" }
1775
2034
  });
1776
2035
  }
1777
2036
  record = this._upsertDeviceRecord(parsed);
1778
- return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
2037
+ return {
2038
+ access: {
2039
+ channel: "qr",
2040
+ scanned,
2041
+ firmwareVersion: parsed.deviceVersion,
2042
+ ...responseUr.accountExport ? { accountExport: true } : {}
2043
+ },
2044
+ masterFingerprint: record.masterFingerprint
2045
+ };
1779
2046
  });
1780
2047
  }
1781
2048
  /**
@@ -1849,11 +2116,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
1849
2116
  record = createDeviceRecord(masterFingerprint);
1850
2117
  this._devices.set(masterFingerprint, record);
1851
2118
  }
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;
2119
+ record.model = parsed.device;
2120
+ record.hardwareDeviceId = parsed.deviceId;
2121
+ if (options?.usbSessionId) {
2122
+ record.usbSessionId = options.usbSessionId;
2123
+ record.usbFirmwareVersion = options.usbFirmwareVersion;
2124
+ record.hadUsbSession = true;
2125
+ }
2126
+ if (!options?.viaUsb) {
2127
+ record.deviceVersion = parsed.deviceVersion;
2128
+ record.qrSynced = true;
2129
+ }
1857
2130
  const info = toDeviceInfo(record);
1858
2131
  const eventType = isNew ? DEVICE.CONNECT : DEVICE.CHANGED;
1859
2132
  this.emitter.emit(eventType, { type: eventType, payload: info });
@@ -1879,7 +2152,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1879
2152
  signal.addEventListener("abort", onAbort, { once: true });
1880
2153
  const pending = this._usbConnectTail.then(async () => {
1881
2154
  _KeystoneAdapter._throwIfAborted(signal);
1882
- return this._connectUsbExclusive(connector, expected, searchTargetId, signal);
2155
+ if (this._unsettledUsbOperations.size > 0) {
2156
+ return failure(
2157
+ HardwareErrorCode2.DeviceBusyInternal,
2158
+ "Keystone USB is still finishing an earlier request"
2159
+ );
2160
+ }
2161
+ const releaseConnect = this._retainUsbOperation("connect");
2162
+ try {
2163
+ return await this._connectUsbExclusive(connector, expected, searchTargetId, signal);
2164
+ } finally {
2165
+ releaseConnect();
2166
+ }
1883
2167
  });
1884
2168
  const settled = pending.finally(() => {
1885
2169
  signal.removeEventListener("abort", onAbort);
@@ -1926,16 +2210,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1926
2210
  }
1927
2211
  _KeystoneAdapter._throwIfAborted(signal);
1928
2212
  const record = this._upsertDeviceRecord(
1929
- { masterFingerprint, accounts: [] },
2213
+ {
2214
+ masterFingerprint,
2215
+ accounts: [],
2216
+ device: session.deviceInfo.modelName ?? session.deviceInfo.model
2217
+ },
1930
2218
  {
1931
2219
  viaUsb: true,
1932
- usbSessionId: session.sessionId
2220
+ usbSessionId: session.sessionId,
2221
+ usbFirmwareVersion: session.deviceInfo.firmwareVersion
1933
2222
  }
1934
2223
  );
1935
2224
  _KeystoneAdapter._throwIfAborted(signal);
1936
- record.hadUsbSession = true;
1937
- record.model = session.deviceInfo.modelName ?? session.deviceInfo.model ?? record.model;
1938
- record.deviceVersion = session.deviceInfo.firmwareVersion ?? record.deviceVersion;
1939
2225
  return success(toDeviceInfo(record));
1940
2226
  } catch (err) {
1941
2227
  if (sessionId) {
@@ -1949,7 +2235,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1949
2235
  }
1950
2236
  /**
1951
2237
  * Probes already-authorized USB devices without a permission picker, then attaches and verifies
1952
- * the requested wallet if present.
2238
+ * the requested wallet if present. Undefined means use QR: no device, or the user chose QR.
1953
2239
  */
1954
2240
  async _tryUsbAttach(signal, expectedMasterFingerprint, options) {
1955
2241
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1993,19 +2279,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
1993
2279
  signal
1994
2280
  );
1995
2281
  _KeystoneAdapter._throwIfAborted(signal);
1996
- if (!attached.success && (attached.payload.code === HardwareErrorCode2.DeviceBusyInternal || attached.payload.code === HardwareErrorCode2.DeviceOneDeviceOnly)) {
2282
+ if (attached.success) return this._devices.get(expectedMasterFingerprint);
2283
+ const { code } = attached.payload;
2284
+ if (code === HardwareErrorCode2.DeviceBusyInternal || code === HardwareErrorCode2.DeviceOneDeviceOnly) {
1997
2285
  throw createHwkError2({
1998
2286
  ...attached.payload,
1999
2287
  message: attached.payload.error
2000
2288
  });
2001
2289
  }
2002
- return attached.success ? this._devices.get(expectedMasterFingerprint) : void 0;
2290
+ if (code === HardwareErrorCode2.DeviceNotFound || this._forcedTransport) return void 0;
2291
+ const answer = await this._askQrFallback(
2292
+ signal,
2293
+ USB_ATTACH_FAILURE_REASONS[code] ?? "usb-unavailable"
2294
+ );
2295
+ if (answer === "retry") return this._tryUsbAttach(signal, expectedMasterFingerprint);
2296
+ if (answer === "cancel") {
2297
+ throw createHwkError2({
2298
+ code: HardwareErrorCode2.UserAborted,
2299
+ message: "User declined to continue by QR while the connected Keystone was unusable"
2300
+ });
2301
+ }
2302
+ return void 0;
2003
2303
  }
2004
2304
  /**
2005
2305
  * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
2006
2306
  * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
2007
2307
  */
2008
- async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
2308
+ async _resolveUr(record, requestUr, animated, operationId, signal, operationName, qrFallback) {
2009
2309
  const releaseOperationRetention = isHardwareOperationId2(operationId) ? this._operations.retain(operationId) : void 0;
2010
2310
  try {
2011
2311
  return await this._resolveUrWithRoute(
@@ -2014,13 +2314,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
2014
2314
  animated,
2015
2315
  operationId,
2016
2316
  signal,
2017
- operationName
2317
+ operationName,
2318
+ qrFallback
2018
2319
  );
2019
2320
  } finally {
2020
2321
  releaseOperationRetention?.();
2021
2322
  }
2022
2323
  }
2023
- async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName) {
2324
+ async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName, qrFallback) {
2024
2325
  let record = callerRecord;
2025
2326
  let interactionRoute;
2026
2327
  if (isHardwareOperationId2(operationId)) {
@@ -2059,13 +2360,31 @@ var KeystoneAdapter = class _KeystoneAdapter {
2059
2360
  requestUr,
2060
2361
  signal
2061
2362
  );
2062
- if (result.success) return result.payload;
2363
+ if (result.success) {
2364
+ const ur = result.payload;
2365
+ return { urType: ur.urType, urData: ur.urData, channel: "usb" };
2366
+ }
2063
2367
  const usbError = rehydrateConnectorError(result.error);
2064
2368
  const { origin: usbErrorOrigin, code: usbErrorCode } = usbError;
2065
2369
  if (usbErrorCode === HardwareErrorCode2.PayloadTooLarge && usbErrorOrigin !== "device") {
2066
2370
  if (!interactionRoute && !this._forcedTransport) {
2371
+ if (!await this._confirmQrFallback(signal, qrFallback)) {
2372
+ throw createHwkError2({
2373
+ code: HardwareErrorCode2.UserAborted,
2374
+ message: "User declined to show the request too large for USB as a QR code"
2375
+ });
2376
+ }
2067
2377
  const displayDevice2 = toDeviceInfo(record);
2068
- return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2378
+ const responseUr = await this._requestQrAndAwaitResponse(
2379
+ displayDevice2,
2380
+ {
2381
+ ...requestUr,
2382
+ animated,
2383
+ ...!operationName ? { allowAccountExport: true } : {}
2384
+ },
2385
+ signal
2386
+ );
2387
+ return { ...responseUr, channel: "qr" };
2069
2388
  }
2070
2389
  throw usbError;
2071
2390
  }
@@ -2076,6 +2395,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2076
2395
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2077
2396
  }
2078
2397
  record.usbSessionId = void 0;
2398
+ record.usbFirmwareVersion = void 0;
2079
2399
  this.emitter.emit(DEVICE.CHANGED, { type: DEVICE.CHANGED, payload: toDeviceInfo(record) });
2080
2400
  if (interactionRoute) {
2081
2401
  throw this._endDisconnectedOperation(
@@ -2107,11 +2427,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2107
2427
  }
2108
2428
  const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
2109
2429
  try {
2110
- return await this._requestQrAndAwaitResponse(
2430
+ const responseUr = await this._requestQrAndAwaitResponse(
2111
2431
  displayDevice,
2112
- { ...requestUr, animated },
2432
+ { ...requestUr, animated, ...!operationName ? { allowAccountExport: true } : {} },
2113
2433
  signal
2114
2434
  );
2435
+ return { ...responseUr, channel: "qr" };
2115
2436
  } catch (error) {
2116
2437
  const { code, _tag: tag } = error;
2117
2438
  if (operationName && (code === HardwareErrorCode2.OperationTimeout || tag === UI_REQUEST_TIMEOUT_TAG)) {
@@ -2145,6 +2466,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
2145
2466
  const target = this._resolveTarget(connectId, deviceId);
2146
2467
  if (bundle?.channel === "qr") {
2147
2468
  const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2469
+ if (target.record && !scanned && bundle.accountExport) {
2470
+ throw createHwkError2({
2471
+ code: HardwareErrorCode2.DevicePathForbidden,
2472
+ message: "Scanned account export does not include this account path",
2473
+ params: { reason: "account-not-exported" }
2474
+ });
2475
+ }
2476
+ this._assertQrChainSupported(bundle.firmwareVersion, hwkChain);
2148
2477
  if (!target.record || !scanned) {
2149
2478
  throw createHwkError2({
2150
2479
  code: HardwareErrorCode2.DeviceMismatch,
@@ -2159,19 +2488,27 @@ var KeystoneAdapter = class _KeystoneAdapter {
2159
2488
  message: "Keystone USB connection was lost during the bundle"
2160
2489
  });
2161
2490
  }
2162
- const operationConnectionType = isHardwareOperationId2(connectId) ? this._operations.resolve(connectId).connectionType : void 0;
2163
2491
  let existingRecord = target.record;
2164
2492
  if (!existingRecord) {
2165
2493
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2166
2494
  _KeystoneAdapter._throwIfAborted(signal);
2167
2495
  }
2168
- const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2169
2496
  const schemas = [keySchema(hwkChain, syncPath)];
2170
2497
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2171
- const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2498
+ const responseUr = await this._resolveUr(
2499
+ existingRecord,
2500
+ requestUr,
2501
+ false,
2502
+ connectId,
2503
+ signal,
2504
+ void 0,
2505
+ bundle?.channel === "usb" ? bundle.qrFallback : void 0
2506
+ );
2172
2507
  _KeystoneAdapter._throwIfAborted(signal);
2173
- const parsed = this.urEngine.parseAccountResponse(responseUr);
2174
- const account = requireExportedPath(parsed, syncPath);
2508
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2509
+ this._assertParsedIdentity(parsed, target);
2510
+ const account = requireExportedPath(parsed, syncPath, responseUr.accountExport);
2511
+ const useSinglePathUsbExport = !responseUr.accountExport && responseUr.channel === "usb";
2175
2512
  let record;
2176
2513
  if (useSinglePathUsbExport && existingRecord) {
2177
2514
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2182,23 +2519,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
2182
2519
  }
2183
2520
  record = existingRecord;
2184
2521
  } else {
2185
- this._assertParsedIdentity(parsed, target);
2186
- record = this._upsertDeviceRecord(parsed, {
2187
- viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2188
- });
2522
+ this._assertQrChainSupported(parsed.deviceVersion, hwkChain);
2523
+ record = this._upsertDeviceRecord(parsed);
2189
2524
  }
2190
2525
  return { record, account: { ...account, hwkChain } };
2191
2526
  }
2192
2527
  /**
2193
- * Resolves which wallet is attached, without a per-path account. `CHAIN_FINGERPRINT_PATHS.evm` is
2194
- * a leaf path, so it is cut to the account path Keystone expects.
2528
+ * Resolves wallet identity without a per-path account. A caller-supplied fingerprint needs no
2529
+ * device round trip; otherwise request the account path from the device.
2195
2530
  */
2196
2531
  async _ensureWalletKnown(connectId, deviceId, chain, signal) {
2197
2532
  const target = this._resolveTarget(connectId, deviceId);
2198
2533
  if (target.record) return { record: target.record };
2199
- const attached = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2200
- _KeystoneAdapter._throwIfAborted(signal);
2201
- if (attached) return { record: attached };
2202
2534
  if (target.expectedMasterFingerprint) {
2203
2535
  return { record: createDeviceRecord(target.expectedMasterFingerprint) };
2204
2536
  }
@@ -2209,19 +2541,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
2209
2541
  });
2210
2542
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2211
2543
  _KeystoneAdapter._throwIfAborted(signal);
2212
- const parsed = this.urEngine.parseAccountResponse(responseUr);
2213
- requireExportedPath(parsed, normalizePath(accountPath));
2214
- return { record: this._upsertDeviceRecord(parsed) };
2544
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2545
+ if (!responseUr.accountExport) requireExportedPath(parsed, normalizePath(accountPath));
2546
+ this._assertQrChainSupported(parsed.deviceVersion, chain);
2547
+ const record = this._upsertDeviceRecord(parsed);
2548
+ return { record };
2549
+ }
2550
+ _assertQrChainSupported(firmwareVersion, chain) {
2551
+ const firmware = getKeystoneFirmwareProfile(firmwareVersion);
2552
+ if (firmware && !firmware.supportedChains.includes(chain)) {
2553
+ throw createHwkError2({
2554
+ code: HardwareErrorCode2.ChainNotSupported,
2555
+ message: `Keystone ${firmware.variant} firmware cannot use ${chain} through this adapter`,
2556
+ params: { firmwareVariant: firmware.variant, chain }
2557
+ });
2558
+ }
2215
2559
  }
2216
- /**
2217
- * The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
2218
- * through the operation route; a cold start returns undefined.
2219
- */
2560
+ /** Only an operation id supplied to the running call owns its UI prompts. */
2220
2561
  _activeOperationId() {
2221
- const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
2222
- if (!activeJobId) return void 0;
2223
- if (isHardwareOperationId2(activeJobId)) return activeJobId;
2224
- return this._operationRouteForIdentifier(activeJobId)?.operationId;
2562
+ return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
2225
2563
  }
2226
2564
  /** Routes are keyed by connectId; a job key may be the bare master fingerprint. */
2227
2565
  _operationRouteForIdentifier(identifier) {
@@ -2254,6 +2592,43 @@ var KeystoneAdapter = class _KeystoneAdapter {
2254
2592
  signal.removeEventListener("abort", onAbort);
2255
2593
  }
2256
2594
  }
2595
+ /**
2596
+ * Asks whether a request too large for USB may be shown as a QR. A timeout or an unanswered
2597
+ * prompt reads as no; a cancelled call keeps its own error.
2598
+ */
2599
+ async _confirmQrFallback(signal, choice) {
2600
+ if (choice?.confirmed !== void 0) return choice.confirmed;
2601
+ const confirmed = await this._askQrFallback(signal, "payload-too-large") === "qr";
2602
+ if (choice) choice.confirmed = confirmed;
2603
+ return confirmed;
2604
+ }
2605
+ /** A timeout or an unanswered prompt reads as cancel; a cancelled call keeps its own error. */
2606
+ async _askQrFallback(signal, reason) {
2607
+ const requestType = UI_REQUEST.REQUEST_QR_FALLBACK_CONFIRM;
2608
+ const requestId = this._uiRegistry.createRequestId();
2609
+ const operationId = this._activeOperationId();
2610
+ const release = operationId ? this._operations.retain(operationId) : void 0;
2611
+ try {
2612
+ const waitPromise = this._uiRegistry.wait(
2613
+ requestType,
2614
+ { requestId, operationId }
2615
+ );
2616
+ this.emitter.emit(requestType, {
2617
+ type: requestType,
2618
+ payload: { vendor: "keystone", requestId, operationId, reason }
2619
+ });
2620
+ let answer;
2621
+ try {
2622
+ answer = await this._awaitQrResponse(requestType, waitPromise, signal);
2623
+ } catch (error) {
2624
+ if (signal.aborted) throw error;
2625
+ }
2626
+ if (answer?.retry && reason !== "payload-too-large") return "retry";
2627
+ return answer?.confirmed ? "qr" : "cancel";
2628
+ } finally {
2629
+ release?.();
2630
+ }
2631
+ }
2257
2632
  /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2258
2633
  async _requestQrAndAwaitResponse(device, data, signal) {
2259
2634
  const requestType = data ? UI_REQUEST.REQUEST_QR_DISPLAY : UI_REQUEST.REQUEST_QR_SCAN;
@@ -2276,7 +2651,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
2276
2651
  });
2277
2652
  }
2278
2653
  const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2279
- return { urType: response.urType, urData: response.urData };
2654
+ if (response.accountExport && data && !data.allowAccountExport) {
2655
+ throw unexpectedQrCodeError("This request cannot be answered with an account export");
2656
+ }
2657
+ return {
2658
+ urType: response.urType,
2659
+ urData: response.urData,
2660
+ ...!data || response.accountExport ? { accountExport: true } : {}
2661
+ };
2280
2662
  } finally {
2281
2663
  release?.();
2282
2664
  }
@@ -2382,10 +2764,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
2382
2764
  /** A response without the request's id is as unrelated as one with another id. */
2383
2765
  static _assertRequestIdMatches(expected, actual) {
2384
2766
  if (!actual || actual.toLowerCase() !== expected.toLowerCase()) {
2385
- throw createHwkError2({
2386
- code: HardwareErrorCode2.DeviceMismatch,
2387
- 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"
2388
- });
2767
+ throw unexpectedQrCodeError(
2768
+ 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",
2769
+ HardwareErrorCode2.DeviceMismatch
2770
+ );
2389
2771
  }
2390
2772
  }
2391
2773
  _unsupported(method, reason) {