@onekeyfe/hwk-keystone-adapter 1.2.8-alpha.122 → 1.2.8-alpha.123

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"));
@@ -220,7 +222,7 @@ function relativeHdPath(relativeDerivePath) {
220
222
  }
221
223
  return `m/${segments.join("/")}`;
222
224
  }
223
- var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.]{1,20})?$/;
225
+ var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.-]{1,20})?$/;
224
226
  var DEVICE_TEXT = /^[^\p{Cc}\p{Cf}]{1,64}$/u;
225
227
  function deviceText(value, pattern) {
226
228
  return typeof value === "string" && pattern.test(value) ? value : void 0;
@@ -276,6 +278,95 @@ var KeystoneUrEngine = class {
276
278
  }
277
279
  return this.parseMultiAccounts(ur);
278
280
  }
281
+ /** Device exports are opt-in: request responses retain their existing format/path checks. */
282
+ parseAccountExport(ur) {
283
+ try {
284
+ const { cbor } = toSdkUr(ur);
285
+ let parsed;
286
+ let keys;
287
+ if (ur.urType === "crypto-account") {
288
+ if (!Object.values(import_bc_ur_registry3.ScriptExpressions).some((script) => script.getTag() === 409)) {
289
+ Object.assign(import_bc_ur_registry3.ScriptExpressions, { TAPROOT: new import_ScriptExpression.ScriptExpression(409, "tr") });
290
+ }
291
+ import_bc_ur_registry3.extend.cbor.patchTags([409]);
292
+ const account = import_bc_ur_registry3.CryptoAccount.fromCBOR(cbor);
293
+ keys = account.getOutputDescriptors().map((output) => {
294
+ const key = output.getHDKey();
295
+ const path = key?.getOrigin()?.getPath();
296
+ const script = output.getScriptExpressions().map((item) => item.getExpression()).join("/");
297
+ 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
+ const children = key?.getChildren();
299
+ if (!key || !validScript || children && children.getPath() !== "0/*") {
300
+ throw new Error("Unsupported account descriptor");
301
+ }
302
+ return key;
303
+ });
304
+ const result = this.sdk.parseAccount(toSdkUr(ur));
305
+ parsed = {
306
+ masterFingerprint: requireBip32MasterFingerprint(result.masterFingerprint),
307
+ accounts: result.keys.map(toParsedAccount)
308
+ };
309
+ } else if (ur.urType === "crypto-multi-accounts") {
310
+ keys = import_bc_ur_registry3.CryptoMultiAccounts.fromCBOR(cbor).getKeys();
311
+ parsed = this.parseMultiAccounts(ur);
312
+ } else if (ur.urType === "crypto-hdkey") {
313
+ keys = [import_bc_ur_registry3.CryptoHDKey.fromCBOR(cbor)];
314
+ parsed = this.parseAccountResponse(ur);
315
+ } else {
316
+ throw new Error("Unsupported account export type");
317
+ }
318
+ if (!keys.length || keys.length !== parsed.accounts.length) {
319
+ throw new Error("Empty account export");
320
+ }
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
+ }
330
+ }
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);
359
+ }
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
+ }
369
+ }
279
370
  // --- EVM ---
