@onekeyfe/hwk-keystone-adapter 1.2.8-alpha.119 → 1.2.8-alpha.120

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,8 +47,6 @@ 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");
52
50
  var import_keystone_sdk = require("@keystonehq/keystone-sdk");
53
51
  var import_bs58check = __toESM(require("bs58check"));
54
52
  var bitcoin = __toESM(require("bitcoinjs-lib"));
@@ -278,93 +276,6 @@ var KeystoneUrEngine = class {
278
276
  }
279
277
  return this.parseMultiAccounts(ur);
280
278
  }
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((segment) => Number(segment.replace("'", "")) >= BIP32_HARDENED_OFFSET)) {
334
- throw new Error("Account export has an unsupported derivation path");
335
- }
336
- let identity = account.publicKey;
337
- if (account.extendedPublicKey) {
338
- const node = import_hdkey.default.fromExtendedKey(account.extendedPublicKey);
339
- if (node.privateKey || !node.publicKey || !node.chainCode) {
340
- throw new Error("Account public keys required");
341
- }
342
- if (node.publicKey.toString("hex") !== account.publicKey.toLowerCase()) {
343
- throw new Error("Account public key does not match its extended key");
344
- }
345
- identity = `${identity}:${node.chainCode.toString("hex")}`;
346
- } else if (!/^[0-9a-f]{64}$/i.test(account.publicKey)) {
347
- throw new Error("Account export is missing a usable public key");
348
- }
349
- const previous = byPath.get(account.path);
350
- if (previous !== void 0 && previous !== identity) {
351
- throw (0, import_hwk_adapter_core.createHwkError)({
352
- code: import_hwk_adapter_core.HardwareErrorCode.DeviceMismatch,
353
- message: "Account export contains conflicting keys for the same path"
354
- });
355
- }
356
- byPath.set(account.path, identity);
357
- }
358
- return parsed;
359
- } catch (error) {
360
- if (error && typeof error === "object" && "code" in error && error.code === import_hwk_adapter_core.HardwareErrorCode.DeviceMismatch)
361
- throw error;
362
- throw (0, import_hwk_adapter_core.createHwkError)({
363
- code: import_hwk_adapter_core.HardwareErrorCode.InvalidParams,
364
- message: "Unable to read account export; scan a supported Keystone account export code"
365
- });
366
- }
367
- }
368
279
  // --- EVM ---
