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

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,5 +1,13 @@
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";
3
11
  import { Curve, KeystoneSDK, QRHardwareCallVersion, UR } from "@keystonehq/keystone-sdk";
4
12
  import bs58check from "bs58check";
5
13
  import * as bitcoin from "bitcoinjs-lib";
@@ -192,7 +200,7 @@ function relativeHdPath(relativeDerivePath) {
192
200
  }
193
201
  return `m/${segments.join("/")}`;
194
202
  }
195
- var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.]{1,20})?$/;
203
+ var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.-]{1,20})?$/;
196
204
  var DEVICE_TEXT = /^[^\p{Cc}\p{Cf}]{1,64}$/u;
197
205
  function deviceText(value, pattern) {
198
206
  return typeof value === "string" && pattern.test(value) ? value : void 0;
@@ -248,6 +256,95 @@ var KeystoneUrEngine = class {
248
256
  }
249
257
  return this.parseMultiAccounts(ur);
250
258
  }
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
+ }
251
348
  // --- EVM ---
252
349
  buildEthSignRequest(input) {
253
350
  const ur = this.sdk.eth.generateSignRequest({
@@ -538,12 +635,15 @@ function accountKey(hwkChain, path) {
538
635
  function createDeviceRecord(masterFingerprint) {
539
636
  return {
540
637
  masterFingerprint,
541
- connectId: walletConnectId(masterFingerprint),
542
- importedAt: Date.now()
638
+ connectId: walletConnectId(masterFingerprint)
543
639
  };
544
640
  }
545
641
  var CAPABILITIES = { persistentDeviceIdentity: true };
546
642
  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;
547
647
  let availableChannels = ["qr"];
548
648
  if (record.usbSessionId) {
549
649
  availableChannels = record.qrSynced ? ["qr", "usb"] : ["usb"];
@@ -552,11 +652,13 @@ function toDeviceInfo(record) {
552
652
  vendor: "keystone",
553
653
  model: record.model ?? "unknown",
554
654
  modelName: record.model,
555
- firmwareVersion: record.deviceVersion ?? "0.0.0",
655
+ firmwareVersion: firmwareVersion ?? "0.0.0",
556
656
  deviceId: record.masterFingerprint,
557
657
  connectId: record.connectId,
558
- connectionType: record.usbSessionId ? "usb" : "qr",
559
- capabilities: CAPABILITIES,
658
+ connectionType,
659
+ capabilities: {
660
+ ...CAPABILITIES
661
+ },
560
662
  raw: {
561
663
  availableChannels,
562
664
  masterFingerprint: record.masterFingerprint,
@@ -576,6 +678,31 @@ function placeholderDeviceInfo() {
576
678
  };
577
679
  }
578
680
 
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
+
579
706
  // src/utils/queueKey.ts
580
707
  import { isHardwareOperationId, parseWalletMasterFingerprint as parseWalletMasterFingerprint2 } from "@onekeyfe/hwk-adapter-core";
581
708
  var KEYSTONE_COLD_START_JOB_LABEL = "keystone-cold-start";
@@ -615,6 +742,7 @@ function keystoneBtcParamsFailure(params) {
615
742
  }
616
743
  return void 0;
617
744
  }
745
+ var KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS = 24;
618
746
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
619
747
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
620
748
  var CHAIN_TYPE_BY_CHAIN = {
@@ -662,12 +790,13 @@ function exactHex(value) {
662
790
  function invalidHexFailure(field) {
663
791
  return failure(HardwareErrorCode2.InvalidParams, `${field} must be an even-length hex string`);
664
792
  }
665
- function requireExportedPath(parsed, path) {
793
+ function requireExportedPath(parsed, path, accountExport = false) {
666
794
  const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
667
795
  if (!account) {
668
796
  throw createHwkError2({
669
- code: HardwareErrorCode2.DeviceMismatch,
670
- message: `Keystone did not return the requested derivation path (${path})`
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" } } : {}
671
800
  });
672
801
  }
673
802
  return account;
@@ -681,7 +810,9 @@ function coinTypeFailure(chain, path) {
681
810
  }
682
811
  function btcAccountFailure(accountPath) {
683
812
  if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
684
- return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
813
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE, {
814
+ reason: "btc-account-limit"
815
+ });
685
816
  }
686
817
  function missingParamFailure(method, param) {
687
818
  return failure(HardwareErrorCode2.InvalidParams, `${method} requires ${param}`);
@@ -713,11 +844,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
713
844
  params: { operationId: operation.operationId, reason }
714
845
  });
715
846
  const queueKey = keystoneQueueKey(operation.operationId);
716
- const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
717
847
  this._jobQueue.cancelActiveAndPending(queueKey, ended);
718
- if (ownsRunningCall) {
719
- this._uiRegistry.cancel(void 0, void 0, operation.operationId);
720
- }
848
+ this._uiRegistry.cancel(void 0, void 0, operation.operationId);
721
849
  }
722
850
  }
723
851
  this.emitter.emit(SDK.OPERATION_ENDED, {
@@ -744,6 +872,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
744
872
  if (!record) return;
745
873
  this._operations.endByConnectionKey(connectId, "disconnect");
746
874
  record.usbSessionId = void 0;
875
+ record.usbFirmwareVersion = void 0;
747
876
  const info = toDeviceInfo(record);
748
877
  if (record.qrSynced) {
749
878
  this.emitter.emit(DEVICE.CHANGED, { type: DEVICE.CHANGED, payload: info });
@@ -753,7 +882,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
753
882
  }
754
883
  };
755
884
  this._handleUsbUiEvent = (event) => {
756
- this.emitter.emit("ui-event", event);
885
+ const operationId = this._activeOperationId();
886
+ this.emitter.emit("ui-event", operationId ? { ...event, operationId } : event);
757
887
  };
758
888
  // ---------------------------------------------------------------------------
759
889
  // All-network bundle, dispatched to the per-chain methods below.
@@ -826,6 +956,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
826
956
  success: true,
827
957
  payload: {
828
958
  ...context.payload,
959
+ ...access?.channel === "qr" && access.accountExport ? { accountExport: true } : {},
829
960
  rootFingerprint: record ? Number.parseInt(record.masterFingerprint, 16) : void 0,
830
961
  deviceIdentity: record ? {
831
962
  vendor: "keystone",
@@ -1075,23 +1206,24 @@ var KeystoneAdapter = class _KeystoneAdapter {
1075
1206
  }
1076
1207
  getDeviceInfo(connectIdOrOperationId, deviceId) {
1077
1208
  try {
1078
- const connectId = isHardwareOperationId2(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1209
+ const operation = isHardwareOperationId2(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId) : void 0;
1210
+ const connectId = operation?.connectId ?? connectIdOrOperationId;
1079
1211
  const { record } = this._resolveTarget(connectId, deviceId);
1080
1212
  if (!record) {
1081
1213
  return Promise.resolve(
1082
1214
  failure(HardwareErrorCode2.DeviceNotFound, "Unknown Keystone device")
1083
1215
  );
1084
1216
  }
1085
- return Promise.resolve(success(toDeviceInfo(record)));
1217
+ const info = operation ? toDeviceInfoForConnection(record, operation.connectionType === "qr" ? "qr" : "usb") : toDeviceInfo(record);
1218
+ return Promise.resolve(success(info));
1086
1219
  } catch (err) {
1087
1220
  return Promise.resolve(this._errorToFailure(err));
1088
1221
  }
1089
1222
  }
1090
1223
  cancel(connectId) {
1091
- let namedOperationConnectId;
1092
1224
  if (isHardwareOperationId2(connectId)) {
1093
1225
  try {
1094
- namedOperationConnectId = this._operations.resolve(connectId).connectId;
1226
+ this._operations.resolve(connectId);
1095
1227
  } catch {
1096
1228
  return;
1097
1229
  }
@@ -1101,15 +1233,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1101
1233
  message: "User aborted operation"
1102
1234
  });
1103
1235
  if (connectId) {
1236
+ const scopedOperationId = isHardwareOperationId2(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1104
1237
  const queueKeys = keystoneCancelQueueKeys([
1105
1238
  connectId,
1106
- this._operationRoutes.get(connectId)?.operationId,
1107
- namedOperationConnectId
1239
+ this._operationRoutes.get(connectId)?.operationId
1108
1240
  ]);
1109
1241
  for (const key of queueKeys) {
1110
1242
  this._jobQueue.cancelActiveAndPending(key, reason);
1111
1243
  }
1112
- const scopedOperationId = isHardwareOperationId2(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
1113
1244
  if (scopedOperationId) {
1114
1245
  this._uiRegistry.cancel(void 0, void 0, scopedOperationId);
1115
1246
  }
@@ -1171,13 +1302,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1171
1302
  });
1172
1303
  responseUr = await this._requestQrAndAwaitResponse(
1173
1304
  displayDevice,
1174
- { ...requestUr, animated: false },
1305
+ { ...requestUr, animated: false, allowAccountExport: true },
1175
1306
  signal
1176
1307
  );
1177
1308
  }
1178
1309
  _KeystoneAdapter._throwIfAborted(signal);
1179
- const parsed = this.urEngine.parseAccountResponse(responseUr);
1180
- if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1310
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1311
+ if (!responseUr.accountExport) requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1181
1312
  const record = this._upsertDeviceRecord(parsed);
1182
1313
  return success(toDeviceInfo(record));
1183
1314
  });
@@ -1774,7 +1905,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1774
1905
  }
1775
1906
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1776
1907
  return {
1777
- access: { channel: "usb", usbSessionId: record.usbSessionId },
1908
+ access: { channel: "usb", usbSessionId: record.usbSessionId, qrFallback: {} },
1778
1909
  masterFingerprint: record.masterFingerprint
1779
1910
  };
1780
1911
  }
@@ -1785,26 +1916,62 @@ var KeystoneAdapter = class _KeystoneAdapter {
1785
1916
  });
1786
1917
  }
1787
1918
  const schemas = Array.from(requestedByKey.values());
1788
- const requestUr = this.urEngine.buildKeyDerivationRequest({
1789
- schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1790
- origin: this._origin
1791
- });
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
+ };
1792
1934
  const responseUr = await this._requestQrAndAwaitResponse(
1793
1935
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1794
- { ...requestUr, animated: false },
1936
+ request,
1795
1937
  signal
1796
1938
  );
1797
1939
  _KeystoneAdapter._throwIfAborted(signal);
1798
- const parsed = this.urEngine.parseAccountResponse(responseUr);
1940
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1799
1941
  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
+ }
1800
1949
  for (const schema of schemas) {
1801
- scanned.set(accountKey(schema.hwkChain, schema.path), {
1802
- ...requireExportedPath(parsed, schema.path),
1803
- hwkChain: schema.hwkChain
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" }
1804
1963
  });
1805
1964
  }
1806
1965
  record = this._upsertDeviceRecord(parsed);
1807
- return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1966
+ return {
1967
+ access: {
1968
+ channel: "qr",
1969
+ scanned,
1970
+ firmwareVersion: parsed.deviceVersion,
1971
+ ...responseUr.accountExport ? { accountExport: true } : {}
1972
+ },
1973
+ masterFingerprint: record.masterFingerprint
1974
+ };
1808
1975
  });
