@onekeyfe/hwk-trezor-adapter 1.2.4 → 1.2.5-alpha.0

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