@onekeyfe/hwk-keystone-adapter 1.2.8-alpha.127 → 1.2.8-alpha.129

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
@@ -187,6 +187,35 @@ function toParsedAccount(key) {
187
187
  };
188
188
  }
189
189
  var BIP32_HARDENED_OFFSET = 2147483648;
190
+ function isExportedAccountPath(path) {
191
+ return /^m(?:\/\d+')+(?:\/\d+)*$/.test(path) && path.slice(2).split("/").every(
192
+ (segment) => Number(segment.endsWith("'") ? segment.slice(0, -1) : segment) < BIP32_HARDENED_OFFSET
193
+ );
194
+ }
195
+ function checkExportedKey(key, account, masterFingerprint, unsupportedDescriptor) {
196
+ if (unsupportedDescriptor || key.isMaster() || key.isPrivateKey()) {
197
+ return { rejected: "unusable-key" };
198
+ }
199
+ const source = key.getOrigin()?.getSourceFingerprint();
200
+ if (source && source.toString("hex") !== masterFingerprint) {
201
+ return { rejected: "different-wallet" };
202
+ }
203
+ if (!account.extendedPublicKey) {
204
+ return /^[0-9a-f]{64}$/i.test(account.publicKey) ? { identity: account.publicKey } : { rejected: "unusable-key" };
205
+ }
206
+ try {
207
+ const node = HDKey.fromExtendedKey(account.extendedPublicKey);
208
+ if (node.privateKey || !node.publicKey || !node.chainCode || node.publicKey.toString("hex") !== account.publicKey.toLowerCase()) {
209
+ return { rejected: "unusable-key" };
210
+ }
211
+ return { identity: `${account.publicKey}:${node.chainCode.toString("hex")}` };
212
+ } catch {
213
+ return { rejected: "unusable-key" };
214
+ }
215
+ }
216
+ function unexpectedQrCodeError(message, code = HardwareErrorCode.InvalidParams) {
217
+ return createHwkError({ code, message, params: { reason: "unexpected-qr-code" } });
218
+ }
190
219
  function relativeHdPath(relativeDerivePath) {
191
220
  const segments = relativeDerivePath.replace(/^m\//i, "").split("/");
192
221
  const valid = segments.every(
@@ -256,26 +285,32 @@ var KeystoneUrEngine = class {
256
285
  }
257
286
  return this.parseMultiAccounts(ur);
258
287
  }
259
- /** Device exports are opt-in: request responses retain their existing format/path checks. */
288
+ /**
289
+ * Device exports are opt-in: request responses retain their existing format/path checks. An
290
+ * export carries whatever the device syncs to other wallets, so each key is checked on its own: a
291
+ * key that fails lands in `rejectedPaths` instead of discarding the whole export.
292
+ */
260
293
  parseAccountExport(ur) {
294
+ let parsed;
295
+ let keys;
296
+ const unsupportedDescriptors = /* @__PURE__ */ new Set();
261
297
  try {
262
298
  const { cbor } = toSdkUr(ur);
263
- let parsed;
264
- let keys;
265
299
  if (ur.urType === "crypto-account") {
266
300
  if (!Object.values(ScriptExpressions).some((script) => script.getTag() === 409)) {
267
301
  Object.assign(ScriptExpressions, { TAPROOT: new ScriptExpression(409, "tr") });
268
302
  }
269
303
  extend3.cbor.patchTags([409]);
270
304
  const account = CryptoAccount.fromCBOR(cbor);
271
- keys = account.getOutputDescriptors().map((output) => {
305
+ keys = account.getOutputDescriptors().map((output, index) => {
272
306
  const key = output.getHDKey();
273
307
  const path = key?.getOrigin()?.getPath();
274
308
  const script = output.getScriptExpressions().map((item) => item.getExpression()).join("/");
275
309
  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
310
  const children = key?.getChildren();
277
- if (!key || !validScript || children && children.getPath() !== "0/*") {
278
- throw new Error("Unsupported account descriptor");
311
+ if (!key) throw new Error("Unsupported account descriptor");
312
+ if (!validScript || children && children.getPath() !== "0/*") {
313
+ unsupportedDescriptors.add(index);
279
314
  }
280
315
  return key;
281
316
  });
@@ -296,54 +331,43 @@ var KeystoneUrEngine = class {
296
331
  if (!keys.length || keys.length !== parsed.accounts.length) {
297
332
  throw new Error("Empty account export");
298
333
  }
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
- }
334
+ } catch {
335
+ throw unexpectedQrCodeError(
336
+ "Unable to read account export; scan a supported Keystone account export code"
337
+ );
338
+ }
339
+ const byPath = /* @__PURE__ */ new Map();
340
+ parsed.accounts.forEach((account, index) => {
341
+ if (!isExportedAccountPath(account.path)) return;
342
+ const entry = byPath.get(account.path) ?? {};
343
+ byPath.set(account.path, entry);
344
+ const check = checkExportedKey(
345
+ keys[index],
346
+ account,
347
+ parsed.masterFingerprint,
348
+ unsupportedDescriptors.has(index)
349
+ );
350
+ if (check.rejected === "different-wallet") {
351
+ entry.rejected = check.rejected;
352
+ } else if (check.identity === void 0) {
353
+ entry.rejected ?? (entry.rejected = check.rejected);
354
+ } else if (entry.identity === void 0) {
355
+ entry.account = account;
356
+ entry.identity = check.identity;
357
+ } else if (entry.identity !== check.identity && entry.rejected !== "different-wallet") {
358
+ entry.rejected = "conflicting-keys";
308
359
  }
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);
360
+ });
361
+ const accounts = [];
362
+ const rejectedPaths = [];
363
+ byPath.forEach((entry, path) => {
364
+ if (entry.account && entry.rejected !== "different-wallet" && entry.rejected !== "conflicting-keys") {
365
+ accounts.push(entry.account);
366
+ } else if (entry.rejected) {
367
+ rejectedPaths.push({ path, reason: entry.rejected });
337
368
  }
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
- }
369
+ });
370
+ return { ...parsed, accounts, rejectedPaths };
347
371
  }
348
372
  // --- EVM ---
349
373
  buildEthSignRequest(input) {
@@ -429,10 +453,10 @@ var KeystoneUrEngine = class {
429
453
  sameTransaction = false;
430
454
  }
431
455
  if (!sameTransaction) {
432
- throw createHwkError({
433
- code: HardwareErrorCode.DeviceMismatch,
434
- message: "Keystone returned a PSBT for another transaction than the one requested"
435
- });
456
+ throw unexpectedQrCodeError(
457
+ "Keystone returned a PSBT for another transaction than the one requested",
458
+ HardwareErrorCode.DeviceMismatch
459
+ );
436
460
  }
437
461
  return signedPsbtHex;
438
462
  }
@@ -742,6 +766,11 @@ function keystoneBtcParamsFailure(params) {
742
766
  }
743
767
  return void 0;
744
768
  }
769
+ var USB_ATTACH_FAILURE_REASONS = {
770
+ [HardwareErrorCode2.DeviceMismatch]: "wallet-mismatch",
771
+ [HardwareErrorCode2.DeviceNotInitialized]: "wallet-mismatch",
772
+ [HardwareErrorCode2.DeviceLocked]: "device-locked"
773
+ };
745
774
  var KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS = 24;
746
775
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
747
776
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
@@ -790,8 +819,37 @@ function exactHex(value) {
790
819
  function invalidHexFailure(field) {
791
820
  return failure(HardwareErrorCode2.InvalidParams, `${field} must be an even-length hex string`);
792
821
  }
822
+ function exportedAccountAt(parsed, path) {
823
+ const rejected = parsed.rejectedPaths?.find((entry) => normalizePath(entry.path) === path);
824
+ switch (rejected?.reason) {
825
+ case "different-wallet":
826
+ throw createHwkError2({
827
+ code: HardwareErrorCode2.DeviceMismatch,
828
+ message: "Account export contains a different wallet fingerprint"
829
+ });
830
+ case "conflicting-keys":
831
+ throw createHwkError2({
832
+ code: HardwareErrorCode2.DeviceMismatch,
833
+ message: "Account export contains conflicting keys for the same path"
834
+ });
835
+ case "unusable-key":
836
+ throw unexpectedQrCodeError(`Account export key at ${path} is not usable`);
837
+ default:
838
+ return parsed.accounts.find((returned) => normalizePath(returned.path) === path);
839
+ }
840
+ }
841
+ function parseScannedAnswer(parse) {
842
+ try {
843
+ return parse();
844
+ } catch (error) {
845
+ if (typeof error?.code === "number") throw error;
846
+ throw unexpectedQrCodeError(
847
+ `Scanned code is not this request's answer: ${error instanceof Error ? error.message : ""}`
848
+ );
849
+ }
850
+ }
793
851
  function requireExportedPath(parsed, path, accountExport = false) {
794
- const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
852
+ const account = exportedAccountAt(parsed, path);
795
853
  if (!account) {
796
854
  throw createHwkError2({
797
855
  code: accountExport ? HardwareErrorCode2.DevicePathForbidden : HardwareErrorCode2.DeviceMismatch,
@@ -824,6 +882,10 @@ function evmMessageSignature(sig) {
824
882
  return { signature: ensure0x(sig.r + sig.s + sig.v) };
825
883
  }
826
884
  var KeystoneAdapter = class _KeystoneAdapter {
885
+ /**
886
+ * `qrKeyRequestLimit` caps the account paths one QR key request may ask for, below the firmware's
887
+ * own limit: a host with no USB to fall back on can refuse a large request before the device does.
888
+ */
827
889
  constructor(options) {
828
890
  this.vendor = "keystone";
829
891
  // No protocol-level cancel exists over Keystone USB, and QR has no transport
@@ -982,6 +1044,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
982
1044
  };
983
1045
  this._origin = options?.origin ?? "OneKey";
984
1046
  this._qrTimeoutMs = options?.qrTimeoutMs;
1047
+ const limit = options?.qrKeyRequestLimit;
1048
+ this._qrKeyRequestLimit = limit !== void 0 && Number.isInteger(limit) && limit > 0 ? Math.min(limit, KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS) : KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS;
985
1049
  this.urEngine = new KeystoneUrEngine(this._origin);
986
1050
  this._jobQueue = new DeviceJobQueue();
987
1051
  this._usbConnector = options?.usbConnector;
@@ -1508,7 +1572,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
1508
1572
  "btcSignPsbt"
1509
1573
  );
1510
1574
  _KeystoneAdapter._throwIfAborted(signal);
1511
- const signedPsbt = this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex);
1575
+ const signedPsbt = parseScannedAnswer(
1576
+ () => this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex)
1577
+ );
1512
1578
  return success({ signedPsbt });
1513
1579
  });
1514
1580
  }
@@ -1855,7 +1921,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1855
1921
  args.operationName
1856
1922
  );
1857
1923
  _KeystoneAdapter._throwIfAborted(signal);
1858
- const signature = args.parseResponse(responseUr);
1924
+ const signature = parseScannedAnswer(() => args.parseResponse(responseUr));
1859
1925
  _KeystoneAdapter._assertRequestIdMatches(requestId, signature.requestId);
1860
1926
  return success(args.toPayload(signature));
1861
1927
  });
