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

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"));
@@ -222,7 +220,7 @@ function relativeHdPath(relativeDerivePath) {
222
220
  }
223
221
  return `m/${segments.join("/")}`;
224
222
  }
225
- var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.-]{1,20})?$/;
223
+ var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.]{1,20})?$/;
226
224
  var DEVICE_TEXT = /^[^\p{Cc}\p{Cf}]{1,64}$/u;
227
225
  function deviceText(value, pattern) {
228
226
  return typeof value === "string" && pattern.test(value) ? value : void 0;
@@ -278,95 +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(
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
- }
370
279
  // --- EVM ---
371
280
  buildEthSignRequest(input) {
372
281
  const ur = this.sdk.eth.generateSignRequest({
@@ -621,15 +530,12 @@ function accountKey(hwkChain, path) {
621
530
  function createDeviceRecord(masterFingerprint) {
622
531
  return {
623
532
  masterFingerprint,
624
- connectId: walletConnectId(masterFingerprint)
533
+ connectId: walletConnectId(masterFingerprint),
534
+ importedAt: Date.now()
625
535
  };
626
536
  }
627
537
  var CAPABILITIES = { persistentDeviceIdentity: true };
628
538
  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;
633
539
  let availableChannels = ["qr"];
634
540
  if (record.usbSessionId) {
635
541
  availableChannels = record.qrSynced ? ["qr", "usb"] : ["usb"];
@@ -638,13 +544,11 @@ function toDeviceInfoForConnection(record, connectionType) {
638
544
  vendor: "keystone",
639
545
  model: record.model ?? "unknown",
640
546
  modelName: record.model,
641
- firmwareVersion: firmwareVersion ?? "0.0.0",
547
+ firmwareVersion: record.deviceVersion ?? "0.0.0",
642
548
  deviceId: record.masterFingerprint,
643
549
  connectId: record.connectId,
644
- connectionType,
645
- capabilities: {
646
- ...CAPABILITIES
647
- },
550
+ connectionType: record.usbSessionId ? "usb" : "qr",
551
+ capabilities: CAPABILITIES,
648
552
  raw: {
649
553
  availableChannels,
650
554
  masterFingerprint: record.masterFingerprint,
@@ -664,31 +568,6 @@ function placeholderDeviceInfo() {
664
568
  };
665
569
  }
666
570
 
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
-
692
571
  // src/utils/queueKey.ts
693
572
  var import_hwk_adapter_core2 = require("@onekeyfe/hwk-adapter-core");
694
573
  var KEYSTONE_COLD_START_JOB_LABEL = "keystone-cold-start";
@@ -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
  });
@@ -1891,7 +1766,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1891
1766
  }
1892
1767
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1893
1768
  return {
1894
- access: { channel: "usb", usbSessionId: record.usbSessionId, qrFallback: {} },
1769
+ access: { channel: "usb", usbSessionId: record.usbSessionId },
1895
1770
  masterFingerprint: record.masterFingerprint
1896
1771
  };
1897
1772
  }
@@ -1902,62 +1777,26 @@ var KeystoneAdapter = class _KeystoneAdapter {
1902
1777
  });
1903
1778
  }
1904
1779
  const schemas = Array.from(requestedByKey.values());
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
- };
1780
+ const requestUr = this.urEngine.buildKeyDerivationRequest({
1781
+ schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1782
+ origin: this._origin
1783
+ });
1920
1784
  const responseUr = await this._requestQrAndAwaitResponse(
1921
1785
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1922
- request,
1786
+ { ...requestUr, animated: false },
1923
1787
  signal
1924
1788
  );
1925
1789
  _KeystoneAdapter._throwIfAborted(signal);
1926
- const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1790
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
1927
1791
  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
- }
1935
1792
  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))) {
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" }
1793
+ scanned.set(accountKey(schema.hwkChain, schema.path), {
1794
+ ...requireExportedPath(parsed, schema.path),
1795
+ hwkChain: schema.hwkChain
1949
1796
  });
1950
1797
  }
1951
1798
  record = this._upsertDeviceRecord(parsed);
1952
- return {
1953
- access: {
1954
- channel: "qr",
1955
- scanned,
1956
- firmwareVersion: parsed.deviceVersion,
1957
- ...responseUr.accountExport ? { accountExport: true } : {}
1958
- },
1959
- masterFingerprint: record.masterFingerprint
1960
- };
1799
+ return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1961
1800
  });
1962
1801
  }