1809
1976
  }
1810
1977
  /**
@@ -1878,11 +2045,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
1878
2045
  record = createDeviceRecord(masterFingerprint);
1879
2046
  this._devices.set(masterFingerprint, record);
1880
2047
  }
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;
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
+ }
1886
2059
  const info = toDeviceInfo(record);
1887
2060
  const eventType = isNew ? DEVICE.CONNECT : DEVICE.CHANGED;
1888
2061
  this.emitter.emit(eventType, { type: eventType, payload: info });
@@ -1966,16 +2139,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1966
2139
  }
1967
2140
  _KeystoneAdapter._throwIfAborted(signal);
1968
2141
  const record = this._upsertDeviceRecord(
1969
- { masterFingerprint, accounts: [] },
2142
+ {
2143
+ masterFingerprint,
2144
+ accounts: [],
2145
+ device: session.deviceInfo.modelName ?? session.deviceInfo.model
2146
+ },
1970
2147
  {
1971
2148
  viaUsb: true,
1972
- usbSessionId: session.sessionId
2149
+ usbSessionId: session.sessionId,
2150
+ usbFirmwareVersion: session.deviceInfo.firmwareVersion
1973
2151
  }
1974
2152
  );
1975
2153
  _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;
1979
2154
  return success(toDeviceInfo(record));
1980
2155
  } catch (err) {
1981
2156
  if (sessionId) {
@@ -2045,7 +2220,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2045
2220
  * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
2046
2221
  * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
2047
2222
  */