@@ -1916,11 +1982,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1916
1982
  });
1917
1983
  }
1918
1984
  const schemas = Array.from(requestedByKey.values());
1919
- if (schemas.length > KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS) {
1985
+ if (schemas.length > this._qrKeyRequestLimit) {
1920
1986
  throw createHwkError2({
1921
1987
  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 }
1988
+ message: `Keystone QR requests take at most ${this._qrKeyRequestLimit} account paths here; this one needs ${schemas.length}`,
1989
+ params: { limit: this._qrKeyRequestLimit, requested: schemas.length }
1924
1990
  });
1925
1991
  }
1926
1992
  const request = {
@@ -1940,12 +2006,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1940
2006
  const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
1941
2007
  this._assertParsedIdentity(parsed, target);
1942
2008
  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
2009
  const usableSchemas = schemas.filter(
1950
2010
  (schema) => !firmware || firmware.supportedChains.includes(schema.hwkChain)
1951
2011
  );
@@ -1958,7 +2018,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1958
2018
  });
1959
2019
  }
1960
2020
  for (const schema of usableSchemas) {
1961
- const exported = responseUr.accountExport ? parsed.accounts.find((account) => normalizePath(account.path) === schema.path) : requireExportedPath(parsed, schema.path);
2021
+ const exported = responseUr.accountExport ? exportedAccountAt(parsed, schema.path) : requireExportedPath(parsed, schema.path);
1962
2022
  if (exported) {
1963
2023
  scanned.set(accountKey(schema.hwkChain, schema.path), {
1964
2024
  ...exported,
@@ -2175,7 +2235,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2175
2235
  }
2176
2236
  /**
2177
2237
  * Probes already-authorized USB devices without a permission picker, then attaches and verifies
2178
- * the requested wallet if present.
2238
+ * the requested wallet if present. Undefined means use QR: no device, or the user chose QR.
2179
2239
  */
2180
2240
  async _tryUsbAttach(signal, expectedMasterFingerprint, options) {
2181
2241
  _KeystoneAdapter._throwIfAborted(signal);
@@ -2219,13 +2279,27 @@ var KeystoneAdapter = class _KeystoneAdapter {
2219
2279
  signal
2220
2280
  );
2221
2281
  _KeystoneAdapter._throwIfAborted(signal);
2222
- if (!attached.success && (attached.payload.code === HardwareErrorCode2.DeviceBusyInternal || attached.payload.code === HardwareErrorCode2.DeviceOneDeviceOnly)) {
2282
+ if (attached.success) return this._devices.get(expectedMasterFingerprint);
2283
+ const { code } = attached.payload;
2284
+ if (code === HardwareErrorCode2.DeviceBusyInternal || code === HardwareErrorCode2.DeviceOneDeviceOnly) {
2223
2285
  throw createHwkError2({
2224
2286
  ...attached.payload,
2225
2287
  message: attached.payload.error
2226
2288
  });
2227
2289
  }
2228
- return attached.success ? this._devices.get(expectedMasterFingerprint) : void 0;
2290
+ if (code === HardwareErrorCode2.DeviceNotFound || this._forcedTransport) return void 0;
2291
+ const answer = await this._askQrFallback(
2292
+ signal,
2293
+ USB_ATTACH_FAILURE_REASONS[code] ?? "usb-unavailable"
2294
+ );
2295
+ if (answer === "retry") return this._tryUsbAttach(signal, expectedMasterFingerprint);
2296
+ if (answer === "cancel") {
2297
+ throw createHwkError2({
2298
+ code: HardwareErrorCode2.UserAborted,
2299
+ message: "User declined to continue by QR while the connected Keystone was unusable"
2300
+ });
2301
+ }
2302
+ return void 0;
2229
2303
  }
2230
2304
  /**
2231
2305
  * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
@@ -2524,29 +2598,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
2524
2598
  */
2525
2599
  async _confirmQrFallback(signal, choice) {
2526
2600
  if (choice?.confirmed !== void 0) return choice.confirmed;
2601
+ const confirmed = await this._askQrFallback(signal, "payload-too-large") === "qr";
2602
+ if (choice) choice.confirmed = confirmed;
2603
+ return confirmed;
2604
+ }
2605
+ /** A timeout or an unanswered prompt reads as cancel; a cancelled call keeps its own error. */
2606
+ async _askQrFallback(signal, reason) {
2527
2607
  const requestType = UI_REQUEST.REQUEST_QR_FALLBACK_CONFIRM;
2528
2608
  const requestId = this._uiRegistry.createRequestId();
2529
2609
  const operationId = this._activeOperationId();
2530
2610
  const release = operationId ? this._operations.retain(operationId) : void 0;
2531
2611
  try {
2532
- const waitPromise = this._uiRegistry.wait(requestType, {
2533
- requestId,
2534
- operationId
2535
- });
2612
+ const waitPromise = this._uiRegistry.wait(
2613
+ requestType,
2614
+ { requestId, operationId }
2615
+ );
2536
2616
  this.emitter.emit(requestType, {
2537
2617
  type: requestType,
2538
- payload: { vendor: "keystone", requestId, operationId }
2618
+ payload: { vendor: "keystone", requestId, operationId, reason }
2539
2619
  });
2540
- let confirmed = false;
2620
+ let answer;
2541
2621
  try {
2542
- confirmed = Boolean(
2543
- (await this._awaitQrResponse(requestType, waitPromise, signal))?.confirmed
2544
- );
2622
+ answer = await this._awaitQrResponse(requestType, waitPromise, signal);
2545
2623
  } catch (error) {
2546
2624
  if (signal.aborted) throw error;
2547
2625
  }
2548
- if (choice) choice.confirmed = confirmed;
2549
- return confirmed;
2626
+ if (answer?.retry && reason !== "payload-too-large") return "retry";
2627
+ return answer?.confirmed ? "qr" : "cancel";
2550
2628
  } finally {
2551
2629
  release?.();
2552
2630
  }
@@ -2574,10 +2652,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2574
2652
  }
2575
2653
  const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2576
2654
  if (response.accountExport && data && !data.allowAccountExport) {
2577
- throw createHwkError2({
2578
- code: HardwareErrorCode2.InvalidParams,
2579
- message: "This request cannot be answered with an account export"
2580
- });
2655
+ throw unexpectedQrCodeError("This request cannot be answered with an account export");
2581
2656
  }
2582
2657
  return {
2583
2658
  urType: response.urType,
@@ -2689,10 +2764,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
2689
2764
  /** A response without the request's id is as unrelated as one with another id. */
2690
2765
  static _assertRequestIdMatches(expected, actual) {
2691
2766
  if (!actual || actual.toLowerCase() !== expected.toLowerCase()) {
2692
- throw createHwkError2({
2693
- code: HardwareErrorCode2.DeviceMismatch,
2694
- message: actual ? "Keystone response requestId does not match the pending request \u2014 discarding a stale or unrelated scan" : "Keystone response carries no requestId \u2014 discarding a stale or unrelated scan"
2695
- });
2767
+ throw unexpectedQrCodeError(
2768
+ actual ? "Keystone response requestId does not match the pending request \u2014 discarding a stale or unrelated scan" : "Keystone response carries no requestId \u2014 discarding a stale or unrelated scan",
2769
+ HardwareErrorCode2.DeviceMismatch
2770
+ );
2696
2771
  }
2697
2772
  }
2698
2773
  _unsupported(method, reason) {