369
280
  buildEthSignRequest(input) {
370
281
  const ur = this.sdk.eth.generateSignRequest({
@@ -553,31 +464,6 @@ var import_bs58 = __toESM(require("bs58"));
553
464
  var import_uuid2 = require("uuid");
554
465
  var import_hwk_adapter_core3 = require("@onekeyfe/hwk-adapter-core");
555
466
 
556
- // src/adapter/firmwareCapabilities.ts
557
- var MULTI_COIN = {
558
- variant: "multi-coin",
559
- supportedChains: ["btc", "evm", "sol", "tron"]
560
- };
561
- var BITCOIN_ONLY = {
562
- variant: "bitcoin-only",
563
- supportedChains: ["btc"]
564
- };
565
- var CYPHERPUNK = {
566
- variant: "cypherpunk",
567
- // Firmware support alone is insufficient: this adapter has no Zcash/Monero methods yet.
568
- supportedChains: ["btc"]
569
- };
570
- function getKeystoneFirmwareProfile(firmwareVersion) {
571
- if (!firmwareVersion || firmwareVersion === "0.0.0") return void 0;
572
- const version = /^\d{1,4}(?:\.\d{1,4}){1,3}(?:-([a-z0-9.-]{1,40}))?$/i.exec(firmwareVersion);
573
- if (!version) return void 0;
574
- const suffix = version[1]?.toUpperCase();
575
- if (!suffix) return MULTI_COIN;
576
- if (suffix === "C" || suffix === "CYPHERPUNK" || suffix === "CYPHERPUNK-B") return CYPHERPUNK;
577
- if (suffix === "B" || suffix === "BTC" || suffix === "BTC-ONLY") return BITCOIN_ONLY;
578
- return void 0;
579
- }
580
-
581
467
  // src/adapter/pathUtils.ts
582
468
  function normalizePath(path) {
583
469
  const trimmed = path.trim();
@@ -644,16 +530,12 @@ function accountKey(hwkChain, path) {
644
530
  function createDeviceRecord(masterFingerprint) {
645
531
  return {
646
532
  masterFingerprint,
647
- connectId: walletConnectId(masterFingerprint)
533
+ connectId: walletConnectId(masterFingerprint),
534
+ importedAt: Date.now()
648
535
  };
649
536
  }
650
537
  var CAPABILITIES = { persistentDeviceIdentity: true };
651
538
  function toDeviceInfo(record) {
652
- return toDeviceInfoForConnection(record, record.usbSessionId ? "usb" : "qr");
653
- }
654
- function toDeviceInfoForConnection(record, connectionType) {
655
- const firmwareVersion = connectionType === "usb" ? record.usbFirmwareVersion : record.deviceVersion;
656
- const firmware = connectionType === "usb" ? getKeystoneFirmwareProfile(firmwareVersion) : void 0;
657
539
  let availableChannels = ["qr"];
658
540
  if (record.usbSessionId) {
659
541
  availableChannels = record.qrSynced ? ["qr", "usb"] : ["usb"];
@@ -662,14 +544,11 @@ function toDeviceInfoForConnection(record, connectionType) {
662
544
  vendor: "keystone",
663
545
  model: record.model ?? "unknown",
664
546
  modelName: record.model,
665
- firmwareVersion: firmwareVersion ?? "0.0.0",
547
+ firmwareVersion: record.deviceVersion ?? "0.0.0",
666
548
  deviceId: record.masterFingerprint,
667
549
  connectId: record.connectId,
668
- connectionType,
669
- capabilities: {
670
- ...CAPABILITIES,
671
- ...firmware ? { supportedChains: [...firmware.supportedChains] } : {}
672
- },
550
+ connectionType: record.usbSessionId ? "usb" : "qr",
551
+ capabilities: CAPABILITIES,
673
552
  raw: {
674
553
  availableChannels,
675
554
  masterFingerprint: record.masterFingerprint,
@@ -728,7 +607,6 @@ function keystoneBtcParamsFailure(params) {
728
607
  }
729
608
  return void 0;
730
609
  }
731
- var KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS = 24;
732
610
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
733
611
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
734
612
  var CHAIN_TYPE_BY_CHAIN = {
@@ -776,13 +654,12 @@ function exactHex(value) {
776
654
  function invalidHexFailure(field) {
777
655
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${field} must be an even-length hex string`);
778
656
  }
779
- function requireExportedPath(parsed, path, accountExport = false) {
657
+ function requireExportedPath(parsed, path) {
780
658
  const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
781
659
  if (!account) {
782
660
  throw (0, import_hwk_adapter_core3.createHwkError)({
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" } } : {}
661
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
662
+ message: `Keystone did not return the requested derivation path (${path})`
786
663
  });
787
664
  }
788
665
  return account;
@@ -796,9 +673,7 @@ function coinTypeFailure(chain, path) {
796
673
  }
797
674
  function btcAccountFailure(accountPath) {
798
675
  if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
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
- });
676
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
802
677
  }
803
678
  function missingParamFailure(method, param) {
804
679
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${method} requires ${param}`);
@@ -830,8 +705,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
830
705
  params: { operationId: operation.operationId, reason }
831
706
  });
832
707
  const queueKey = keystoneQueueKey(operation.operationId);
708
+ const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
833
709
  this._jobQueue.cancelActiveAndPending(queueKey, ended);
834
- this._uiRegistry.cancel(void 0, void 0, operation.operationId);
710
+ if (ownsRunningCall) {
711
+ this._uiRegistry.cancel(void 0, void 0, operation.operationId);
712
+ }
835
713
  }
836
714
  }
837
715
  this.emitter.emit(import_hwk_adapter_core3.SDK.OPERATION_ENDED, {
@@ -858,7 +736,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
858
736
  if (!record) return;
859
737
  this._operations.endByConnectionKey(connectId, "disconnect");
860
738
  record.usbSessionId = void 0;
861
- record.usbFirmwareVersion = void 0;
862
739
  const info = toDeviceInfo(record);
863
740
  if (record.qrSynced) {
864
741
  this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: info });
@@ -868,8 +745,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
868
745
  }
869
746
  };
870
747
  this._handleUsbUiEvent = (event) => {
871
- const operationId = this._activeOperationId();
872
- this.emitter.emit("ui-event", operationId ? { ...event, operationId } : event);
748
+ this.emitter.emit("ui-event", event);
873
749
  };
874
750
  // ---------------------------------------------------------------------------
875
751
  // All-network bundle, dispatched to the per-chain methods below.
@@ -942,7 +818,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
942
818
  success: true,
943
819
  payload: {
944
820
  ...context.payload,
945
- ...access?.channel === "qr" && access.accountExport ? { accountExport: true } : {},
946
821
  rootFingerprint: record ? Number.parseInt(record.masterFingerprint, 16) : void 0,
947
822
  deviceIdentity: record ? {
948
823
  vendor: "keystone",
@@ -1192,24 +1067,23 @@ var KeystoneAdapter = class _KeystoneAdapter {
1192
1067
  }
1193
1068
  getDeviceInfo(connectIdOrOperationId, deviceId) {
1194
1069
  try {
1195
- const operation = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId) : void 0;
1196
- const connectId = operation?.connectId ?? connectIdOrOperationId;
1070
+ const connectId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1197
1071
  const { record } = this._resolveTarget(connectId, deviceId);
1198
1072
  if (!record) {
1199
1073
  return Promise.resolve(
1200
1074
  (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound, "Unknown Keystone device")
1201
1075
  );
1202
1076
  }
1203
- const info = operation ? toDeviceInfoForConnection(record, operation.connectionType === "qr" ? "qr" : "usb") : toDeviceInfo(record);
1204
- return Promise.resolve((0, import_hwk_adapter_core3.success)(info));
1077
+ return Promise.resolve((0, import_hwk_adapter_core3.success)(toDeviceInfo(record)));
1205
1078
  } catch (err) {
1206
1079
  return Promise.resolve(this._errorToFailure(err));
1207
1080
  }
1208
1081
  }
1209
1082
  cancel(connectId) {
1083
+ let namedOperationConnectId;
1210
1084
  if ((0, import_hwk_adapter_core3.isHardwareOperationId)(connectId)) {
1211
1085
  try {
1212
- this._operations.resolve(connectId);
1086
+ namedOperationConnectId = this._operations.resolve(connectId).connectId;
1213
1087
  } catch {
1214
1088
  return;
1215
1089
  }
@@ -1219,14 +1093,15 @@ var KeystoneAdapter = class _KeystoneAdapter {
1219
1093
  message: "User aborted operation"
1220
1094
  });
1221
1095
  if (connectId) {
1222
- const scopedOperationId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1223
1096
  const queueKeys = keystoneCancelQueueKeys([
1224
1097
  connectId,
1225
- this._operationRoutes.get(connectId)?.operationId
1098
+ this._operationRoutes.get(connectId)?.operationId,
1099
+ namedOperationConnectId
1226
1100
  ]);
1227
1101
  for (const key of queueKeys) {
1228
1102
  this._jobQueue.cancelActiveAndPending(key, reason);
1229
1103
  }
1104
+ const scopedOperationId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1230
1105
  if (scopedOperationId) {
1231
1106
  this._uiRegistry.cancel(void 0, void 0, scopedOperationId);
1232
1107
  }
@@ -1288,13 +1163,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1288
1163
  });
1289
1164
  responseUr = await this._requestQrAndAwaitResponse(
1290
1165
  displayDevice,
1291
- { ...requestUr, animated: false, allowAccountExport: true },
1166
+ { ...requestUr, animated: false },
1292
1167
  signal
1293
1168
  );
1294
1169
  }
1295
1170
  _KeystoneAdapter._throwIfAborted(signal);
1296
- const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1297
- if (!responseUr.accountExport) requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1171
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
1172
+ if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1298
1173
  const record = this._upsertDeviceRecord(parsed);
1299
1174
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
1300
1175
  });
@@ -1491,7 +1366,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1491
1366
  true,
1492
1367
  connectId,
1493
1368
  signal,
1494
- "btc",
1495
1369
  "btcSignPsbt"
1496
1370
  );
1497
1371
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1839,7 +1713,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1839
1713
  true,
1840
1714
  connectId,
1841
1715
  signal,
1842
- args.chain,
1843
1716
  args.operationName
1844
1717
  );
1845
1718
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1893,7 +1766,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1893
1766
  }