280
371
  buildEthSignRequest(input) {
281
372
  const ur = this.sdk.eth.generateSignRequest({
@@ -530,12 +621,15 @@ function accountKey(hwkChain, path) {
530
621
  function createDeviceRecord(masterFingerprint) {
531
622
  return {
532
623
  masterFingerprint,
533
- connectId: walletConnectId(masterFingerprint),
534
- importedAt: Date.now()
624
+ connectId: walletConnectId(masterFingerprint)
535
625
  };
536
626
  }
537
627
  var CAPABILITIES = { persistentDeviceIdentity: true };
538
628
  function toDeviceInfo(record) {
629
+ return toDeviceInfoForConnection(record, record.usbSessionId ? "usb" : "qr");
630
+ }
631
+ function toDeviceInfoForConnection(record, connectionType) {
632
+ const firmwareVersion = connectionType === "usb" ? record.usbFirmwareVersion : record.deviceVersion;
539
633
  let availableChannels = ["qr"];
540
634
  if (record.usbSessionId) {
541
635
  availableChannels = record.qrSynced ? ["qr", "usb"] : ["usb"];
@@ -544,11 +638,13 @@ function toDeviceInfo(record) {
544
638
  vendor: "keystone",
545
639
  model: record.model ?? "unknown",
546
640
  modelName: record.model,
547
- firmwareVersion: record.deviceVersion ?? "0.0.0",
641
+ firmwareVersion: firmwareVersion ?? "0.0.0",
548
642
  deviceId: record.masterFingerprint,
549
643
  connectId: record.connectId,
550
- connectionType: record.usbSessionId ? "usb" : "qr",
551
- capabilities: CAPABILITIES,
644
+ connectionType,
645
+ capabilities: {
646
+ ...CAPABILITIES
647
+ },
552
648
  raw: {
553
649
  availableChannels,
554
650
  masterFingerprint: record.masterFingerprint,
@@ -568,6 +664,31 @@ function placeholderDeviceInfo() {
568
664
  };
569
665
  }
570
666
 
667
+ // src/adapter/firmwareCapabilities.ts
668
+ var MULTI_COIN = {
669
+ variant: "multi-coin",
670
+ supportedChains: ["btc", "evm", "sol", "tron"]
671
+ };
672
+ var BITCOIN_ONLY = {
673
+ variant: "bitcoin-only",
674
+ supportedChains: ["btc"]
675
+ };
676
+ var CYPHERPUNK = {
677
+ variant: "cypherpunk",
678
+ // Firmware support alone is insufficient: this adapter has no Zcash/Monero methods yet.
679
+ supportedChains: ["btc"]
680
+ };
681
+ function getKeystoneFirmwareProfile(firmwareVersion) {
682
+ if (!firmwareVersion || firmwareVersion === "0.0.0") return void 0;
683
+ const version = /^\d{1,4}(?:\.\d{1,4}){1,3}(?:-([a-z0-9.-]{1,40}))?$/i.exec(firmwareVersion);
684
+ if (!version) return void 0;
685
+ const suffix = version[1]?.toUpperCase();
686
+ if (!suffix) return MULTI_COIN;
687
+ if (suffix === "C" || suffix === "CYPHERPUNK" || suffix === "CYPHERPUNK-B") return CYPHERPUNK;
688
+ if (suffix === "B" || suffix === "BTC" || suffix === "BTC-ONLY") return BITCOIN_ONLY;
689
+ return void 0;
690
+ }
691
+
571
692
  // src/utils/queueKey.ts
572
693
  var import_hwk_adapter_core2 = require("@onekeyfe/hwk-adapter-core");
573
694
  var KEYSTONE_COLD_START_JOB_LABEL = "keystone-cold-start";
@@ -607,6 +728,7 @@ function keystoneBtcParamsFailure(params) {
607
728
  }
608
729
  return void 0;
609
730
  }
731
+ var KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS = 24;
610
732
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
611
733
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
612
734
  var CHAIN_TYPE_BY_CHAIN = {
@@ -654,12 +776,13 @@ function exactHex(value) {
654
776
  function invalidHexFailure(field) {
655
777
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${field} must be an even-length hex string`);
656
778
  }
657
- function requireExportedPath(parsed, path) {
779
+ function requireExportedPath(parsed, path, accountExport = false) {
658
780
  const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
659
781
  if (!account) {
660
782
  throw (0, import_hwk_adapter_core3.createHwkError)({
661
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
662
- message: `Keystone did not return the requested derivation path (${path})`
783
+ code: accountExport ? import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden : import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
784
+ message: `Keystone did not return the requested derivation path (${path})`,
785
+ ...accountExport ? { params: { reason: "account-not-exported" } } : {}
663
786
  });
664
787
  }
665
788
  return account;
@@ -673,7 +796,9 @@ function coinTypeFailure(chain, path) {
673
796
  }
674
797
  function btcAccountFailure(accountPath) {
675
798
  if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
676
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
799
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE, {
800
+ reason: "btc-account-limit"
801
+ });
677
802
  }
678
803
  function missingParamFailure(method, param) {
679
804
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${method} requires ${param}`);
@@ -705,11 +830,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
705
830
  params: { operationId: operation.operationId, reason }
706
831
  });
707
832
  const queueKey = keystoneQueueKey(operation.operationId);
708
- const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
709
833
  this._jobQueue.cancelActiveAndPending(queueKey, ended);
710
- if (ownsRunningCall) {
711
- this._uiRegistry.cancel(void 0, void 0, operation.operationId);
712
- }
834
+ this._uiRegistry.cancel(void 0, void 0, operation.operationId);
713
835
  }
714
836
  }
715
837
  this.emitter.emit(import_hwk_adapter_core3.SDK.OPERATION_ENDED, {
@@ -736,6 +858,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
736
858
  if (!record) return;
737
859
  this._operations.endByConnectionKey(connectId, "disconnect");
738
860
  record.usbSessionId = void 0;
861
+ record.usbFirmwareVersion = void 0;
739
862
  const info = toDeviceInfo(record);
740
863
  if (record.qrSynced) {
741
864
  this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: info });
@@ -745,7 +868,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
745
868
  }
746
869
  };
747
870
  this._handleUsbUiEvent = (event) => {
748
- this.emitter.emit("ui-event", event);
871
+ const operationId = this._activeOperationId();
872
+ this.emitter.emit("ui-event", operationId ? { ...event, operationId } : event);
749
873
  };
750
874
  // ---------------------------------------------------------------------------
751
875
  // All-network bundle, dispatched to the per-chain methods below.
@@ -818,6 +942,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
818
942
  success: true,
819
943
  payload: {
820
944
  ...context.payload,
945
+ ...access?.channel === "qr" && access.accountExport ? { accountExport: true } : {},
821
946
  rootFingerprint: record ? Number.parseInt(record.masterFingerprint, 16) : void 0,
822
947
  deviceIdentity: record ? {
823
948
  vendor: "keystone",
@@ -1067,23 +1192,24 @@ var KeystoneAdapter = class _KeystoneAdapter {
1067
1192
  }
1068
1193
  getDeviceInfo(connectIdOrOperationId, deviceId) {
1069
1194
  try {
1070
- const connectId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1195
+ const operation = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId) : void 0;
1196
+ const connectId = operation?.connectId ?? connectIdOrOperationId;
1071
1197
  const { record } = this._resolveTarget(connectId, deviceId);
1072
1198
  if (!record) {
1073
1199
  return Promise.resolve(
1074
1200
  (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound, "Unknown Keystone device")
1075
1201
  );
1076
1202
  }
1077
- return Promise.resolve((0, import_hwk_adapter_core3.success)(toDeviceInfo(record)));
1203
+ const info = operation ? toDeviceInfoForConnection(record, operation.connectionType === "qr" ? "qr" : "usb") : toDeviceInfo(record);
1204
+ return Promise.resolve((0, import_hwk_adapter_core3.success)(info));
1078
1205
  } catch (err) {
1079
1206
  return Promise.resolve(this._errorToFailure(err));
1080
1207
  }
1081
1208
  }
1082
1209
  cancel(connectId) {
1083
- let namedOperationConnectId;
1084
1210
  if ((0, import_hwk_adapter_core3.isHardwareOperationId)(connectId)) {
1085
1211
  try {
1086
- namedOperationConnectId = this._operations.resolve(connectId).connectId;
1212
+ this._operations.resolve(connectId);
1087
1213
  } catch {
1088
1214
  return;
1089
1215
  }
@@ -1093,15 +1219,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1093
1219
  message: "User aborted operation"
1094
1220
  });
1095
1221
  if (connectId) {
1222
+ const scopedOperationId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1096
1223
  const queueKeys = keystoneCancelQueueKeys([
1097
1224
  connectId,
1098
- this._operationRoutes.get(connectId)?.operationId,
1099
- namedOperationConnectId
1225
+ this._operationRoutes.get(connectId)?.operationId
1100
1226
  ]);
1101
1227
  for (const key of queueKeys) {
1102
1228
  this._jobQueue.cancelActiveAndPending(key, reason);
1103
1229
  }
1104
- const scopedOperationId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1105
1230
  if (scopedOperationId) {
1106
1231
  this._uiRegistry.cancel(void 0, void 0, scopedOperationId);
1107
1232
  }
@@ -1163,13 +1288,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1163
1288
  });
1164
1289
  responseUr = await this._requestQrAndAwaitResponse(
1165
1290
  displayDevice,
1166
- { ...requestUr, animated: false },
1291
+ { ...requestUr, animated: false, allowAccountExport: true },
1167
1292
  signal
1168
1293
  );
1169
1294
  }
1170
1295
  _KeystoneAdapter._throwIfAborted(signal);
1171
- const parsed = this.urEngine.parseAccountResponse(responseUr);
1172
- if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1296
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1297
+ if (!responseUr.accountExport) requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1173
1298
  const record = this._upsertDeviceRecord(parsed);
1174
1299
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
1175
1300
  });
