@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.mjs CHANGED
@@ -1,13 +1,5 @@
1
1
  // src/urEngine/KeystoneUrEngine.ts
2
2
  import { generateAddressFromXpub } from "@keystonehq/bc-ur-registry-eth";
3
- import {
4
- CryptoAccount,
5
- CryptoHDKey,
6
- CryptoMultiAccounts,
7
- ScriptExpressions,
8
- extend as extend3
9
- } from "@keystonehq/bc-ur-registry";
10
- import { ScriptExpression } from "@keystonehq/bc-ur-registry/dist/ScriptExpression.js";
11
3
  import { Curve, KeystoneSDK, QRHardwareCallVersion, UR } from "@keystonehq/keystone-sdk";
12
4
  import bs58check from "bs58check";
13
5
  import * as bitcoin from "bitcoinjs-lib";
@@ -200,7 +192,7 @@ function relativeHdPath(relativeDerivePath) {
200
192
  }
201
193
  return `m/${segments.join("/")}`;
202
194
  }
203
- var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.-]{1,20})?$/;
195
+ var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.]{1,20})?$/;
204
196
  var DEVICE_TEXT = /^[^\p{Cc}\p{Cf}]{1,64}$/u;
205
197
  function deviceText(value, pattern) {
206
198
  return typeof value === "string" && pattern.test(value) ? value : void 0;
@@ -256,95 +248,6 @@ var KeystoneUrEngine = class {
256
248
  }
257
249
  return this.parseMultiAccounts(ur);
258
250
  }
259
- /** Device exports are opt-in: request responses retain their existing format/path checks. */
260
- parseAccountExport(ur) {
261
- try {
262
- const { cbor } = toSdkUr(ur);
263
- let parsed;
264
- let keys;
265
- if (ur.urType === "crypto-account") {
266
- if (!Object.values(ScriptExpressions).some((script) => script.getTag() === 409)) {
267
- Object.assign(ScriptExpressions, { TAPROOT: new ScriptExpression(409, "tr") });
268
- }
269
- extend3.cbor.patchTags([409]);
270
- const account = CryptoAccount.fromCBOR(cbor);
271
- keys = account.getOutputDescriptors().map((output) => {
272
- const key = output.getHDKey();
273
- const path = key?.getOrigin()?.getPath();
274
- const script = output.getScriptExpressions().map((item) => item.getExpression()).join("/");
275
- 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";
276
- const children = key?.getChildren();
277
- if (!key || !validScript || children && children.getPath() !== "0/*") {
278
- throw new Error("Unsupported account descriptor");
279
- }
280
- return key;
281
- });
282
- const result = this.sdk.parseAccount(toSdkUr(ur));
283
- parsed = {
284
- masterFingerprint: requireBip32MasterFingerprint(result.masterFingerprint),
285
- accounts: result.keys.map(toParsedAccount)
286
- };
287
- } else if (ur.urType === "crypto-multi-accounts") {
288
- keys = CryptoMultiAccounts.fromCBOR(cbor).getKeys();
289
- parsed = this.parseMultiAccounts(ur);
290
- } else if (ur.urType === "crypto-hdkey") {
291
- keys = [CryptoHDKey.fromCBOR(cbor)];
292
- parsed = this.parseAccountResponse(ur);
293
- } else {
294
- throw new Error("Unsupported account export type");
295
- }
296
- if (!keys.length || keys.length !== parsed.accounts.length) {
297
- throw new Error("Empty account export");
298
- }
299
- for (const key of keys) {
300
- if (key.isMaster() || key.isPrivateKey()) throw new Error("Account public keys required");
301
- const source = key.getOrigin()?.getSourceFingerprint();
302
- if (source && source.toString("hex") !== parsed.masterFingerprint) {
303
- throw createHwkError({
304
- code: HardwareErrorCode.DeviceMismatch,
305
- message: "Account export contains a different wallet fingerprint"
306
- });
307
- }
308
- }
309
- const byPath = /* @__PURE__ */ new Map();
310
- for (const account of parsed.accounts) {
311
- if (!/^m(?:\/\d+')+(?:\/\d+)*$/.test(account.path) || account.path.slice(2).split("/").some(
312
- (segment) => Number(segment.endsWith("'") ? segment.slice(0, -1) : segment) >= BIP32_HARDENED_OFFSET
313
- )) {
314
- throw new Error("Account export has an unsupported derivation path");
315
- }
316
- let identity = account.publicKey;
317
- if (account.extendedPublicKey) {
318
- const node = HDKey.fromExtendedKey(account.extendedPublicKey);
319
- if (node.privateKey || !node.publicKey || !node.chainCode) {
320
- throw new Error("Account public keys required");
321
- }
322
- if (node.publicKey.toString("hex") !== account.publicKey.toLowerCase()) {
323
- throw new Error("Account public key does not match its extended key");
324
- }
325
- identity = `${identity}:${node.chainCode.toString("hex")}`;
326
- } else if (!/^[0-9a-f]{64}$/i.test(account.publicKey)) {
327
- throw new Error("Account export is missing a usable public key");
328
- }
329
- const previous = byPath.get(account.path);
330
- if (previous !== void 0 && previous !== identity) {
331
- throw createHwkError({
332
- code: HardwareErrorCode.DeviceMismatch,
333
- message: "Account export contains conflicting keys for the same path"
334
- });
335
- }
336
- byPath.set(account.path, identity);
337
- }
338
- return parsed;
339
- } catch (error) {
340
- if (error && typeof error === "object" && "code" in error && error.code === HardwareErrorCode.DeviceMismatch)
341
- throw error;
342
- throw createHwkError({
343
- code: HardwareErrorCode.InvalidParams,
344
- message: "Unable to read account export; scan a supported Keystone account export code"
345
- });
346
- }
347
- }
348
251
  // --- EVM ---