1894
1767
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1895
1768
  return {
1896
- access: { channel: "usb", usbSessionId: record.usbSessionId, qrFallback: {} },
1769
+ access: { channel: "usb", usbSessionId: record.usbSessionId },
1897
1770
  masterFingerprint: record.masterFingerprint
1898
1771
  };
1899
1772
  }
@@ -1904,62 +1777,26 @@ var KeystoneAdapter = class _KeystoneAdapter {
1904
1777
  });
1905
1778
  }
1906
1779
  const schemas = Array.from(requestedByKey.values());
1907
- if (schemas.length > KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS) {
1908
- throw (0, import_hwk_adapter_core3.createHwkError)({
1909
- code: import_hwk_adapter_core3.HardwareErrorCode.QrRequestTooLarge,
1910
- message: `Keystone accepts at most ${KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS} account paths per QR request; this one needs ${schemas.length}`,
1911
- params: { limit: KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS, requested: schemas.length }
1912
- });
1913
- }
1914
- const request = {
1915
- ...this.urEngine.buildKeyDerivationRequest({
1916
- schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1917
- origin: this._origin
1918
- }),
1919
- animated: false,
1920
- allowAccountExport: true
1921
- };
1780
+ const requestUr = this.urEngine.buildKeyDerivationRequest({
1781
+ schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1782
+ origin: this._origin
1783
+ });
1922
1784
  const responseUr = await this._requestQrAndAwaitResponse(
1923
1785
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1924
- request,
1786
+ { ...requestUr, animated: false },
1925
1787
  signal
1926
1788
  );