@@ -1766,7 +1891,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1766
1891
  }
1767
1892
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1768
1893
  return {
1769
- access: { channel: "usb", usbSessionId: record.usbSessionId },
1894
+ access: { channel: "usb", usbSessionId: record.usbSessionId, qrFallback: {} },
1770
1895
  masterFingerprint: record.masterFingerprint
1771
1896
  };
1772
1897
  }
@@ -1777,26 +1902,62 @@ var KeystoneAdapter = class _KeystoneAdapter {
1777
1902
  });
1778
1903
  }
1779
1904
  const schemas = Array.from(requestedByKey.values());
1780
- const requestUr = this.urEngine.buildKeyDerivationRequest({
1781
- schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1782
- origin: this._origin
1783
- });
1905
+ if (schemas.length > KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS) {
1906
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1907
+ 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 }
1910
+ });
1911
+ }
1912
+ const request = {
1913
+ ...this.urEngine.buildKeyDerivationRequest({
1914
+ schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1915
+ origin: this._origin
1916
+ }),
1917
+ animated: false,
1918
+ allowAccountExport: true
1919
+ };
1784
1920
  const responseUr = await this._requestQrAndAwaitResponse(
1785
1921
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1786
- { ...requestUr, animated: false },
1922
+ request,
1787
1923
  signal
1788
1924
  );