2048
- async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
2223
+ async _resolveUr(record, requestUr, animated, operationId, signal, operationName, qrFallback) {
2049
2224
  const releaseOperationRetention = isHardwareOperationId2(operationId) ? this._operations.retain(operationId) : void 0;
2050
2225
  try {
2051
2226
  return await this._resolveUrWithRoute(
@@ -2054,13 +2229,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
2054
2229
  animated,
2055
2230
  operationId,
2056
2231
  signal,
2057
- operationName
2232
+ operationName,
2233
+ qrFallback
2058
2234
  );
2059
2235
  } finally {
2060
2236
  releaseOperationRetention?.();
2061
2237
  }
2062
2238
  }
2063
- async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName) {
2239
+ async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName, qrFallback) {
2064
2240
  let record = callerRecord;
2065
2241
  let interactionRoute;
2066
2242
  if (isHardwareOperationId2(operationId)) {
@@ -2099,13 +2275,31 @@ var KeystoneAdapter = class _KeystoneAdapter {
2099
2275
  requestUr,
2100
2276
  signal
2101
2277
  );
2102
- if (result.success) return result.payload;
2278
+ if (result.success) {
2279
+ const ur = result.payload;
2280
+ return { urType: ur.urType, urData: ur.urData, channel: "usb" };
2281
+ }
2103
2282
  const usbError = rehydrateConnectorError(result.error);
2104
2283
  const { origin: usbErrorOrigin, code: usbErrorCode } = usbError;
2105
2284
  if (usbErrorCode === HardwareErrorCode2.PayloadTooLarge && usbErrorOrigin !== "device") {
2106
2285
  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
+ }
2107
2292
  const displayDevice2 = toDeviceInfo(record);
2108
- return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2293
+ const responseUr = await this._requestQrAndAwaitResponse(
2294
+ displayDevice2,
2295
+ {
2296
+ ...requestUr,
2297
+ animated,
2298
+ ...!operationName ? { allowAccountExport: true } : {}
2299
+ },
2300
+ signal
2301
+ );
2302
+ return { ...responseUr, channel: "qr" };
2109
2303
  }
2110
2304
  throw usbError;
2111
2305
  }
