@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.13 → 1.2.8-alpha.130

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)) {
@@ -589,6 +614,32 @@ function debugError(...args) {
589
614
  emitLog("error", ...args);
590
615
  }
591
616
 
617
+ // src/utils/logSummary.ts
618
+ import { summarizeForLog as summarizeForLogCore } from "@onekeyfe/hwk-adapter-core";
619
+ import { Psbt, Transaction } from "bitcoinjs-lib";
620
+ var HEX_RE = /^(0x)?[0-9a-fA-F]+$/;
621
+ var BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
622
+ function parsePsbt(input) {
623
+ if (typeof input !== "string") return Psbt.fromBuffer(input);
624
+ if (HEX_RE.test(input)) return Psbt.fromHex(input.replace(/^0x/i, ""));
625
+ if (BASE64_RE.test(input)) return Psbt.fromBase64(input);
626
+ return void 0;
627
+ }
628
+ var describePsbtForLog = (key, value) => {
629
+ if (key !== "psbt") return void 0;
630
+ try {
631
+ const psbt = parsePsbt(value);
632
+ if (!psbt) return void 0;
633
+ const unsignedTx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());
634
+ return `inputs=${psbt.inputCount} outputs=${psbt.txOutputs.length} txid=${unsignedTx.getId()}`;
635
+ } catch {
636
+ return void 0;
637
+ }
638
+ };
639
+ function summarizeForLog(value, options = {}) {
640
+ return summarizeForLogCore(value, { ...options, describePayload: describePsbtForLog });
641
+ }
642
+
592
643
  // src/adapter/methods/allNetworkGetAddress.ts