1789
1925
  _KeystoneAdapter._throwIfAborted(signal);
1790
- const parsed = this.urEngine.parseAccountResponse(responseUr);
1926
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1791
1927
  this._assertParsedIdentity(parsed, target);
1928
+ const firmware = getKeystoneFirmwareProfile(parsed.deviceVersion);
1929
+ if (responseUr.accountExport && parsed.accounts.some((account) => !isBip32Path(account.path))) {
1930
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1931
+ code: import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1932
+ message: "Account export contains an invalid derivation path"
1933
+ });
1934
+ }
1792
1935
  for (const schema of schemas) {
1793
- scanned.set(accountKey(schema.hwkChain, schema.path), {
1794
- ...requireExportedPath(parsed, schema.path),
1795
- hwkChain: schema.hwkChain
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))) {
1938
+ scanned.set(accountKey(schema.hwkChain, schema.path), {
1939
+ ...exported,
1940
+ hwkChain: schema.hwkChain
1941
+ });
1942
+ }
1943
+ }
1944
+ if (responseUr.accountExport && !scanned.size) {
1945
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1946
+ code: import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden,
1947
+ message: "Account export contains none of the requested supported account paths",
1948
+ params: { reason: "account-not-exported" }
1796
1949
  });
1797
1950
  }
1798
1951
  record = this._upsertDeviceRecord(parsed);
