@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.107 → 1.2.8-alpha.109

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.d.mts CHANGED
@@ -228,6 +228,11 @@ declare class LedgerAdapter implements IHardwareWallet {
228
228
  cancel(connectId?: string): void;
229
229
  /** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
230
230
  getChainFingerprint(connectId: string, deviceId: string, chain: ChainForFingerprint): Promise<Response<string>>;
231
+ /**
232
+ * Fingerprints the first recorded chain whose app the device can open. Only a missing app
233
+ * moves on to the next chain; when every app is missing, the first chain offers its install.
234
+ */
235
+ private _fingerprintFirstOpenableChain;
231
236
  /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
232
237
  private _saveSelectedBleBinding;
233
238
  private _dropSession;
package/dist/index.d.ts CHANGED
@@ -228,6 +228,11 @@ declare class LedgerAdapter implements IHardwareWallet {
228
228
  cancel(connectId?: string): void;
229
229
  /** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
230
230
  getChainFingerprint(connectId: string, deviceId: string, chain: ChainForFingerprint): Promise<Response<string>>;
231
+ /**
232
+ * Fingerprints the first recorded chain whose app the device can open. Only a missing app
233
+ * moves on to the next chain; when every app is missing, the first chain offers its install.
234
+ */
235
+ private _fingerprintFirstOpenableChain;
231
236
  /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
232
237
  private _saveSelectedBleBinding;
233
238
  private _dropSession;
package/dist/index.js CHANGED
@@ -219,6 +219,7 @@ var ERROR_TAG = {
219
219
  // outcome when the user doesn't confirm pairing on the device, or the
220
220
  // existing bond is invalid. Observed in production after ~30s.
221
221
  PairingRefused: "PairingRefusedError",
222
+ PeerRemovedPairing: "PeerRemovedPairingError",
222
223
  // DMK remote-network failures (manager-api HTTP / secure-channel WS).
223
224
  WebSocketConnection: "WebSocketConnectionError",
224
225
  HttpFetch: "FetchError",
@@ -247,6 +248,27 @@ function isDeviceNotAdvertisingError(err) {
247
248
  if (!err || typeof err !== "object") return false;
248
249
  return err._tag === ERROR_TAG.DeviceNotAdvertising;
249
250
  }
251
+ function isBleBondInvalidError(err) {
252
+ const pending = [err];
253
+ const seen = /* @__PURE__ */ new Set();
254
+ while (pending.length > 0) {
255
+ const candidate = pending.pop();
256
+ if (candidate && typeof candidate === "object" && !seen.has(candidate)) {
257
+ seen.add(candidate);
258
+ const e = candidate;
259
+ if (e._tag === ERROR_TAG.PeerRemovedPairing || e.iosErrorCode === 14 || e.attErrorCode === 5 || e.nativeErrorDomain === "CBErrorDomain" && e.nativeErrorCode === 14) {
260
+ return true;
261
+ }
262
+ const reason = typeof e.reason === "string" ? e.reason : "";
263
+ const message = typeof e.message === "string" ? e.message : "";
264
+ if (/\bCBErrorDomain:14(?:\s|$)/.test(message) || reason.includes("Peer removed pairing information") || reason.includes("GATT_INSUF_AUTHENTICATION")) {
265
+ return true;
266
+ }
267
+ pending.push(e.originalError, e.err);
268
+ }
269
+ }
270
+ return false;
271
+ }
250
272
  var PAIRING_FAILURE_TAGS = /* @__PURE__ */ new Set([
251
273
  ERROR_TAG.BlePairingTimeout,
252
274
  ERROR_TAG.BleGattBondingFailed,
@@ -265,6 +287,7 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
265
287
  ERROR_TAG.BlePairingTimeout,
266
288
  ERROR_TAG.BleGattBondingFailed,
267
289
  ERROR_TAG.PairingRefused,
290
+ ERROR_TAG.PeerRemovedPairing,
268
291
  ERROR_TAG.DeviceNotRecognized,
269
292
  ERROR_TAG.NoAccessibleDevice,
270
293
  ERROR_TAG.UnknownDevice,
@@ -501,6 +524,8 @@ function mapLedgerError(err, opts) {
501
524
  code = import_hwk_adapter_core.HardwareErrorCode.DeviceLocked;
502
525
  } else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
503
526
  code = import_hwk_adapter_core.HardwareErrorCode.DeviceNotFound;
527
+ } else if (isBleBondInvalidError(err)) {
528
+ code = import_hwk_adapter_core.HardwareErrorCode.BleBondInvalid;
504
529
  } else if (isBlePairingFailureError(err)) {
505
530
  code = import_hwk_adapter_core.HardwareErrorCode.BlePairingTimeout;
506
531
  } else if (isDeviceBusyError(err)) {
@@ -1113,6 +1138,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1113
1138
  this._discoveredDevices.clear();
1114
1139
  this._sessions.clear();
1115
1140
  this._sessionTransports.clear();
1141
+ this._activeConnectionType = void 0;
1116
1142
  this._pendingOperationBindings.clear();
1117
1143
  this._pendingPickBindings.clear();
1118
1144
  this._selectedBleReconnectTargets.clear();
@@ -1245,6 +1271,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1245
1271
  /** Binds the picked BLE device; with a recorded wallet identity it must match first. */
1246
1272
  async bindBleDevice(params) {
1247
1273
  const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
1274
+ const identities = identity ? [identity, ...params.fallbackIdentities ?? []] : [];
1248
1275
  try {
1249
1276
  return await this._jobQueue.enqueue(
1250
1277
  "__ledger_bind_ble__",
@@ -1281,24 +1308,27 @@ var _LedgerAdapter = class _LedgerAdapter {
1281
1308
  message: "Selected Ledger connection ended"
1282
1309
  });
1283
1310
  }
1284
- const fingerprint = await this._computeChainFingerprint(
1285
- identity.chain,
1286
- (method, callParams) => this._runConnectorCall(
1287
- connectId,
1288
- method,
1289
- callParams,
1290
- signal,
1291
- void 0,
1292
- void 0,
1293
- { autoInstallApp: true },
1294
- { connection: { connectId, sessionId } }
1311
+ const checked = await this._fingerprintFirstOpenableChain(
1312
+ identities,
1313
+ (chain, autoInstallApp) => this._computeChainFingerprint(
1314
+ chain,
1315
+ (method, callParams) => this._runConnectorCall(
1316
+ connectId,
1317
+ method,
1318
+ callParams,
1319
+ signal,
1320
+ void 0,
1321
+ void 0,
1322
+ { autoInstallApp },
1323
+ { connection: { connectId, sessionId } }
1324
+ )
1295
1325
  )
1296
1326
  );
1297
- if (fingerprint !== identity.value) {
1327
+ if (checked.fingerprint !== checked.identity.value) {
1298
1328
  await this._dropSession(connectId, signal);
1299
1329
  throw (0, import_hwk_adapter_core4.createHwkError)({
1300
1330
  code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
1301
- message: formatDeviceMismatchError(identity.value, fingerprint)
1331
+ message: formatDeviceMismatchError(checked.identity.value, checked.fingerprint)
1302
1332
  });
1303
1333
  }
1304
1334
  await this._saveSelectedBleBinding(
@@ -1307,7 +1337,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1307
1337
  attempt,
1308
1338
  void 0,
1309
1339
  signal,
1310
- identity
1340
+ checked.identity
1311
1341
  );
1312
1342
  }
1313
1343
  if (!attempt.bindingSaved) {
@@ -2083,6 +2113,24 @@ var _LedgerAdapter = class _LedgerAdapter {
2083
2113
  return this.errorToFailure(err);
2084
2114
  }
2085
2115
  }
2116
+ /**
2117
+ * Fingerprints the first recorded chain whose app the device can open. Only a missing app
2118
+ * moves on to the next chain; when every app is missing, the first chain offers its install.
2119
+ */
2120
+ async _fingerprintFirstOpenableChain(identities, fingerprintOf) {
2121
+ const [first] = identities;
2122
+ if (identities.length > 1) {
2123
+ for (const identity of identities) {
2124
+ try {
2125
+ return { identity, fingerprint: await fingerprintOf(identity.chain, false) };
2126
+ } catch (error) {
2127
+ const isAppMissing = isAppNotInstalledError(error) || error?.code === import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled;
2128
+ if (!isAppMissing) throw error;
2129
+ }
2130
+ }
2131
+ }
2132
+ return { identity: first, fingerprint: await fingerprintOf(first.chain, true) };
2133
+ }
2086
2134
  /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
2087
2135
  async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
2088
2136
  try {
@@ -2331,7 +2379,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2331
2379
  async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
2332
2380
  if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
2333
2381
  this._assertConnectorReady("connectDevice");
2334
- if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
2382
+ if (!this.connector.availableTransports?.includes("usb") && this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
2335
2383
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
2336
2384
  code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
2337
2385
  });
@@ -2365,6 +2413,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2365
2413
  if (this._doConnectAbortController === controller) {
2366
2414
  this._connectingPromise = null;
2367
2415
  this._doConnectAbortController = null;
2416
+ if (this._sessions.size === 0) this._activeConnectionType = void 0;
2368
2417
  }
2369
2418
  }
2370
2419
  })();
@@ -2407,19 +2456,16 @@ var _LedgerAdapter = class _LedgerAdapter {
2407
2456
  if (knownBle?.transport === "ble") {
2408
2457
  return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
2409
2458
  }
2410
- if (targetConnectId && context?.knownConnections === void 0) {
2411
- throw (0, import_hwk_adapter_core4.createHwkError)({
2412
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
2413
- message: "Ledger connection metadata is required before starting Bluetooth binding"
2414
- });
2415
- }
2459
+ const bleContext = context ?? {};
2460
+ bleContext.allowBleSelection = true;
2461
+ bleContext.usbFallbackConnectId = usbTarget ?? targetConnectId;
2416
2462
  const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
2417
2463
  return this._connectFirstOrSelect(
2418
2464
  bleDevices,
2419
2465
  void 0,
2420
2466
  allowUsbEphemeralFallback,
2421
2467
  preserveOperationId,
2422
- context,
2468
+ bleContext,
2423
2469
  internalSignal
2424
2470
  );
2425
2471
  }
@@ -2508,7 +2554,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2508
2554
  }
2509
2555
  }
2510
2556
  const requiresBleSelection = this._isBleConnection();
2511
- if (requiresBleSelection && !allowUsbEphemeralFallback) {
2557
+ if (requiresBleSelection && !allowUsbEphemeralFallback && !context?.allowBleSelection) {
2512
2558
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
2513
2559
  code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
2514
2560
  });
@@ -2520,7 +2566,8 @@ var _LedgerAdapter = class _LedgerAdapter {
2520
2566
  const knownUsb = context?.knownConnections?.find(
2521
2567
  (connection) => connection.transport === "usb"
2522
2568
  );
2523
- const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
2569
+ const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : context?.usbFallbackConnectId ?? targetConnectId;
2570
+ const maySelectAnyUsb = allowUsbEphemeralFallback || !usbConnectId && !context?.knownConnections?.some((connection) => connection.transport !== "qr");
2524
2571
  const { device, requestId } = await (0, import_hwk_adapter_core4.requestBleDeviceSelection)({
2525
2572
  emitter: this.emitter,
2526
2573
  registry: this._uiRegistry,
@@ -2531,7 +2578,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2531
2578
  const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
2532
2579
  const candidate = usbDevices.find(
2533
2580
  (device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
2534
- ) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2581
+ ) ?? (maySelectAnyUsb && usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2535
2582
  if (candidate) return [candidate];
2536
2583
  }
2537
2584
  return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
@@ -3553,11 +3600,14 @@ var import_hwk_adapter_core5 = require("@onekeyfe/hwk-adapter-core");
3553
3600
  var import_device_management_kit = require("@ledgerhq/device-management-kit");
3554
3601
  var IDLE_WATCHDOG_MS = 65e3;
3555
3602
  var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
3603
+ var INTERACTION_PROMPT_DELAY_MS = 500;
3556
3604
  function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
3557
3605
  return new Promise((resolve, reject) => {
3558
3606
  let settled = false;
3559
3607
  let lastStep;
3560
3608
  let activeInteraction;
3609
+ let pendingInteraction;
3610
+ let pendingInteractionTimer = null;
3561
3611
  const observedSteps = [];
3562
3612
  let sub;
3563
3613
  let timer = null;
@@ -3585,31 +3635,52 @@ function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_
3585
3635
  }
3586
3636
  return false;
3587
3637
  };
3638
+ const cancelPendingInteraction = () => {
3639
+ if (pendingInteractionTimer) clearTimeout(pendingInteractionTimer);
3640
+ pendingInteractionTimer = null;
3641
+ pendingInteraction = void 0;
3642
+ };
3643
+ const showInteraction = (interactionName) => {
3644
+ activeInteraction = interactionName;
3645
+ debugLog(
3646
+ "[DeviceAction] requiredUserInteraction",
3647
+ `interaction=${interactionName}`,
3648
+ `step=${lastStep ?? "unknown"}`
3649
+ );
3650
+ if (interactionName === "unlock-device" && timer) {
3651
+ clearTimeout(timer);
3652
+ timer = null;
3653
+ }
3654
+ onInteraction?.(interactionName);
3655
+ };
3588
3656
  const emitInteraction = (interaction) => {
3589
3657
  if (!onInteraction) {
3590
3658
  return;
3591
3659
  }
3592
3660
  if (!interaction || interaction === "none") {
3661
+ cancelPendingInteraction();
3593
3662
  clearActiveInteraction();
3594
3663
  return;
3595
3664
  }
3596
3665
  const interactionName = String(interaction);
3597
- if (interactionName === activeInteraction) {
3666
+ if (interactionName === activeInteraction || interactionName === pendingInteraction) {
3598
3667
  return;
3599
3668
  }
3600
- activeInteraction = interactionName;
3601
- debugLog(
3602
- "[DeviceAction] requiredUserInteraction",
3603
- `interaction=${interactionName}`,
3604
- `step=${lastStep ?? "unknown"}`
3605
- );
3606
- if (interaction === "unlock-device" && timer) {
3607
- clearTimeout(timer);
3608
- timer = null;
3669
+ cancelPendingInteraction();
3670
+ clearActiveInteraction();
3671
+ if (interactionName === "unlock-device") {
3672
+ showInteraction(interactionName);
3673
+ return;
3609
3674
  }
3610
- onInteraction(interactionName);
3675
+ pendingInteraction = interactionName;
3676
+ pendingInteractionTimer = setTimeout(() => {
3677
+ pendingInteractionTimer = null;
3678
+ pendingInteraction = void 0;
3679
+ if (!settled) showInteraction(interactionName);
3680
+ }, INTERACTION_PROMPT_DELAY_MS);
3611
3681
  };
3612
3682
  const completeInteraction = () => {
3683
+ cancelPendingInteraction();
3613
3684
  if (!clearActiveInteraction()) {
3614
3685
  onInteraction?.("interaction-complete");
3615
3686
  }
@@ -5187,6 +5258,13 @@ var LedgerConnectorBase = class {
5187
5258
  } catch (err) {
5188
5259
  this._resetSignersAndSessions();
5189
5260
  if (isLedgerBleConnectionType(this.connectionType)) {
5261
+ if (isBleBondInvalidError(err)) {
5262
+ throw (0, import_hwk_adapter_core13.createHwkError)({
5263
+ code: import_hwk_adapter_core13.HardwareErrorCode.BleBondInvalid,
5264
+ message: "Ledger Bluetooth pairing is no longer valid. Forget this device in system Bluetooth settings, then reconnect.",
5265
+ _tag: ERROR_TAG.PeerRemovedPairing
5266
+ });
5267
+ }
5190
5268
  const tag = err?._tag;
5191
5269
  if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
5192
5270
  throw err;