593
644
  var LEDGER_BTC_NETWORK_COIN_MAP = {
594
645
  tbtc: "Testnet",
@@ -690,7 +741,7 @@ function createAllNetworkGetAddress({
690
741
  debugLog("[LedgerAdapter][RES]", {
691
742
  method: "allNetworkGetAddress",
692
743
  success: result.success,
693
- payload: result
744
+ payload: summarizeForLog(result, { method: "allNetworkGetAddress", role: "result" })
694
745
  });
695
746
  return result;
696
747
  } finally {
@@ -861,21 +912,16 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
861
912
  function formatDeviceMismatchError(expected, actual) {
862
913
  return `Wrong device: expected ${expected}, got ${actual}`;
863
914
  }
864
- var LOG_REDACTED_RESULT_KEYS = ["ufvk", "orchardFvk"];
865
- function isSigningMethod(method) {
866
- return /sign/i.test(method);
867
- }
868
- function redactResultForLog(result, method) {
869
- if (isSigningMethod(method)) return "[redacted]";
870
- if (!result || typeof result !== "object") return result;
871
- const keys = LOG_REDACTED_RESULT_KEYS.filter((key) => key in result);
872
- if (!keys.length) return result;
873
- return { ...result, ...Object.fromEntries(keys.map((key) => [key, "[redacted]"])) };
874
- }
875
915
  function isLostConnectionError(err) {
876
916
  return isDeviceDisconnectedError(err) || isDeviceNotAdvertisingError(err) || isTimeoutError(err) || isConnectionLevelError(err);
877
917
  }
878
918
  var BTC_HIGH_INDEX_THRESHOLD = 100;
919
+ var APP_MANAGEMENT_METHODS = /* @__PURE__ */ new Set([
920
+ "installApp",
921
+ "listInstalledApps",
922
+ "listInstalledNames",
923
+ "listAvailableApps"
924
+ ]);
879
925
  function btcAccountIndexFromPath(path) {
880
926
  const segments = path.replace(/^m\//, "").split("/");
881
927
  if (segments.length < 3) return null;
@@ -899,7 +945,7 @@ var _LedgerAdapter = class _LedgerAdapter {
899
945
  type: SDK.OPERATION_ENDED,
900
946
  payload: { operationId: operation.operationId, reason }
901
947
  });
902
- if (reason === "timeout") {
948
+ if (reason === "timeout" && !this._bareCallMayUseConnection(operation)) {
903
949
  void this._releaseOperationConnection(operation);
904
950
  }
905
951
  }
@@ -990,6 +1036,7 @@ var _LedgerAdapter = class _LedgerAdapter {
990
1036
  // need to subscribe in one place. The AppInstallProgress variant re-keys
991
1037
  // sessionId to connectId via `_sessions`, and drops if no mapping exists.
992
1038
  this.uiEventForwarder = (event) => {
1039
+ const operationId = this._activeOperationId();
993
1040
  if (event.type === EConnectorInteraction.AppInstallProgress) {
994
1041
  let connectId;
995
1042
  for (const [cid, sid] of this._sessions) {
@@ -1018,6 +1065,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1018
1065
  this._installProgressLastEmittedValue = progress;
1019
1066
  this.emitter.emit("ui-event", {
1020
1067
  type: EConnectorInteraction.AppInstallProgress,
1068
+ ...operationId ? { operationId } : {},
1021
1069
  payload: {
1022
1070
  connectId,
1023
1071
  appName,
@@ -1026,7 +1074,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1026
1074
  });
1027
1075
  return;
1028
1076
  }
1029
- this.emitter.emit("ui-event", event);
1077
+ this.emitter.emit("ui-event", operationId ? { ...event, operationId } : event);
1030
1078
  };
1031
1079
  this.connector = connector;
1032
1080
  this._defaultAutoInstallApp = options?.autoInstallApp ?? false;
@@ -1085,6 +1133,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1085
1133
  this._discoveredDevices.clear();
1086
1134
  this._sessions.clear();
1087
1135
  this._sessionTransports.clear();
1136
+ this._activeConnectionType = void 0;
1088
1137
  this._pendingOperationBindings.clear();
1089
1138
  this._pendingPickBindings.clear();
1090
1139
  this._selectedBleReconnectTargets.clear();
@@ -1217,6 +1266,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1217
1266
  /** Binds the picked BLE device; with a recorded wallet identity it must match first. */
1218
1267
  async bindBleDevice(params) {
1219
1268
  const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
1269
+ const identities = identity ? [identity, ...params.fallbackIdentities ?? []] : [];
1220
1270
  try {
1221
1271
  return await this._jobQueue.enqueue(
1222
1272
  "__ledger_bind_ble__",
@@ -1253,24 +1303,27 @@ var _LedgerAdapter = class _LedgerAdapter {
1253
1303
  message: "Selected Ledger connection ended"
1254
1304
  });
1255
1305
  }
1256
- const fingerprint = await this._computeChainFingerprint(
1257
- identity.chain,
1258
- (method, callParams) => this._runConnectorCall(
1259
- connectId,
1260
- method,
1261
- callParams,
1262
- signal,
1263
- void 0,
1264
- void 0,
1265
- { autoInstallApp: true },
1266
- { connection: { connectId, sessionId } }
1306
+ const checked = await this._fingerprintFirstOpenableChain(
1307
+ identities,
1308
+ (chain, autoInstallApp) => this._computeChainFingerprint(
1309
+ chain,
1310
+ (method, callParams) => this._runConnectorCall(
1311
+ connectId,
1312
+ method,
1313
+ callParams,
1314
+ signal,
1315
+ void 0,
1316
+ void 0,
1317
+ { autoInstallApp },
1318
+ { connection: { connectId, sessionId } }
1319
+ )
1267
1320
  )
1268
1321
  );
1269
- if (fingerprint !== identity.value) {
1322
+ if (checked.fingerprint !== checked.identity.value) {
1270
1323
  await this._dropSession(connectId, signal);
1271
1324
  throw createHwkError({
1272
1325
  code: HardwareErrorCode3.DeviceMismatch,
1273
- message: formatDeviceMismatchError(identity.value, fingerprint)
1326
+ message: formatDeviceMismatchError(checked.identity.value, checked.fingerprint)
1274
1327
  });
1275
1328
  }
1276
1329
  await this._saveSelectedBleBinding(
@@ -1279,7 +1332,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1279
1332
  attempt,
1280
1333
  void 0,
1281
1334
  signal,
1282
- identity
1335
+ checked.identity
1283
1336
  );
1284
1337
  }
1285
1338
  if (!attempt.bindingSaved) {
@@ -1443,7 +1496,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1443
1496
  const operation = this._operations.findActive(operationId);
1444
1497
  if (operation) this._cancelOperationWork(operation);
1445
1498
  const endedOperation = this._operations.release(operationId);
1446
- if (!endedOperation) return;
1499
+ if (!endedOperation || this._bareCallMayUseConnection(endedOperation)) return;
1447
1500
  const { connectId } = endedOperation;
1448
1501
  debugLog("[LedgerAdapter][REQ]", {
1449
1502
  method: "releaseOperation",
@@ -1477,7 +1530,18 @@ var _LedgerAdapter = class _LedgerAdapter {
1477
1530
  const queueKey = ledgerQueueKey({ operationId });
1478
1531
  const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
1479
1532
  this._jobQueue.cancelActiveAndPending(queueKey, reason);
1480
- if (ownsRunningCall) this._uiRegistry.cancel(void 0, void 0, operationId);
1533
+ if (!ownsRunningCall) return;
1534
+ this._uiRegistry.cancel(void 0, void 0, operationId);
1535
+ void this.connector.cancel(this._sessions.get(operation.connectId) ?? operation.connectId);
1536
+ }
1537
+ /**
1538
+ * A running call by bare connectId (or still resolving its device by identity) may be on this
1539
+ * connection, e.g. waiting for an unlock; its later stages need it, so it stays cached for that
1540
+ * caller like any bare call's session. A lost connection is torn down regardless.
1541
+ */
1542
+ _bareCallMayUseConnection(operation) {
1543
+ const activeKey = this._jobQueue.getActiveJob()?.deviceId;
1544
+ return activeKey !== void 0 && !isHardwareOperationId(activeKey) && (activeKey === operation.connectId || activeKey === LEDGER_DEFAULT_QUEUE_KEY || operation.connectionKeys.includes(activeKey));
1481
1545
  }
1482
1546
  async _releaseOperationConnection(operation) {
1483
1547
  const sessionIds = /* @__PURE__ */ new Set();
@@ -1772,7 +1836,13 @@ var _LedgerAdapter = class _LedgerAdapter {
1772
1836
  params
1773
1837
  );
1774
1838
  }
1775
- tronSignMessage(connectId, deviceId, params) {
1839
+ async tronSignMessage(connectId, deviceId, params) {
1840
+ if (params?.messageType !== "V2") {
1841
+ return failure2(
1842
+ HardwareErrorCode3.MethodNotSupported,
1843
+ 'Ledger signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1844
+ );
1845
+ }
1776
1846
  return this.callChainWithMergedParams(
1777
1847
  connectId,
1778
1848
  deviceId,
@@ -1994,17 +2064,27 @@ var _LedgerAdapter = class _LedgerAdapter {
1994
2064
  } else {
1995
2065
  this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
1996
2066
  }
1997
- if (resolvedConnectId) {
1998
- const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
1999
- void this.connector.cancel(sessionId);
2000
- } else {
2001
- for (const sid of this._sessions.values()) void this.connector.cancel(sid);
2067
+ const connectingConnectId = this._connectingConnectId;
2068
+ const targetKeys = new Set(
2069
+ [
2070
+ connectId,
2071
+ resolvedConnectId,
2072
+ ...pendingOperationId ? this._operations.find(pendingOperationId)?.connectionKeys ?? [] : []
2073
+ ].filter(Boolean)
2074
+ );
2075
+ const ownsPendingConnect = !connectId || activeJobId !== void 0 && queueKeys.has(activeJobId) || connectingConnectId !== void 0 && targetKeys.has(connectingConnectId);
2076
+ if (activeJobId === void 0 || ownsPendingConnect) {
2077
+ if (resolvedConnectId) {
2078
+ const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
2079
+ void this.connector.cancel(sessionId);
2080
+ } else {
2081
+ for (const sid of this._sessions.values()) void this.connector.cancel(sid);
2082
+ }
2002
2083
  }
2003
- if (this._connectingPromise) {
2084
+ if (this._connectingPromise && ownsPendingConnect) {
2004
2085
  this._doConnectAbortController?.abort(userAbortReason);
2005
2086
  }
2006
- const connectingConnectId = this._connectingConnectId;
2007
- if (connectingConnectId) void this.connector.cancel(connectingConnectId);
2087
+ if (connectingConnectId && ownsPendingConnect) void this.connector.cancel(connectingConnectId);
2008
2088
  }
2009
2089
  // ---------------------------------------------------------------------------
2010
2090
  // Chain fingerprint
@@ -2030,6 +2110,24 @@ var _LedgerAdapter = class _LedgerAdapter {
2030
2110
  return this.errorToFailure(err);
2031
2111
  }
2032
2112
  }
2113
+ /**
2114
+ * Fingerprints the first recorded chain whose app the device can open. Only a missing app
2115
+ * moves on to the next chain; when every app is missing, the first chain offers its install.
2116
+ */
2117
+ async _fingerprintFirstOpenableChain(identities, fingerprintOf) {
2118
+ const [first] = identities;
2119
+ if (identities.length > 1) {
2120
+ for (const identity of identities) {
2121
+ try {
2122
+ return { identity, fingerprint: await fingerprintOf(identity.chain, false) };
2123
+ } catch (error) {
2124
+ const isAppMissing = isAppNotInstalledError(error) || error?.code === HardwareErrorCode3.AppNotInstalled;
2125
+ if (!isAppMissing) throw error;
2126
+ }
2127
+ }
2128
+ }
2129
+ return { identity: first, fingerprint: await fingerprintOf(first.chain, true) };
2130
+ }
2033
2131
  /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
2034
2132
  async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
2035
2133
  try {
@@ -2165,7 +2263,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2165
2263
  } catch (err) {
2166
2264
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
2167
2265
  type: UI_REQUEST.CLOSE_UI_WINDOW,
2168
- payload: {}
2266
+ payload: { operationId }
2169
2267
  });
2170
2268
  throw Object.assign(new Error("User cancelled Ledger connection"), {
2171
2269
  _tag: ERROR_TAG.UserAborted,
@@ -2229,7 +2327,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2229
2327
  } catch (err) {
2230
2328
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
2231
2329
  type: UI_REQUEST.CLOSE_UI_WINDOW,
2232
- payload: {}
2330
+ payload: { operationId }
2233
2331
  });
2234
2332
  return false;
2235
2333
  }
@@ -2267,7 +2365,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2267
2365
  } catch (err) {
2268
2366
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
2269
2367
  type: UI_REQUEST.CLOSE_UI_WINDOW,
2270
- payload: {}
2368
+ payload: { operationId }
2271
2369
  });
2272
2370
  return false;
2273
2371
  }
@@ -2278,7 +2376,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2278
2376
  async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
2279
2377
  if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
2280
2378
  this._assertConnectorReady("connectDevice");
2281
- if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
2379
+ if (!this.connector.availableTransports?.includes("usb") && this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
2282
2380
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
2283
2381
  code: HardwareErrorCode3.DeviceNotFound
2284
2382
  });
@@ -2312,6 +2410,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2312
2410
  if (this._doConnectAbortController === controller) {
2313
2411
  this._connectingPromise = null;
2314
2412
  this._doConnectAbortController = null;
2413
+ if (this._sessions.size === 0) this._activeConnectionType = void 0;
2315
2414
  }
2316
2415
  }
2317
2416
  })();
@@ -2331,7 +2430,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2331
2430
  (connection) => connection.transport === "usb"
2332
2431
  );
2333
2432
  const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
2334
- if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
2433
+ if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback || context?.takesPluggedUsb)) {
2335
2434
  return this._connectFirstOrSelect(
2336
2435
  usbDevices,
2337
2436
  usbTarget,
@@ -2354,19 +2453,16 @@ var _LedgerAdapter = class _LedgerAdapter {
2354
2453
  if (knownBle?.transport === "ble") {
2355
2454
  return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
2356
2455
  }
2357
- if (targetConnectId && context?.knownConnections === void 0) {
2358
- throw createHwkError({
2359
- code: HardwareErrorCode3.DeviceNotFound,
2360
- message: "Ledger connection metadata is required before starting Bluetooth binding"
2361
- });
2362
- }
2456
+ const bleContext = context ?? {};
2457
+ bleContext.allowBleSelection = true;
2458
+ bleContext.usbFallbackConnectId = usbTarget ?? targetConnectId;
2363
2459
  const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
2364
2460
  return this._connectFirstOrSelect(
2365
2461
  bleDevices,
2366
2462
  void 0,
2367
2463
  allowUsbEphemeralFallback,
2368
2464
  preserveOperationId,
2369
- context,
2465
+ bleContext,
2370
2466
  internalSignal
2371
2467
  );
2372
2468
  }
@@ -2455,7 +2551,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2455
2551
  }
2456
2552
  }
2457
2553
  const requiresBleSelection = this._isBleConnection();
2458
- if (requiresBleSelection && !allowUsbEphemeralFallback) {
2554
+ if (requiresBleSelection && !allowUsbEphemeralFallback && !context?.allowBleSelection) {
2459
2555
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
2460
2556
  code: HardwareErrorCode3.DeviceNotFound
2461
2557
  });
@@ -2467,7 +2563,8 @@ var _LedgerAdapter = class _LedgerAdapter {
2467
2563
  const knownUsb = context?.knownConnections?.find(
2468
2564
  (connection) => connection.transport === "usb"
2469
2565
  );
2470
- const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
2566
+ const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : context?.usbFallbackConnectId ?? targetConnectId;
2567
+ const maySelectAnyUsb = allowUsbEphemeralFallback || !usbConnectId && !context?.knownConnections?.some((connection) => connection.transport !== "qr");
2471
2568
  const { device, requestId } = await requestBleDeviceSelection({
2472
2569
  emitter: this.emitter,
2473
2570
  registry: this._uiRegistry,
@@ -2478,7 +2575,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2478
2575
  const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
2479
2576
  const candidate = usbDevices.find(
2480
2577
  (device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
2481
- ) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2578
+ ) ?? (maySelectAnyUsb && usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2482
2579
  if (candidate) return [candidate];
2483
2580
  }
2484
2581
  return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
@@ -2686,7 +2783,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2686
2783
  debugLog("[LedgerAdapter][REQ]", {
2687
2784
  method,
2688
2785
  connectId: effectiveConnectId || "(empty)",
2689
- params: isSigningMethod(method) ? "[redacted]" : params
2786
+ params: summarizeForLog(params, { method })
2690
2787
  });
2691
2788
  const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
2692
2789
  try {
@@ -2739,7 +2836,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2739
2836
  debugLog("[LedgerAdapter][RES]", {
2740
2837
  method,
2741
2838
  success: true,
2742
- payload: redactResultForLog(result, method)
2839
+ payload: summarizeForLog(result, { method, role: "result" })
2743
2840
  });
2744
2841
  return result;
2745
2842
  } catch (err) {
@@ -2798,7 +2895,8 @@ var _LedgerAdapter = class _LedgerAdapter {
2798
2895
  /** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
2799
2896
  async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
2800
2897
  _LedgerAdapter._throwIfAborted(signal);
2801
- if (!operationId) {
2898
+ const resolvesAppManagementTransport = APP_MANAGEMENT_METHODS.has(method) && this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble");
2899
+ if (!operationId && !resolvesAppManagementTransport) {
2802
2900
  await this._ensureDevicePermission(
2803
2901
  connectId,
2804
2902
  permissionDeviceId ?? fingerprint?.deviceId,
@@ -2831,7 +2929,8 @@ var _LedgerAdapter = class _LedgerAdapter {
2831
2929
  );
2832
2930
  const connectionAttempt = {
2833
2931
  ...commonParams,
2834
- deferBindingSave: checksWallet
2932
+ deferBindingSave: checksWallet,
2933
+ ...APP_MANAGEMENT_METHODS.has(method) ? { takesPluggedUsb: true } : {}
2835
2934
  };
2836
2935
  const bundleConnection = installContext?.connection;
2837
2936
  if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
@@ -2871,6 +2970,16 @@ var _LedgerAdapter = class _LedgerAdapter {
2871
2970
  _tag: ERROR_TAG.DeviceSessionNotFound
2872
2971
  });
2873
2972
  }
2973
+ if (!operationId && resolvesAppManagementTransport) {
2974
+ const transport = this._sessionTransports.get(sessionId);
2975
+ await this._ensureDevicePermission(
2976
+ resolvedConnectId,
2977
+ permissionDeviceId ?? fingerprint?.deviceId,
2978
+ signal,
2979
+ transport && (isLedgerBleConnectionType(transport) ? "ble" : "hid")
2980
+ );
2981
+ _LedgerAdapter._throwIfAborted(signal);
2982
+ }
2874
2983
  try {
2875
2984
  const isBleSession = this._sessionTransports.get(sessionId) === "ble";
2876
2985
  if (!operationId && connectionAttempt.pendingBinding) {
@@ -3064,7 +3173,7 @@ var _LedgerAdapter = class _LedgerAdapter {
3064
3173
  }
3065
3174
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
3066
3175
  type: UI_REQUEST.CLOSE_UI_WINDOW,
3067
- payload: {}
3176
+ payload: { operationId }
3068
3177
  });
3069
3178
  return await this._runConnectorCall(
3070
3179
  resolvedConnectId,
@@ -3103,11 +3212,11 @@ var _LedgerAdapter = class _LedgerAdapter {
3103
3212
  * Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
3104
3213
  * replies. Without connectId the request is environment-level, else device-level.
3105
3214
  */
3106
- async _ensureDevicePermission(connectId, deviceId, signal) {
3215
+ async _ensureDevicePermission(connectId, deviceId, signal, transportOverride) {
3107
3216
  if (signal?.aborted) {
3108
3217
  _LedgerAdapter._throwIfAborted(signal);
3109
3218
  }
3110
- const transportType = this.activeTransport ?? "hid";
3219
+ const transportType = transportOverride ?? this.activeTransport ?? "hid";
3111
3220
  const operationId = this._activeOperationId();
3112
3221
  const waitPromise = this._uiRegistry.wait(
3113
3222
  UI_REQUEST.REQUEST_DEVICE_PERMISSION,
@@ -3131,7 +3240,7 @@ var _LedgerAdapter = class _LedgerAdapter {
3131
3240
  if (err?._tag === UI_REQUEST_PREEMPTED_TAG) {
3132
3241
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
3133
3242
  type: UI_REQUEST.CLOSE_UI_WINDOW,
3134
- payload: {}
3243
+ payload: { operationId }
3135
3244
  });
3136
3245
  throw Object.assign(new Error("Device permission request superseded"), {
3137
3246
  _tag: ERROR_TAG.UserAborted,
@@ -3224,6 +3333,7 @@ var LedgerAdapter = _LedgerAdapter;
3224
3333
  import {
3225
3334
  EConnectorInteraction as EConnectorInteraction3,
3226
3335
  HardwareErrorCode as HardwareErrorCode7,
3336
+ createHwkError as createHwkError2,
3227
3337
  isKnownNonTargetHardwareVendor,
3228
3338
  serializeConnectorError
3229
3339
  } from "@onekeyfe/hwk-adapter-core";
@@ -3505,11 +3615,14 @@ import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
3505
3615
  import { DeviceActionStatus } from "@ledgerhq/device-management-kit";
3506
3616
  var IDLE_WATCHDOG_MS = 65e3;
3507
3617
  var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
3618
+ var INTERACTION_PROMPT_DELAY_MS = 500;
3508
3619
  function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
3509
3620
  return new Promise((resolve, reject) => {
3510
3621
  let settled = false;
3511
3622
  let lastStep;
3512
3623
  let activeInteraction;
3624
+ let pendingInteraction;
3625
+ let pendingInteractionTimer = null;
3513
3626
  const observedSteps = [];
3514
3627
  let sub;
3515
3628
  let timer = null;
@@ -3537,31 +3650,52 @@ function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_
3537
3650
  }
3538
3651
  return false;
3539
3652
  };
3653
+ const cancelPendingInteraction = () => {
3654
+ if (pendingInteractionTimer) clearTimeout(pendingInteractionTimer);
3655
+ pendingInteractionTimer = null;
3656
+ pendingInteraction = void 0;
3657
+ };
3658
+ const showInteraction = (interactionName) => {
3659
+ activeInteraction = interactionName;
3660
+ debugLog(
3661
+ "[DeviceAction] requiredUserInteraction",
3662
+ `interaction=${interactionName}`,
3663
+ `step=${lastStep ?? "unknown"}`
3664
+ );
3665
+ if (interactionName === "unlock-device" && timer) {
3666
+ clearTimeout(timer);
3667
+ timer = null;
3668
+ }
3669
+ onInteraction?.(interactionName);
3670
+ };
3540
3671
  const emitInteraction = (interaction) => {
3541
3672
  if (!onInteraction) {
3542
3673
  return;
3543
3674
  }
3544
3675
  if (!interaction || interaction === "none") {
3676
+ cancelPendingInteraction();
3545
3677
  clearActiveInteraction();
3546
3678
  return;
3547
3679
  }
3548
3680
  const interactionName = String(interaction);
3549
- if (interactionName === activeInteraction) {
3681
+ if (interactionName === activeInteraction || interactionName === pendingInteraction) {
3550
3682
  return;
3551
3683
  }
3552
- activeInteraction = interactionName;
3553
- debugLog(
3554
- "[DeviceAction] requiredUserInteraction",
3555
- `interaction=${interactionName}`,
3556
- `step=${lastStep ?? "unknown"}`
3557
- );
3558
- if (interaction === "unlock-device" && timer) {
3559
- clearTimeout(timer);
3560
- timer = null;
3684
+ cancelPendingInteraction();
3685
+ clearActiveInteraction();
3686
+ if (interactionName === "unlock-device") {
3687
+ showInteraction(interactionName);
3688
+ return;
3561
3689
  }
3562
- onInteraction(interactionName);
3690
+ pendingInteraction = interactionName;
3691
+ pendingInteractionTimer = setTimeout(() => {
3692
+ pendingInteractionTimer = null;
3693
+ pendingInteraction = void 0;
3694
+ if (!settled) showInteraction(interactionName);
3695
+ }, INTERACTION_PROMPT_DELAY_MS);
3563
3696
  };
3564
3697
  const completeInteraction = () => {
3698
+ cancelPendingInteraction();
3565
3699
  if (!clearActiveInteraction()) {
3566
3700
  onInteraction?.("interaction-complete");
3567
3701
  }
@@ -3921,7 +4055,7 @@ async function _getEthSigner(ctx, sessionId) {
3921
4055
 
3922
4056
  // src/connector/chains/btc.ts
3923
4057
  import { HardwareErrorCode as HardwareErrorCode5, stripHex as stripHex2 } from "@onekeyfe/hwk-adapter-core";
3924
- import { Psbt } from "bitcoinjs-lib";
4058
+ import { Psbt as Psbt2 } from "bitcoinjs-lib";
3925
4059
 
3926
4060
  // src/signer/SignerBtc.ts
3927
4061
  import { hexToBytes as hexToBytes2 } from "@onekeyfe/hwk-adapter-core";
@@ -3966,7 +4100,7 @@ var SignerBtc = class {
3966
4100
  "[SignerBtc] getExtendedPublicKey result type:",
3967
4101
  typeof result,
3968
4102
  "value:",
3969
- typeof result === "string" ? `${result.substring(0, 20)}...` : JSON.stringify(result).substring(0, 50)
4103
+ summarizeForLog(result)
3970
4104
  );
3971
4105
  if (typeof result === "string") return result;
3972
4106
  return result.extendedPublicKey;
@@ -4097,7 +4231,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
4097
4231
  const xpub = await btcSigner.getExtendedPublicKey(path, {
4098
4232
  checkOnDevice: params.showOnDevice ?? false
4099
4233
  });
4100
- debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", `${xpub?.substring(0, 20)}...`);
4234
+ debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
4101
4235
  return { xpub, path: params.path };
4102
4236
  } catch (err) {
4103
4237
  debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
@@ -4218,7 +4352,7 @@ function _isScriptPathInput(input) {
4218
4352
  return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
4219
4353
  }
4220
4354
  function _applySignaturesToPsbt(psbtHex, signatures) {
4221
- const psbt = Psbt.fromHex(psbtHex);
4355
+ const psbt = Psbt2.fromHex(psbtHex);
4222
4356
  for (const sig of signatures) {
4223
4357
  const input = psbt.data.inputs[sig.inputIndex];
4224
4358
  if (!input) {
@@ -4849,6 +4983,14 @@ var METHOD_PREFIX_TO_APP_NAME = {
4849
4983
  tron: "Tron",
4850
4984
  zcash: "Zcash"
4851
4985
  };
4986
+ function withOpenAppName(event, data, appName) {
4987
+ if (event !== "ui-event") return data;
4988
+ const uiEvent = data;
4989
+ if (uiEvent.type !== EConnectorInteraction3.ConfirmOpenApp || uiEvent.payload.appName) {
4990
+ return data;
4991
+ }
4992
+ return { ...uiEvent, payload: { ...uiEvent.payload, appName } };
4993
+ }
4852
4994
  var HARDWARE_ERROR_CODE_VALUES = new Set(
4853
4995
  Object.values(HardwareErrorCode7).filter((value) => typeof value === "number")
4854
4996
  );
@@ -5139,6 +5281,13 @@ var LedgerConnectorBase = class {
5139
5281
  } catch (err) {
5140
5282
  this._resetSignersAndSessions();
5141
5283
  if (isLedgerBleConnectionType(this.connectionType)) {
5284
+ if (isBleBondInvalidError(err)) {
5285
+ throw createHwkError2({
5286
+ code: HardwareErrorCode7.BleBondInvalid,
5287
+ message: "Ledger Bluetooth pairing is no longer valid. Forget this device in system Bluetooth settings, then reconnect.",
5288
+ _tag: ERROR_TAG.PeerRemovedPairing
5289
+ });
5290
+ }
5142
5291
  const tag = err?._tag;
5143
5292
  if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
5144
5293
  throw err;
@@ -5241,7 +5390,7 @@ var LedgerConnectorBase = class {
5241
5390
  // whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
5242
5391
  // locally (see LedgerAdapter._unwrapConnectorResult).
5243
5392
  async call(sessionId, method, params) {
5244
- debugLog("[DMK] call:", method, JSON.stringify(params));
5393
+ debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
5245
5394
  try {
5246
5395
  const payload = await this._dispatch(sessionId, method, params);
5247
5396
  return { success: true, payload };
@@ -5650,8 +5799,8 @@ var LedgerConnectorBase = class {
5650
5799
  // ---------------------------------------------------------------------------
5651
5800
  /**
5652
5801
  * Return a per-call ctx with the chain's Ledger app name pre-bound to
5653
- * wrapError, so chain handlers don't need to repeat `{ defaultAppName: 'X' }`
5654
- * at every catch site. Falls through unchanged for unknown methods.
5802
+ * UI prompts and wrapError, so chain handlers don't need to repeat the name.
5803
+ * Falls through unchanged for unknown methods.
5655
5804
  */
5656
5805
  _ctxForMethod(method) {
5657
5806
  const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
@@ -5659,7 +5808,8 @@ var LedgerConnectorBase = class {
5659
5808
  if (!defaultAppName) return this._ctx;
5660
5809
  return {
5661
5810
  ...this._ctx,
5662
- wrapError: (err, opts) => this._wrapError(err, { defaultAppName, ...opts })
5811
+ wrapError: (err, opts) => this._wrapError(err, { defaultAppName, ...opts }),
5812
+ emit: (event, data) => this._ctx.emit(event, withOpenAppName(event, data, defaultAppName))
5663
5813
  };
5664
5814
  }
5665
5815
  _wrapError(err, opts) {