1799
- return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1952
+ return {
1953
+ access: {
1954
+ channel: "qr",
1955
+ scanned,
1956
+ firmwareVersion: parsed.deviceVersion,
1957
+ ...responseUr.accountExport ? { accountExport: true } : {}
1958
+ },
1959
+ masterFingerprint: record.masterFingerprint
1960
+ };
1800
1961
  });
1801
1962
  }
1802
1963
  /**
@@ -1870,11 +2031,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
1870
2031
  record = createDeviceRecord(masterFingerprint);
1871
2032
  this._devices.set(masterFingerprint, record);
1872
2033
  }
1873
- record.model = parsed.device ?? record.model;
1874
- record.deviceVersion = parsed.deviceVersion ?? record.deviceVersion;
1875
- record.hardwareDeviceId = parsed.deviceId ?? record.hardwareDeviceId;
1876
- record.usbSessionId = options?.usbSessionId ?? record.usbSessionId;
1877
- if (!options?.viaUsb) record.qrSynced = true;
2034
+ record.model = parsed.device;
2035
+ record.hardwareDeviceId = parsed.deviceId;
2036
+ if (options?.usbSessionId) {
2037
+ record.usbSessionId = options.usbSessionId;
2038
+ record.usbFirmwareVersion = options.usbFirmwareVersion;
2039
+ record.hadUsbSession = true;
2040
+ }
2041
+ if (!options?.viaUsb) {
2042
+ record.deviceVersion = parsed.deviceVersion;
2043
+ record.qrSynced = true;
2044
+ }
1878
2045
  const info = toDeviceInfo(record);
1879
2046
  const eventType = isNew ? import_hwk_adapter_core3.DEVICE.CONNECT : import_hwk_adapter_core3.DEVICE.CHANGED;
1880
2047
  this.emitter.emit(eventType, { type: eventType, payload: info });
@@ -1958,16 +2125,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1958
2125
  }
1959
2126
  _KeystoneAdapter._throwIfAborted(signal);
1960
2127
  const record = this._upsertDeviceRecord(
1961
- { masterFingerprint, accounts: [] },
2128
+ {
2129
+ masterFingerprint,
2130
+ accounts: [],
2131
+ device: session.deviceInfo.modelName ?? session.deviceInfo.model
2132
+ },
1962
2133
  {
1963
2134
  viaUsb: true,
1964
- usbSessionId: session.sessionId
2135
+ usbSessionId: session.sessionId,
2136
+ usbFirmwareVersion: session.deviceInfo.firmwareVersion
1965
2137
  }
1966
2138
  );
1967
2139
  _KeystoneAdapter._throwIfAborted(signal);
1968
- record.hadUsbSession = true;
1969
- record.model = session.deviceInfo.modelName ?? session.deviceInfo.model ?? record.model;
1970
- record.deviceVersion = session.deviceInfo.firmwareVersion ?? record.deviceVersion;
1971
2140
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
1972
2141
  } catch (err) {
1973
2142
  if (sessionId) {
@@ -2037,7 +2206,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2037
2206
  * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
2038
2207
  * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
2039
2208
  */