1927
1789
  _KeystoneAdapter._throwIfAborted(signal);
1928
- const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1790
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
1929
1791
  this._assertParsedIdentity(parsed, target);
1930
- const firmware = getKeystoneFirmwareProfile(parsed.deviceVersion);
1931
- if (responseUr.accountExport && parsed.accounts.some((account) => !isBip32Path(account.path))) {
1932
- throw (0, import_hwk_adapter_core3.createHwkError)({
1933
- code: import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1934
- message: "Account export contains an invalid derivation path"
1935
- });
1936
- }
1937
1792
  for (const schema of schemas) {
1938
- const exported = responseUr.accountExport ? parsed.accounts.find((account) => normalizePath(account.path) === schema.path) : requireExportedPath(parsed, schema.path);
1939
- if (exported && (!responseUr.accountExport || !firmware || firmware.supportedChains.includes(schema.hwkChain))) {
1940
- scanned.set(accountKey(schema.hwkChain, schema.path), {
1941
- ...exported,
1942
- hwkChain: schema.hwkChain
1943
- });
1944
- }
1945
- }
1946
- if (responseUr.accountExport && !scanned.size) {
1947
- throw (0, import_hwk_adapter_core3.createHwkError)({
1948
- code: import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden,
1949
- message: "Account export contains none of the requested supported account paths",
1950
- params: { reason: "account-not-exported" }
1793
+ scanned.set(accountKey(schema.hwkChain, schema.path), {
1794
+ ...requireExportedPath(parsed, schema.path),
1795
+ hwkChain: schema.hwkChain
1951
1796
  });
1952
1797
  }
1953
1798
  record = this._upsertDeviceRecord(parsed);
1954
- return {
1955
- access: {
1956
- channel: "qr",
1957
- scanned,
1958
- firmwareVersion: parsed.deviceVersion,
1959
- ...responseUr.accountExport ? { accountExport: true } : {}
1960
- },
1961
- masterFingerprint: record.masterFingerprint
1962
- };
1799
+ return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1963
1800
  });