349
252
  buildEthSignRequest(input) {
350
253
  const ur = this.sdk.eth.generateSignRequest({
@@ -635,15 +538,12 @@ function accountKey(hwkChain, path) {
635
538
  function createDeviceRecord(masterFingerprint) {
636
539
  return {
637
540
  masterFingerprint,
638
- connectId: walletConnectId(masterFingerprint)
541
+ connectId: walletConnectId(masterFingerprint),
542
+ importedAt: Date.now()
639
543
  };
640
544
  }
641
545
  var CAPABILITIES = { persistentDeviceIdentity: true };
642
546
  function toDeviceInfo(record) {
643
- return toDeviceInfoForConnection(record, record.usbSessionId ? "usb" : "qr");
644
- }
645
- function toDeviceInfoForConnection(record, connectionType) {
646
- const firmwareVersion = connectionType === "usb" ? record.usbFirmwareVersion : record.deviceVersion;
647
547
  let availableChannels = ["qr"];
648
548
  if (record.usbSessionId) {
649
549
  availableChannels = record.qrSynced ? ["qr", "usb"] : ["usb"];
@@ -652,13 +552,11 @@ function toDeviceInfoForConnection(record, connectionType) {
652
552
  vendor: "keystone",
653
553
  model: record.model ?? "unknown",
654
554
  modelName: record.model,
655
- firmwareVersion: firmwareVersion ?? "0.0.0",
555
+ firmwareVersion: record.deviceVersion ?? "0.0.0",
656
556
  deviceId: record.masterFingerprint,
657
557
  connectId: record.connectId,
658
- connectionType,
659
- capabilities: {
660
- ...CAPABILITIES
661
- },
558
+ connectionType: record.usbSessionId ? "usb" : "qr",
559
+ capabilities: CAPABILITIES,
662
560
  raw: {
663
561
  availableChannels,
664
562
  masterFingerprint: record.masterFingerprint,
@@ -678,31 +576,6 @@ function placeholderDeviceInfo() {
678
576
  };
679
577
  }
680
578
 
681
- // src/adapter/firmwareCapabilities.ts
682
- var MULTI_COIN = {
683
- variant: "multi-coin",
684
- supportedChains: ["btc", "evm", "sol", "tron"]
685
- };
686
- var BITCOIN_ONLY = {
687
- variant: "bitcoin-only",
688
- supportedChains: ["btc"]
689
- };
690
- var CYPHERPUNK = {
691
- variant: "cypherpunk",
692
- // Firmware support alone is insufficient: this adapter has no Zcash/Monero methods yet.
693
- supportedChains: ["btc"]
694
- };
695
- function getKeystoneFirmwareProfile(firmwareVersion) {
696
- if (!firmwareVersion || firmwareVersion === "0.0.0") return void 0;
697
- const version = /^\d{1,4}(?:\.\d{1,4}){1,3}(?:-([a-z0-9.-]{1,40}))?$/i.exec(firmwareVersion);
698
- if (!version) return void 0;
699
- const suffix = version[1]?.toUpperCase();
700
- if (!suffix) return MULTI_COIN;
701
- if (suffix === "C" || suffix === "CYPHERPUNK" || suffix === "CYPHERPUNK-B") return CYPHERPUNK;
702
- if (suffix === "B" || suffix === "BTC" || suffix === "BTC-ONLY") return BITCOIN_ONLY;
703
- return void 0;
704
- }
705
-
706
579
  // src/utils/queueKey.ts
707
580
  import { isHardwareOperationId, parseWalletMasterFingerprint as parseWalletMasterFingerprint2 } from "@onekeyfe/hwk-adapter-core";
708
581
  var KEYSTONE_COLD_START_JOB_LABEL = "keystone-cold-start";
@@ -742,7 +615,6 @@ function keystoneBtcParamsFailure(params) {
742
615
  }
743
616
  return void 0;
744
617
  }
745
- var KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS = 24;
746
618
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
747
619
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
748
620
  var CHAIN_TYPE_BY_CHAIN = {
@@ -790,13 +662,12 @@ function exactHex(value) {
790
662
  function invalidHexFailure(field) {
791
663
  return failure(HardwareErrorCode2.InvalidParams, `${field} must be an even-length hex string`);
792
664
  }
793
- function requireExportedPath(parsed, path, accountExport = false) {
665
+ function requireExportedPath(parsed, path) {
794
666
  const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
795
667
  if (!account) {
796
668
  throw createHwkError2({
797
- code: accountExport ? HardwareErrorCode2.DevicePathForbidden : HardwareErrorCode2.DeviceMismatch,
798
- message: `Keystone did not return the requested derivation path (${path})`,
799
- ...accountExport ? { params: { reason: "account-not-exported" } } : {}
669
+ code: HardwareErrorCode2.DeviceMismatch,
670
+ message: `Keystone did not return the requested derivation path (${path})`
800
671
  });
801
672
  }
802
673
  return account;
@@ -810,9 +681,7 @@ function coinTypeFailure(chain, path) {
810
681
  }
811
682
  function btcAccountFailure(accountPath) {
812
683
  if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
813
- return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE, {
814
- reason: "btc-account-limit"
815
- });
684
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
816
685
  }
817
686
  function missingParamFailure(method, param) {
818
687
  return failure(HardwareErrorCode2.InvalidParams, `${method} requires ${param}`);
@@ -844,8 +713,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
844
713
  params: { operationId: operation.operationId, reason }
845
714
  });
846
715
  const queueKey = keystoneQueueKey(operation.operationId);
716
+ const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
847
717
  this._jobQueue.cancelActiveAndPending(queueKey, ended);
848
- this._uiRegistry.cancel(void 0, void 0, operation.operationId);
718
+ if (ownsRunningCall) {
719
+ this._uiRegistry.cancel(void 0, void 0, operation.operationId);
720
+ }
849
721
  }
850
722
  }
851
723
  this.emitter.emit(SDK.OPERATION_ENDED, {
@@ -872,7 +744,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
872
744
  if (!record) return;
873
745
  this._operations.endByConnectionKey(connectId, "disconnect");
874
746
  record.usbSessionId = void 0;
875
- record.usbFirmwareVersion = void 0;
876
747
  const info = toDeviceInfo(record);
877
748
  if (record.qrSynced) {
878
749
  this.emitter.emit(DEVICE.CHANGED, { type: DEVICE.CHANGED, payload: info });
@@ -882,8 +753,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
882
753
  }
883
754
  };
884
755
  this._handleUsbUiEvent = (event) => {
885
- const operationId = this._activeOperationId();
886
- this.emitter.emit("ui-event", operationId ? { ...event, operationId } : event);
756
+ this.emitter.emit("ui-event", event);
887
757
  };
888
758
  // ---------------------------------------------------------------------------
889
759
  // All-network bundle, dispatched to the per-chain methods below.
@@ -956,7 +826,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
956
826
  success: true,
957
827
  payload: {
958
828
  ...context.payload,
959
- ...access?.channel === "qr" && access.accountExport ? { accountExport: true } : {},
960
829
  rootFingerprint: record ? Number.parseInt(record.masterFingerprint, 16) : void 0,
961
830
  deviceIdentity: record ? {
962
831
  vendor: "keystone",
@@ -1206,24 +1075,23 @@ var KeystoneAdapter = class _KeystoneAdapter {
1206
1075
  }
1207
1076
  getDeviceInfo(connectIdOrOperationId, deviceId) {
1208
1077
  try {
1209
- const operation = isHardwareOperationId2(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId) : void 0;
1210
- const connectId = operation?.connectId ?? connectIdOrOperationId;
1078
+ const connectId = isHardwareOperationId2(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1211
1079
  const { record } = this._resolveTarget(connectId, deviceId);
1212
1080
  if (!record) {
1213
1081
  return Promise.resolve(
1214
1082
  failure(HardwareErrorCode2.DeviceNotFound, "Unknown Keystone device")
1215
1083
  );
1216
1084
  }
1217
- const info = operation ? toDeviceInfoForConnection(record, operation.connectionType === "qr" ? "qr" : "usb") : toDeviceInfo(record);
1218
- return Promise.resolve(success(info));
1085
+ return Promise.resolve(success(toDeviceInfo(record)));
1219
1086
  } catch (err) {
1220
1087
  return Promise.resolve(this._errorToFailure(err));
1221
1088
  }
1222
1089
  }
1223
1090
  cancel(connectId) {
1091
+ let namedOperationConnectId;
1224
1092
  if (isHardwareOperationId2(connectId)) {
1225
1093
  try {
1226
- this._operations.resolve(connectId);
1094
+ namedOperationConnectId = this._operations.resolve(connectId).connectId;
1227
1095
  } catch {
1228
1096
  return;
1229
1097
  }
@@ -1233,14 +1101,15 @@ var KeystoneAdapter = class _KeystoneAdapter {
1233
1101
  message: "User aborted operation"
1234
1102
  });
1235
1103
  if (connectId) {
1236
- const scopedOperationId = isHardwareOperationId2(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1237
1104
  const queueKeys = keystoneCancelQueueKeys([
1238
1105
  connectId,
1239
- this._operationRoutes.get(connectId)?.operationId
1106
+ this._operationRoutes.get(connectId)?.operationId,
1107
+ namedOperationConnectId
1240
1108
  ]);
1241
1109
  for (const key of queueKeys) {
1242
1110
  this._jobQueue.cancelActiveAndPending(key, reason);
1243
1111
  }
1112
+ const scopedOperationId = isHardwareOperationId2(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1244
1113
  if (scopedOperationId) {
1245
1114
  this._uiRegistry.cancel(void 0, void 0, scopedOperationId);
1246
1115
  }
@@ -1302,13 +1171,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1302
1171
  });
1303
1172
  responseUr = await this._requestQrAndAwaitResponse(
1304
1173
  displayDevice,
1305
- { ...requestUr, animated: false, allowAccountExport: true },
1174
+ { ...requestUr, animated: false },
1306
1175
  signal
1307
1176
  );
1308
1177
  }
1309
1178
  _KeystoneAdapter._throwIfAborted(signal);
1310
- const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1311
- if (!responseUr.accountExport) requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1179
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
1180
+ if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1312
1181
  const record = this._upsertDeviceRecord(parsed);
1313
1182
  return success(toDeviceInfo(record));
1314
1183
  });
@@ -1905,7 +1774,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1905
1774
  }
1906
1775
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1907
1776
  return {
1908
- access: { channel: "usb", usbSessionId: record.usbSessionId, qrFallback: {} },
1777
+ access: { channel: "usb", usbSessionId: record.usbSessionId },
1909
1778
  masterFingerprint: record.masterFingerprint
1910
1779
  };
1911
1780
  }
@@ -1916,62 +1785,26 @@ var KeystoneAdapter = class _KeystoneAdapter {
1916
1785
  });
1917
1786
  }
1918
1787
  const schemas = Array.from(requestedByKey.values());
1919
- if (schemas.length > KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS) {
1920
- throw createHwkError2({
1921
- code: HardwareErrorCode2.QrRequestTooLarge,
1922
- message: `Keystone accepts at most ${KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS} account paths per QR request; this one needs ${schemas.length}`,
1923
- params: { limit: KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS, requested: schemas.length }
1924
- });
1925
- }
1926
- const request = {
1927
- ...this.urEngine.buildKeyDerivationRequest({
1928
- schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1929
- origin: this._origin
1930
- }),
1931
- animated: false,
1932
- allowAccountExport: true
1933
- };
1788
+ const requestUr = this.urEngine.buildKeyDerivationRequest({
1789
+ schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1790
+ origin: this._origin
1791
+ });
1934
1792
  const responseUr = await this._requestQrAndAwaitResponse(
1935
1793
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1936
- request,
1794
+ { ...requestUr, animated: false },
1937
1795
  signal
1938
1796
  );
1939
1797
  _KeystoneAdapter._throwIfAborted(signal);
1940
- const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1798
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
1941
1799
  this._assertParsedIdentity(parsed, target);
1942
- const firmware = getKeystoneFirmwareProfile(parsed.deviceVersion);
1943
- if (responseUr.accountExport && parsed.accounts.some((account) => !isBip32Path(account.path))) {
1944
- throw createHwkError2({
1945
- code: HardwareErrorCode2.InvalidParams,
1946
- message: "Account export contains an invalid derivation path"
1947
- });
1948
- }
1949
1800
  for (const schema of schemas) {
1950
- const exported = responseUr.accountExport ? parsed.accounts.find((account) => normalizePath(account.path) === schema.path) : requireExportedPath(parsed, schema.path);
1951
- if (exported && (!responseUr.accountExport || !firmware || firmware.supportedChains.includes(schema.hwkChain))) {
1952
- scanned.set(accountKey(schema.hwkChain, schema.path), {
1953
- ...exported,
1954
- hwkChain: schema.hwkChain
1955
- });
1956
- }
1957
- }
1958
- if (responseUr.accountExport && !scanned.size) {
1959
- throw createHwkError2({
1960
- code: HardwareErrorCode2.DevicePathForbidden,
1961
- message: "Account export contains none of the requested supported account paths",
1962
- params: { reason: "account-not-exported" }
1801
+ scanned.set(accountKey(schema.hwkChain, schema.path), {
1802
+ ...requireExportedPath(parsed, schema.path),
1803
+ hwkChain: schema.hwkChain
1963
1804
  });
1964
1805
  }
1965
1806
  record = this._upsertDeviceRecord(parsed);
1966
- return {
1967
- access: {
1968
- channel: "qr",
1969
- scanned,
1970
- firmwareVersion: parsed.deviceVersion,
1971
- ...responseUr.accountExport ? { accountExport: true } : {}
1972
- },
1973
- masterFingerprint: record.masterFingerprint
1974
- };
1807
+ return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1975
1808
  });
1976
1809
  }
1977
1810
  /**
@@ -2045,17 +1878,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
2045
1878
  record = createDeviceRecord(masterFingerprint);
2046
1879
  this._devices.set(masterFingerprint, record);
2047
1880
  }
2048
- record.model = parsed.device;
2049
- record.hardwareDeviceId = parsed.deviceId;
2050
- if (options?.usbSessionId) {
2051
- record.usbSessionId = options.usbSessionId;
2052
- record.usbFirmwareVersion = options.usbFirmwareVersion;
2053
- record.hadUsbSession = true;
2054
- }
2055
- if (!options?.viaUsb) {
2056
- record.deviceVersion = parsed.deviceVersion;
2057
- record.qrSynced = true;
2058
- }
1881
+ record.model = parsed.device ?? record.model;
1882
+ record.deviceVersion = parsed.deviceVersion ?? record.deviceVersion;
1883
+ record.hardwareDeviceId = parsed.deviceId ?? record.hardwareDeviceId;
1884
+ record.usbSessionId = options?.usbSessionId ?? record.usbSessionId;
1885
+ if (!options?.viaUsb) record.qrSynced = true;
2059
1886
  const info = toDeviceInfo(record);
2060
1887
  const eventType = isNew ? DEVICE.CONNECT : DEVICE.CHANGED;
2061
1888
  this.emitter.emit(eventType, { type: eventType, payload: info });
@@ -2139,18 +1966,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
2139
1966
  }
2140
1967
  _KeystoneAdapter._throwIfAborted(signal);
2141
1968
  const record = this._upsertDeviceRecord(
2142
- {
2143
- masterFingerprint,
2144
- accounts: [],
2145
- device: session.deviceInfo.modelName ?? session.deviceInfo.model
2146
- },
1969
+ { masterFingerprint, accounts: [] },
2147
1970
  {
2148
1971
  viaUsb: true,
2149
- usbSessionId: session.sessionId,
2150
- usbFirmwareVersion: session.deviceInfo.firmwareVersion
1972
+ usbSessionId: session.sessionId
2151
1973
  }
2152
1974
  );
2153
1975
  _KeystoneAdapter._throwIfAborted(signal);
1976
+ record.hadUsbSession = true;
1977
+ record.model = session.deviceInfo.modelName ?? session.deviceInfo.model ?? record.model;
1978
+ record.deviceVersion = session.deviceInfo.firmwareVersion ?? record.deviceVersion;
2154
1979
  return success(toDeviceInfo(record));
2155
1980
  } catch (err) {
2156
1981
  if (sessionId) {
@@ -2220,7 +2045,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2220
2045
  * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
2221
2046
  * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
2222
2047
  */
2223
- async _resolveUr(record, requestUr, animated, operationId, signal, operationName, qrFallback) {
2048
+ async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
2224
2049
  const releaseOperationRetention = isHardwareOperationId2(operationId) ? this._operations.retain(operationId) : void 0;
2225
2050
  try {
2226
2051
  return await this._resolveUrWithRoute(
@@ -2229,14 +2054,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
2229
2054
  animated,
2230
2055
  operationId,
2231
2056
  signal,
2232
- operationName,
2233
- qrFallback
2057
+ operationName
2234
2058
  );
2235
2059
  } finally {
2236
2060
  releaseOperationRetention?.();
2237
2061
  }
2238
2062
  }
2239
- async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName, qrFallback) {
2063
+ async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName) {
2240
2064
  let record = callerRecord;
2241
2065
  let interactionRoute;
2242
2066
  if (isHardwareOperationId2(operationId)) {
@@ -2275,30 +2099,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
2275
2099
  requestUr,
2276
2100
  signal
2277
2101
  );
2278
- if (result.success) {
2279
- const ur = result.payload;
2280
- return { urType: ur.urType, urData: ur.urData };
2281
- }
2102
+ if (result.success) return result.payload;
2282
2103
  const usbError = rehydrateConnectorError(result.error);
2283
2104
  const { origin: usbErrorOrigin, code: usbErrorCode } = usbError;
2284
2105
  if (usbErrorCode === HardwareErrorCode2.PayloadTooLarge && usbErrorOrigin !== "device") {
2285
2106
  if (!interactionRoute && !this._forcedTransport) {
2286
- if (!await this._confirmQrFallback(signal, qrFallback)) {
2287
- throw createHwkError2({
2288
- code: HardwareErrorCode2.UserAborted,
2289
- message: "User declined to show the request too large for USB as a QR code"
2290
- });
2291
- }
2292
2107
  const displayDevice2 = toDeviceInfo(record);
2293
- return this._requestQrAndAwaitResponse(
2294
- displayDevice2,
2295
- {
2296
- ...requestUr,
2297
- animated,
2298
- ...!operationName ? { allowAccountExport: true } : {}
2299
- },
2300
- signal
2301
- );
2108
+ return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2302
2109
  }
2303
2110
  throw usbError;
2304
2111
  }
@@ -2309,7 +2116,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2309
2116
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2310
2117
  }
2311
2118
  record.usbSessionId = void 0;
2312
- record.usbFirmwareVersion = void 0;
2313
2119
  this.emitter.emit(DEVICE.CHANGED, { type: DEVICE.CHANGED, payload: toDeviceInfo(record) });
2314
2120
  if (interactionRoute) {
2315
2121
  throw this._endDisconnectedOperation(
@@ -2343,7 +2149,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2343
2149
  try {
2344
2150
  return await this._requestQrAndAwaitResponse(
2345
2151
  displayDevice,
2346
- { ...requestUr, animated, ...!operationName ? { allowAccountExport: true } : {} },
2152
+ { ...requestUr, animated },
2347
2153
  signal
2348
2154
  );
2349
2155
  } catch (error) {
@@ -2379,20 +2185,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2379
2185
  const target = this._resolveTarget(connectId, deviceId);
2380
2186
  if (bundle?.channel === "qr") {
2381
2187
  const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2382
- if (target.record && !scanned && bundle.accountExport) {
2383
- throw createHwkError2({
2384
- code: HardwareErrorCode2.DevicePathForbidden,
2385
- message: "Scanned account export does not include this account path",
2386
- params: { reason: "account-not-exported" }
2387
- });
2388
- }
2389
2188
  if (!target.record || !scanned) {
2390
2189
  throw createHwkError2({
2391
2190
  code: HardwareErrorCode2.DeviceMismatch,
2392
2191
  message: `Keystone did not return the requested derivation path (${syncPath})`
2393
2192
  });
2394
2193
  }
2395
- this._assertQrChainSupported(bundle.firmwareVersion, hwkChain);
2396
2194
  return { record: target.record, account: scanned };
2397
2195
  }
2398
2196
  if (bundle?.channel === "usb" && target.record?.usbSessionId !== bundle.usbSessionId) {
@@ -2407,22 +2205,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
2407
2205
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2408
2206
  _KeystoneAdapter._throwIfAborted(signal);
2409
2207
  }
2208
+ const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2410
2209
  const schemas = [keySchema(hwkChain, syncPath)];
2411
2210
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2412
- const responseUr = await this._resolveUr(
2413
- existingRecord,
2414
- requestUr,
2415
- false,
2416
- connectId,
2417
- signal,
2418
- void 0,
2419
- bundle?.channel === "usb" ? bundle.qrFallback : void 0
2420
- );
2211
+ const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2421
2212
  _KeystoneAdapter._throwIfAborted(signal);
2422
- const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2423
- this._assertParsedIdentity(parsed, target);
2424
- const account = requireExportedPath(parsed, syncPath, responseUr.accountExport);
2425
- const useSinglePathUsbExport = !responseUr.accountExport && (operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId));
2213
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
2214
+ const account = requireExportedPath(parsed, syncPath);
2426
2215
  let record;
2427
2216
  if (useSinglePathUsbExport && existingRecord) {
2428
2217
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2433,8 +2222,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
2433
2222
  }
2434
2223
  record = existingRecord;
2435
2224
  } else {
2436
- this._assertQrChainSupported(parsed.deviceVersion, hwkChain);
2437
- record = this._upsertDeviceRecord(parsed);
2225
+ this._assertParsedIdentity(parsed, target);
2226
+ record = this._upsertDeviceRecord(parsed, {
2227
+ viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2228
+ });
2438
2229
  }
2439
2230
  return { record, account: { ...account, hwkChain } };
2440
2231
  }
@@ -2458,25 +2249,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
2458
2249
  });
2459
2250
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2460
2251
  _KeystoneAdapter._throwIfAborted(signal);
2461
- const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2462
- requireExportedPath(parsed, normalizePath(accountPath), responseUr.accountExport);
2463
- this._assertQrChainSupported(parsed.deviceVersion, chain);
2464
- const record = this._upsertDeviceRecord(parsed);
2465
- return { record };
2466
- }
2467
- _assertQrChainSupported(firmwareVersion, chain) {
2468
- const firmware = getKeystoneFirmwareProfile(firmwareVersion);
2469
- if (firmware && !firmware.supportedChains.includes(chain)) {
2470
- throw createHwkError2({
2471
- code: HardwareErrorCode2.ChainNotSupported,
2472
- message: `Keystone ${firmware.variant} firmware cannot use ${chain} through this adapter`,
2473
- params: { firmwareVariant: firmware.variant, chain }
2474
- });
2475
- }
2252
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
2253
+ requireExportedPath(parsed, normalizePath(accountPath));
2254
+ return { record: this._upsertDeviceRecord(parsed) };
2476
2255
  }