2040
- async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
2209
+ async _resolveUr(record, requestUr, animated, operationId, signal, operationName, qrFallback) {
2041
2210
  const releaseOperationRetention = (0, import_hwk_adapter_core3.isHardwareOperationId)(operationId) ? this._operations.retain(operationId) : void 0;
2042
2211
  try {
2043
2212
  return await this._resolveUrWithRoute(
@@ -2046,13 +2215,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
2046
2215
  animated,
2047
2216
  operationId,
2048
2217
  signal,
2049
- operationName
2218
+ operationName,
2219
+ qrFallback
2050
2220
  );
2051
2221
  } finally {
2052
2222
  releaseOperationRetention?.();
2053
2223
  }
2054
2224
  }
2055
- async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName) {
2225
+ async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName, qrFallback) {
2056
2226
  let record = callerRecord;
2057
2227
  let interactionRoute;
2058
2228
  if ((0, import_hwk_adapter_core3.isHardwareOperationId)(operationId)) {
@@ -2091,13 +2261,31 @@ var KeystoneAdapter = class _KeystoneAdapter {
2091
2261
  requestUr,
2092
2262
  signal
2093
2263
  );
2094
- if (result.success) return result.payload;
2264
+ if (result.success) {
2265
+ const ur = result.payload;
2266
+ return { urType: ur.urType, urData: ur.urData, channel: "usb" };
2267
+ }
2095
2268
  const usbError = (0, import_hwk_adapter_core3.rehydrateConnectorError)(result.error);
2096
2269
  const { origin: usbErrorOrigin, code: usbErrorCode } = usbError;
2097
2270
  if (usbErrorCode === import_hwk_adapter_core3.HardwareErrorCode.PayloadTooLarge && usbErrorOrigin !== "device") {
2098
2271
  if (!interactionRoute && !this._forcedTransport) {
2272
+ if (!await this._confirmQrFallback(signal, qrFallback)) {
2273
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2274
+ code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
2275
+ message: "User declined to show the request too large for USB as a QR code"
2276
+ });
2277
+ }
2099
2278
  const displayDevice2 = toDeviceInfo(record);
2100
- return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2279
+ const responseUr = await this._requestQrAndAwaitResponse(
2280
+ displayDevice2,
2281
+ {
2282
+ ...requestUr,
2283
+ animated,
2284
+ ...!operationName ? { allowAccountExport: true } : {}
2285
+ },
2286
+ signal
2287
+ );
2288
+ return { ...responseUr, channel: "qr" };
2101
2289
  }
2102
2290
  throw usbError;
2103
2291
  }
@@ -2108,6 +2296,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2108
2296
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2109
2297
  }
2110
2298
  record.usbSessionId = void 0;
2299
+ record.usbFirmwareVersion = void 0;
2111
2300
  this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: toDeviceInfo(record) });
