@onekeyfe/hwk-keystone-adapter 1.2.8-alpha.124 → 1.2.8-alpha.126

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.d.mts CHANGED
@@ -35,6 +35,15 @@ interface KeystoneParsedMultiAccounts {
35
35
  deviceId?: string;
36
36
  deviceVersion?: string;
37
37
  accounts: KeystoneParsedAccount[];
38
+ /**
39
+ * Export only: paths the export carried but could not vouch for. They are left out of `accounts`
40
+ * and only fail a caller that asks for one of them.
41
+ */
42
+ rejectedPaths?: KeystoneRejectedExportPath[];
43
+ }
44
+ interface KeystoneRejectedExportPath {
45
+ path: string;
46
+ reason: 'different-wallet' | 'conflicting-keys' | 'unusable-key';
38
47
  }
39
48
  interface KeystoneEthSignRequestInput {
40
49
  requestId: string;
@@ -133,7 +142,11 @@ declare class KeystoneUrEngine {
133
142
  * hdkey source fingerprint is the mfp only because every request here derives from the seed.
134
143
  */
135
144
  parseAccountResponse(ur: KeystoneUr): KeystoneParsedMultiAccounts;
136
- /** Device exports are opt-in: request responses retain their existing format/path checks. */
145
+ /**
146
+ * Device exports are opt-in: request responses retain their existing format/path checks. An
147
+ * export carries whatever the device syncs to other wallets, so each key is checked on its own: a
148
+ * key that fails lands in `rejectedPaths` instead of discarding the whole export.
149
+ */
137
150
  parseAccountExport(ur: KeystoneUr): KeystoneParsedMultiAccounts;
138
151
  buildEthSignRequest(input: KeystoneEthSignRequestInput): KeystoneUr;
139
152
  parseEthSignature(ur: KeystoneUr): KeystoneEthSignatureResult;
@@ -257,6 +270,8 @@ declare class KeystoneAdapter implements IHardwareWallet {
257
270
  private readonly _origin;
258
271
  /** Host answer timeout for QR display/scan requests; undefined uses the registry default. */
259
272
  private readonly _qrTimeoutMs;
273
+ /** At most this many account paths per QR key request; see the constructor option. */
274
+ private readonly _qrKeyRequestLimit;
260
275
  /** Host-supplied USB connector; undefined means QR-only. */
261
276
  private readonly _usbConnector;
262
277
  /** Serializes USB open/identity handshakes that run outside the job queue. */
@@ -270,10 +285,15 @@ declare class KeystoneAdapter implements IHardwareWallet {
270
285
  private _forcedTransport;
271
286
  private readonly _handleUsbDisconnect;
272
287
  private readonly _handleUsbUiEvent;
288
+ /**
289
+ * `qrKeyRequestLimit` caps the account paths one QR key request may ask for, below the firmware's
290
+ * own limit: a host with no USB to fall back on can refuse a large request before the device does.
291
+ */
273
292
  constructor(options?: {
274
293
  origin?: string;
275
294
  qrTimeoutMs?: number;
276
295
  usbConnector?: IConnector;
296
+ qrKeyRequestLimit?: number;
277
297
  });
278
298
  get activeTransport(): TransportType | null;
279
299
  getAvailableTransports(): TransportType[];
@@ -382,7 +402,7 @@ declare class KeystoneAdapter implements IHardwareWallet {
382
402
  private _connectUsbExclusive;
383
403
  /**
384
404
  * Probes already-authorized USB devices without a permission picker, then attaches and verifies
385
- * the requested wallet if present.
405
+ * the requested wallet if present. Undefined means use QR: no device, or the user chose QR.
386
406
  */
387
407
  private _tryUsbAttach;
388
408
  /**
@@ -419,6 +439,8 @@ declare class KeystoneAdapter implements IHardwareWallet {
419
439
  * prompt reads as no; a cancelled call keeps its own error.
420
440
  */
421
441
  private _confirmQrFallback;
442
+ /** A timeout or an unanswered prompt reads as cancel; a cancelled call keeps its own error. */
443
+ private _askQrFallback;
422
444
  /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
423
445
  private _requestQrAndAwaitResponse;
424
446
  private _callUsbResolveUr;
package/dist/index.d.ts CHANGED
@@ -35,6 +35,15 @@ interface KeystoneParsedMultiAccounts {
35
35
  deviceId?: string;
36
36
  deviceVersion?: string;
37
37
  accounts: KeystoneParsedAccount[];
38
+ /**
39
+ * Export only: paths the export carried but could not vouch for. They are left out of `accounts`
40
+ * and only fail a caller that asks for one of them.
41
+ */
42
+ rejectedPaths?: KeystoneRejectedExportPath[];
43
+ }
44
+ interface KeystoneRejectedExportPath {
45
+ path: string;
46
+ reason: 'different-wallet' | 'conflicting-keys' | 'unusable-key';
38
47
  }
39
48
  interface KeystoneEthSignRequestInput {
40
49
  requestId: string;
@@ -133,7 +142,11 @@ declare class KeystoneUrEngine {
133
142
  * hdkey source fingerprint is the mfp only because every request here derives from the seed.
134
143
  */
135
144
  parseAccountResponse(ur: KeystoneUr): KeystoneParsedMultiAccounts;
136
- /** Device exports are opt-in: request responses retain their existing format/path checks. */
145
+ /**
146
+ * Device exports are opt-in: request responses retain their existing format/path checks. An
147
+ * export carries whatever the device syncs to other wallets, so each key is checked on its own: a
148
+ * key that fails lands in `rejectedPaths` instead of discarding the whole export.
149
+ */
137
150
  parseAccountExport(ur: KeystoneUr): KeystoneParsedMultiAccounts;
138
151
  buildEthSignRequest(input: KeystoneEthSignRequestInput): KeystoneUr;
139
152
  parseEthSignature(ur: KeystoneUr): KeystoneEthSignatureResult;
@@ -257,6 +270,8 @@ declare class KeystoneAdapter implements IHardwareWallet {
257
270
  private readonly _origin;
258
271
  /** Host answer timeout for QR display/scan requests; undefined uses the registry default. */
259
272
  private readonly _qrTimeoutMs;
273
+ /** At most this many account paths per QR key request; see the constructor option. */
274
+ private readonly _qrKeyRequestLimit;
260
275
  /** Host-supplied USB connector; undefined means QR-only. */
261
276
  private readonly _usbConnector;
262
277
  /** Serializes USB open/identity handshakes that run outside the job queue. */
@@ -270,10 +285,15 @@ declare class KeystoneAdapter implements IHardwareWallet {
270
285
  private _forcedTransport;
271
286
  private readonly _handleUsbDisconnect;
272
287
  private readonly _handleUsbUiEvent;
288
+ /**
289
+ * `qrKeyRequestLimit` caps the account paths one QR key request may ask for, below the firmware's
290
+ * own limit: a host with no USB to fall back on can refuse a large request before the device does.
291
+ */
273
292
  constructor(options?: {
274
293
  origin?: string;
275
294
  qrTimeoutMs?: number;
276
295
  usbConnector?: IConnector;
296
+ qrKeyRequestLimit?: number;
277
297
  });
278
298
  get activeTransport(): TransportType | null;
279
299
  getAvailableTransports(): TransportType[];
@@ -382,7 +402,7 @@ declare class KeystoneAdapter implements IHardwareWallet {
382
402
  private _connectUsbExclusive;
383
403
  /**
384
404
  * Probes already-authorized USB devices without a permission picker, then attaches and verifies
385
- * the requested wallet if present.
405
+ * the requested wallet if present. Undefined means use QR: no device, or the user chose QR.
386
406
  */
387
407
  private _tryUsbAttach;
388
408
  /**
@@ -419,6 +439,8 @@ declare class KeystoneAdapter implements IHardwareWallet {
419
439
  * prompt reads as no; a cancelled call keeps its own error.
420
440
  */
421
441
  private _confirmQrFallback;
442
+ /** A timeout or an unanswered prompt reads as cancel; a cancelled call keeps its own error. */
443
+ private _askQrFallback;
422
444
  /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
423
445
  private _requestQrAndAwaitResponse;
424
446
  private _callUsbResolveUr;
package/dist/index.js CHANGED
@@ -209,6 +209,35 @@ function toParsedAccount(key) {
209
209
  };
210
210
  }
211
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
+ }
212
241
  function relativeHdPath(relativeDerivePath) {
213
242
  const segments = relativeDerivePath.replace(/^m\//i, "").split("/");
214
243
  const valid = segments.every(
@@ -278,26 +307,32 @@ var KeystoneUrEngine = class {
278
307
  }
279
308
  return this.parseMultiAccounts(ur);
280
309
  }
281
- /** Device exports are opt-in: request responses retain their existing format/path checks. */
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
+ */
282
315
  parseAccountExport(ur) {
316
+ let parsed;
317
+ let keys;
318
+ const unsupportedDescriptors = /* @__PURE__ */ new Set();
283
319
  try {
284
320
  const { cbor } = toSdkUr(ur);
285
- let parsed;
286
- let keys;
287
321
  if (ur.urType === "crypto-account") {
288
322
  if (!Object.values(import_bc_ur_registry3.ScriptExpressions).some((script) => script.getTag() === 409)) {
289
323
  Object.assign(import_bc_ur_registry3.ScriptExpressions, { TAPROOT: new import_ScriptExpression.ScriptExpression(409, "tr") });
290
324
  }
291
325
  import_bc_ur_registry3.extend.cbor.patchTags([409]);
292
326
  const account = import_bc_ur_registry3.CryptoAccount.fromCBOR(cbor);
293
- keys = account.getOutputDescriptors().map((output) => {
327
+ keys = account.getOutputDescriptors().map((output, index) => {
294
328
  const key = output.getHDKey();
295
329
  const path = key?.getOrigin()?.getPath();
296
330
  const script = output.getScriptExpressions().map((item) => item.getExpression()).join("/");
297
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";
298
332
  const children = key?.getChildren();
299
- if (!key || !validScript || children && children.getPath() !== "0/*") {
300
- throw new Error("Unsupported account descriptor");
333
+ if (!key) throw new Error("Unsupported account descriptor");
334
+ if (!validScript || children && children.getPath() !== "0/*") {
335
+ unsupportedDescriptors.add(index);
301
336
  }
302
337
  return key;
303
338
  });
@@ -318,54 +353,43 @@ var KeystoneUrEngine = class {
318
353
  if (!keys.length || keys.length !== parsed.accounts.length) {
319
354
  throw new Error("Empty account export");
320
355
  }
321
- for (const key of keys) {
322
- if (key.isMaster() || key.isPrivateKey()) throw new Error("Account public keys required");
323
- const source = key.getOrigin()?.getSourceFingerprint();
324
- if (source && source.toString("hex") !== parsed.masterFingerprint) {
325
- throw (0, import_hwk_adapter_core.createHwkError)({
326
- code: import_hwk_adapter_core.HardwareErrorCode.DeviceMismatch,
327
- message: "Account export contains a different wallet fingerprint"
328
- });
329
- }
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";
330
381
  }
331
- const byPath = /* @__PURE__ */ new Map();
332
- for (const account of parsed.accounts) {
333
- if (!/^m(?:\/\d+')+(?:\/\d+)*$/.test(account.path) || account.path.slice(2).split("/").some(
334
- (segment) => Number(segment.endsWith("'") ? segment.slice(0, -1) : segment) >= BIP32_HARDENED_OFFSET
335
- )) {
336
- throw new Error("Account export has an unsupported derivation path");
337
- }
338
- let identity = account.publicKey;
339
- if (account.extendedPublicKey) {
340
- const node = import_hdkey.default.fromExtendedKey(account.extendedPublicKey);
341
- if (node.privateKey || !node.publicKey || !node.chainCode) {
342
- throw new Error("Account public keys required");
343
- }
344
- if (node.publicKey.toString("hex") !== account.publicKey.toLowerCase()) {
345
- throw new Error("Account public key does not match its extended key");
346
- }
347
- identity = `${identity}:${node.chainCode.toString("hex")}`;
348
- } else if (!/^[0-9a-f]{64}$/i.test(account.publicKey)) {
349
- throw new Error("Account export is missing a usable public key");
350
- }
351
- const previous = byPath.get(account.path);
352
- if (previous !== void 0 && previous !== identity) {
353
- throw (0, import_hwk_adapter_core.createHwkError)({
354
- code: import_hwk_adapter_core.HardwareErrorCode.DeviceMismatch,
355
- message: "Account export contains conflicting keys for the same path"
356
- });
357
- }
358
- byPath.set(account.path, identity);
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 });
359
390
  }
360
- return parsed;
361
- } catch (error) {
362
- if (error && typeof error === "object" && "code" in error && error.code === import_hwk_adapter_core.HardwareErrorCode.DeviceMismatch)
363
- throw error;
364
- throw (0, import_hwk_adapter_core.createHwkError)({
365
- code: import_hwk_adapter_core.HardwareErrorCode.InvalidParams,
366
- message: "Unable to read account export; scan a supported Keystone account export code"
367
- });
368
- }
391
+ });
392
+ return { ...parsed, accounts, rejectedPaths };
369
393
  }
370
394
  // --- EVM ---
371
395
  buildEthSignRequest(input) {
@@ -451,10 +475,10 @@ var KeystoneUrEngine = class {
451
475
  sameTransaction = false;
452
476
  }
453
477
  if (!sameTransaction) {
454
- throw (0, import_hwk_adapter_core.createHwkError)({
455
- code: import_hwk_adapter_core.HardwareErrorCode.DeviceMismatch,
456
- message: "Keystone returned a PSBT for another transaction than the one requested"
457
- });
478
+ throw unexpectedQrCodeError(
479
+ "Keystone returned a PSBT for another transaction than the one requested",
480
+ import_hwk_adapter_core.HardwareErrorCode.DeviceMismatch
481
+ );
458
482
  }
459
483
  return signedPsbtHex;
460
484
  }
@@ -728,6 +752,11 @@ function keystoneBtcParamsFailure(params) {
728
752
  }
729
753
  return void 0;
730
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
+ };
731
760
  var KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS = 24;
732
761
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
733
762
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
@@ -776,8 +805,37 @@ function exactHex(value) {
776
805
  function invalidHexFailure(field) {
777
806
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${field} must be an even-length hex string`);
778
807
  }
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
+ }
779
837
  function requireExportedPath(parsed, path, accountExport = false) {
780
- const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
838
+ const account = exportedAccountAt(parsed, path);
781
839
  if (!account) {
782
840
  throw (0, import_hwk_adapter_core3.createHwkError)({
783
841
  code: accountExport ? import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden : import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
@@ -810,6 +868,10 @@ function evmMessageSignature(sig) {
810
868
  return { signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) };
811
869
  }
812
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
+ */
813
875
  constructor(options) {
814
876
  this.vendor = "keystone";
815
877
  // No protocol-level cancel exists over Keystone USB, and QR has no transport
@@ -968,6 +1030,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
968
1030
  };
969
1031
  this._origin = options?.origin ?? "OneKey";
970
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;
971
1035
  this.urEngine = new KeystoneUrEngine(this._origin);
972
1036
  this._jobQueue = new import_hwk_adapter_core3.DeviceJobQueue();
973
1037
  this._usbConnector = options?.usbConnector;
@@ -1494,7 +1558,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
1494
1558
  "btcSignPsbt"
1495
1559
  );
1496
1560
  _KeystoneAdapter._throwIfAborted(signal);
1497
- const signedPsbt = this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex);
1561
+ const signedPsbt = parseScannedAnswer(
1562
+ () => this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex)
1563
+ );
1498
1564
  return (0, import_hwk_adapter_core3.success)({ signedPsbt });
1499
1565
  });
1500
1566
  }
@@ -1841,7 +1907,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1841
1907
  args.operationName
1842
1908
  );
1843
1909
  _KeystoneAdapter._throwIfAborted(signal);
1844
- const signature = args.parseResponse(responseUr);
1910
+ const signature = parseScannedAnswer(() => args.parseResponse(responseUr));
1845
1911
  _KeystoneAdapter._assertRequestIdMatches(requestId, signature.requestId);
1846
1912
  return (0, import_hwk_adapter_core3.success)(args.toPayload(signature));
1847
1913
  });
@@ -1902,11 +1968,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1902
1968
  });
1903
1969
  }
1904
1970
  const schemas = Array.from(requestedByKey.values());
1905
- if (schemas.length > KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS) {
1971
+ if (schemas.length > this._qrKeyRequestLimit) {
1906
1972
  throw (0, import_hwk_adapter_core3.createHwkError)({
1907
1973
  code: import_hwk_adapter_core3.HardwareErrorCode.QrRequestTooLarge,
1908
- message: `Keystone accepts at most ${KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS} account paths per QR request; this one needs ${schemas.length}`,
1909
- params: { limit: KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS, requested: schemas.length }
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 }
1910
1976
  });
1911
1977
  }
1912
1978
  const request = {
@@ -1926,15 +1992,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1926
1992
  const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1927
1993
  this._assertParsedIdentity(parsed, target);
1928
1994
  const firmware = getKeystoneFirmwareProfile(parsed.deviceVersion);
1929
- if (responseUr.accountExport && parsed.accounts.some((account) => !isBip32Path(account.path))) {
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) {
1930
2000
  throw (0, import_hwk_adapter_core3.createHwkError)({
1931
- code: import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1932
- message: "Account export contains an invalid derivation path"
2001
+ code: import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
2002
+ message: `Keystone ${firmware.variant} firmware cannot use any requested chain`,
2003
+ params: { firmwareVariant: firmware.variant }
1933
2004
  });
1934
2005
  }
1935
- for (const schema of schemas) {
1936
- const exported = responseUr.accountExport ? parsed.accounts.find((account) => normalizePath(account.path) === schema.path) : requireExportedPath(parsed, schema.path);
1937
- if (exported && (!responseUr.accountExport || !firmware || firmware.supportedChains.includes(schema.hwkChain))) {
2006
+ for (const schema of usableSchemas) {
2007
+ const exported = responseUr.accountExport ? exportedAccountAt(parsed, schema.path) : requireExportedPath(parsed, schema.path);
2008
+ if (exported) {
1938
2009
  scanned.set(accountKey(schema.hwkChain, schema.path), {
1939
2010
  ...exported,
1940
2011
  hwkChain: schema.hwkChain
@@ -2150,7 +2221,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2150
2221
  }
2151
2222
  /**
2152
2223
  * Probes already-authorized USB devices without a permission picker, then attaches and verifies
2153
- * the requested wallet if present.
2224
+ * the requested wallet if present. Undefined means use QR: no device, or the user chose QR.
2154
2225
  */
2155
2226
  async _tryUsbAttach(signal, expectedMasterFingerprint, options) {
2156
2227
  _KeystoneAdapter._throwIfAborted(signal);
@@ -2194,13 +2265,27 @@ var KeystoneAdapter = class _KeystoneAdapter {
2194
2265
  signal
2195
2266
  );
2196
2267
  _KeystoneAdapter._throwIfAborted(signal);
2197
- 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) {
2198
2271
  throw (0, import_hwk_adapter_core3.createHwkError)({
2199
2272
  ...attached.payload,
2200
2273
  message: attached.payload.error
2201
2274
  });
2202
2275
  }
2203
- 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;
2204
2289
  }
2205
2290
  /**
2206
2291
  * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
@@ -2374,13 +2459,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
2374
2459
  params: { reason: "account-not-exported" }
2375
2460
  });
2376
2461
  }
2462
+ this._assertQrChainSupported(bundle.firmwareVersion, hwkChain);
2377
2463
  if (!target.record || !scanned) {
2378
2464
  throw (0, import_hwk_adapter_core3.createHwkError)({
2379
2465
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2380
2466
  message: `Keystone did not return the requested derivation path (${syncPath})`
2381
2467
  });
2382
2468
  }
2383
- this._assertQrChainSupported(bundle.firmwareVersion, hwkChain);
2384
2469
  return { record: target.record, account: scanned };
2385
2470
  }
2386
2471
  if (bundle?.channel === "usb" && target.record?.usbSessionId !== bundle.usbSessionId) {
@@ -2443,7 +2528,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2443
2528
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2444
2529
  _KeystoneAdapter._throwIfAborted(signal);
2445
2530
  const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2446
- requireExportedPath(parsed, normalizePath(accountPath), responseUr.accountExport);
2531
+ if (!responseUr.accountExport) requireExportedPath(parsed, normalizePath(accountPath));
2447
2532
  this._assertQrChainSupported(parsed.deviceVersion, chain);
2448
2533
  const record = this._upsertDeviceRecord(parsed);
2449
2534
  return { record };
@@ -2499,29 +2584,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
2499
2584
  */
2500
2585
  async _confirmQrFallback(signal, choice) {
2501
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) {
2502
2593
  const requestType = import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_FALLBACK_CONFIRM;
2503
2594
  const requestId = this._uiRegistry.createRequestId();
2504
2595
  const operationId = this._activeOperationId();
2505
2596
  const release = operationId ? this._operations.retain(operationId) : void 0;
2506
2597
  try {
2507
- const waitPromise = this._uiRegistry.wait(requestType, {
2508
- requestId,
2509
- operationId
2510
- });
2598
+ const waitPromise = this._uiRegistry.wait(
2599
+ requestType,
2600
+ { requestId, operationId }
2601
+ );
2511
2602
  this.emitter.emit(requestType, {
2512
2603
  type: requestType,
2513
- payload: { vendor: "keystone", requestId, operationId }
2604
+ payload: { vendor: "keystone", requestId, operationId, reason }
2514
2605
  });
2515
- let confirmed = false;
2606
+ let answer;
2516
2607
  try {
2517
- confirmed = Boolean(
2518
- (await this._awaitQrResponse(requestType, waitPromise, signal))?.confirmed
2519
- );
2608
+ answer = await this._awaitQrResponse(requestType, waitPromise, signal);
2520
2609
  } catch (error) {
2521
2610
  if (signal.aborted) throw error;
2522
2611
  }
2523
- if (choice) choice.confirmed = confirmed;
2524
- return confirmed;
2612
+ if (answer?.retry && reason !== "payload-too-large") return "retry";
2613
+ return answer?.confirmed ? "qr" : "cancel";
2525
2614
  } finally {
2526
2615
  release?.();
2527
2616
  }
@@ -2549,10 +2638,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2549
2638
  }
2550
2639
  const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2551
2640
  if (response.accountExport && data && !data.allowAccountExport) {
2552
- throw (0, import_hwk_adapter_core3.createHwkError)({
2553
- code: import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
2554
- message: "This request cannot be answered with an account export"
2555
- });
2641
+ throw unexpectedQrCodeError("This request cannot be answered with an account export");
2556
2642
  }
2557
2643
  return {
2558
2644
  urType: response.urType,
@@ -2664,10 +2750,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
2664
2750
  /** A response without the request's id is as unrelated as one with another id. */
2665
2751
  static _assertRequestIdMatches(expected, actual) {
2666
2752
  if (!actual || actual.toLowerCase() !== expected.toLowerCase()) {
2667
- throw (0, import_hwk_adapter_core3.createHwkError)({
2668
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2669
- 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"
2670
- });
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
+ );
2671
2757
  }
2672
2758
  }
2673
2759
  _unsupported(method, reason) {