2477
- /** Only an operation id supplied to the running call owns its UI prompts. */
2256
+ /**
2257
+ * The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
2258
+ * through the operation route; a cold start returns undefined.
2259
+ */
2478
2260
  _activeOperationId() {
2479
- return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
2261
+ const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
2262
+ if (!activeJobId) return void 0;
2263
+ if (isHardwareOperationId2(activeJobId)) return activeJobId;
2264
+ return this._operationRouteForIdentifier(activeJobId)?.operationId;
2480
2265
  }
2481
2266
  /** Routes are keyed by connectId; a job key may be the bare master fingerprint. */
2482
2267
  _operationRouteForIdentifier(identifier) {
@@ -2509,39 +2294,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2509
2294
  signal.removeEventListener("abort", onAbort);
2510
2295
  }
2511
2296
  }
2512
- /**
2513
- * Asks whether a request too large for USB may be shown as a QR. A timeout or an unanswered
2514
- * prompt reads as no; a cancelled call keeps its own error.
2515
- */
2516
- async _confirmQrFallback(signal, choice) {
2517
- if (choice?.confirmed !== void 0) return choice.confirmed;
2518
- const requestType = UI_REQUEST.REQUEST_QR_FALLBACK_CONFIRM;
2519
- const requestId = this._uiRegistry.createRequestId();
2520
- const operationId = this._activeOperationId();
2521
- const release = operationId ? this._operations.retain(operationId) : void 0;
2522
- try {
2523
- const waitPromise = this._uiRegistry.wait(requestType, {
2524
- requestId,
2525
- operationId
2526
- });
2527
- this.emitter.emit(requestType, {
2528
- type: requestType,
2529
- payload: { vendor: "keystone", requestId, operationId }
2530
- });
2531
- let confirmed = false;
2532
- try {
2533
- confirmed = Boolean(
2534
- (await this._awaitQrResponse(requestType, waitPromise, signal))?.confirmed
2535
- );
2536
- } catch (error) {
2537
- if (signal.aborted) throw error;
2538
- }
2539
- if (choice) choice.confirmed = confirmed;
2540
- return confirmed;
2541
- } finally {
2542
- release?.();
2543
- }
2544
- }
2545
2297
  /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2546
2298
  async _requestQrAndAwaitResponse(device, data, signal) {
2547
2299
  const requestType = data ? UI_REQUEST.REQUEST_QR_DISPLAY : UI_REQUEST.REQUEST_QR_SCAN;
@@ -2564,17 +2316,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2564
2316
  });
2565
2317
  }
2566
2318
  const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2567
- if (response.accountExport && data && !data.allowAccountExport) {
2568
- throw createHwkError2({
2569
- code: HardwareErrorCode2.InvalidParams,
2570
- message: "This request cannot be answered with an account export"
2571
- });
2572
- }
2573
- return {
2574
- urType: response.urType,
2575
- urData: response.urData,
2576
- ...!data || response.accountExport ? { accountExport: true } : {}
2577
- };
2319
+ return { urType: response.urType, urData: response.urData };
2578
2320
  } finally {
2579
2321
  release?.();
2580
2322
  }