2112
2301
  if (interactionRoute) {
2113
2302
  throw this._endDisconnectedOperation(
@@ -2139,11 +2328,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2139
2328
  }
2140
2329
  const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
2141
2330
  try {
2142
- return await this._requestQrAndAwaitResponse(
2331
+ const responseUr = await this._requestQrAndAwaitResponse(
2143
2332
  displayDevice,
2144
- { ...requestUr, animated },
2333
+ { ...requestUr, animated, ...!operationName ? { allowAccountExport: true } : {} },
2145
2334
  signal
2146
2335
  );
2336
+ return { ...responseUr, channel: "qr" };
2147
2337
  } catch (error) {
2148
2338
  const { code, _tag: tag } = error;
2149
2339
  if (operationName && (code === import_hwk_adapter_core3.HardwareErrorCode.OperationTimeout || tag === import_hwk_adapter_core3.UI_REQUEST_TIMEOUT_TAG)) {
@@ -2177,12 +2367,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2177
2367
  const target = this._resolveTarget(connectId, deviceId);
2178
2368
  if (bundle?.channel === "qr") {
2179
2369
  const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2370
+ if (target.record && !scanned && bundle.accountExport) {
2371
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2372
+ code: import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden,
2373
+ message: "Scanned account export does not include this account path",
2374
+ params: { reason: "account-not-exported" }
2375
+ });
2376
+ }
2180
2377
  if (!target.record || !scanned) {
2181
2378
  throw (0, import_hwk_adapter_core3.createHwkError)({
2182
2379
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2183
2380
  message: `Keystone did not return the requested derivation path (${syncPath})`
2184
2381
  });
2185
2382
  }
2383
+ this._assertQrChainSupported(bundle.firmwareVersion, hwkChain);
2186
2384
  return { record: target.record, account: scanned };
2187
2385
  }
2188
2386
  if (bundle?.channel === "usb" && target.record?.usbSessionId !== bundle.usbSessionId) {
@@ -2191,19 +2389,27 @@ var KeystoneAdapter = class _KeystoneAdapter {
2191
2389
  message: "Keystone USB connection was lost during the bundle"
2192
2390
  });
2193
2391
  }
2194
- const operationConnectionType = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? this._operations.resolve(connectId).connectionType : void 0;
2195
2392
  let existingRecord = target.record;
2196
2393
  if (!existingRecord) {
2197
2394
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2198
2395
  _KeystoneAdapter._throwIfAborted(signal);
2199
2396
  }
2200
- const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2201
2397
  const schemas = [keySchema(hwkChain, syncPath)];
2202
2398
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2203
- const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2399
+ const responseUr = await this._resolveUr(
2400
+ existingRecord,
2401
+ requestUr,
2402
+ false,
2403
+ connectId,
2404
+ signal,
2405
+ void 0,
2406
+ bundle?.channel === "usb" ? bundle.qrFallback : void 0
2407
+ );
2204
2408
  _KeystoneAdapter._throwIfAborted(signal);
2205
- const parsed = this.urEngine.parseAccountResponse(responseUr);
2206
- const account = requireExportedPath(parsed, syncPath);
2409
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2410
+ this._assertParsedIdentity(parsed, target);
2411
+ const account = requireExportedPath(parsed, syncPath, responseUr.accountExport);
2412
+ const useSinglePathUsbExport = !responseUr.accountExport && responseUr.channel === "usb";
2207
2413
  let record;
2208
2414
  if (useSinglePathUsbExport && existingRecord) {
2209
2415
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2214,23 +2420,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
2214
2420
  }
2215
2421
  record = existingRecord;
2216
2422
  } else {
2217
- this._assertParsedIdentity(parsed, target);
2218
- record = this._upsertDeviceRecord(parsed, {
2219
- viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2220
- });
2423
+ this._assertQrChainSupported(parsed.deviceVersion, hwkChain);
2424
+ record = this._upsertDeviceRecord(parsed);
2221
2425
  }
2222
2426
  return { record, account: { ...account, hwkChain } };
2223
2427
  }
2224
2428
  /**
2225
- * Resolves which wallet is attached, without a per-path account. `CHAIN_FINGERPRINT_PATHS.evm` is
2226
- * a leaf path, so it is cut to the account path Keystone expects.
2429
+ * Resolves wallet identity without a per-path account. A caller-supplied fingerprint needs no
2430
+ * device round trip; otherwise request the account path from the device.
2227
2431
  */
2228
2432
  async _ensureWalletKnown(connectId, deviceId, chain, signal) {
2229
2433
  const target = this._resolveTarget(connectId, deviceId);
2230
2434
  if (target.record) return { record: target.record };
2231
- const attached = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2232
- _KeystoneAdapter._throwIfAborted(signal);
2233
- if (attached) return { record: attached };
2234
2435
  if (target.expectedMasterFingerprint) {
2235
2436
  return { record: createDeviceRecord(target.expectedMasterFingerprint) };
2236
2437
  }
@@ -2241,19 +2442,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
2241
2442
  });
2242
2443
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2243
2444
  _KeystoneAdapter._throwIfAborted(signal);