@@ -2116,6 +2310,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2116
2310
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2117
2311
  }
2118
2312
  record.usbSessionId = void 0;
2313
+ record.usbFirmwareVersion = void 0;
2119
2314
  this.emitter.emit(DEVICE.CHANGED, { type: DEVICE.CHANGED, payload: toDeviceInfo(record) });
2120
2315
  if (interactionRoute) {
2121
2316
  throw this._endDisconnectedOperation(
@@ -2147,11 +2342,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2147
2342
  }
2148
2343
  const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
2149
2344
  try {
2150
- return await this._requestQrAndAwaitResponse(
2345
+ const responseUr = await this._requestQrAndAwaitResponse(
2151
2346
  displayDevice,
2152
- { ...requestUr, animated },
2347
+ { ...requestUr, animated, ...!operationName ? { allowAccountExport: true } : {} },
2153
2348
  signal
2154
2349
  );
2350
+ return { ...responseUr, channel: "qr" };
2155
2351
  } catch (error) {
2156
2352
  const { code, _tag: tag } = error;
2157
2353
  if (operationName && (code === HardwareErrorCode2.OperationTimeout || tag === UI_REQUEST_TIMEOUT_TAG)) {
@@ -2185,12 +2381,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2185
2381
  const target = this._resolveTarget(connectId, deviceId);
2186
2382
  if (bundle?.channel === "qr") {
2187
2383
  const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2384
+ if (target.record && !scanned && bundle.accountExport) {
2385
+ throw createHwkError2({
2386
+ code: HardwareErrorCode2.DevicePathForbidden,
2387
+ message: "Scanned account export does not include this account path",
2388
+ params: { reason: "account-not-exported" }
2389
+ });
2390
+ }
2188
2391
  if (!target.record || !scanned) {
2189
2392
  throw createHwkError2({
2190
2393
  code: HardwareErrorCode2.DeviceMismatch,
2191
2394
  message: `Keystone did not return the requested derivation path (${syncPath})`
2192
2395
  });
2193
2396
  }
2397
+ this._assertQrChainSupported(bundle.firmwareVersion, hwkChain);
2194
2398
  return { record: target.record, account: scanned };
2195
2399
  }
2196
2400
  if (bundle?.channel === "usb" && target.record?.usbSessionId !== bundle.usbSessionId) {
@@ -2199,19 +2403,27 @@ var KeystoneAdapter = class _KeystoneAdapter {
2199
2403
  message: "Keystone USB connection was lost during the bundle"
2200
2404
  });
2201
2405
  }
2202
- const operationConnectionType = isHardwareOperationId2(connectId) ? this._operations.resolve(connectId).connectionType : void 0;
2203
2406
  let existingRecord = target.record;
2204
2407
  if (!existingRecord) {
2205
2408
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2206
2409
  _KeystoneAdapter._throwIfAborted(signal);
2207
2410
  }
2208
- const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2209
2411
  const schemas = [keySchema(hwkChain, syncPath)];
2210
2412
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2211
- const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2413
+ const responseUr = await this._resolveUr(
2414
+ existingRecord,
2415
+ requestUr,
2416
+ false,
2417
+ connectId,
2418
+ signal,
2419
+ void 0,
2420
+ bundle?.channel === "usb" ? bundle.qrFallback : void 0
2421
+ );
2212
2422
  _KeystoneAdapter._throwIfAborted(signal);
2213
- const parsed = this.urEngine.parseAccountResponse(responseUr);
2214
- const account = requireExportedPath(parsed, syncPath);
2423
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2424
+ this._assertParsedIdentity(parsed, target);
2425
+ const account = requireExportedPath(parsed, syncPath, responseUr.accountExport);
2426
+ const useSinglePathUsbExport = !responseUr.accountExport && responseUr.channel === "usb";
2215
2427
  let record;
2216
2428
  if (useSinglePathUsbExport && existingRecord) {
2217
2429
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2222,23 +2434,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
2222
2434
  }
2223
2435
  record = existingRecord;
2224
2436
  } else {
2225
- this._assertParsedIdentity(parsed, target);
2226
- record = this._upsertDeviceRecord(parsed, {
2227
- viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2228
- });
2437
+ this._assertQrChainSupported(parsed.deviceVersion, hwkChain);
2438
+ record = this._upsertDeviceRecord(parsed);
2229
2439
  }
2230
2440
  return { record, account: { ...account, hwkChain } };
2231
2441
  }
2232
2442
  /**
2233
- * Resolves which wallet is attached, without a per-path account. `CHAIN_FINGERPRINT_PATHS.evm` is
2234
- * a leaf path, so it is cut to the account path Keystone expects.
2443
+ * Resolves wallet identity without a per-path account. A caller-supplied fingerprint needs no
2444
+ * device round trip; otherwise request the account path from the device.
2235
2445
  */
2236
2446
  async _ensureWalletKnown(connectId, deviceId, chain, signal) {
2237
2447
  const target = this._resolveTarget(connectId, deviceId);
2238
2448
  if (target.record) return { record: target.record };
2239
- const attached = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2240
- _KeystoneAdapter._throwIfAborted(signal);
2241
- if (attached) return { record: attached };
2242
2449
  if (target.expectedMasterFingerprint) {
2243
2450
  return { record: createDeviceRecord(target.expectedMasterFingerprint) };
2244
2451
  }
@@ -2249,19 +2456,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
2249
2456
  });