1964
1801
  }
1965
1802
  /**
@@ -2033,17 +1870,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
2033
1870
  record = createDeviceRecord(masterFingerprint);
2034
1871
  this._devices.set(masterFingerprint, record);
2035
1872
  }
2036
- record.model = parsed.device;
2037
- record.hardwareDeviceId = parsed.deviceId;
2038
- if (options?.usbSessionId) {
2039
- record.usbSessionId = options.usbSessionId;
2040
- record.usbFirmwareVersion = options.usbFirmwareVersion;
2041
- record.hadUsbSession = true;
2042
- }
2043
- if (!options?.viaUsb) {
2044
- record.deviceVersion = parsed.deviceVersion;
2045
- record.qrSynced = true;
2046
- }
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;
2047
1878
  const info = toDeviceInfo(record);
2048
1879
  const eventType = isNew ? import_hwk_adapter_core3.DEVICE.CONNECT : import_hwk_adapter_core3.DEVICE.CHANGED;
2049
1880
  this.emitter.emit(eventType, { type: eventType, payload: info });
@@ -2127,18 +1958,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
2127
1958
  }
2128
1959
  _KeystoneAdapter._throwIfAborted(signal);
2129
1960
  const record = this._upsertDeviceRecord(
2130
- {
2131
- masterFingerprint,
2132
- accounts: [],
2133
- device: session.deviceInfo.modelName ?? session.deviceInfo.model
2134
- },
1961
+ { masterFingerprint, accounts: [] },
2135
1962
  {
2136
1963
  viaUsb: true,
2137
- usbSessionId: session.sessionId,
2138
- usbFirmwareVersion: session.deviceInfo.firmwareVersion
1964
+ usbSessionId: session.sessionId
2139
1965
  }
2140
1966
  );
2141
1967
  _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;
2142
1971
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
2143
1972
  } catch (err) {
2144
1973
  if (sessionId) {
@@ -2208,7 +2037,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2208
2037
  * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
2209
2038
  * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
2210
2039
  */
2211
- async _resolveUr(record, requestUr, animated, operationId, signal, chain, operationName, qrFallback) {
2040
+ async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
2212
2041
  const releaseOperationRetention = (0, import_hwk_adapter_core3.isHardwareOperationId)(operationId) ? this._operations.retain(operationId) : void 0;
2213
2042
  try {
2214
2043
  return await this._resolveUrWithRoute(
@@ -2217,15 +2046,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
2217
2046
  animated,
2218
2047
  operationId,
2219
2048
  signal,
2220
- chain,
2221
- operationName,
2222
- qrFallback
2049
+ operationName
2223
2050
  );
2224
2051
  } finally {
2225
2052
  releaseOperationRetention?.();
2226
2053
  }
2227
2054
  }
2228
- async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, chain, operationName, qrFallback) {
2055
+ async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName) {
2229
2056
  let record = callerRecord;
2230
2057
  let interactionRoute;
2231
2058
  if ((0, import_hwk_adapter_core3.isHardwareOperationId)(operationId)) {
@@ -2258,37 +2085,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
2258
2085
  message: "USB channel is not connected for this Keystone wallet"
2259
2086
  });
2260
2087
  }
2261
- this._assertChainSupported(record.usbFirmwareVersion, chain);
2262
2088
  const result = await this._callUsbResolveUr(
2263
2089
  this._usbConnector,
2264
2090
  record.usbSessionId,
2265
2091
  requestUr,
2266
2092
  signal
2267
2093
  );
2268
- if (result.success) {
2269
- const ur = result.payload;
2270
- return { urType: ur.urType, urData: ur.urData };
2271
- }
2094
+ if (result.success) return result.payload;
2272
2095
  const usbError = (0, import_hwk_adapter_core3.rehydrateConnectorError)(result.error);
2273
2096
  const { origin: usbErrorOrigin, code: usbErrorCode } = usbError;