2244
- const parsed = this.urEngine.parseAccountResponse(responseUr);
2245
- requireExportedPath(parsed, normalizePath(accountPath));
2246
- return { record: this._upsertDeviceRecord(parsed) };
2445
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2446
+ requireExportedPath(parsed, normalizePath(accountPath), responseUr.accountExport);
2447
+ this._assertQrChainSupported(parsed.deviceVersion, chain);
2448
+ const record = this._upsertDeviceRecord(parsed);
2449
+ return { record };
2450
+ }
2451
+ _assertQrChainSupported(firmwareVersion, chain) {
2452
+ const firmware = getKeystoneFirmwareProfile(firmwareVersion);
2453
+ if (firmware && !firmware.supportedChains.includes(chain)) {
2454
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2455
+ code: import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
2456
+ message: `Keystone ${firmware.variant} firmware cannot use ${chain} through this adapter`,
2457
+ params: { firmwareVariant: firmware.variant, chain }
2458
+ });
2459
+ }
2247
2460
  }
2248
- /**
2249
- * The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
2250
- * through the operation route; a cold start returns undefined.
2251
- */
2461
+ /** Only an operation id supplied to the running call owns its UI prompts. */
2252
2462
  _activeOperationId() {
2253
- const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
2254
- if (!activeJobId) return void 0;
2255
- if ((0, import_hwk_adapter_core3.isHardwareOperationId)(activeJobId)) return activeJobId;
2256
- return this._operationRouteForIdentifier(activeJobId)?.operationId;
2463
+ return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
2257
2464
  }
2258
2465
  /** Routes are keyed by connectId; a job key may be the bare master fingerprint. */
2259
2466
  _operationRouteForIdentifier(identifier) {
@@ -2286,6 +2493,39 @@ var KeystoneAdapter = class _KeystoneAdapter {
2286
2493
  signal.removeEventListener("abort", onAbort);
2287
2494
  }
2288
2495
  }
2496
+ /**
2497
+ * Asks whether a request too large for USB may be shown as a QR. A timeout or an unanswered
2498
+ * prompt reads as no; a cancelled call keeps its own error.
2499
+ */
2500
+ async _confirmQrFallback(signal, choice) {
2501
+ if (choice?.confirmed !== void 0) return choice.confirmed;
2502
+ const requestType = import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_FALLBACK_CONFIRM;
2503
+ const requestId = this._uiRegistry.createRequestId();
2504
+ const operationId = this._activeOperationId();
2505
+ const release = operationId ? this._operations.retain(operationId) : void 0;
2506
+ try {
2507
+ const waitPromise = this._uiRegistry.wait(requestType, {
2508
+ requestId,
2509
+ operationId
2510
+ });
2511
+ this.emitter.emit(requestType, {
2512
+ type: requestType,
2513
+ payload: { vendor: "keystone", requestId, operationId }
2514
+ });
2515
+ let confirmed = false;
2516
+ try {
2517
+ confirmed = Boolean(
2518
+ (await this._awaitQrResponse(requestType, waitPromise, signal))?.confirmed
2519
+ );
2520
+ } catch (error) {
2521
+ if (signal.aborted) throw error;
2522
+ }
2523
+ if (choice) choice.confirmed = confirmed;
2524
+ return confirmed;
2525
+ } finally {
2526
+ release?.();
2527
+ }
2528
+ }
2289
2529
  /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2290
2530
  async _requestQrAndAwaitResponse(device, data, signal) {
2291
2531
  const requestType = data ? import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY : import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN;
@@ -2308,7 +2548,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
2308
2548
  });
2309
2549
  }
2310
2550
  const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2311
- return { urType: response.urType, urData: response.urData };
2551
+ 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
+ });
2556
+ }
2557
+ return {
2558
+ urType: response.urType,
2559
+ urData: response.urData,
2560
+ ...!data || response.accountExport ? { accountExport: true } : {}
2561
+ };
2312
2562
  } finally {
2313
2563
  release?.();
2314
2564
  }