2250
2457
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2251
2458
  _KeystoneAdapter._throwIfAborted(signal);
2252
- const parsed = this.urEngine.parseAccountResponse(responseUr);
2253
- requireExportedPath(parsed, normalizePath(accountPath));
2254
- return { record: this._upsertDeviceRecord(parsed) };
2459
+ const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
2460
+ requireExportedPath(parsed, normalizePath(accountPath), responseUr.accountExport);
2461
+ this._assertQrChainSupported(parsed.deviceVersion, chain);
2462
+ const record = this._upsertDeviceRecord(parsed);
2463
+ return { record };
2464
+ }
2465
+ _assertQrChainSupported(firmwareVersion, chain) {
2466
+ const firmware = getKeystoneFirmwareProfile(firmwareVersion);
2467
+ if (firmware && !firmware.supportedChains.includes(chain)) {
2468
+ throw createHwkError2({
2469
+ code: HardwareErrorCode2.ChainNotSupported,
2470
+ message: `Keystone ${firmware.variant} firmware cannot use ${chain} through this adapter`,
2471
+ params: { firmwareVariant: firmware.variant, chain }
2472
+ });
2473
+ }
2255
2474
  }
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
- */
2475
+ /** Only an operation id supplied to the running call owns its UI prompts. */
2260
2476
  _activeOperationId() {
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;
2477
+ return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
2265
2478
  }
