@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.110 → 1.2.8-alpha.111

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
@@ -196,6 +196,7 @@ var ERROR_TAG = {
196
196
  // outcome when the user doesn't confirm pairing on the device, or the
197
197
  // existing bond is invalid. Observed in production after ~30s.
198
198
  PairingRefused: "PairingRefusedError",
199
+ PeerRemovedPairing: "PeerRemovedPairingError",
199
200
  // DMK remote-network failures (manager-api HTTP / secure-channel WS).
200
201
  WebSocketConnection: "WebSocketConnectionError",
201
202
  HttpFetch: "FetchError",
@@ -224,6 +225,27 @@ function isDeviceNotAdvertisingError(err) {
224
225
  if (!err || typeof err !== "object") return false;
225
226
  return err._tag === ERROR_TAG.DeviceNotAdvertising;
226
227
  }
228
+ function isBleBondInvalidError(err) {
229
+ const pending = [err];
230
+ const seen = /* @__PURE__ */ new Set();
231
+ while (pending.length > 0) {
232
+ const candidate = pending.pop();
233
+ if (candidate && typeof candidate === "object" && !seen.has(candidate)) {
234
+ seen.add(candidate);
235
+ const e = candidate;
236
+ if (e._tag === ERROR_TAG.PeerRemovedPairing || e.iosErrorCode === 14 || e.attErrorCode === 5 || e.nativeErrorDomain === "CBErrorDomain" && e.nativeErrorCode === 14) {
237
+ return true;
238
+ }
239
+ const reason = typeof e.reason === "string" ? e.reason : "";
240
+ const message = typeof e.message === "string" ? e.message : "";
241
+ if (/\bCBErrorDomain:14(?:\s|$)/.test(message) || reason.includes("Peer removed pairing information") || reason.includes("GATT_INSUF_AUTHENTICATION")) {
242
+ return true;
243
+ }
244
+ pending.push(e.originalError, e.err);
245
+ }
246
+ }
247
+ return false;
248
+ }
227
249
  var PAIRING_FAILURE_TAGS = /* @__PURE__ */ new Set([
228
250
  ERROR_TAG.BlePairingTimeout,
229
251
  ERROR_TAG.BleGattBondingFailed,
@@ -242,6 +264,7 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
242
264
  ERROR_TAG.BlePairingTimeout,
243
265
  ERROR_TAG.BleGattBondingFailed,
244
266
  ERROR_TAG.PairingRefused,
267
+ ERROR_TAG.PeerRemovedPairing,
245
268
  ERROR_TAG.DeviceNotRecognized,
246
269
  ERROR_TAG.NoAccessibleDevice,
247
270
  ERROR_TAG.UnknownDevice,
@@ -478,6 +501,8 @@ function mapLedgerError(err, opts) {
478
501
  code = HardwareErrorCode.DeviceLocked;
479
502
  } else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
480
503
  code = HardwareErrorCode.DeviceNotFound;
504
+ } else if (isBleBondInvalidError(err)) {
505
+ code = HardwareErrorCode.BleBondInvalid;
481
506
  } else if (isBlePairingFailureError(err)) {
482
507
  code = HardwareErrorCode.BlePairingTimeout;
483
508
  } else if (isDeviceBusyError(err)) {
@@ -1100,6 +1125,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1100
1125
  this._discoveredDevices.clear();
1101
1126
  this._sessions.clear();
1102
1127
  this._sessionTransports.clear();
1128
+ this._activeConnectionType = void 0;
1103
1129
  this._pendingOperationBindings.clear();
1104
1130
  this._pendingPickBindings.clear();
1105
1131
  this._selectedBleReconnectTargets.clear();
@@ -1232,6 +1258,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1232
1258
  /** Binds the picked BLE device; with a recorded wallet identity it must match first. */
1233
1259
  async bindBleDevice(params) {
1234
1260
  const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
1261
+ const identities = identity ? [identity, ...params.fallbackIdentities ?? []] : [];
1235
1262
  try {
1236
1263
  return await this._jobQueue.enqueue(
1237
1264
  "__ledger_bind_ble__",
@@ -1268,24 +1295,27 @@ var _LedgerAdapter = class _LedgerAdapter {
1268
1295
  message: "Selected Ledger connection ended"
1269
1296
  });
1270
1297
  }
1271
- const fingerprint = await this._computeChainFingerprint(
1272
- identity.chain,
1273
- (method, callParams) => this._runConnectorCall(
1274
- connectId,
1275
- method,
1276
- callParams,
1277
- signal,
1278
- void 0,
1279
- void 0,
1280
- { autoInstallApp: true },
1281
- { connection: { connectId, sessionId } }
1298
+ const checked = await this._fingerprintFirstOpenableChain(
1299
+ identities,
1300
+ (chain, autoInstallApp) => this._computeChainFingerprint(
1301
+ chain,
1302
+ (method, callParams) => this._runConnectorCall(
1303
+ connectId,
1304
+ method,
1305
+ callParams,
1306
+ signal,
1307
+ void 0,
1308
+ void 0,
1309
+ { autoInstallApp },
1310
+ { connection: { connectId, sessionId } }
1311
+ )
1282
1312
  )
1283
1313
  );
1284
- if (fingerprint !== identity.value) {
1314
+ if (checked.fingerprint !== checked.identity.value) {
1285
1315
  await this._dropSession(connectId, signal);
1286
1316
  throw createHwkError({
1287
1317
  code: HardwareErrorCode3.DeviceMismatch,
1288
- message: formatDeviceMismatchError(identity.value, fingerprint)
1318
+ message: formatDeviceMismatchError(checked.identity.value, checked.fingerprint)
1289
1319
  });
1290
1320
  }
1291
1321
  await this._saveSelectedBleBinding(
@@ -1294,7 +1324,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1294
1324
  attempt,
1295
1325
  void 0,
1296
1326
  signal,
1297
- identity
1327
+ checked.identity
1298
1328
  );
1299
1329
  }
1300
1330
  if (!attempt.bindingSaved) {
@@ -2070,6 +2100,24 @@ var _LedgerAdapter = class _LedgerAdapter {
2070
2100
  return this.errorToFailure(err);
2071
2101
  }
2072
2102
  }
2103
+ /**
2104
+ * Fingerprints the first recorded chain whose app the device can open. Only a missing app
2105
+ * moves on to the next chain; when every app is missing, the first chain offers its install.
2106
+ */
2107
+ async _fingerprintFirstOpenableChain(identities, fingerprintOf) {
2108
+ const [first] = identities;
2109
+ if (identities.length > 1) {
2110
+ for (const identity of identities) {
2111
+ try {
2112
+ return { identity, fingerprint: await fingerprintOf(identity.chain, false) };
2113
+ } catch (error) {
2114
+ const isAppMissing = isAppNotInstalledError(error) || error?.code === HardwareErrorCode3.AppNotInstalled;
2115
+ if (!isAppMissing) throw error;
2116
+ }
2117
+ }
2118
+ }
2119
+ return { identity: first, fingerprint: await fingerprintOf(first.chain, true) };
2120
+ }
2073
2121
  /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
2074
2122
  async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
2075
2123
  try {
@@ -2318,7 +2366,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2318
2366
  async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
2319
2367
  if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
2320
2368
  this._assertConnectorReady("connectDevice");
2321
- if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
2369
+ if (!this.connector.availableTransports?.includes("usb") && this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
2322
2370
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
2323
2371
  code: HardwareErrorCode3.DeviceNotFound
2324
2372
  });
@@ -2352,6 +2400,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2352
2400
  if (this._doConnectAbortController === controller) {
2353
2401
  this._connectingPromise = null;
2354
2402
  this._doConnectAbortController = null;
2403
+ if (this._sessions.size === 0) this._activeConnectionType = void 0;
2355
2404
  }
2356
2405
  }
2357
2406
  })();
@@ -2394,19 +2443,16 @@ var _LedgerAdapter = class _LedgerAdapter {
2394
2443
  if (knownBle?.transport === "ble") {
2395
2444
  return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
2396
2445
  }
2397
- if (targetConnectId && context?.knownConnections === void 0) {
2398
- throw createHwkError({
2399
- code: HardwareErrorCode3.DeviceNotFound,
2400
- message: "Ledger connection metadata is required before starting Bluetooth binding"
2401
- });
2402
- }
2446
+ const bleContext = context ?? {};
2447
+ bleContext.allowBleSelection = true;
2448
+ bleContext.usbFallbackConnectId = usbTarget ?? targetConnectId;
2403
2449
  const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
2404
2450
  return this._connectFirstOrSelect(
2405
2451
  bleDevices,
2406
2452
  void 0,
2407
2453
  allowUsbEphemeralFallback,
2408
2454
  preserveOperationId,
2409
- context,
2455
+ bleContext,
2410
2456
  internalSignal
2411
2457
  );
2412
2458
  }
@@ -2495,7 +2541,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2495
2541
  }
2496
2542
  }
2497
2543
  const requiresBleSelection = this._isBleConnection();
2498
- if (requiresBleSelection && !allowUsbEphemeralFallback) {
2544
+ if (requiresBleSelection && !allowUsbEphemeralFallback && !context?.allowBleSelection) {
2499
2545
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
2500
2546
  code: HardwareErrorCode3.DeviceNotFound
2501
2547
  });
@@ -2507,7 +2553,8 @@ var _LedgerAdapter = class _LedgerAdapter {
2507
2553
  const knownUsb = context?.knownConnections?.find(
2508
2554
  (connection) => connection.transport === "usb"
2509
2555
  );
2510
- const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
2556
+ const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : context?.usbFallbackConnectId ?? targetConnectId;
2557
+ const maySelectAnyUsb = allowUsbEphemeralFallback || !usbConnectId && !context?.knownConnections?.some((connection) => connection.transport !== "qr");
2511
2558
  const { device, requestId } = await requestBleDeviceSelection({
2512
2559
  emitter: this.emitter,
2513
2560
  registry: this._uiRegistry,
@@ -2518,7 +2565,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2518
2565
  const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
2519
2566
  const candidate = usbDevices.find(
2520
2567
  (device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
2521
- ) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2568
+ ) ?? (maySelectAnyUsb && usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2522
2569
  if (candidate) return [candidate];
2523
2570
  }
2524
2571
  return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
@@ -3264,6 +3311,7 @@ var LedgerAdapter = _LedgerAdapter;
3264
3311
  import {
3265
3312
  EConnectorInteraction as EConnectorInteraction3,
3266
3313
  HardwareErrorCode as HardwareErrorCode7,
3314
+ createHwkError as createHwkError2,
3267
3315
  isKnownNonTargetHardwareVendor,
3268
3316
  serializeConnectorError
3269
3317
  } from "@onekeyfe/hwk-adapter-core";
@@ -3545,11 +3593,14 @@ import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
3545
3593
  import { DeviceActionStatus } from "@ledgerhq/device-management-kit";
3546
3594
  var IDLE_WATCHDOG_MS = 65e3;
3547
3595
  var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
3596
+ var INTERACTION_PROMPT_DELAY_MS = 500;
3548
3597
  function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
3549
3598
  return new Promise((resolve, reject) => {
3550
3599
  let settled = false;
3551
3600
  let lastStep;
3552
3601
  let activeInteraction;
3602
+ let pendingInteraction;
3603
+ let pendingInteractionTimer = null;
3553
3604
  const observedSteps = [];
3554
3605
  let sub;
3555
3606
  let timer = null;
@@ -3577,31 +3628,52 @@ function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_
3577
3628
  }
3578
3629
  return false;
3579
3630
  };
3631
+ const cancelPendingInteraction = () => {
3632
+ if (pendingInteractionTimer) clearTimeout(pendingInteractionTimer);
3633
+ pendingInteractionTimer = null;
3634
+ pendingInteraction = void 0;
3635
+ };
3636
+ const showInteraction = (interactionName) => {
3637
+ activeInteraction = interactionName;
3638
+ debugLog(
3639
+ "[DeviceAction] requiredUserInteraction",
3640
+ `interaction=${interactionName}`,
3641
+ `step=${lastStep ?? "unknown"}`
3642
+ );
3643
+ if (interactionName === "unlock-device" && timer) {
3644
+ clearTimeout(timer);
3645
+ timer = null;
3646
+ }
3647
+ onInteraction?.(interactionName);
3648
+ };
3580
3649
  const emitInteraction = (interaction) => {
3581
3650
  if (!onInteraction) {
3582
3651
  return;
3583
3652
  }
3584
3653
  if (!interaction || interaction === "none") {
3654
+ cancelPendingInteraction();
3585
3655
  clearActiveInteraction();
3586
3656
  return;
3587
3657
  }
3588
3658
  const interactionName = String(interaction);
3589
- if (interactionName === activeInteraction) {
3659
+ if (interactionName === activeInteraction || interactionName === pendingInteraction) {
3590
3660
  return;
3591
3661
  }
3592
- activeInteraction = interactionName;
3593
- debugLog(
3594
- "[DeviceAction] requiredUserInteraction",
3595
- `interaction=${interactionName}`,
3596
- `step=${lastStep ?? "unknown"}`
3597
- );
3598
- if (interaction === "unlock-device" && timer) {
3599
- clearTimeout(timer);
3600
- timer = null;
3662
+ cancelPendingInteraction();
3663
+ clearActiveInteraction();
3664
+ if (interactionName === "unlock-device") {
3665
+ showInteraction(interactionName);
3666
+ return;
3601
3667
  }
3602
- onInteraction(interactionName);
3668
+ pendingInteraction = interactionName;
3669
+ pendingInteractionTimer = setTimeout(() => {
3670
+ pendingInteractionTimer = null;
3671
+ pendingInteraction = void 0;
3672
+ if (!settled) showInteraction(interactionName);
3673
+ }, INTERACTION_PROMPT_DELAY_MS);
3603
3674
  };
3604
3675
  const completeInteraction = () => {
3676
+ cancelPendingInteraction();
3605
3677
  if (!clearActiveInteraction()) {
3606
3678
  onInteraction?.("interaction-complete");
3607
3679
  }
@@ -5179,6 +5251,13 @@ var LedgerConnectorBase = class {
5179
5251
  } catch (err) {
5180
5252
  this._resetSignersAndSessions();
5181
5253
  if (isLedgerBleConnectionType(this.connectionType)) {
5254
+ if (isBleBondInvalidError(err)) {
5255
+ throw createHwkError2({
5256
+ code: HardwareErrorCode7.BleBondInvalid,
5257
+ message: "Ledger Bluetooth pairing is no longer valid. Forget this device in system Bluetooth settings, then reconnect.",
5258
+ _tag: ERROR_TAG.PeerRemovedPairing
5259
+ });
5260
+ }
5182
5261
  const tag = err?._tag;
5183
5262
  if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
5184
5263
  throw err;