1963
1802
  /**
@@ -2031,17 +1870,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
2031
1870
  record = createDeviceRecord(masterFingerprint);
2032
1871
  this._devices.set(masterFingerprint, record);
2033
1872
  }
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
- }
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;
2045
1878
  const info = toDeviceInfo(record);
2046
1879
  const eventType = isNew ? import_hwk_adapter_core3.DEVICE.CONNECT : import_hwk_adapter_core3.DEVICE.CHANGED;
2047
1880
  this.emitter.emit(eventType, { type: eventType, payload: info });
@@ -2125,18 +1958,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
2125
1958
  }
2126
1959
  _KeystoneAdapter._throwIfAborted(signal);
2127
1960
  const record = this._upsertDeviceRecord(
2128
- {
2129
- masterFingerprint,
2130
- accounts: [],
2131
- device: session.deviceInfo.modelName ?? session.deviceInfo.model
2132
- },
1961
+ { masterFingerprint, accounts: [] },
2133
1962
  {
2134
1963
  viaUsb: true,
2135
- usbSessionId: session.sessionId,
2136
- usbFirmwareVersion: session.deviceInfo.firmwareVersion
1964
+ usbSessionId: session.sessionId
2137
1965
  }
2138
1966
  );
2139
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;
2140
1971
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
2141
1972
  } catch (err) {
2142
1973
  if (sessionId) {
@@ -2206,7 +2037,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2206
2037
  * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
2207
2038
  * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
2208
2039
  */
2209
- async _resolveUr(record, requestUr, animated, operationId, signal, operationName, qrFallback) {
2040
+ async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
2210
2041
  const releaseOperationRetention = (0, import_hwk_adapter_core3.isHardwareOperationId)(operationId) ? this._operations.retain(operationId) : void 0;
2211
2042
  try {
2212
2043
  return await this._resolveUrWithRoute(
@@ -2215,14 +2046,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
2215
2046
  animated,
2216
2047
  operationId,
2217
2048
  signal,
2218
- operationName,
2219
- qrFallback
2049
+ operationName
2220
2050
  );
2221
2051
  } finally {
2222
2052
  releaseOperationRetention?.();
2223
2053
  }
2224
2054
  }
2225
- async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName, qrFallback) {
2055
+ async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName) {
2226
2056
  let record = callerRecord;
2227
2057
  let interactionRoute;
2228
2058
  if ((0, import_hwk_adapter_core3.isHardwareOperationId)(operationId)) {
@@ -2261,30 +2091,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
2261
2091
  requestUr,
2262
2092
  signal
2263
2093
  );
2264
- if (result.success) {
2265
- const ur = result.payload;
2266
- return { urType: ur.urType, urData: ur.urData };
2267
- }
2094
+ if (result.success) return result.payload;
2268
2095
  const usbError = (0, import_hwk_adapter_core3.rehydrateConnectorError)(result.error);
2269
2096
  const { origin: usbErrorOrigin, code: usbErrorCode } = usbError;
2270
2097
  if (usbErrorCode === import_hwk_adapter_core3.HardwareErrorCode.PayloadTooLarge && usbErrorOrigin !== "device") {
2271
2098
  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
- }
2278
2099
  const displayDevice2 = toDeviceInfo(record);
2279
- return this._requestQrAndAwaitResponse(
2280
- displayDevice2,
2281
- {
2282
- ...requestUr,
2283
- animated,
2284
- ...!operationName ? { allowAccountExport: true } : {}
2285
- },
2286
- signal
2287
- );
2100
+ return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2288
2101
  }
2289
2102
  throw usbError;
2290
2103
  }
@@ -2295,7 +2108,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2295
2108
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2296
2109
  }
2297
2110
  record.usbSessionId = void 0;
2298
- record.usbFirmwareVersion = void 0;
2299
2111
  this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: toDeviceInfo(record) });
2300
2112
  if (interactionRoute) {
2301
2113
  throw this._endDisconnectedOperation(
@@ -2329,7 +2141,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2329
2141
  try {
2330
2142
  return await this._requestQrAndAwaitResponse(
2331
2143
  displayDevice,
2332
- { ...requestUr, animated, ...!operationName ? { allowAccountExport: true } : {} },
2144
+ { ...requestUr, animated },
2333
2145
  signal
2334
2146
  );
2335
2147
  } catch (error) {
@@ -2365,20 +2177,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2365
2177
  const target = this._resolveTarget(connectId, deviceId);
2366
2178
  if (bundle?.channel === "qr") {
2367
2179
  const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2368
- if (target.record && !scanned && bundle.accountExport) {
2369
- throw (0, import_hwk_adapter_core3.createHwkError)({
2370
- code: import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden,
2371
- message: "Scanned account export does not include this account path",
2372
- params: { reason: "account-not-exported" }
2373
- });
2374
- }
2375
2180
  if (!target.record || !scanned) {
2376
2181
  throw (0, import_hwk_adapter_core3.createHwkError)({
2377
2182
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2378
2183
  message: `Keystone did not return the requested derivation path (${syncPath})`
2379
2184
  });
2380
2185
  }
2381
- this._assertQrChainSupported(bundle.firmwareVersion, hwkChain);
2382
2186
  return { record: target.record, account: scanned };
2383
2187
  }
2384
2188
  if (bundle?.channel === "usb" && target.record?.usbSessionId !== bundle.usbSessionId) {
@@ -2393,22 +2197,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
2393
2197
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2394
2198
  _KeystoneAdapter._throwIfAborted(signal);
2395
2199
  }
2200
+ const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2396
2201
  const schemas = [keySchema(hwkChain, syncPath)];
2397
2202
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2398
- const responseUr = await this._resolveUr(
2399
- existingRecord,
2400
- requestUr,
2401
- false,
2402
- connectId,
2403
- signal,
2404
- void 0,
2405
- bundle?.channel === "usb" ? bundle.qrFallback : void 0
2406
- );
2203
+ const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2407
2204
  _KeystoneAdapter._throwIfAborted(signal);
2408
- const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2409
- this._assertParsedIdentity(parsed, target);
2410
- const account = requireExportedPath(parsed, syncPath, responseUr.accountExport);
2411
- 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);
2412
2207
  let record;
2413
2208
  if (useSinglePathUsbExport && existingRecord) {
2414
2209
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2419,8 +2214,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
2419
2214
  }
2420
2215
  record = existingRecord;
2421
2216
  } else {
2422
- this._assertQrChainSupported(parsed.deviceVersion, hwkChain);
2423
- record = this._upsertDeviceRecord(parsed);
2217
+ this._assertParsedIdentity(parsed, target);
2218
+ record = this._upsertDeviceRecord(parsed, {
2219
+ viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2220
+ });
2424
2221
  }
2425
2222
  return { record, account: { ...account, hwkChain } };
2426
2223
  }