2266
2479
  /** Routes are keyed by connectId; a job key may be the bare master fingerprint. */
2267
2480
  _operationRouteForIdentifier(identifier) {
@@ -2294,6 +2507,39 @@ var KeystoneAdapter = class _KeystoneAdapter {
2294
2507
  signal.removeEventListener("abort", onAbort);
2295
2508
  }
2296
2509
  }
2510
+ /**
2511
+ * Asks whether a request too large for USB may be shown as a QR. A timeout or an unanswered
2512
+ * prompt reads as no; a cancelled call keeps its own error.
2513
+ */
2514
+ async _confirmQrFallback(signal, choice) {
2515
+ if (choice?.confirmed !== void 0) return choice.confirmed;
2516
+ const requestType = UI_REQUEST.REQUEST_QR_FALLBACK_CONFIRM;
2517
+ const requestId = this._uiRegistry.createRequestId();
2518
+ const operationId = this._activeOperationId();
2519
+ const release = operationId ? this._operations.retain(operationId) : void 0;
2520
+ try {
2521
+ const waitPromise = this._uiRegistry.wait(requestType, {
2522
+ requestId,
2523
+ operationId
2524
+ });
2525
+ this.emitter.emit(requestType, {
2526
+ type: requestType,
2527
+ payload: { vendor: "keystone", requestId, operationId }
2528
+ });
2529
+ let confirmed = false;
2530
+ try {
2531
+ confirmed = Boolean(
2532
+ (await this._awaitQrResponse(requestType, waitPromise, signal))?.confirmed
2533
+ );
2534
+ } catch (error) {
2535
+ if (signal.aborted) throw error;
2536
+ }
2537
+ if (choice) choice.confirmed = confirmed;
2538
+ return confirmed;
2539
+ } finally {
2540
+ release?.();
2541
+ }
2542
+ }
2297
2543
  /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2298
2544
  async _requestQrAndAwaitResponse(device, data, signal) {
2299
2545
  const requestType = data ? UI_REQUEST.REQUEST_QR_DISPLAY : UI_REQUEST.REQUEST_QR_SCAN;
@@ -2316,7 +2562,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
2316
2562
  });
2317
2563
  }
2318
2564
  const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2319
- return { urType: response.urType, urData: response.urData };
2565
+ if (response.accountExport && data && !data.allowAccountExport) {
2566
+ throw createHwkError2({
2567
+ code: HardwareErrorCode2.InvalidParams,
2568
+ message: "This request cannot be answered with an account export"
2569
+ });
2570
+ }
2571
+ return {
2572
+ urType: response.urType,
2573
+ urData: response.urData,
2574
+ ...!data || response.accountExport ? { accountExport: true } : {}
2575
+ };
2320
2576
  } finally {
2321
2577
  release?.();
2322
2578
  }