@onekeyfe/hwk-trezor-adapter 1.2.8-alpha.4 → 1.2.8-alpha.50

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.js CHANGED
@@ -9,6 +9,25 @@
9
9
 
10
10
 
11
11
 
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
12
31
 
13
32
 
14
33
  var _hwkadaptercore = require('@onekeyfe/hwk-adapter-core');
@@ -762,10 +781,34 @@ function debugLog(...args) {
762
781
  emitLog("debug", ...args);
763
782
  }
764
783
 
784
+ // src/utils/queueKey.ts
785
+ function trezorQueueKey({
786
+ operationId,
787
+ connectId
788
+ }) {
789
+ return operationId || connectId || "";
790
+ }
791
+
765
792
  // src/adapter/TrezorAdapter.ts
766
793
  var KNOWN_HARDWARE_ERROR_CODES = new Set(
767
794
  Object.values(_hwkadaptercore.HardwareErrorCode).filter((value) => typeof value === "number")
768
795
  );
796
+ var ALL_NETWORK_COMMON_PARAM_KEYS = [
797
+ "autoInstallApp",
798
+ "passphraseState",
799
+ "useEmptyPassphrase",
800
+ "operationId",
801
+ "knownConnections",
802
+ "extra",
803
+ "allowDeviceSelection",
804
+ "supportedTransports"
805
+ ];
806
+ var ALL_NETWORK_ROUTING_PARAM_KEYS = [
807
+ "operationId",
808
+ "knownConnections",
809
+ "allowDeviceSelection",
810
+ "supportedTransports"
811
+ ];
769
812
  var TREZOR_BTC_NETWORK_COIN_MAP = {
770
813
  btc: "Bitcoin",
771
814
  bitcoin: "Bitcoin",
@@ -782,9 +825,24 @@ var TREZOR_BTC_NETWORK_COIN_MAP = {
782
825
  dash: "Dash"
783
826
  };
784
827
  var _TrezorAdapter = class _TrezorAdapter {
785
- constructor(connector) {
828
+ constructor(connector, options) {
786
829
  this.vendor = "trezor";
830
+ // The connector has no protocol-level cancel: the adapter stops waiting and
831
+ // drops the late response, the device carries on.
832
+ this.cancelCapability = "stops-waiting";
787
833
  this._emitter = new (0, _hwkadaptercore.TypedEventEmitter)();
834
+ this._operations = new (0, _hwkadaptercore.OperationRegistry)({
835
+ vendor: "trezor",
836
+ onEnded: (operation, reason) => {
837
+ this._emitter.emit(_hwkadaptercore.SDK.OPERATION_ENDED, {
838
+ type: _hwkadaptercore.SDK.OPERATION_ENDED,
839
+ payload: { operationId: operation.operationId, reason }
840
+ });
841
+ if (reason === "timeout") {
842
+ void this._releaseOperationConnection(operation).catch(() => void 0);
843
+ }
844
+ }
845
+ });
788
846
  this._devices = /* @__PURE__ */ new Map();
789
847
  this._sessions = /* @__PURE__ */ new Map();
790
848
  this._connectingPromises = /* @__PURE__ */ new Map();
@@ -793,12 +851,21 @@ var _TrezorAdapter = class _TrezorAdapter {
793
851
  this._uiRegistry = new (0, _hwkadaptercore.UiRequestRegistry)();
794
852
  this._passphraseRequestContextByConnectId = /* @__PURE__ */ new Map();
795
853
  this._verifiedPassphraseSessionsByConnectId = /* @__PURE__ */ new Map();
854
+ /** Raw connector calls that outlive an aborted caller, keyed by session. */
855
+ this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
856
+ this._connectorIdleWaiters = /* @__PURE__ */ new Set();
857
+ this._resetPromise = null;
858
+ this._connectorTeardownTail = Promise.resolve();
859
+ this._pendingConnectorTeardowns = 0;
860
+ this._stateGeneration = 0;
861
+ this._knownDeviceConnections = /* @__PURE__ */ new Map();
796
862
  this._onDeviceConnect = (data) => {
797
863
  const device = this._connectorDeviceToDeviceInfo(data.device);
798
864
  this._devices.set(device.connectId, device);
799
865
  this._emitter.emit(_hwkadaptercore.DEVICE.CONNECT, { type: _hwkadaptercore.DEVICE.CONNECT, payload: device });
800
866
  };
801
867
  this._onDeviceDisconnect = (data) => {
868
+ this._operations.endByConnectionKey(data.connectId, "disconnect");
802
869
  this._sessions.delete(data.connectId);
803
870
  this._verifiedPassphraseSessionsByConnectId.delete(data.connectId);
804
871
  this._devices.delete(data.connectId);
@@ -818,25 +885,32 @@ var _TrezorAdapter = class _TrezorAdapter {
818
885
  payload: { device }
819
886
  });
820
887
  };
888
+ // The one outlet for every connector-raised UI request (PIN, passphrase,
889
+ // button, THP pairing), so the operation is stamped here instead of at each
890
+ // connector call site.
821
891
  this._onUiRequest = (data) => {
892
+ const operationId = this._activeOperationId();
893
+ const basePayload = data.payload && typeof data.payload === "object" ? data.payload : {};
894
+ const attribution = operationId === void 0 ? {} : { operationId };
822
895
  if (data.type === _hwkadaptercore.UI_REQUEST.REQUEST_PASSPHRASE) {
823
- const payload = data.payload && typeof data.payload === "object" ? data.payload : {};
824
- const connectId = typeof payload.connectId === "string" ? payload.connectId : void 0;
896
+ const connectId = typeof basePayload.connectId === "string" ? basePayload.connectId : void 0;
825
897
  const context = connectId ? this._passphraseRequestContextByConnectId.get(connectId) : void 0;
826
898
  this._emitter.emit(
827
899
  data.type,
828
900
  {
829
901
  ...data,
830
902
  payload: {
831
- ...payload,
903
+ ...basePayload,
832
904
  ..._optionalChain([context, 'optionalAccess', _13 => _13.passphraseState]) !== void 0 ? { passphraseState: context.passphraseState } : {},
833
- ..._optionalChain([context, 'optionalAccess', _14 => _14.useEmptyPassphrase]) !== void 0 ? { useEmptyPassphrase: context.useEmptyPassphrase } : {}
905
+ ..._optionalChain([context, 'optionalAccess', _14 => _14.useEmptyPassphrase]) !== void 0 ? { useEmptyPassphrase: context.useEmptyPassphrase } : {},
906
+ ...attribution
834
907
  }
835
908
  }
836
909
  );
837
910
  return;
838
911
  }
839
- this._emitter.emit(data.type, data);
912
+ const payload = operationId === void 0 ? data.payload : { ...basePayload, ...attribution };
913
+ this._emitter.emit(data.type, { ...data, payload });
840
914
  };
841
915
  this._onUiEvent = (data) => {
842
916
  this._emitter.emit("ui-event", data);
@@ -848,6 +922,11 @@ var _TrezorAdapter = class _TrezorAdapter {
848
922
  });
849
923
  };
850
924
  this._connector = connector;
925
+ for (const connection of _nullishCoalesce(_optionalChain([options, 'optionalAccess', _15 => _15.knownDeviceConnections]), () => ( []))) {
926
+ if (connection.deviceId) {
927
+ this._knownDeviceConnections.set(connection.deviceId, { ...connection });
928
+ }
929
+ }
851
930
  this._jobQueue = new (0, _hwkadaptercore.DeviceJobQueue)();
852
931
  this._registerConnectorEvents();
853
932
  }
@@ -872,39 +951,55 @@ var _TrezorAdapter = class _TrezorAdapter {
872
951
  const {
873
952
  passphraseState,
874
953
  autoInstallApp: _autoInstallApp,
954
+ operationId,
875
955
  useEmptyPassphrase,
956
+ knownConnections,
957
+ extra,
958
+ allowDeviceSelection,
959
+ supportedTransports,
876
960
  ...rest
877
961
  } = params;
878
962
  return {
879
963
  passphraseState: typeof passphraseState === "string" ? passphraseState : void 0,
880
964
  useEmptyPassphrase: typeof useEmptyPassphrase === "boolean" ? useEmptyPassphrase : void 0,
965
+ operationId: typeof operationId === "string" ? operationId : void 0,
966
+ connectionContext: _hwkadaptercore.pickConnectionContext.call(void 0, {
967
+ knownConnections,
968
+ extra,
969
+ allowDeviceSelection,
970
+ supportedTransports
971
+ }),
881
972
  rest
882
973
  };
883
974
  }
884
975
  return { rest: _nullishCoalesce(params, () => ( {})) };
885
976
  }
886
977
  static _withAllNetworkRequestCommonParams(item, commonParams) {
887
- const autoInstallApp = _optionalChain([commonParams, 'optionalAccess', _15 => _15.autoInstallApp]);
888
- const passphraseState = _optionalChain([commonParams, 'optionalAccess', _16 => _16.passphraseState]);
889
- const useEmptyPassphrase = _optionalChain([commonParams, 'optionalAccess', _17 => _17.useEmptyPassphrase]);
890
- if (autoInstallApp === void 0 && passphraseState === void 0 && useEmptyPassphrase === void 0) {
891
- return item;
892
- }
978
+ const defined = ALL_NETWORK_COMMON_PARAM_KEYS.filter((key) => _optionalChain([commonParams, 'optionalAccess', _16 => _16[key]]) !== void 0);
893
979
  return {
894
980
  ...item,
895
- ...autoInstallApp !== void 0 ? { autoInstallApp } : {},
896
- ...passphraseState !== void 0 ? { passphraseState } : {},
897
- ...useEmptyPassphrase !== void 0 ? { useEmptyPassphrase } : {}
981
+ ...Object.fromEntries(defined.map((key) => [key, _optionalChain([commonParams, 'optionalAccess', _17 => _17[key]])])),
982
+ ...Object.fromEntries(ALL_NETWORK_ROUTING_PARAM_KEYS.map((key) => [key, _optionalChain([commonParams, 'optionalAccess', _18 => _18[key]])]))
898
983
  };
899
984
  }
900
985
  static _normalizeLogKey(key) {
901
986
  return key.replace(/[_-]/g, "").toLowerCase();
902
987
  }
903
- // Mirrors hd-core's logBlockEvent: a signing method's body is the user's
904
- // transaction, so it is dropped wholesale; other methods redact by key.
905
- static _sanitizeForLog(value, methodName) {
906
- if (methodName && /sign/i.test(methodName)) return "[redacted]";
907
- return _TrezorAdapter._redactForLog(value, /* @__PURE__ */ new WeakSet());
988
+ // [REQ]/[RES] bodies: paths, chain ids and flags stay readable; transaction
989
+ // contents, keys and addresses become length + short hash; secrets are redacted.
990
+ static _sanitizeForLog(value, methodName, role = "params") {
991
+ return _hwkadaptercore.summarizeForLog.call(void 0, value, { method: methodName, role });
992
+ }
993
+ // A failure payload is an error record, so its message/error text stays readable.
994
+ static _responseForLog(response, methodName) {
995
+ if (response.success) {
996
+ return _TrezorAdapter._sanitizeForLog(response.payload, methodName, "result");
997
+ }
998
+ const out = _hwkadaptercore.summarizeForLog.call(void 0,
999
+ { error: response.payload },
1000
+ { method: methodName, role: "result" }
1001
+ );
1002
+ return out && typeof out === "object" ? out.error : out;
908
1003
  }
909
1004
  static _redactForLog(value, seen) {
910
1005
  if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
@@ -925,14 +1020,17 @@ var _TrezorAdapter = class _TrezorAdapter {
925
1020
  static _errorForLog(error) {
926
1021
  if (!error || typeof error !== "object") return error;
927
1022
  const typed = error;
928
- return _TrezorAdapter._sanitizeForLog({
929
- name: typed.name,
930
- message: typed.message,
931
- code: typed.code,
932
- errorCode: typed.errorCode,
933
- statusCode: typed.statusCode,
934
- response: typed.response
935
- });
1023
+ return _TrezorAdapter._redactForLog(
1024
+ {
1025
+ name: typed.name,
1026
+ message: typed.message,
1027
+ code: typed.code,
1028
+ errorCode: typed.errorCode,
1029
+ statusCode: typed.statusCode,
1030
+ response: typed.response
1031
+ },
1032
+ /* @__PURE__ */ new WeakSet()
1033
+ );
936
1034
  }
937
1035
  _setPassphraseRequestContext(connectId, context) {
938
1036
  const previous = this._passphraseRequestContextByConnectId.get(connectId);
@@ -950,8 +1048,8 @@ var _TrezorAdapter = class _TrezorAdapter {
950
1048
  };
951
1049
  }
952
1050
  static _trezorFailureMessage(error) {
953
- const response = _optionalChain([error, 'optionalAccess', _18 => _18.response]);
954
- const message = _optionalChain([response, 'optionalAccess', _19 => _19.message]);
1051
+ const response = _optionalChain([error, 'optionalAccess', _19 => _19.response]);
1052
+ const message = _optionalChain([response, 'optionalAccess', _20 => _20.message]);
955
1053
  if (!message || typeof message !== "object") return {};
956
1054
  const failureMessage = message;
957
1055
  return {
@@ -960,7 +1058,7 @@ var _TrezorAdapter = class _TrezorAdapter {
960
1058
  };
961
1059
  }
962
1060
  static _mapTrezorFailureCode(error) {
963
- const directCode = _optionalChain([error, 'optionalAccess', _20 => _20.code]);
1061
+ const directCode = _optionalChain([error, 'optionalAccess', _21 => _21.code]);
964
1062
  if (directCode === "Device_InitializeFailed") {
965
1063
  return _hwkadaptercore.HardwareErrorCode.PinCancelled;
966
1064
  }
@@ -973,7 +1071,7 @@ var _TrezorAdapter = class _TrezorAdapter {
973
1071
  if (directCode === "Failure_UnexpectedMessage") {
974
1072
  return _hwkadaptercore.HardwareErrorCode.MethodNotSupported;
975
1073
  }
976
- const message = _optionalChain([error, 'optionalAccess', _21 => _21.message]);
1074
+ const message = _optionalChain([error, 'optionalAccess', _22 => _22.message]);
977
1075
  if (typeof message === "string" && message.includes("Failed to execute 'transfer") && message.includes("on 'USBDevice'")) {
978
1076
  return _hwkadaptercore.HardwareErrorCode.TransportError;
979
1077
  }
@@ -1018,13 +1116,11 @@ var _TrezorAdapter = class _TrezorAdapter {
1018
1116
  * selected is gone (the device evicted it from its limited slot pool). The
1019
1117
  * caller drops the stale cache entry and recreates from scratch.
1020
1118
  *
1021
- * NOTE: the exact eviction code still needs real-device confirmation — match
1022
- * conservatively so a genuine error isn't mistaken for an evicted session
1023
- * (which would silently re-prompt the passphrase).
1119
+ * Match only the protocol's explicit unallocated-channel code. Guessing from
1120
+ * an error message could replay a request after an unrelated business error.
1024
1121
  */
1025
1122
  static _isStaleSessionError(code) {
1026
- if (typeof code !== "string") return false;
1027
- return code === "ThpUnallocatedChannel" || /invalid.?session|unallocated.?session|session.?not.?found/i.test(code);
1123
+ return code === "ThpUnallocatedChannel";
1028
1124
  }
1029
1125
  static _errorCode(error) {
1030
1126
  return _nullishCoalesce(error.code, () => ( _TrezorAdapter._trezorFailureMessage(error).code));
@@ -1038,13 +1134,13 @@ var _TrezorAdapter = class _TrezorAdapter {
1038
1134
  return protocolError.name === "TrezorProtocolError" && protocolError.code === "Malformed protocol format" && protocolError.message === "Malformed protocol format";
1039
1135
  }
1040
1136
  /**
1041
- * Race a promise against an abort signal. Copied from LedgerAdapter:
1042
- * IConnector.call() can't actually be cancelled at the protocol level, but
1043
- * the caller gets the abort immediately and the underlying work completes
1044
- * uselessly in the background.
1137
+ * Race a promise against an abort signal. IConnector.call() can't actually
1138
+ * be cancelled at the protocol level, so the caller gets the abort while the
1139
+ * adapter keeps the transport exclusively reserved until the raw call drains.
1045
1140
  */
1046
1141
  static _abortable(signal, promise) {
1047
1142
  if (signal.aborted) {
1143
+ void promise.catch(() => void 0);
1048
1144
  return Promise.reject(
1049
1145
  _nullishCoalesce(signal.reason, () => ( new Error("Aborted")))
1050
1146
  );
@@ -1066,17 +1162,37 @@ var _TrezorAdapter = class _TrezorAdapter {
1066
1162
  );
1067
1163
  });
1068
1164
  }
1069
- async _connectSession(connectId, signal) {
1165
+ async _connectSession(connectId, signal, stateGeneration, transportType) {
1070
1166
  const connectOnce = async () => {
1071
- const connectPromise = this._connector.connect(connectId);
1072
- if (!signal) return connectPromise;
1167
+ if (_optionalChain([signal, 'optionalAccess', _23 => _23.aborted])) {
1168
+ throw _nullishCoalesce(signal.reason, () => ( new Error("Aborted")));
1169
+ }
1170
+ this._assertConnectorIdle("connectDevice");
1171
+ const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
1172
+ let connectPromise;
1073
1173
  try {
1074
- return await _TrezorAdapter._abortable(signal, connectPromise);
1174
+ connectPromise = transportType ? this._connector.connect(connectId, { transportType }) : this._connector.connect(connectId);
1075
1175
  } catch (error) {
1076
- void connectPromise.then(
1077
- (orphan) => this._connector.disconnect(orphan.sessionId).catch(() => void 0),
1078
- () => void 0
1079
- );
1176
+ releaseOperation();
1177
+ throw error;
1178
+ }
1179
+ if (!signal) {
1180
+ try {
1181
+ return await connectPromise;
1182
+ } finally {
1183
+ releaseOperation();
1184
+ }
1185
+ }
1186
+ try {
1187
+ const session2 = await _TrezorAdapter._abortable(signal, connectPromise);
1188
+ releaseOperation();
1189
+ return session2;
1190
+ } catch (error) {
1191
+ if (signal.aborted) {
1192
+ void connectPromise.then((orphan) => this._connector.disconnect(orphan.sessionId).catch(() => void 0)).catch(() => void 0).finally(releaseOperation);
1193
+ } else {
1194
+ releaseOperation();
1195
+ }
1080
1196
  throw error;
1081
1197
  }
1082
1198
  };
@@ -1084,7 +1200,7 @@ var _TrezorAdapter = class _TrezorAdapter {
1084
1200
  try {
1085
1201
  session = await connectOnce();
1086
1202
  } catch (error) {
1087
- if (_optionalChain([signal, 'optionalAccess', _22 => _22.aborted]) || !_TrezorAdapter._isRecoverableProtocolResidueError(error)) {
1203
+ if (_optionalChain([signal, 'optionalAccess', _24 => _24.aborted]) || !_TrezorAdapter._isRecoverableProtocolResidueError(error)) {
1088
1204
  throw error;
1089
1205
  }
1090
1206
  debugLog("[TrezorAdapter] retrying connect after draining a stale THP frame", {
@@ -1092,8 +1208,13 @@ var _TrezorAdapter = class _TrezorAdapter {
1092
1208
  });
1093
1209
  session = await connectOnce();
1094
1210
  }
1095
- if (this._disconnectRequested.delete(connectId)) {
1096
- await this._connector.disconnect(session.sessionId).catch(() => void 0);
1211
+ if (_optionalChain([signal, 'optionalAccess', _25 => _25.aborted]) || stateGeneration !== this._stateGeneration || this._disconnectRequested.delete(connectId)) {
1212
+ const releaseCleanup = this._retainConnectorOperation(`disconnect:${session.sessionId}`);
1213
+ try {
1214
+ await this._connector.disconnect(session.sessionId).catch(() => void 0);
1215
+ } finally {
1216
+ releaseCleanup();
1217
+ }
1097
1218
  throw Object.assign(new Error("Trezor connection aborted"), {
1098
1219
  code: _hwkadaptercore.HardwareErrorCode.UserAborted
1099
1220
  });
@@ -1109,14 +1230,9 @@ var _TrezorAdapter = class _TrezorAdapter {
1109
1230
  async init(_config) {
1110
1231
  }
1111
1232
  async dispose() {
1233
+ await this._resetStateAndDisconnectSessions();
1112
1234
  this._unregisterConnectorEvents();
1113
- this._uiRegistry.reset();
1114
- this._jobQueue.clear();
1115
1235
  this._connector.reset();
1116
- this._devices.clear();
1117
- this._sessions.clear();
1118
- this._verifiedPassphraseSessionsByConnectId.clear();
1119
- this._connectingPromises.clear();
1120
1236
  this._emitter.removeAllListeners();
1121
1237
  }
1122
1238
  /**
@@ -1125,12 +1241,31 @@ var _TrezorAdapter = class _TrezorAdapter {
1125
1241
  * error flows. Aborts active jobs and releases UI waits.
1126
1242
  */
1127
1243
  resetState() {
1244
+ void this._resetStateAndDisconnectSessions();
1245
+ }
1246
+ _resetStateAndDisconnectSessions() {
1247
+ if (this._resetPromise) return this._resetPromise;
1248
+ const sessionIds = new Set(this._sessions.values());
1249
+ this._stateGeneration += 1;
1250
+ this._operations.endAll("runtime-reset");
1128
1251
  this._uiRegistry.reset();
1252
+ this._connector.uiResponse({ type: _hwkadaptercore.UI_RESPONSE.CANCEL });
1129
1253
  this._jobQueue.clear();
1130
1254
  this._devices.clear();
1131
1255
  this._sessions.clear();
1132
1256
  this._verifiedPassphraseSessionsByConnectId.clear();
1133
1257
  this._connectingPromises.clear();
1258
+ const resetPromise = this._runConnectorTeardown(async () => {
1259
+ for (const sessionId of sessionIds) {
1260
+ await this._connector.disconnect(sessionId).catch(() => void 0);
1261
+ }
1262
+ });
1263
+ this._resetPromise = resetPromise;
1264
+ return resetPromise.finally(() => {
1265
+ if (this._resetPromise === resetPromise) {
1266
+ this._resetPromise = null;
1267
+ }
1268
+ });
1134
1269
  }
1135
1270
  getAvailableTransports() {
1136
1271
  return this.activeTransport ? [this.activeTransport] : [];
@@ -1138,32 +1273,160 @@ var _TrezorAdapter = class _TrezorAdapter {
1138
1273
  async switchTransport(_type) {
1139
1274
  }
1140
1275
  async searchDevices(options) {
1141
- await this._ensureDevicePermission();
1276
+ await this._ensureDevicePermission(void 0, void 0, _optionalChain([options, 'optionalAccess', _26 => _26.transportType]));
1277
+ return this._searchDevices(options);
1278
+ }
1279
+ async _searchDevices(options, signal) {
1280
+ if (_optionalChain([options, 'optionalAccess', _27 => _27.transportType]) && !this._availableTransports().includes(options.transportType))
1281
+ return [];
1282
+ if (_optionalChain([options, 'optionalAccess', _28 => _28.resetSession])) {
1283
+ await this._resetStateAndDisconnectSessions();
1284
+ } else {
1285
+ await this._connectorTeardownTail;
1286
+ }
1287
+ if (_optionalChain([signal, 'optionalAccess', _29 => _29.aborted])) throw signal.reason;
1288
+ const stateGeneration = this._stateGeneration;
1142
1289
  const scanned = await this._connector.searchDevices(
1143
- _optionalChain([options, 'optionalAccess', _23 => _23.waitForAllTransports]) ? { waitForAll: true } : void 0
1290
+ _optionalChain([options, 'optionalAccess', _30 => _30.waitForAllTransports]) || _optionalChain([options, 'optionalAccess', _31 => _31.transportType]) ? {
1291
+ ...options.waitForAllTransports ? { waitForAll: true } : {},
1292
+ ...options.transportType ? { transportType: options.transportType } : {}
1293
+ } : void 0
1144
1294
  );
1295
+ if (_optionalChain([signal, 'optionalAccess', _32 => _32.aborted])) throw signal.reason;
1296
+ if (stateGeneration !== this._stateGeneration) {
1297
+ throw _hwkadaptercore.createHwkError.call(void 0, {
1298
+ code: _hwkadaptercore.HardwareErrorCode.UserAborted,
1299
+ message: "Trezor discovery belongs to an ended operation"
1300
+ });
1301
+ }
1145
1302
  const scannedIds = new Set(scanned.map((d) => d.connectId));
1146
1303
  for (const connectId of [...this._devices.keys()]) {
1147
- if (!scannedIds.has(connectId) && !this._sessions.has(connectId)) {
1304
+ if ((!_optionalChain([options, 'optionalAccess', _33 => _33.transportType]) || _optionalChain([this, 'access', _34 => _34._devices, 'access', _35 => _35.get, 'call', _36 => _36(connectId), 'optionalAccess', _37 => _37.connectionType]) === options.transportType) && !scannedIds.has(connectId) && !this._sessions.has(connectId)) {
1148
1305
  this._devices.delete(connectId);
1149
1306
  }
1150
1307
  }
1151
1308
  for (const device of scanned) {
1152
1309
  const info = this._connectorDeviceToDeviceInfo(device);
1153
- this._devices.set(info.connectId, info);
1310
+ if (!this._sessions.has(info.connectId)) this._devices.set(info.connectId, info);
1311
+ }
1312
+ return Array.from(this._devices.values()).filter(
1313
+ (device) => !_optionalChain([options, 'optionalAccess', _38 => _38.transportType]) || device.connectionType === options.transportType
1314
+ );
1315
+ }
1316
+ async searchDeviceTargets(options) {
1317
+ const devices = await this.searchDevices(options);
1318
+ return devices.map((device) => _hwkadaptercore.toPhysicalDeviceSearchTarget.call(void 0, "trezor", device));
1319
+ }
1320
+ async bindBleDevice(params) {
1321
+ if (_optionalChain([params, 'access', _39 => _39.identity, 'optionalAccess', _40 => _40.vendor]) !== "trezor" || !params.identity.value) {
1322
+ return _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.InvalidParams, "Trezor device identity is required");
1323
+ }
1324
+ const { value: deviceId } = params.identity;
1325
+ try {
1326
+ return await this._jobQueue.enqueue(
1327
+ deviceId,
1328
+ async (signal) => {
1329
+ const selected = await this._selectBleDeviceForBinding(
1330
+ deviceId,
1331
+ signal,
1332
+ { extra: params.extra },
1333
+ "manual-rebind"
1334
+ );
1335
+ try {
1336
+ const persisted = await this._emitVerifiedBinding(
1337
+ deviceId,
1338
+ selected.connectId,
1339
+ selected.selectionRequestId,
1340
+ { extra: params.extra },
1341
+ signal
1342
+ );
1343
+ if (!persisted) {
1344
+ throw _hwkadaptercore.createHwkError.call(void 0, {
1345
+ code: _hwkadaptercore.HardwareErrorCode.UnknownError,
1346
+ message: "Bluetooth binding could not be saved",
1347
+ origin: "host"
1348
+ });
1349
+ }
1350
+ this._rememberVerifiedConnection(deviceId, selected.connectId);
1351
+ return _hwkadaptercore.success.call(void 0, selected.connectId);
1352
+ } catch (error) {
1353
+ await this._releaseProvisionalConnection(selected.connectId, signal);
1354
+ throw error;
1355
+ }
1356
+ },
1357
+ {
1358
+ label: "bindBleDevice",
1359
+ rejectIfBusy: true,
1360
+ busyError: _TrezorAdapter._createDeviceBusyError("bindBleDevice")
1361
+ }
1362
+ );
1363
+ } catch (error) {
1364
+ return this._errorToFailure(error);
1154
1365
  }
1155
- return Array.from(this._devices.values());
1156
1366
  }
1157
- async connectDevice(connectId) {
1367
+ async connectDevice(searchTargetId) {
1368
+ const scope = this._jobQueue.createCancelScope(searchTargetId);
1158
1369
  try {
1159
- await this._ensureDevicePermission(connectId);
1160
- await this._ensureSession(connectId);
1161
- return _hwkadaptercore.success.call(void 0, connectId);
1370
+ await _TrezorAdapter._abortable(
1371
+ scope.signal,
1372
+ this._ensureDevicePermission(
1373
+ searchTargetId,
1374
+ void 0,
1375
+ _optionalChain([this, 'access', _41 => _41._devices, 'access', _42 => _42.get, 'call', _43 => _43(searchTargetId), 'optionalAccess', _44 => _44.connectionType])
1376
+ )
1377
+ );
1378
+ await this._ensureSession(searchTargetId, scope.signal);
1379
+ if (scope.signal.aborted) throw scope.signal.reason;
1380
+ const device = this._devices.get(searchTargetId);
1381
+ if (!device) {
1382
+ return _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.DeviceNotFound, "Trezor device not found after connect");
1383
+ }
1384
+ this._operations.endByConnectionKey(searchTargetId, "explicit");
1385
+ const operation = this._operations.create({
1386
+ searchTargetId,
1387
+ connectId: searchTargetId,
1388
+ device,
1389
+ connectionType: device.connectionType,
1390
+ connectionKeys: [_nullishCoalesce(this._sessions.get(searchTargetId), () => ( ""))]
1391
+ });
1392
+ return _hwkadaptercore.success.call(void 0, operation.operationId);
1162
1393
  } catch (error) {
1394
+ if (scope.signal.aborted) {
1395
+ await this._waitForConnectorOperationsToDrain();
1396
+ return _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.UserAborted, "Trezor connection aborted");
1397
+ }
1163
1398
  return this._errorToFailure(error);
1399
+ } finally {
1400
+ scope.release();
1164
1401
  }
1165
1402
  }
1166
- async disconnectDevice(connectId) {
1403
+ async releaseOperation(operationId) {
1404
+ const operation = this._operations.findActive(operationId);
1405
+ if (operation) this._cancelOperationWork(operation);
1406
+ const endedOperation = this._operations.release(operationId);
1407
+ if (!endedOperation) return;
1408
+ await this._releaseOperationConnection(endedOperation);
1409
+ }
1410
+ /**
1411
+ * Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
1412
+ * that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
1413
+ */
1414
+ _cancelOperationWork(operation) {
1415
+ const { operationId } = operation;
1416
+ const reason = _hwkadaptercore.createHwkError.call(void 0, {
1417
+ code: _hwkadaptercore.HardwareErrorCode.OperationEnded,
1418
+ message: "Trezor operation was released",
1419
+ params: { operationId, reason: "explicit" }
1420
+ });
1421
+ const queueKey = trezorQueueKey({ operationId });
1422
+ const ownsRunningCall = _optionalChain([this, 'access', _45 => _45._jobQueue, 'access', _46 => _46.getActiveJob, 'call', _47 => _47(), 'optionalAccess', _48 => _48.deviceId]) === queueKey;
1423
+ this._jobQueue.cancelActiveAndPending(queueKey, reason);
1424
+ if (!ownsRunningCall) return;
1425
+ this._uiRegistry.cancel(void 0, void 0, operationId);
1426
+ this._connector.uiResponse({ type: _hwkadaptercore.UI_RESPONSE.CANCEL });
1427
+ }
1428
+ async _releaseOperationConnection(operation) {
1429
+ const { connectId } = operation;
1167
1430
  const connecting = this._connectingPromises.has(connectId);
1168
1431
  this._connectingPromises.delete(connectId);
1169
1432
  const sessionId = this._sessions.get(connectId);
@@ -1171,90 +1434,131 @@ var _TrezorAdapter = class _TrezorAdapter {
1171
1434
  if (connecting) this._disconnectRequested.add(connectId);
1172
1435
  return;
1173
1436
  }
1174
- this._sessions.delete(connectId);
1175
- this._verifiedPassphraseSessionsByConnectId.delete(connectId);
1176
- await this._connector.disconnect(sessionId);
1437
+ await this._disconnectSession(connectId, sessionId);
1177
1438
  }
1178
- async getDeviceInfo(connectId, deviceId) {
1439
+ async getDeviceInfo(connectIdOrOperationId, deviceId) {
1440
+ let connectId;
1441
+ try {
1442
+ connectId = _hwkadaptercore.isHardwareOperationId.call(void 0, connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1443
+ } catch (error) {
1444
+ return this._errorToFailure(error);
1445
+ }
1179
1446
  const device = _nullishCoalesce(this._devices.get(connectId), () => ( Array.from(this._devices.values()).find((item) => item.deviceId === deviceId)));
1180
1447
  if (!device) return _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.DeviceNotFound, "Trezor device not found");
1181
1448
  return _hwkadaptercore.success.call(void 0, device);
1182
1449
  }
1183
- getSupportedChains() {
1184
- return ["btc", "evm", "sol", "tron"];
1185
- }
1186
1450
  async allNetworkGetAddress(connectId, deviceId, params) {
1451
+ const target = _hwkadaptercore.resolveHardwareOperationTarget.call(void 0, connectId, params.operationId, "trezor");
1452
+ if (!target.success) return target;
1453
+ let effectiveTargetId = _nullishCoalesce(target.payload.targetId, () => ( ""));
1454
+ let releaseOperationRetention;
1455
+ try {
1456
+ releaseOperationRetention = target.payload.operationId ? this._operations.retain(target.payload.operationId) : void 0;
1457
+ } catch (error) {
1458
+ return this._errorToFailure(error);
1459
+ }
1460
+ const cancelScope = this._jobQueue.createCancelScope(
1461
+ trezorQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
1462
+ );
1187
1463
  let liveDeviceId = "";
1464
+ const bundleContext = {};
1188
1465
  const topLevelFailureIndexes = /* @__PURE__ */ new Set();
1189
1466
  const isSingleNetworkBundle = params.bundle.every(
1190
- (item) => item.network === _optionalChain([params, 'access', _24 => _24.bundle, 'access', _25 => _25[0], 'optionalAccess', _26 => _26.network])
1467
+ (item) => item.network === _optionalChain([params, 'access', _49 => _49.bundle, 'access', _50 => _50[0], 'optionalAccess', _51 => _51.network])
1191
1468
  );
1192
- const getLiveDeviceId = async () => {
1469
+ const getLiveDeviceId = async (expectedDeviceId) => {
1193
1470
  if (liveDeviceId) return _hwkadaptercore.success.call(void 0, liveDeviceId);
1194
- const deviceIdResponse = await this._getTrezorDeviceId(connectId);
1471
+ const deviceIdResponse = await this._getTrezorDeviceId(
1472
+ effectiveTargetId,
1473
+ expectedDeviceId || deviceId,
1474
+ params,
1475
+ bundleContext
1476
+ );
1195
1477
  if (deviceIdResponse.success) {
1196
1478
  liveDeviceId = deviceIdResponse.payload;
1479
+ if (!target.payload.operationId) {
1480
+ effectiveTargetId = _nullishCoalesce(_optionalChain([bundleContext, 'access', _52 => _52.connection, 'optionalAccess', _53 => _53.connectId]), () => ( effectiveTargetId));
1481
+ }
1197
1482
  }
1198
1483
  return deviceIdResponse;
1199
1484
  };
1200
- return _hwkadaptercore.runAllNetworkGetAddress.call(void 0, {
1201
- connectId,
1202
- deviceId,
1203
- params,
1204
- normalizeItem: _TrezorAdapter._normalizeAllNetworkItem,
1205
- callItem: async ({ method, item, index }) => {
1206
- const expectedDeviceId = _nullishCoalesce(_TrezorAdapter._getItemDeviceId(item), () => ( deviceId));
1207
- if (expectedDeviceId) {
1208
- const fingerprint = await getLiveDeviceId();
1209
- if (!fingerprint.success) {
1485
+ try {
1486
+ return await _hwkadaptercore.runAllNetworkGetAddress.call(void 0, {
1487
+ connectId: effectiveTargetId,
1488
+ deviceId,
1489
+ params,
1490
+ normalizeItem: _TrezorAdapter._normalizeAllNetworkItem,
1491
+ callItem: async ({ method, item, index }) => {
1492
+ if (cancelScope.signal.aborted) {
1210
1493
  topLevelFailureIndexes.add(index);
1211
- return fingerprint;
1494
+ return _hwkadaptercore.buildAllNetworkCancelledFailure.call(void 0, cancelScope.signal);
1212
1495
  }
1213
- if (expectedDeviceId !== fingerprint.payload) {
1214
- topLevelFailureIndexes.add(index);
1215
- return _hwkadaptercore.failure.call(void 0,
1216
- _hwkadaptercore.HardwareErrorCode.DeviceMismatch,
1217
- `Wrong device: expected ${expectedDeviceId}, got ${fingerprint.payload}`,
1218
- { expected: expectedDeviceId, actual: fingerprint.payload }
1219
- );
1496
+ const expectedDeviceId = _nullishCoalesce(_TrezorAdapter._getItemDeviceId(item), () => ( deviceId));
1497
+ if (expectedDeviceId) {
1498
+ const fingerprint = await getLiveDeviceId(expectedDeviceId);
1499
+ if (!fingerprint.success) {
1500
+ topLevelFailureIndexes.add(index);
1501
+ return fingerprint;
1502
+ }
1503
+ if (expectedDeviceId !== fingerprint.payload) {
1504
+ topLevelFailureIndexes.add(index);
1505
+ return _hwkadaptercore.failure.call(void 0,
1506
+ _hwkadaptercore.HardwareErrorCode.DeviceMismatch,
1507
+ `Wrong device: expected ${expectedDeviceId}, got ${fingerprint.payload}`,
1508
+ { expected: expectedDeviceId, actual: fingerprint.payload }
1509
+ );
1510
+ }
1220
1511
  }
1221
- }
1222
- const callItem = _TrezorAdapter._withAllNetworkRequestCommonParams(item, params);
1223
- return this._callAllNetworkMethod(connectId, method, callItem);
1224
- },
1225
- attachIdentity: async ({ item, chain, payload }) => {
1226
- if (!liveDeviceId) {
1227
- const fingerprint = await getLiveDeviceId();
1228
- if (!fingerprint.success) {
1229
- return { ...item, success: false, payload: fingerprint.payload };
1512
+ const callItem = _TrezorAdapter._withAllNetworkRequestCommonParams(item, params);
1513
+ return this._callAllNetworkMethod(effectiveTargetId, method, callItem, bundleContext);
1514
+ },
1515
+ attachIdentity: async ({ item, chain, payload, index }) => {
1516
+ if (!liveDeviceId) {
1517
+ if (cancelScope.signal.aborted) {
1518
+ topLevelFailureIndexes.add(index);
1519
+ const cancelled = _hwkadaptercore.buildAllNetworkCancelledFailure.call(void 0, cancelScope.signal);
1520
+ return { ...item, success: false, payload: cancelled.payload };
1521
+ }
1522
+ const fingerprint = await getLiveDeviceId(deviceId);
1523
+ if (!fingerprint.success) {
1524
+ return { ...item, success: false, payload: fingerprint.payload };
1525
+ }
1230
1526
  }
1527
+ return {
1528
+ ...item,
1529
+ success: true,
1530
+ payload: {
1531
+ ...payload,
1532
+ deviceIdentity: {
1533
+ vendor: "trezor",
1534
+ type: "deviceId",
1535
+ value: liveDeviceId
1536
+ },
1537
+ chainFingerprint: liveDeviceId,
1538
+ chainFingerprintChain: chain
1539
+ }
1540
+ };
1541
+ },
1542
+ // One named boolean per abort reason.
1543
+ shouldAbortBundle: (response, { index }) => {
1544
+ const isSessionLevelFailure = topLevelFailureIndexes.has(index);
1545
+ const isWholeChainForbidden = isSingleNetworkBundle && _optionalChain([response, 'access', _54 => _54.payload, 'optionalAccess', _55 => _55.code]) === _hwkadaptercore.HardwareErrorCode.DevicePathForbidden;
1546
+ const { code } = _nullishCoalesce(response.payload, () => ( {}));
1547
+ return isSessionLevelFailure || isWholeChainForbidden || _hwkadaptercore.isWalletSafetyFailure.call(void 0, code) || _hwkadaptercore.isUserRefusal.call(void 0, code) || _hwkadaptercore.isConnectionLost.call(void 0, code);
1231
1548
  }
1232
- return {
1233
- ...item,
1234
- success: true,
1235
- payload: {
1236
- ...payload,
1237
- deviceIdentity: {
1238
- vendor: "trezor",
1239
- type: "deviceId",
1240
- value: liveDeviceId
1241
- },
1242
- chainFingerprint: liveDeviceId,
1243
- chainFingerprintChain: chain
1244
- }
1245
- };
1246
- },
1247
- // One named boolean per abort reason.
1248
- shouldAbortBundle: (response, { index }) => {
1249
- const isSessionLevelFailure = topLevelFailureIndexes.has(index);
1250
- const isWholeChainForbidden = isSingleNetworkBundle && _optionalChain([response, 'access', _27 => _27.payload, 'optionalAccess', _28 => _28.code]) === _hwkadaptercore.HardwareErrorCode.DevicePathForbidden;
1251
- const isPassphrasePolicyFailure = _optionalChain([response, 'access', _29 => _29.payload, 'optionalAccess', _30 => _30.code]) === _hwkadaptercore.HardwareErrorCode.PassphraseAlwaysOnDevice;
1252
- return isSessionLevelFailure || isWholeChainForbidden || isPassphrasePolicyFailure;
1253
- }
1254
- });
1549
+ });
1550
+ } finally {
1551
+ cancelScope.release();
1552
+ _optionalChain([releaseOperationRetention, 'optionalCall', _56 => _56()]);
1553
+ }
1255
1554
  }
1256
- getFeatures(connectId) {
1257
- return this._callDeviceManagerMethod("getFeatures", connectId, {});
1555
+ getFeatures(connectId, operationContext) {
1556
+ return this._callDeviceManagerMethod(
1557
+ "getFeatures",
1558
+ connectId,
1559
+ {},
1560
+ operationContext
1561
+ );
1258
1562
  }
1259
1563
  /**
1260
1564
  * Device authenticity attestation. Sends a host-generated challenge, has the
@@ -1289,7 +1593,7 @@ var _TrezorAdapter = class _TrezorAdapter {
1289
1593
  if (!internalModel) {
1290
1594
  return _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.UnknownError, "Device internal_model unavailable");
1291
1595
  }
1292
- const challengeHex = _nullishCoalesce(_optionalChain([params, 'access', _31 => _31.challenge, 'optionalAccess', _32 => _32.toLowerCase, 'call', _33 => _33()]), () => ( Buffer.from(_utils.randomBytes.call(void 0, 32)).toString("hex")));
1596
+ const challengeHex = _nullishCoalesce(_optionalChain([params, 'access', _57 => _57.challenge, 'optionalAccess', _58 => _58.toLowerCase, 'call', _59 => _59()]), () => ( Buffer.from(_utils.randomBytes.call(void 0, 32)).toString("hex")));
1293
1597
  const challenge = Buffer.from(challengeHex, "hex");
1294
1598
  const proofRes = await this._callDeviceManagerMethod(
1295
1599
  "authenticateDevice",
@@ -1314,28 +1618,65 @@ var _TrezorAdapter = class _TrezorAdapter {
1314
1618
  }
1315
1619
  });
1316
1620
  }
1317
- deviceSettings(connectId, params) {
1621
+ deviceSettings(connectId, params, operationContext) {
1318
1622
  return this._callDeviceManagerMethod(
1319
1623
  "deviceSettings",
1320
1624
  connectId,
1321
- params
1625
+ params,
1626
+ operationContext
1322
1627
  );
1323
1628
  }
1324
- setBrightness(connectId, params = {}) {
1629
+ setBrightness(connectId, params = {}, operationContext) {
1325
1630
  return this._callDeviceManagerMethod(
1326
1631
  "setBrightness",
1327
1632
  connectId,
1328
- params
1633
+ params,
1634
+ operationContext
1329
1635
  );
1330
1636
  }
1331
- changePin(connectId, params = {}) {
1332
- return this._callDeviceManagerMethod("changePin", connectId, params);
1637
+ changePin(connectId, params = {}, operationContext) {
1638
+ return this._callDeviceManagerMethod(
1639
+ "changePin",
1640
+ connectId,
1641
+ params,
1642
+ operationContext
1643
+ );
1333
1644
  }
1334
- wipeDevice(connectId) {
1335
- return this._callDeviceManagerMethod("wipeDevice", connectId, {});
1645
+ wipeDevice(connectId, operationContext) {
1646
+ return this._callDeviceManagerMethod(
1647
+ "wipeDevice",
1648
+ connectId,
1649
+ {},
1650
+ operationContext
1651
+ );
1336
1652
  }
1337
- async _getTrezorDeviceId(connectId) {
1338
- const features = await this.getFeatures(connectId);
1653
+ async _getTrezorDeviceId(connectId, expectedDeviceId, commonParams, bundleContext) {
1654
+ const hasConnectionContext = _optionalChain([commonParams, 'optionalAccess', _60 => _60.knownConnections]) !== void 0 || _optionalChain([commonParams, 'optionalAccess', _61 => _61.extra]) !== void 0;
1655
+ const features = bundleContext || hasConnectionContext ? await this._callMethod(
1656
+ "getFeatures",
1657
+ connectId,
1658
+ hasConnectionContext || !connectId ? expectedDeviceId : void 0,
1659
+ hasConnectionContext ? {
1660
+ operationId: commonParams.operationId,
1661
+ knownConnections: commonParams.knownConnections,
1662
+ extra: commonParams.extra,
1663
+ allowDeviceSelection: commonParams.allowDeviceSelection,
1664
+ supportedTransports: commonParams.supportedTransports,
1665
+ passphraseState: commonParams.passphraseState,
1666
+ useEmptyPassphrase: commonParams.useEmptyPassphrase
1667
+ } : {},
1668
+ false,
1669
+ bundleContext
1670
+ ) : await this.getFeatures(
1671
+ connectId,
1672
+ !connectId && expectedDeviceId ? {
1673
+ expectedDeviceIdentity: {
1674
+ vendor: "trezor",
1675
+ type: "deviceId",
1676
+ value: expectedDeviceId
1677
+ }
1678
+ } : void 0
1679
+ );
1339
1680
  if (!features.success) return features;
1340
1681
  const liveDeviceId = features.payload.device_id;
1341
1682
  if (typeof liveDeviceId !== "string" || liveDeviceId.length === 0) {
@@ -1344,23 +1685,64 @@ var _TrezorAdapter = class _TrezorAdapter {
1344
1685
  return _hwkadaptercore.success.call(void 0, liveDeviceId);
1345
1686
  }
1346
1687
  cancel(connectId) {
1688
+ if (_hwkadaptercore.isHardwareOperationId.call(void 0, connectId)) {
1689
+ try {
1690
+ this._operations.resolve(connectId);
1691
+ } catch (e5) {
1692
+ return;
1693
+ }
1694
+ }
1347
1695
  const userAbortReason = Object.assign(new Error("User aborted operation"), {
1348
1696
  code: _hwkadaptercore.HardwareErrorCode.UserAborted
1349
1697
  });
1350
- this._uiRegistry.cancel();
1351
- this._connector.uiResponse({ type: _hwkadaptercore.UI_RESPONSE.CANCEL });
1352
- if (connectId) {
1353
- this._jobQueue.forceCancelActive(connectId, userAbortReason);
1354
- void this._connector.cancel(_nullishCoalesce(this._sessions.get(connectId), () => ( connectId)));
1698
+ const activeJobId = _optionalChain([this, 'access', _62 => _62._jobQueue, 'access', _63 => _63.getActiveJob, 'call', _64 => _64(), 'optionalAccess', _65 => _65.deviceId]);
1699
+ const targetId = _nullishCoalesce(connectId, () => ( activeJobId));
1700
+ if (targetId) {
1701
+ let resolvedConnectId = targetId;
1702
+ let operationId;
1703
+ if (_hwkadaptercore.isHardwareOperationId.call(void 0, targetId)) {
1704
+ try {
1705
+ operationId = targetId;
1706
+ resolvedConnectId = this._operations.resolve(targetId).connectId;
1707
+ } catch (e6) {
1708
+ resolvedConnectId = "";
1709
+ }
1710
+ }
1711
+ const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
1712
+ const pendingOperationId = _nullishCoalesce(operationId, () => ( _optionalChain([interactionForPhysicalId, 'optionalAccess', _66 => _66.operationId])));
1713
+ if (!connectId) {
1714
+ this._uiRegistry.cancel();
1715
+ } else if (pendingOperationId) {
1716
+ this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
1717
+ }
1718
+ const queueKeys = /* @__PURE__ */ new Set([trezorQueueKey({ connectId: targetId })]);
1719
+ if (pendingOperationId) queueKeys.add(trezorQueueKey({ operationId: pendingOperationId }));
1720
+ const ownsConnectorInteraction = activeJobId !== void 0 ? queueKeys.has(activeJobId) || pendingOperationId !== void 0 && this._activeOperationId() === pendingOperationId : this._connectingPromises.size === 1 && this._connectingPromises.has(resolvedConnectId);
1721
+ if (connectId === void 0 || ownsConnectorInteraction) {
1722
+ this._connector.uiResponse({ type: _hwkadaptercore.UI_RESPONSE.CANCEL });
1723
+ }
1724
+ for (const key of queueKeys) {
1725
+ this._jobQueue.cancelActiveAndPending(key, userAbortReason);
1726
+ }
1727
+ if (resolvedConnectId) {
1728
+ void this._connector.cancel(_nullishCoalesce(this._sessions.get(resolvedConnectId), () => ( resolvedConnectId)));
1729
+ }
1355
1730
  return;
1356
1731
  }
1357
- for (const cid of this._sessions.keys()) {
1358
- this._jobQueue.forceCancelActive(cid, userAbortReason);
1359
- }
1732
+ this._uiRegistry.cancel();
1733
+ this._connector.uiResponse({ type: _hwkadaptercore.UI_RESPONSE.CANCEL });
1734
+ this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
1360
1735
  for (const sessionId of this._sessions.values()) {
1361
1736
  void this._connector.cancel(sessionId);
1362
1737
  }
1363
1738
  }
1739
+ /**
1740
+ * Operation owning the running job: its queue key when pinned, else the live
1741
+ * operation of its connectId, so a mid-call UI request can name it.
1742
+ */
1743
+ _activeOperationId() {
1744
+ return this._operations.findOperationIdByJobKey(_optionalChain([this, 'access', _67 => _67._jobQueue, 'access', _68 => _68.getActiveJob, 'call', _69 => _69(), 'optionalAccess', _70 => _70.deviceId]));
1745
+ }
1364
1746
  /**
1365
1747
  * Routes to BOTH the adapter's local UI registry (preemption decisions,
1366
1748
  * future SELECT_DEVICE / DEVICE_PERMISSION) AND the connector's registry
@@ -1369,6 +1751,7 @@ var _TrezorAdapter = class _TrezorAdapter {
1369
1751
  */
1370
1752
  uiResponse(response) {
1371
1753
  this._uiRegistry.resolve(response.type, response.payload);
1754
+ if (response.type === _hwkadaptercore.UI_RESPONSE.RECEIVE_SELECT_DEVICE) return;
1372
1755
  this._connector.uiResponse(response);
1373
1756
  }
1374
1757
  /**
@@ -1380,8 +1763,8 @@ var _TrezorAdapter = class _TrezorAdapter {
1380
1763
  * Unlike Ledger (which hashes a per-chain address), it is chain-global, so
1381
1764
  * `chain` is accepted for API parity but ignored.
1382
1765
  */
1383
- async getChainFingerprint(connectId, _deviceId, _chain) {
1384
- return this._getTrezorDeviceId(connectId);
1766
+ async getChainFingerprint(connectId, deviceId, _chain) {
1767
+ return this._getTrezorDeviceId(connectId, deviceId);
1385
1768
  }
1386
1769
  /**
1387
1770
  * Resolve the active passphrase wallet identity (`passphraseState`).
@@ -1391,17 +1774,87 @@ var _TrezorAdapter = class _TrezorAdapter {
1391
1774
  * can't interleave with a chain call on the same device (which would desync
1392
1775
  * the THP session selection).
1393
1776
  */
1394
- getPassphraseState(connectId, passphraseState) {
1395
- return this._jobQueue.enqueue(
1777
+ getPassphraseState(connectId, passphraseState, operationContext) {
1778
+ const expectedIdentity = _optionalChain([operationContext, 'optionalAccess', _71 => _71.expectedDeviceIdentity]);
1779
+ if (expectedIdentity && (expectedIdentity.vendor !== "trezor" || expectedIdentity.type !== "deviceId")) {
1780
+ return Promise.resolve(
1781
+ _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.InvalidParams, "Trezor device identity is required")
1782
+ );
1783
+ }
1784
+ const target = _hwkadaptercore.resolveHardwareOperationTarget.call(void 0,
1396
1785
  connectId,
1786
+ _optionalChain([operationContext, 'optionalAccess', _72 => _72.operationId]),
1787
+ "trezor"
1788
+ );
1789
+ if (!target.success) return Promise.resolve(target);
1790
+ const { operationId } = target.payload;
1791
+ let resolvedConnectId = _nullishCoalesce(target.payload.targetId, () => ( ""));
1792
+ let releaseOperationRetention;
1793
+ if (operationId) {
1794
+ try {
1795
+ resolvedConnectId = this._operations.resolve(operationId).connectId;
1796
+ releaseOperationRetention = this._operations.retain(operationId);
1797
+ } catch (error) {
1798
+ return Promise.resolve(this._errorToFailure(error));
1799
+ }
1800
+ }
1801
+ return this._jobQueue.enqueue(
1802
+ trezorQueueKey({ operationId, connectId: resolvedConnectId }),
1397
1803
  async (signal) => {
1398
- const restorePassphraseRequestContext = this._setPassphraseRequestContext(connectId, {
1399
- passphraseState
1400
- });
1804
+ let selectionRequestId;
1805
+ let verified = false;
1401
1806
  try {
1402
- return await this._resolvePassphraseState(connectId, passphraseState, signal);
1807
+ if (!operationId && _optionalChain([expectedIdentity, 'optionalAccess', _73 => _73.value]) && (!connectId || _optionalChain([operationContext, 'optionalAccess', _74 => _74.knownConnections]) !== void 0)) {
1808
+ const resolved = await this._resolveExpectedDeviceConnectId(
1809
+ expectedIdentity.value,
1810
+ signal,
1811
+ operationContext
1812
+ );
1813
+ resolvedConnectId = resolved.connectId;
1814
+ selectionRequestId = resolved.selectionRequestId;
1815
+ }
1816
+ if (_optionalChain([expectedIdentity, 'optionalAccess', _75 => _75.value])) {
1817
+ if (!operationId) await this._ensureSession(resolvedConnectId, signal);
1818
+ if (_optionalChain([this, 'access', _76 => _76._devices, 'access', _77 => _77.get, 'call', _78 => _78(resolvedConnectId), 'optionalAccess', _79 => _79.deviceId]) !== expectedIdentity.value) {
1819
+ return _hwkadaptercore.failure.call(void 0,
1820
+ _hwkadaptercore.HardwareErrorCode.DeviceMismatch,
1821
+ "Trezor device identity does not match"
1822
+ );
1823
+ }
1824
+ }
1825
+ const restorePassphraseRequestContext = this._setPassphraseRequestContext(
1826
+ resolvedConnectId,
1827
+ {
1828
+ passphraseState
1829
+ }
1830
+ );
1831
+ try {
1832
+ const result = await this._resolvePassphraseState(
1833
+ resolvedConnectId,
1834
+ passphraseState,
1835
+ signal,
1836
+ operationId
1837
+ );
1838
+ if (result.success && _optionalChain([expectedIdentity, 'optionalAccess', _80 => _80.value])) {
1839
+ await this._emitVerifiedBinding(
1840
+ expectedIdentity.value,
1841
+ resolvedConnectId,
1842
+ selectionRequestId,
1843
+ operationContext,
1844
+ signal
1845
+ );
1846
+ verified = true;
1847
+ this._rememberVerifiedConnection(expectedIdentity.value, resolvedConnectId);
1848
+ }
1849
+ return result;
1850
+ } finally {
1851
+ restorePassphraseRequestContext();
1852
+ }
1403
1853
  } finally {
1404
- restorePassphraseRequestContext();
1854
+ if (selectionRequestId && !verified) {
1855
+ this._emitBindingStatus(selectionRequestId, signal.aborted ? "cancelled" : "failed");
1856
+ await this._releaseProvisionalConnection(resolvedConnectId, signal);
1857
+ }
1405
1858
  }
1406
1859
  },
1407
1860
  {
@@ -1409,7 +1862,7 @@ var _TrezorAdapter = class _TrezorAdapter {
1409
1862
  rejectIfBusy: true,
1410
1863
  busyError: _TrezorAdapter._createDeviceBusyError("getPassphraseState")
1411
1864
  }
1412
- ).catch((error) => this._errorToFailure(error));
1865
+ ).catch((error) => this._errorToFailure(error)).finally(() => _optionalChain([releaseOperationRetention, 'optionalCall', _81 => _81()]));
1413
1866
  }
1414
1867
  evmGetAddress(connectId, deviceId, params) {
1415
1868
  return this._callWalletMethod("evmGetAddress", connectId, deviceId, params);
@@ -1472,11 +1925,100 @@ var _TrezorAdapter = class _TrezorAdapter {
1472
1925
  }
1473
1926
  return result;
1474
1927
  }
1475
- static async _callConnector(connector, sessionId, method, params, signal) {
1476
- const promise = connector.call(sessionId, method, params);
1928
+ async _callConnector(sessionId, method, params, signal) {
1929
+ if (_optionalChain([signal, 'optionalAccess', _82 => _82.aborted])) {
1930
+ throw _nullishCoalesce(signal.reason, () => ( new Error("Aborted")));
1931
+ }
1932
+ this._assertConnectorIdle(method);
1933
+ const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
1934
+ let promise;
1935
+ try {
1936
+ promise = this._connector.call(sessionId, method, params).finally(() => {
1937
+ releaseOperation();
1938
+ });
1939
+ } catch (error) {
1940
+ releaseOperation();
1941
+ throw error;
1942
+ }
1477
1943
  const result = signal ? await _TrezorAdapter._abortable(signal, promise) : await promise;
1478
1944
  return _TrezorAdapter._unwrapConnectorResult(result);
1479
1945
  }
1946
+ _assertConnectorIdle(method) {
1947
+ if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
1948
+ throw _TrezorAdapter._createDeviceBusyError(method);
1949
+ }
1950
+ }
1951
+ _runConnectorTeardown(task) {
1952
+ const previous = this._connectorTeardownTail;
1953
+ let releaseTail = () => void 0;
1954
+ this._connectorTeardownTail = new Promise((resolve) => {
1955
+ releaseTail = resolve;
1956
+ });
1957
+ this._pendingConnectorTeardowns += 1;
1958
+ return (async () => {
1959
+ try {
1960
+ await previous;
1961
+ await this._waitForConnectorOperationsToDrain();
1962
+ await task();
1963
+ } finally {
1964
+ this._pendingConnectorTeardowns -= 1;
1965
+ releaseTail();
1966
+ }
1967
+ })();
1968
+ }
1969
+ async _disconnectSession(connectId, sessionId = this._sessions.get(connectId)) {
1970
+ this._sessions.delete(connectId);
1971
+ this._verifiedPassphraseSessionsByConnectId.delete(connectId);
1972
+ if (sessionId) await this._runConnectorTeardown(() => this._connector.disconnect(sessionId));
1973
+ }
1974
+ _availableTransports() {
1975
+ return _nullishCoalesce(this._connector.availableTransports, () => ( [this._connector.connectionType]));
1976
+ }
1977
+ /** Transports the connector offers and the host's model table allows; discovery opens no other. */
1978
+ _allowedTransports(context) {
1979
+ const supported = _optionalChain([context, 'optionalAccess', _83 => _83.supportedTransports]);
1980
+ const available = this._availableTransports();
1981
+ return supported ? available.filter((transport) => supported.includes(transport)) : available;
1982
+ }
1983
+ async _releaseProvisionalConnection(connectId, signal) {
1984
+ const sessionId = this._sessions.get(connectId);
1985
+ this._sessions.delete(connectId);
1986
+ this._verifiedPassphraseSessionsByConnectId.delete(connectId);
1987
+ if (!sessionId) return;
1988
+ const teardown = this._runConnectorTeardown(() => this._connector.disconnect(sessionId)).catch(
1989
+ () => void 0
1990
+ );
1991
+ if (!signal.aborted) await teardown;
1992
+ }
1993
+ _waitForConnectorOperationsToDrain() {
1994
+ if (this._unsettledConnectorOperations.size === 0) {
1995
+ return Promise.resolve();
1996
+ }
1997
+ return new Promise((resolve) => {
1998
+ this._connectorIdleWaiters.add(resolve);
1999
+ });
2000
+ }
2001
+ _retainConnectorOperation(key) {
2002
+ this._unsettledConnectorOperations.set(
2003
+ key,
2004
+ (_nullishCoalesce(this._unsettledConnectorOperations.get(key), () => ( 0))) + 1
2005
+ );
2006
+ let released = false;
2007
+ return () => {
2008
+ if (released) return;
2009
+ released = true;
2010
+ const remaining = (_nullishCoalesce(this._unsettledConnectorOperations.get(key), () => ( 1))) - 1;
2011
+ if (remaining > 0) {
2012
+ this._unsettledConnectorOperations.set(key, remaining);
2013
+ } else {
2014
+ this._unsettledConnectorOperations.delete(key);
2015
+ }
2016
+ if (this._unsettledConnectorOperations.size === 0) {
2017
+ for (const resolve of this._connectorIdleWaiters) resolve();
2018
+ this._connectorIdleWaiters.clear();
2019
+ }
2020
+ };
2021
+ }
1480
2022
  static _normalizeAllNetworkItem(method, item) {
1481
2023
  if (method !== "btcGetAddress" && method !== "btcGetPublicKey") {
1482
2024
  return item;
@@ -1495,18 +2037,14 @@ var _TrezorAdapter = class _TrezorAdapter {
1495
2037
  const { deviceId } = item;
1496
2038
  return typeof deviceId === "string" && deviceId.length > 0 ? deviceId : void 0;
1497
2039
  }
1498
- _callAllNetworkMethod(connectId, method, item) {
2040
+ _callAllNetworkMethod(connectId, method, item, bundleContext) {
1499
2041
  switch (method) {
1500
2042
  case "evmGetAddress":
1501
- return this.evmGetAddress(connectId, "", item);
1502
2043
  case "btcGetAddress":
1503
- return this.btcGetAddress(connectId, "", item);
1504
2044
  case "btcGetPublicKey":
1505
- return this.btcGetPublicKey(connectId, "", item);
1506
2045
  case "solGetAddress":
1507
- return this.solGetAddress(connectId, "", item);
1508
2046
  case "tronGetAddress":
1509
- return this.tronGetAddress(connectId, "", item);
2047
+ return this._callMethod(method, connectId, "", item, true, bundleContext);
1510
2048
  default:
1511
2049
  return Promise.resolve(
1512
2050
  _hwkadaptercore.failure.call(void 0,
@@ -1525,11 +2063,51 @@ var _TrezorAdapter = class _TrezorAdapter {
1525
2063
  _callWalletMethod(methodName, connectId, deviceId, params) {
1526
2064
  return this._callMethod(methodName, connectId, deviceId, params, true);
1527
2065
  }
1528
- _callDeviceManagerMethod(methodName, connectId, params) {
1529
- return this._callMethod(methodName, connectId, void 0, params, false);
2066
+ _callDeviceManagerMethod(methodName, connectId, params, operationContext) {
2067
+ const expectedIdentity = _optionalChain([operationContext, 'optionalAccess', _84 => _84.expectedDeviceIdentity]);
2068
+ if (expectedIdentity && (expectedIdentity.vendor !== "trezor" || expectedIdentity.type !== "deviceId")) {
2069
+ return Promise.resolve(
2070
+ _hwkadaptercore.failure.call(void 0,
2071
+ _hwkadaptercore.HardwareErrorCode.InvalidParams,
2072
+ "Trezor device-manager operations require a Trezor deviceId identity"
2073
+ )
2074
+ );
2075
+ }
2076
+ return this._callMethod(
2077
+ methodName,
2078
+ connectId,
2079
+ _optionalChain([expectedIdentity, 'optionalAccess', _85 => _85.value]),
2080
+ {
2081
+ ...params && typeof params === "object" ? params : {},
2082
+ knownConnections: _optionalChain([operationContext, 'optionalAccess', _86 => _86.knownConnections]),
2083
+ extra: _optionalChain([operationContext, 'optionalAccess', _87 => _87.extra]),
2084
+ allowDeviceSelection: _optionalChain([operationContext, 'optionalAccess', _88 => _88.allowDeviceSelection]),
2085
+ supportedTransports: _optionalChain([operationContext, 'optionalAccess', _89 => _89.supportedTransports]),
2086
+ ..._optionalChain([operationContext, 'optionalAccess', _90 => _90.operationId]) ? { operationId: operationContext.operationId } : {}
2087
+ },
2088
+ false
2089
+ );
1530
2090
  }
1531
- async _callMethod(methodName, connectId, deviceId, params, requiresWalletIntent) {
2091
+ async _callMethod(methodName, connectId, deviceId, params, requiresWalletIntent, bundleContext) {
1532
2092
  const call = _TrezorAdapter._normalizeCallArgs(connectId, deviceId, params);
2093
+ const commonParams = _TrezorAdapter._splitCommonParams(call.params);
2094
+ const positionalOperationId = _hwkadaptercore.isHardwareOperationId.call(void 0, call.connectId) ? call.connectId : void 0;
2095
+ if (positionalOperationId && commonParams.operationId && positionalOperationId !== commonParams.operationId) {
2096
+ return _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.InvalidParams, "Conflicting Trezor operation ids", {
2097
+ positionalOperationId,
2098
+ commonOperationId: commonParams.operationId
2099
+ });
2100
+ }
2101
+ const operationId = _nullishCoalesce(commonParams.operationId, () => ( positionalOperationId));
2102
+ let releaseOperationRetention;
2103
+ try {
2104
+ if (operationId) {
2105
+ call.connectId = this._operations.resolve(operationId).connectId;
2106
+ releaseOperationRetention = this._operations.retain(operationId);
2107
+ }
2108
+ } catch (error) {
2109
+ return this._errorToFailure(error);
2110
+ }
1533
2111
  debugLog("[TrezorAdapter][REQ]", {
1534
2112
  method: methodName,
1535
2113
  connectId: call.connectId || "(empty)",
@@ -1538,15 +2116,40 @@ var _TrezorAdapter = class _TrezorAdapter {
1538
2116
  });
1539
2117
  try {
1540
2118
  const response = await this._jobQueue.enqueue(
1541
- call.connectId,
1542
- (signal) => this._callWithRetry(
1543
- call.connectId,
1544
- methodName,
1545
- call.params,
1546
- requiresWalletIntent,
1547
- true,
1548
- signal
1549
- ),
2119
+ trezorQueueKey({ operationId, connectId: call.connectId }),
2120
+ async (signal) => {
2121
+ let effectiveConnectId = call.connectId;
2122
+ let selectionRequestId;
2123
+ try {
2124
+ if (!_optionalChain([bundleContext, 'optionalAccess', _91 => _91.connection]) && !operationId && deviceId && (!connectId || _optionalChain([commonParams, 'access', _92 => _92.connectionContext, 'optionalAccess', _93 => _93.knownConnections]) !== void 0)) {
2125
+ const resolved = await this._resolveExpectedDeviceConnectId(
2126
+ deviceId,
2127
+ signal,
2128
+ commonParams.connectionContext
2129
+ );
2130
+ effectiveConnectId = resolved.connectId;
2131
+ selectionRequestId = resolved.selectionRequestId;
2132
+ }
2133
+ } catch (error) {
2134
+ return this._errorToFailure(error);
2135
+ }
2136
+ const response2 = await this._callWithRetry(
2137
+ _nullishCoalesce(_optionalChain([bundleContext, 'optionalAccess', _94 => _94.connection, 'optionalAccess', _95 => _95.connectId]), () => ( effectiveConnectId)),
2138
+ methodName,
2139
+ call.params,
2140
+ deviceId || "",
2141
+ requiresWalletIntent,
2142
+ true,
2143
+ signal,
2144
+ operationId,
2145
+ selectionRequestId,
2146
+ bundleContext
2147
+ );
2148
+ if (!response2.success && selectionRequestId) {
2149
+ await this._releaseProvisionalConnection(effectiveConnectId, signal);
2150
+ }
2151
+ return response2;
2152
+ },
1550
2153
  {
1551
2154
  label: methodName,
1552
2155
  rejectIfBusy: true,
@@ -1556,7 +2159,7 @@ var _TrezorAdapter = class _TrezorAdapter {
1556
2159
  debugLog("[TrezorAdapter][RES]", {
1557
2160
  method: methodName,
1558
2161
  success: response.success,
1559
- payload: _TrezorAdapter._sanitizeForLog(response.payload, methodName)
2162
+ payload: _TrezorAdapter._responseForLog(response, methodName)
1560
2163
  });
1561
2164
  return response;
1562
2165
  } catch (error) {
@@ -1564,19 +2167,56 @@ var _TrezorAdapter = class _TrezorAdapter {
1564
2167
  debugLog("[TrezorAdapter][RES]", {
1565
2168
  method: methodName,
1566
2169
  success: false,
1567
- payload: _TrezorAdapter._sanitizeForLog(response.payload, methodName)
2170
+ payload: _TrezorAdapter._responseForLog(response, methodName)
1568
2171
  });
1569
2172
  return response;
2173
+ } finally {
2174
+ _optionalChain([releaseOperationRetention, 'optionalCall', _96 => _96()]);
1570
2175
  }
1571
2176
  }
1572
- async _callWithRetry(connectId, methodName, params, requiresWalletIntent, allowRetry, signal) {
1573
- const { passphraseState, useEmptyPassphrase, rest } = _TrezorAdapter._splitCommonParams(params);
2177
+ async _callWithRetry(connectId, methodName, params, expectedDeviceId, requiresWalletIntent, allowRetry, signal, operationId, selectionRequestId, bundleContext) {
2178
+ const { passphraseState, useEmptyPassphrase, rest, connectionContext } = _TrezorAdapter._splitCommonParams(params);
2179
+ let pendingBindingRequestId = selectionRequestId;
2180
+ let businessCallStarted = false;
1574
2181
  const restorePassphraseRequestContext = this._setPassphraseRequestContext(connectId, {
1575
2182
  passphraseState,
1576
2183
  useEmptyPassphrase
1577
2184
  });
1578
2185
  try {
1579
- const sessionId = await this._ensureSession(connectId, signal);
2186
+ if (_optionalChain([bundleContext, 'optionalAccess', _97 => _97.connection])) {
2187
+ const pinned = bundleContext.connection;
2188
+ if (this._sessions.get(pinned.connectId) !== pinned.sessionId) {
2189
+ return _hwkadaptercore.failure.call(void 0,
2190
+ _hwkadaptercore.HardwareErrorCode.DeviceDisconnected,
2191
+ "Trezor all-network connection ended"
2192
+ );
2193
+ }
2194
+ }
2195
+ const sessionId = operationId ? this._sessions.get(this._operations.resolve(operationId).connectId) : await this._ensureSession(connectId, signal);
2196
+ if (!sessionId) {
2197
+ if (operationId) {
2198
+ this._operations.end(operationId, "disconnect");
2199
+ return _hwkadaptercore.failure.call(void 0,
2200
+ _hwkadaptercore.HardwareErrorCode.OperationEnded,
2201
+ "Trezor operation connection is no longer active",
2202
+ { operationId, reason: "disconnect" }
2203
+ );
2204
+ }
2205
+ return _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.DeviceNotFound, "Trezor session was not found");
2206
+ }
2207
+ if (bundleContext && !bundleContext.connection) {
2208
+ bundleContext.connection = { connectId, sessionId };
2209
+ }
2210
+ if (expectedDeviceId) {
2211
+ const actualDeviceId = _optionalChain([this, 'access', _98 => _98._devices, 'access', _99 => _99.get, 'call', _100 => _100(connectId), 'optionalAccess', _101 => _101.deviceId]);
2212
+ if (!actualDeviceId || actualDeviceId !== expectedDeviceId) {
2213
+ return _hwkadaptercore.failure.call(void 0,
2214
+ _hwkadaptercore.HardwareErrorCode.DeviceMismatch,
2215
+ `Wrong device: expected ${expectedDeviceId}, got ${actualDeviceId || "unknown"}`,
2216
+ { expected: expectedDeviceId, actual: actualDeviceId || "" }
2217
+ );
2218
+ }
2219
+ }
1580
2220
  if (requiresWalletIntent && !passphraseState && useEmptyPassphrase !== true) {
1581
2221
  return _hwkadaptercore.failure.call(void 0,
1582
2222
  _hwkadaptercore.HardwareErrorCode.InvalidParams,
@@ -1591,39 +2231,85 @@ var _TrezorAdapter = class _TrezorAdapter {
1591
2231
  } else if (useEmptyPassphrase === true) {
1592
2232
  await _TrezorAdapter._abortable(signal, this._createFreshAppSession(sessionId, signal));
1593
2233
  }
2234
+ if (expectedDeviceId) {
2235
+ await this._emitVerifiedBinding(
2236
+ expectedDeviceId,
2237
+ connectId,
2238
+ pendingBindingRequestId,
2239
+ connectionContext,
2240
+ signal
2241
+ );
2242
+ pendingBindingRequestId = void 0;
2243
+ this._rememberVerifiedConnection(expectedDeviceId, connectId);
2244
+ }
2245
+ businessCallStarted = true;
1594
2246
  const result = await _TrezorAdapter._abortable(
1595
2247
  signal,
1596
- _TrezorAdapter._callConnector(this._connector, sessionId, methodName, rest)
2248
+ this._callConnector(sessionId, methodName, rest, signal)
1597
2249
  );
1598
2250
  return _hwkadaptercore.success.call(void 0, result);
1599
2251
  } catch (error) {
1600
2252
  if (signal.aborted) {
2253
+ if (pendingBindingRequestId) {
2254
+ this._emitBindingStatus(pendingBindingRequestId, "cancelled");
2255
+ pendingBindingRequestId = void 0;
2256
+ }
1601
2257
  return this._errorToFailure(error);
1602
2258
  }
1603
2259
  const code = _TrezorAdapter._errorCode(error);
1604
- if (allowRetry && code === _hwkadaptercore.HardwareErrorCode.DeviceDisconnected) {
2260
+ const willRetryStaleSession = allowRetry && (passphraseState || useEmptyPassphrase === true) && _TrezorAdapter._isStaleSessionError(code);
2261
+ if (pendingBindingRequestId && !willRetryStaleSession) {
2262
+ this._emitBindingStatus(pendingBindingRequestId, "failed");
2263
+ pendingBindingRequestId = void 0;
2264
+ }
2265
+ const ambiguousTransportFailure = code === _hwkadaptercore.HardwareErrorCode.DeviceDisconnected || code === _hwkadaptercore.HardwareErrorCode.OperationTimeout || code === _hwkadaptercore.HardwareErrorCode.TransportError;
2266
+ if (ambiguousTransportFailure) {
1605
2267
  this._sessions.delete(connectId);
1606
2268
  this._verifiedPassphraseSessionsByConnectId.delete(connectId);
1607
- return await this._callWithRetry(
1608
- connectId,
1609
- methodName,
1610
- params,
1611
- requiresWalletIntent,
1612
- false,
1613
- signal
1614
- );
2269
+ const mayHaveCompleted = businessCallStarted && !_hwkadaptercore.canReplayHardwareMethodAfterTransportFailure.call(void 0, methodName);
2270
+ const mayHaveCompletedMessage = `Trezor ${methodName} may have completed before the connection was lost`;
2271
+ if (operationId) {
2272
+ this._operations.end(operationId, "disconnect");
2273
+ const endedParams = { operationId, reason: "disconnect" };
2274
+ return mayHaveCompleted ? _hwkadaptercore.failure.call(void 0,
2275
+ _hwkadaptercore.HardwareErrorCode.OperationEnded,
2276
+ mayHaveCompletedMessage,
2277
+ _hwkadaptercore.operationMayHaveCompletedParams.call(void 0, methodName, endedParams),
2278
+ void 0,
2279
+ { scope: "unknown" }
2280
+ ) : _hwkadaptercore.failure.call(void 0,
2281
+ _hwkadaptercore.HardwareErrorCode.OperationEnded,
2282
+ "Trezor operation connection was lost",
2283
+ endedParams
2284
+ );
2285
+ }
2286
+ if (mayHaveCompleted) {
2287
+ return _hwkadaptercore.failure.call(void 0,
2288
+ code,
2289
+ mayHaveCompletedMessage,
2290
+ _hwkadaptercore.operationMayHaveCompletedParams.call(void 0, methodName),
2291
+ void 0,
2292
+ { scope: "unknown" }
2293
+ );
2294
+ }
1615
2295
  }
1616
- if (allowRetry && (passphraseState || useEmptyPassphrase === true) && _TrezorAdapter._isStaleSessionError(code)) {
2296
+ if (willRetryStaleSession) {
1617
2297
  if (passphraseState) {
1618
2298
  this._forgetVerifiedPassphraseSession(connectId, passphraseState);
1619
2299
  }
2300
+ const retryBindingRequestId = pendingBindingRequestId;
2301
+ pendingBindingRequestId = void 0;
1620
2302
  return await this._callWithRetry(
1621
2303
  connectId,
1622
2304
  methodName,
1623
2305
  params,
2306
+ expectedDeviceId,
1624
2307
  requiresWalletIntent,
1625
2308
  false,
1626
- signal
2309
+ signal,
2310
+ operationId,
2311
+ retryBindingRequestId,
2312
+ bundleContext
1627
2313
  );
1628
2314
  }
1629
2315
  debugLog("[TrezorAdapter][ERROR]", {
@@ -1634,36 +2320,249 @@ var _TrezorAdapter = class _TrezorAdapter {
1634
2320
  return this._errorToFailure(error);
1635
2321
  } finally {
1636
2322
  restorePassphraseRequestContext();
2323
+ if (pendingBindingRequestId) {
2324
+ this._emitBindingStatus(pendingBindingRequestId, signal.aborted ? "cancelled" : "failed");
2325
+ pendingBindingRequestId = void 0;
2326
+ }
1637
2327
  }
1638
2328
  }
1639
- async _ensureSession(connectId, signal) {
2329
+ async _ensureSession(connectId, signal, transportType) {
1640
2330
  const existing = this._sessions.get(connectId);
1641
2331
  if (existing) return existing;
1642
2332
  const pending = this._connectingPromises.get(connectId);
1643
2333
  if (pending) return pending;
2334
+ const stateGeneration = this._stateGeneration;
1644
2335
  const promise = (async () => {
2336
+ if (_optionalChain([signal, 'optionalAccess', _102 => _102.aborted])) {
2337
+ throw Object.assign(new Error("Trezor connection aborted"), {
2338
+ code: _hwkadaptercore.HardwareErrorCode.UserAborted
2339
+ });
2340
+ }
1645
2341
  try {
1646
- if (_optionalChain([signal, 'optionalAccess', _34 => _34.aborted])) {
1647
- throw Object.assign(new Error("Trezor connection aborted"), {
1648
- code: _hwkadaptercore.HardwareErrorCode.UserAborted
1649
- });
1650
- }
1651
- try {
1652
- return await this._connectSession(connectId, signal);
1653
- } catch (error) {
1654
- if (_TrezorAdapter._isConnectionUnavailableError(error)) {
1655
- this._sessions.delete(connectId);
1656
- this._verifiedPassphraseSessionsByConnectId.delete(connectId);
1657
- }
1658
- throw error;
2342
+ return await this._connectSession(connectId, signal, stateGeneration, transportType);
2343
+ } catch (error) {
2344
+ if (_TrezorAdapter._isConnectionUnavailableError(error)) {
2345
+ this._sessions.delete(connectId);
2346
+ this._verifiedPassphraseSessionsByConnectId.delete(connectId);
1659
2347
  }
1660
- } finally {
1661
- this._connectingPromises.delete(connectId);
1662
- this._disconnectRequested.delete(connectId);
2348
+ throw error;
1663
2349
  }
1664
2350
  })();
1665
2351
  this._connectingPromises.set(connectId, promise);
1666
- return promise;
2352
+ try {
2353
+ return await promise;
2354
+ } finally {
2355
+ if (this._connectingPromises.get(connectId) === promise) {
2356
+ this._connectingPromises.delete(connectId);
2357
+ }
2358
+ this._disconnectRequested.delete(connectId);
2359
+ }
2360
+ }
2361
+ /** An identity probe tears down only a session it opened; another caller's stays up. */
2362
+ _hasSessionOrConnect(connectId) {
2363
+ return this._sessions.has(connectId) || this._connectingPromises.has(connectId);
2364
+ }
2365
+ async _resolveExpectedDeviceConnectId(expectedDeviceId, signal, context) {
2366
+ const connectedMatch = Array.from(this._devices.values()).find(
2367
+ (device) => device.deviceId === expectedDeviceId && this._sessions.has(device.connectId)
2368
+ );
2369
+ if (connectedMatch) return { connectId: connectedMatch.connectId };
2370
+ const allowedTransports = this._allowedTransports(context);
2371
+ if (allowedTransports.includes("usb")) {
2372
+ await _TrezorAdapter._abortable(
2373
+ signal,
2374
+ this._ensureDevicePermission(void 0, expectedDeviceId, "usb")
2375
+ );
2376
+ }
2377
+ const candidates = allowedTransports.includes("usb") ? await _TrezorAdapter._abortable(
2378
+ signal,
2379
+ this._searchDevices({ transportType: "usb" }, signal)
2380
+ ) : [];
2381
+ const mismatchedDeviceIds = [];
2382
+ const knownConnection = this._knownDeviceConnections.get(expectedDeviceId);
2383
+ const knownUsbIds = _optionalChain([context, 'optionalAccess', _103 => _103.knownConnections]) !== void 0 ? context.knownConnections.flatMap(
2384
+ (connection) => connection.transport === "usb" ? [connection.connectId] : []
2385
+ ) : [_optionalChain([knownConnection, 'optionalAccess', _104 => _104.usbConnectId])].filter((id) => Boolean(id));
2386
+ const suppliedBleIds = _optionalChain([context, 'optionalAccess', _105 => _105.knownConnections, 'optionalAccess', _106 => _106.flatMap, 'call', _107 => _107(
2387
+ (connection) => connection.transport === "ble" ? [connection.connectId] : []
2388
+ )]);
2389
+ const knownBleIds = _optionalChain([suppliedBleIds, 'optionalAccess', _108 => _108.length]) ? suppliedBleIds : [_optionalChain([knownConnection, 'optionalAccess', _109 => _109.bleConnectId])].filter((id) => Boolean(id));
2390
+ const usbCandidates = candidates.filter(
2391
+ (device) => device.connectionType === "usb" && (!knownUsbIds.length || knownUsbIds.includes(device.connectId))
2392
+ );
2393
+ for (const candidate of usbCandidates) {
2394
+ let sessionId;
2395
+ const probeOpensSession = !this._hasSessionOrConnect(candidate.connectId);
2396
+ try {
2397
+ sessionId = await this._ensureSession(candidate.connectId, signal, "usb");
2398
+ const actualDeviceId = _nullishCoalesce(_optionalChain([this, 'access', _110 => _110._devices, 'access', _111 => _111.get, 'call', _112 => _112(candidate.connectId), 'optionalAccess', _113 => _113.deviceId]), () => ( ""));
2399
+ if (actualDeviceId === expectedDeviceId) return { connectId: candidate.connectId };
2400
+ mismatchedDeviceIds.push(actualDeviceId || "unknown");
2401
+ } catch (error) {
2402
+ if (signal.aborted) throw error;
2403
+ if (!_TrezorAdapter._isConnectionUnavailableError(error)) throw error;
2404
+ }
2405
+ if (sessionId && probeOpensSession) {
2406
+ await this._disconnectSession(candidate.connectId, sessionId);
2407
+ }
2408
+ }
2409
+ if (mismatchedDeviceIds.length) {
2410
+ throw _hwkadaptercore.createHwkError.call(void 0, {
2411
+ code: _hwkadaptercore.HardwareErrorCode.DeviceSearchMismatch,
2412
+ message: "The connected Trezor is not the wallet this operation needs. Unplug it and connect the right device.",
2413
+ params: { connectedDeviceIds: mismatchedDeviceIds }
2414
+ });
2415
+ }
2416
+ if (usbCandidates.length > 0) {
2417
+ throw _hwkadaptercore.createHwkError.call(void 0, {
2418
+ code: _hwkadaptercore.HardwareErrorCode.DeviceNotFound,
2419
+ message: "Trezor devices are present but none could be opened to check its identity."
2420
+ });
2421
+ }
2422
+ const [knownBleConnectId] = knownBleIds;
2423
+ if (knownBleConnectId && allowedTransports.includes("ble")) {
2424
+ await _TrezorAdapter._abortable(
2425
+ signal,
2426
+ this._ensureDevicePermission(knownBleConnectId, expectedDeviceId, "ble")
2427
+ );
2428
+ const probeOpensSession = !this._hasSessionOrConnect(knownBleConnectId);
2429
+ await this._ensureSession(knownBleConnectId, signal, "ble");
2430
+ const actualDeviceId = _optionalChain([this, 'access', _114 => _114._devices, 'access', _115 => _115.get, 'call', _116 => _116(knownBleConnectId), 'optionalAccess', _117 => _117.deviceId]);
2431
+ if (actualDeviceId === expectedDeviceId) return { connectId: knownBleConnectId };
2432
+ if (probeOpensSession) await this._disconnectSession(knownBleConnectId);
2433
+ throw _hwkadaptercore.createHwkError.call(void 0, {
2434
+ code: _hwkadaptercore.HardwareErrorCode.DeviceMismatch,
2435
+ message: "The bound Trezor Bluetooth device has a different identity"
2436
+ });
2437
+ }
2438
+ if (_optionalChain([context, 'optionalAccess', _118 => _118.supportedTransports]) && !context.supportedTransports.includes("ble")) {
2439
+ throw _hwkadaptercore.createHwkError.call(void 0, {
2440
+ code: _hwkadaptercore.HardwareErrorCode.DeviceNotFound,
2441
+ message: "This Trezor model has no Bluetooth transport; connect it over USB"
2442
+ });
2443
+ }
2444
+ if (_optionalChain([context, 'optionalAccess', _119 => _119.allowDeviceSelection]) === false) {
2445
+ throw _hwkadaptercore.createHwkError.call(void 0, {
2446
+ code: _hwkadaptercore.HardwareErrorCode.DeviceNotFound,
2447
+ message: "No known Trezor connection is available"
2448
+ });
2449
+ }
2450
+ return this._selectBleDeviceForBinding(expectedDeviceId, signal, context, "missing-binding");
2451
+ }
2452
+ async _selectBleDeviceForBinding(expectedDeviceId, signal, context, reason) {
2453
+ const availableTransports = this._allowedTransports(context);
2454
+ const allowUsbFallback = reason !== "manual-rebind" && availableTransports.includes("usb");
2455
+ const knownUsbIds = _optionalChain([context, 'optionalAccess', _120 => _120.knownConnections]) ? context.knownConnections.flatMap(
2456
+ (connection) => connection.transport === "usb" ? [connection.connectId] : []
2457
+ ) : [_optionalChain([this, 'access', _121 => _121._knownDeviceConnections, 'access', _122 => _122.get, 'call', _123 => _123(expectedDeviceId), 'optionalAccess', _124 => _124.usbConnectId])];
2458
+ if (availableTransports.includes("ble")) {
2459
+ await _TrezorAdapter._abortable(
2460
+ signal,
2461
+ this._ensureDevicePermission(void 0, expectedDeviceId, "ble")
2462
+ );
2463
+ }
2464
+ const bleCandidates = (await _TrezorAdapter._abortable(
2465
+ signal,
2466
+ this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal)
2467
+ )).filter((device) => device.connectionType === "ble");
2468
+ if (signal.aborted) throw signal.reason;
2469
+ const rejectedConnectIds = /* @__PURE__ */ new Set();
2470
+ const bindingSessionId = this._uiRegistry.createRequestId();
2471
+ let rejectedConnectId;
2472
+ while (availableTransports.includes("ble") && this._emitter.listenerCount(_hwkadaptercore.UI_REQUEST.REQUEST_SELECT_DEVICE)) {
2473
+ const { device: selected, requestId } = await _hwkadaptercore.requestBleDeviceSelection.call(void 0, {
2474
+ emitter: this._emitter,
2475
+ registry: this._uiRegistry,
2476
+ signal,
2477
+ allowUsbFallback,
2478
+ scan: async () => {
2479
+ if (allowUsbFallback) {
2480
+ const usbCandidates = (await this._searchDevices({ transportType: "usb" }, signal)).filter(
2481
+ (device) => device.connectionType === "usb" && !rejectedConnectIds.has(device.connectId)
2482
+ );
2483
+ const candidate = _nullishCoalesce(usbCandidates.find((device) => knownUsbIds.includes(device.connectId)), () => ( usbCandidates[0]));
2484
+ if (candidate) return [candidate];
2485
+ }
2486
+ return (await this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal)).filter(
2487
+ (device) => device.connectionType === "ble" && !rejectedConnectIds.has(device.connectId)
2488
+ );
2489
+ },
2490
+ request: {
2491
+ devices: bleCandidates.filter((device) => !rejectedConnectIds.has(device.connectId)),
2492
+ bindingSessionId,
2493
+ rejectedConnectId,
2494
+ context: {
2495
+ kind: "bind-connection",
2496
+ transport: "ble",
2497
+ reason
2498
+ },
2499
+ extra: _optionalChain([context, 'optionalAccess', _125 => _125.extra]),
2500
+ operationId: this._activeOperationId()
2501
+ }
2502
+ });
2503
+ let probeOpensSession = false;
2504
+ try {
2505
+ if (reason === "manual-rebind") {
2506
+ this._operations.endByConnectionKey(selected.connectId, "explicit");
2507
+ await this._releaseProvisionalConnection(selected.connectId, signal);
2508
+ }
2509
+ probeOpensSession = !this._hasSessionOrConnect(selected.connectId);
2510
+ await this._ensureSession(selected.connectId, signal, selected.connectionType);
2511
+ } catch (error) {
2512
+ this._emitBindingStatus(requestId, signal.aborted ? "cancelled" : "failed");
2513
+ throw error;
2514
+ }
2515
+ if (_optionalChain([this, 'access', _126 => _126._devices, 'access', _127 => _127.get, 'call', _128 => _128(selected.connectId), 'optionalAccess', _129 => _129.deviceId]) !== expectedDeviceId) {
2516
+ if (probeOpensSession) await this._disconnectSession(selected.connectId);
2517
+ rejectedConnectId = selected.connectId;
2518
+ rejectedConnectIds.add(selected.connectId);
2519
+ continue;
2520
+ }
2521
+ if (selected.connectionType === "usb") {
2522
+ this._emitBindingStatus(requestId, "cancelled");
2523
+ return { connectId: selected.connectId };
2524
+ }
2525
+ return { connectId: selected.connectId, selectionRequestId: requestId };
2526
+ }
2527
+ throw _hwkadaptercore.createHwkError.call(void 0, {
2528
+ code: _hwkadaptercore.HardwareErrorCode.DeviceNotFound,
2529
+ message: "No readable Trezor device is available"
2530
+ });
2531
+ }
2532
+ _emitBindingStatus(selectionRequestId, status) {
2533
+ _hwkadaptercore.emitDeviceBindingStatus.call(void 0, this._emitter, selectionRequestId, status);
2534
+ }
2535
+ _rememberVerifiedConnection(deviceId, connectId) {
2536
+ const device = this._devices.get(connectId);
2537
+ if (!device || device.deviceId !== deviceId) return;
2538
+ const known = _nullishCoalesce(this._knownDeviceConnections.get(deviceId), () => ( { deviceId }));
2539
+ if (device.connectionType === "ble") {
2540
+ known.bleConnectId = connectId;
2541
+ } else if (device.connectionType === "usb" && _optionalChain([device, 'access', _130 => _130.capabilities, 'optionalAccess', _131 => _131.persistentDeviceIdentity])) {
2542
+ known.usbConnectId = connectId;
2543
+ }
2544
+ this._knownDeviceConnections.set(deviceId, known);
2545
+ }
2546
+ async _emitVerifiedBinding(deviceId, connectId, selectionRequestId, context, signal) {
2547
+ if (!selectionRequestId) return false;
2548
+ const device = this._devices.get(connectId);
2549
+ if (!device || device.deviceId !== deviceId || device.connectionType !== "ble") {
2550
+ this._emitBindingStatus(selectionRequestId, "cancelled");
2551
+ return false;
2552
+ }
2553
+ const outcome = await _hwkadaptercore.requestSaveDeviceBinding.call(void 0,
2554
+ this._emitter,
2555
+ this._uiRegistry,
2556
+ {
2557
+ selectionRequestId,
2558
+ connection: { transport: "ble", connectId },
2559
+ identity: { vendor: "trezor", type: "deviceId", value: deviceId },
2560
+ extra: _optionalChain([context, 'optionalAccess', _132 => _132.extra]),
2561
+ operationId: this._activeOperationId()
2562
+ },
2563
+ signal
2564
+ );
2565
+ return outcome.saved;
1667
2566
  }
1668
2567
  /**
1669
2568
  * Pin the device's active wallet session to `passphraseState` (the target
@@ -1685,12 +2584,21 @@ var _TrezorAdapter = class _TrezorAdapter {
1685
2584
  if (reused) return;
1686
2585
  const created = await _TrezorAdapter._abortable(
1687
2586
  signal,
1688
- _TrezorAdapter._callConnector(this._connector, sessionId, "__thpCreateSession", {
1689
- passphraseMode: "prompt"
1690
- })
2587
+ this._callConnector(
2588
+ sessionId,
2589
+ "__thpCreateSession",
2590
+ {
2591
+ passphraseMode: "prompt"
2592
+ },
2593
+ signal
2594
+ )
1691
2595
  );
1692
- if (_optionalChain([created, 'optionalAccess', _35 => _35.protocol]) === "thp" && !created.thpSessionId) return;
1693
- if (_optionalChain([created, 'optionalAccess', _36 => _36.protocol]) !== "thp" && _optionalChain([created, 'optionalAccess', _37 => _37.protocol]) !== "v1") return;
2596
+ if (_optionalChain([created, 'optionalAccess', _133 => _133.protocol]) === "thp" && !created.thpSessionId || _optionalChain([created, 'optionalAccess', _134 => _134.protocol]) !== "thp" && _optionalChain([created, 'optionalAccess', _135 => _135.protocol]) !== "v1") {
2597
+ throw _hwkadaptercore.createHwkError.call(void 0, {
2598
+ code: _hwkadaptercore.HardwareErrorCode.TransportError,
2599
+ message: "Cannot verify the requested Trezor wallet session"
2600
+ });
2601
+ }
1694
2602
  const state = await this._deriveState(sessionId, signal);
1695
2603
  if (state !== passphraseState) {
1696
2604
  throw Object.assign(
@@ -1704,13 +2612,13 @@ var _TrezorAdapter = class _TrezorAdapter {
1704
2612
  }
1705
2613
  _rememberVerifiedPassphraseSession(connectId, passphraseState, sessionId, created) {
1706
2614
  let session;
1707
- if (_optionalChain([created, 'optionalAccess', _38 => _38.protocol]) === "thp" && typeof created.thpSessionId === "string") {
2615
+ if (_optionalChain([created, 'optionalAccess', _136 => _136.protocol]) === "thp" && typeof created.thpSessionId === "string") {
1708
2616
  session = {
1709
2617
  sessionId,
1710
2618
  protocol: "thp",
1711
2619
  thpSessionId: created.thpSessionId
1712
2620
  };
1713
- } else if (_optionalChain([created, 'optionalAccess', _39 => _39.protocol]) === "v1") {
2621
+ } else if (_optionalChain([created, 'optionalAccess', _137 => _137.protocol]) === "v1") {
1714
2622
  session = {
1715
2623
  sessionId,
1716
2624
  protocol: "v1"
@@ -1730,7 +2638,7 @@ var _TrezorAdapter = class _TrezorAdapter {
1730
2638
  }
1731
2639
  }
1732
2640
  async _reuseVerifiedPassphraseSession(connectId, sessionId, passphraseState, signal) {
1733
- const cached = _optionalChain([this, 'access', _40 => _40._verifiedPassphraseSessionsByConnectId, 'access', _41 => _41.get, 'call', _42 => _42(connectId), 'optionalAccess', _43 => _43.get, 'call', _44 => _44(passphraseState)]);
2641
+ const cached = _optionalChain([this, 'access', _138 => _138._verifiedPassphraseSessionsByConnectId, 'access', _139 => _139.get, 'call', _140 => _140(connectId), 'optionalAccess', _141 => _141.get, 'call', _142 => _142(passphraseState)]);
1734
2642
  if (!cached || cached.sessionId !== sessionId) {
1735
2643
  this._forgetVerifiedPassphraseSession(connectId, passphraseState);
1736
2644
  return false;
@@ -1740,9 +2648,14 @@ var _TrezorAdapter = class _TrezorAdapter {
1740
2648
  if (!cached.thpSessionId) return false;
1741
2649
  await _TrezorAdapter._abortable(
1742
2650
  signal,
1743
- _TrezorAdapter._callConnector(this._connector, sessionId, "__thpSelectSession", {
1744
- thpSessionId: cached.thpSessionId
1745
- })
2651
+ this._callConnector(
2652
+ sessionId,
2653
+ "__thpSelectSession",
2654
+ {
2655
+ thpSessionId: cached.thpSessionId
2656
+ },
2657
+ signal
2658
+ )
1746
2659
  );
1747
2660
  }
1748
2661
  const state = await this._deriveState(sessionId, signal);
@@ -1760,9 +2673,14 @@ var _TrezorAdapter = class _TrezorAdapter {
1760
2673
  async _createFreshAppSession(sessionId, signal) {
1761
2674
  await _TrezorAdapter._abortable(
1762
2675
  signal,
1763
- _TrezorAdapter._callConnector(this._connector, sessionId, "__thpCreateSession", {
1764
- passphraseMode: "empty"
1765
- })
2676
+ this._callConnector(
2677
+ sessionId,
2678
+ "__thpCreateSession",
2679
+ {
2680
+ passphraseMode: "empty"
2681
+ },
2682
+ signal
2683
+ )
1766
2684
  );
1767
2685
  }
1768
2686
  /**
@@ -1777,12 +2695,17 @@ var _TrezorAdapter = class _TrezorAdapter {
1777
2695
  async _deriveState(sessionId, signal) {
1778
2696
  const derived = await _TrezorAdapter._abortable(
1779
2697
  signal,
1780
- _TrezorAdapter._callConnector(this._connector, sessionId, "btcGetPublicKey", {
1781
- path: "m/44'/0'/0'",
1782
- showOnDevice: false
1783
- })
2698
+ this._callConnector(
2699
+ sessionId,
2700
+ "btcGetPublicKey",
2701
+ {
2702
+ path: "m/44'/0'/0'",
2703
+ showOnDevice: false
2704
+ },
2705
+ signal
2706
+ )
1784
2707
  );
1785
- const state = _optionalChain([derived, 'optionalAccess', _45 => _45.publicKey]);
2708
+ const state = _optionalChain([derived, 'optionalAccess', _143 => _143.publicKey]);
1786
2709
  if (!state) {
1787
2710
  throw Object.assign(new Error("Failed to derive passphrase state (wallet public key)"), {
1788
2711
  code: _hwkadaptercore.HardwareErrorCode.UnknownError
@@ -1790,25 +2713,36 @@ var _TrezorAdapter = class _TrezorAdapter {
1790
2713
  }
1791
2714
  return state;
1792
2715
  }
1793
- async _resolvePassphraseState(connectId, passphraseState, signal) {
2716
+ async _resolvePassphraseState(connectId, passphraseState, signal, operationId) {
1794
2717
  try {
1795
- const sessionId = await this._ensureSession(connectId, signal);
2718
+ const sessionId = operationId ? this._sessions.get(this._operations.resolve(operationId).connectId) : await this._ensureSession(connectId, signal);
2719
+ if (!sessionId) {
2720
+ return _hwkadaptercore.failure.call(void 0,
2721
+ _hwkadaptercore.HardwareErrorCode.OperationEnded,
2722
+ "Trezor operation connection is no longer active"
2723
+ );
2724
+ }
1796
2725
  if (passphraseState) {
1797
2726
  await this._alignAppSession(connectId, sessionId, passphraseState, signal);
1798
2727
  return _hwkadaptercore.success.call(void 0, passphraseState);
1799
2728
  }
1800
2729
  const created = await _TrezorAdapter._abortable(
1801
2730
  signal,
1802
- _TrezorAdapter._callConnector(this._connector, sessionId, "__thpCreateSession", {
1803
- passphraseMode: "prompt"
1804
- })
2731
+ this._callConnector(
2732
+ sessionId,
2733
+ "__thpCreateSession",
2734
+ {
2735
+ passphraseMode: "prompt"
2736
+ },
2737
+ signal
2738
+ )
1805
2739
  );
1806
2740
  const state = await this._deriveState(sessionId, signal);
1807
2741
  const features = await _TrezorAdapter._abortable(
1808
2742
  signal,
1809
- _TrezorAdapter._callConnector(this._connector, sessionId, "getFeatures", { refresh: true })
2743
+ this._callConnector(sessionId, "getFeatures", { refresh: true }, signal)
1810
2744
  );
1811
- if (_optionalChain([features, 'optionalAccess', _46 => _46.passphrase_protection]) !== true) {
2745
+ if (_optionalChain([features, 'optionalAccess', _144 => _144.passphrase_protection]) !== true) {
1812
2746
  return _hwkadaptercore.success.call(void 0, null);
1813
2747
  }
1814
2748
  this._rememberVerifiedPassphraseSession(connectId, state, sessionId, created);
@@ -1856,7 +2790,16 @@ var _TrezorAdapter = class _TrezorAdapter {
1856
2790
  }
1857
2791
  const trustedNumericCode = typeof typed.code === "number" && KNOWN_HARDWARE_ERROR_CODES.has(typed.code) ? typed.code : void 0;
1858
2792
  const code = _nullishCoalesce(_nullishCoalesce(trustedNumericCode, () => ( _TrezorAdapter._mapTrezorFailureCode(error))), () => ( _hwkadaptercore.HardwareErrorCode.UnknownError));
1859
- return _hwkadaptercore.failure.call(void 0, code, _nullishCoalesce(typed.message, () => ( String(error))));
2793
+ const stampedOrigin = _optionalChain([error, 'optionalAccess', _145 => _145.origin]);
2794
+ const origin = stampedOrigin === "device" || stampedOrigin === "transport" || stampedOrigin === "host" ? stampedOrigin : _hwkadaptercore.defaultOriginForCode.call(void 0, code);
2795
+ const params = typed.params && typeof typed.params === "object" ? typed.params : void 0;
2796
+ return _hwkadaptercore.failure.call(void 0,
2797
+ code,
2798
+ _nullishCoalesce(typed.message, () => ( String(error))),
2799
+ params,
2800
+ origin,
2801
+ _hwkadaptercore.isHwkRecoveryHint.call(void 0, typed.recovery) ? typed.recovery : void 0
2802
+ );
1860
2803
  }
1861
2804
  /**
1862
2805
  * Emit `REQUEST_DEVICE_PERMISSION` and await the host's
@@ -1871,29 +2814,33 @@ var _TrezorAdapter = class _TrezorAdapter {
1871
2814
  * - no `connectId` → environment-level check (scan / picker)
1872
2815
  * - with `connectId` → device-level check (per-call gating)
1873
2816
  */
1874
- async _ensureDevicePermission(connectId, deviceId) {
2817
+ async _ensureDevicePermission(connectId, deviceId, requestedTransport) {
1875
2818
  if (!this._emitter.listenerCount(_hwkadaptercore.UI_REQUEST.REQUEST_DEVICE_PERMISSION)) {
1876
2819
  return;
1877
2820
  }
1878
- const transportType = _nullishCoalesce(this.activeTransport, () => ( "usb"));
2821
+ const transportType = _nullishCoalesce(_nullishCoalesce(requestedTransport, () => ( this.activeTransport)), () => ( "usb"));
2822
+ const operationId = this._activeOperationId();
1879
2823
  const waitPromise = this._uiRegistry.wait(
1880
2824
  _hwkadaptercore.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
1881
- { timeoutMs: 6e4 }
2825
+ { timeoutMs: 6e4, operationId }
1882
2826
  );
1883
2827
  this._emitter.emit(_hwkadaptercore.UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
1884
2828
  type: _hwkadaptercore.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
1885
- payload: { transportType, connectId, deviceId }
2829
+ payload: { transportType, connectId, deviceId, operationId }
1886
2830
  });
1887
- const { granted } = await waitPromise;
2831
+ const { granted, reason } = await waitPromise;
1888
2832
  if (!granted) {
1889
2833
  throw Object.assign(new Error("Device permission denied"), {
1890
- code: _hwkadaptercore.HardwareErrorCode.DevicePermissionDenied
2834
+ code: _hwkadaptercore.HardwareErrorCode.DevicePermissionDenied,
2835
+ ...reason ? { params: { permissionDeniedReason: reason } } : {}
1891
2836
  });
1892
2837
  }
1893
2838
  }
1894
2839
  };
1895
2840
  // Keys are matched after normalizeLogKey, so snake_case/camelCase both hit.
1896
2841
  _TrezorAdapter._sensitiveLogKeys = /* @__PURE__ */ new Set([
2842
+ "extra",
2843
+ "knownconnections",
1897
2844
  "credential",
1898
2845
  "credentials",
1899
2846
  "entropy",
@@ -2012,7 +2959,7 @@ async function fetchDefinitionHex(url, fetchImpl) {
2012
2959
  }
2013
2960
  return arrayBufferToHex(await response.arrayBuffer());
2014
2961
  });
2015
- } catch (e5) {
2962
+ } catch (e7) {
2016
2963
  return void 0;
2017
2964
  }
2018
2965
  }
@@ -2041,7 +2988,7 @@ async function fetchSolanaTokenDefinition({
2041
2988
  }
2042
2989
  return Buffer.from(await response.arrayBuffer()).toString("hex");
2043
2990
  });
2044
- } catch (e6) {
2991
+ } catch (e8) {
2045
2992
  return void 0;
2046
2993
  }
2047
2994
  }