2274
2097
  if (usbErrorCode === import_hwk_adapter_core3.HardwareErrorCode.PayloadTooLarge && usbErrorOrigin !== "device") {
2275
2098
  if (!interactionRoute && !this._forcedTransport) {
2276
- if (!await this._confirmQrFallback(signal, qrFallback)) {
2277
- throw (0, import_hwk_adapter_core3.createHwkError)({
2278
- code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
2279
- message: "User declined to show the request too large for USB as a QR code"
2280
- });
2281
- }
2282
2099
  const displayDevice2 = toDeviceInfo(record);
2283
- return this._requestQrAndAwaitResponse(
2284
- displayDevice2,
2285
- {
2286
- ...requestUr,
2287
- animated,
2288
- ...!operationName ? { allowAccountExport: true } : {}
2289
- },
2290
- signal
2291
- );
2100
+ return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2292
2101
  }
2293
2102
  throw usbError;
2294
2103
  }
@@ -2299,7 +2108,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2299
2108
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2300
2109
  }
2301
2110
  record.usbSessionId = void 0;
2302
- record.usbFirmwareVersion = void 0;
2303
2111
  this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: toDeviceInfo(record) });
2304
2112
  if (interactionRoute) {
2305
2113
  throw this._endDisconnectedOperation(
@@ -2333,7 +2141,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2333
2141
  try {
2334
2142
  return await this._requestQrAndAwaitResponse(
2335
2143
  displayDevice,
2336
- { ...requestUr, animated, ...!operationName ? { allowAccountExport: true } : {} },
2144
+ { ...requestUr, animated },
2337
2145
  signal
2338
2146
  );
2339
2147
  } catch (error) {
@@ -2369,20 +2177,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2369
2177
  const target = this._resolveTarget(connectId, deviceId);
2370
2178
  if (bundle?.channel === "qr") {
2371
2179
  const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2372
- if (target.record && !scanned && bundle.accountExport) {
2373
- throw (0, import_hwk_adapter_core3.createHwkError)({
2374
- code: import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden,
2375
- message: "Scanned account export does not include this account path",
2376
- params: { reason: "account-not-exported" }
2377
- });
2378
- }
2379
2180
  if (!target.record || !scanned) {
2380
2181
  throw (0, import_hwk_adapter_core3.createHwkError)({
2381
2182
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2382
2183
  message: `Keystone did not return the requested derivation path (${syncPath})`
2383
2184
  });
2384
2185
  }
2385
- this._assertChainSupported(bundle.firmwareVersion, hwkChain);
2386
2186
  return { record: target.record, account: scanned };
2387
2187
  }
2388
2188
  if (bundle?.channel === "usb" && target.record?.usbSessionId !== bundle.usbSessionId) {
@@ -2397,23 +2197,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
2397
2197
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2398
2198
  _KeystoneAdapter._throwIfAborted(signal);
2399
2199
  }
2200
+ const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2400
2201
  const schemas = [keySchema(hwkChain, syncPath)];
2401
2202
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2402
- const responseUr = await this._resolveUr(
2403
- existingRecord,
2404
- requestUr,
2405
- false,
2406
- connectId,
2407
- signal,
2408
- hwkChain,
2409
- void 0,
2410
- bundle?.channel === "usb" ? bundle.qrFallback : void 0
2411
- );
2203
+ const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2412
2204
  _KeystoneAdapter._throwIfAborted(signal);
2413
- const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2414
- this._assertParsedIdentity(parsed, target);
2415
- const account = requireExportedPath(parsed, syncPath, responseUr.accountExport);
2416
- const useSinglePathUsbExport = !responseUr.accountExport && (operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId));
2205
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
2206
+ const account = requireExportedPath(parsed, syncPath);
2417
2207
  let record;
2418
2208
  if (useSinglePathUsbExport && existingRecord) {
2419
2209
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2424,8 +2214,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
2424
2214
  }
2425
2215
  record = existingRecord;
2426
2216
  } else {
2427
- this._assertChainSupported(parsed.deviceVersion, hwkChain);
2428
- record = this._upsertDeviceRecord(parsed);
2217
+ this._assertParsedIdentity(parsed, target);
2218
+ record = this._upsertDeviceRecord(parsed, {
2219
+ viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2220
+ });
2429
2221
  }
2430
2222
  return { record, account: { ...account, hwkChain } };
2431
2223
  }