@@ -2444,25 +2241,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
2444
2241
  });
2445
2242
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2446
2243
  _KeystoneAdapter._throwIfAborted(signal);
2447
- const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2448
- requireExportedPath(parsed, normalizePath(accountPath), responseUr.accountExport);
2449
- this._assertQrChainSupported(parsed.deviceVersion, chain);
2450
- const record = this._upsertDeviceRecord(parsed);
2451
- return { record };
2452
- }
2453
- _assertQrChainSupported(firmwareVersion, chain) {
2454
- const firmware = getKeystoneFirmwareProfile(firmwareVersion);
2455
- if (firmware && !firmware.supportedChains.includes(chain)) {
2456
- throw (0, import_hwk_adapter_core3.createHwkError)({
2457
- code: import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
2458
- message: `Keystone ${firmware.variant} firmware cannot use ${chain} through this adapter`,
2459
- params: { firmwareVariant: firmware.variant, chain }
2460
- });
2461
- }
2244
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
2245
+ requireExportedPath(parsed, normalizePath(accountPath));
2246
+ return { record: this._upsertDeviceRecord(parsed) };
2462
2247
  }
2463
- /** 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
+ */
2464
2252
  _activeOperationId() {
2465
- 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;
2466
2257
  }
2467
2258
  /** Routes are keyed by connectId; a job key may be the bare master fingerprint. */
2468
2259
  _operationRouteForIdentifier(identifier) {
@@ -2495,39 +2286,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2495
2286
  signal.removeEventListener("abort", onAbort);
2496
2287
  }
2497
2288
  }
2498
- /**
2499
- * Asks whether a request too large for USB may be shown as a QR. A timeout or an unanswered
2500
- * prompt reads as no; a cancelled call keeps its own error.
2501
- */
2502
- async _confirmQrFallback(signal, choice) {
2503
- if (choice?.confirmed !== void 0) return choice.confirmed;
2504
- const requestType = import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_FALLBACK_CONFIRM;
2505
- const requestId = this._uiRegistry.createRequestId();
2506
- const operationId = this._activeOperationId();
2507
- const release = operationId ? this._operations.retain(operationId) : void 0;
2508
- try {
2509
- const waitPromise = this._uiRegistry.wait(requestType, {
2510
- requestId,
2511
- operationId
2512
- });
2513
- this.emitter.emit(requestType, {
2514
- type: requestType,
2515
- payload: { vendor: "keystone", requestId, operationId }
2516
- });
2517
- let confirmed = false;
2518
- try {
2519
- confirmed = Boolean(
2520
- (await this._awaitQrResponse(requestType, waitPromise, signal))?.confirmed
2521
- );
2522
- } catch (error) {
2523
- if (signal.aborted) throw error;
2524
- }
2525
- if (choice) choice.confirmed = confirmed;
2526
- return confirmed;
2527
- } finally {
2528
- release?.();
2529
- }
2530
- }
2531
2289
  /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2532
2290
  async _requestQrAndAwaitResponse(device, data, signal) {
2533
2291
  const requestType = data ? import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY : import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN;
@@ -2550,17 +2308,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2550
2308
  });
2551
2309
  }
2552
2310
  const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2553
- if (response.accountExport && data && !data.allowAccountExport) {
2554
- throw (0, import_hwk_adapter_core3.createHwkError)({
2555
- code: import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
2556
- message: "This request cannot be answered with an account export"
2557
- });
2558
- }
2559
- return {
2560
- urType: response.urType,
2561
- urData: response.urData,
2562
- ...!data || response.accountExport ? { accountExport: true } : {}
2563
- };
2311
+ return { urType: response.urType, urData: response.urData };
2564
2312
  } finally {
2565
2313
  release?.();
2566
2314
  }