@@ -2447,27 +2239,21 @@ var KeystoneAdapter = class _KeystoneAdapter {
2447
2239
  schemas: [keySchema(chain, accountPath)],
2448
2240
  origin: this._origin
2449
2241
  });
2450
- const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal, chain);
2242
+ const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2451
2243
  _KeystoneAdapter._throwIfAborted(signal);
2452
- const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2453
- requireExportedPath(parsed, normalizePath(accountPath), responseUr.accountExport);
2454
- this._assertChainSupported(parsed.deviceVersion, chain);
2455
- const record = this._upsertDeviceRecord(parsed);
2456
- return { record };
2457
- }
2458
- _assertChainSupported(firmwareVersion, chain) {
2459
- const firmware = getKeystoneFirmwareProfile(firmwareVersion);
2460
- if (firmware && !firmware.supportedChains.includes(chain)) {
2461
- throw (0, import_hwk_adapter_core3.createHwkError)({
2462
- code: import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
2463
- message: `Keystone ${firmware.variant} firmware cannot use ${chain} through this adapter`,
2464
- params: { firmwareVariant: firmware.variant, chain }
2465
- });
2466
- }
2244
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
2245
+ requireExportedPath(parsed, normalizePath(accountPath));
2246
+ return { record: this._upsertDeviceRecord(parsed) };
2467
2247
  }
2468
- /** Only an operation id supplied to the running call owns its UI prompts. */
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
+ */
2469
2252
  _activeOperationId() {
2470
- return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
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;
2471
2257
  }
2472
2258
  /** Routes are keyed by connectId; a job key may be the bare master fingerprint. */
2473
2259
  _operationRouteForIdentifier(identifier) {
@@ -2500,37 +2286,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2500
2286
  signal.removeEventListener("abort", onAbort);
2501
2287
  }
2502
2288
  }
2503
- /**
2504
- * Asks whether a request too large for USB may be shown as a QR. A timeout or an unanswered
2505
- * prompt reads as no; a cancelled call keeps its own error.
2506
- */
2507
- async _confirmQrFallback(signal, choice) {
2508
- if (choice?.confirmed !== void 0) return choice.confirmed;
2509
- const requestType = import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_FALLBACK_CONFIRM;
2510
- const operationId = this._activeOperationId();
2511
- const release = operationId ? this._operations.retain(operationId) : void 0;
2512
- try {
2513
- const waitPromise = this._uiRegistry.wait(requestType, {
2514
- operationId
2515
- });
2516
- this.emitter.emit(requestType, {
2517
- type: requestType,
2518
- payload: { vendor: "keystone", operationId }
2519
- });
2520
- let confirmed = false;
2521
- try {
2522
- confirmed = Boolean(
2523
- (await this._awaitQrResponse(requestType, waitPromise, signal))?.confirmed
2524
- );
2525
- } catch (error) {
2526
- if (signal.aborted) throw error;
2527
- }
2528
- if (choice) choice.confirmed = confirmed;
2529
- return confirmed;
2530
- } finally {
2531
- release?.();
2532
- }
2533
- }
2534
2289
  /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2535
2290
  async _requestQrAndAwaitResponse(device, data, signal) {
2536
2291
  const requestType = data ? import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY : import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN;
@@ -2553,17 +2308,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2553
2308
  });
2554
2309
  }
2555
2310
  const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2556
- if (response.accountExport && data && !data.allowAccountExport) {
2557
- throw (0, import_hwk_adapter_core3.createHwkError)({
2558
- code: import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
2559
- message: "This request cannot be answered with an account export"
2560
- });
2561
- }
2562
- return {
2563
- urType: response.urType,
2564
- urData: response.urData,
2565
- ...!data || response.accountExport ? { accountExport: true } : {}
2566
- };
2311
+ return { urType: response.urType, urData: response.urData };
2567
2312
  } finally {
2568
2313
  release?.();
2569
2314
  }