Skip to main content

ton_connect_core/
http_session.rs

1//! Durable HTTP bridge session identity and replay state.
2
3use serde::{Deserialize, Deserializer, Serialize, de};
4use thiserror::Error;
5
6use crate::{
7    ClientId, HttpBridgeUrl, PersistedSessionKeyPair, RawAccountAddress, SessionCrypto,
8    SessionKeyPairError, WalletSessionPhase, WalletSessionState,
9};
10
11/// Confidential state required to resume one wallet-side HTTP bridge session.
12///
13/// The serialized value contains the session secret key and must receive the
14/// same storage protection as other authentication credentials.
15#[derive(Serialize)]
16#[serde(rename_all = "camelCase", deny_unknown_fields)]
17pub struct PersistedHttpSession {
18    key_pair: PersistedSessionKeyPair,
19    peer_client_id: ClientId,
20    bridge_url: HttpBridgeUrl,
21    reducer: WalletSessionState,
22    connected_address: Option<RawAccountAddress>,
23    last_bridge_event_id: Option<String>,
24}
25
26#[derive(Deserialize)]
27#[serde(rename_all = "camelCase", deny_unknown_fields)]
28struct PersistedHttpSessionWire {
29    key_pair: PersistedSessionKeyPair,
30    peer_client_id: ClientId,
31    bridge_url: HttpBridgeUrl,
32    reducer: WalletSessionState,
33    connected_address: Option<RawAccountAddress>,
34    last_bridge_event_id: Option<String>,
35}
36
37impl<'de> Deserialize<'de> for PersistedHttpSession {
38    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
39    where
40        D: Deserializer<'de>,
41    {
42        let wire = PersistedHttpSessionWire::deserialize(deserializer)?;
43        validate_event_id(wire.last_bridge_event_id.as_deref()).map_err(de::Error::custom)?;
44        validate_account_binding(wire.reducer.phase(), wire.connected_address)
45            .map_err(de::Error::custom)?;
46        let _ = SessionCrypto::from_persisted(&wire.key_pair).map_err(de::Error::custom)?;
47        Ok(Self {
48            key_pair: wire.key_pair,
49            peer_client_id: wire.peer_client_id,
50            bridge_url: wire.bridge_url,
51            reducer: wire.reducer,
52            connected_address: wire.connected_address,
53            last_bridge_event_id: wire.last_bridge_event_id,
54        })
55    }
56}
57
58impl PersistedHttpSession {
59    /// Captures a complete resumable session snapshot.
60    pub fn new(
61        crypto: &SessionCrypto,
62        peer_client_id: ClientId,
63        bridge_url: HttpBridgeUrl,
64        reducer: WalletSessionState,
65        connected_address: Option<RawAccountAddress>,
66        last_bridge_event_id: Option<String>,
67    ) -> Result<Self, HttpSessionError> {
68        validate_event_id(last_bridge_event_id.as_deref())?;
69        validate_account_binding(reducer.phase(), connected_address)?;
70        Ok(Self {
71            key_pair: crypto.persisted_keypair(),
72            peer_client_id,
73            bridge_url,
74            reducer,
75            connected_address,
76            last_bridge_event_id,
77        })
78    }
79
80    /// Restores and verifies the local session crypto identity.
81    pub fn restore_crypto(&self) -> Result<SessionCrypto, HttpSessionError> {
82        SessionCrypto::from_persisted(&self.key_pair).map_err(Into::into)
83    }
84
85    /// Returns the dApp bridge client identifier fixed for this session.
86    #[must_use]
87    pub const fn peer_client_id(&self) -> ClientId {
88        self.peer_client_id
89    }
90
91    /// Returns the bridge base used by this session.
92    #[must_use]
93    pub const fn bridge_url(&self) -> &HttpBridgeUrl {
94        &self.bridge_url
95    }
96
97    /// Returns the durable request/event reducer state.
98    #[must_use]
99    pub const fn reducer(&self) -> &WalletSessionState {
100        &self.reducer
101    }
102
103    /// Returns the account fixed for the connected session lifetime.
104    #[must_use]
105    pub const fn connected_address(&self) -> Option<RawAccountAddress> {
106        self.connected_address
107    }
108
109    /// Returns the SSE cursor to use on the next subscription.
110    #[must_use]
111    pub fn last_bridge_event_id(&self) -> Option<&str> {
112        self.last_bridge_event_id.as_deref()
113    }
114
115    /// Updates the SSE cursor after the surrounding state is durably committed.
116    pub fn set_last_bridge_event_id(
117        &mut self,
118        value: Option<String>,
119    ) -> Result<(), HttpSessionError> {
120        validate_event_id(value.as_deref())?;
121        self.last_bridge_event_id = value;
122        Ok(())
123    }
124
125    /// Replaces the reducer after the prepared transition is durably committed.
126    pub fn set_reducer(
127        &mut self,
128        reducer: WalletSessionState,
129        connected_address: Option<RawAccountAddress>,
130    ) -> Result<(), HttpSessionError> {
131        validate_account_binding(reducer.phase(), connected_address)?;
132        self.reducer = reducer;
133        self.connected_address = connected_address;
134        Ok(())
135    }
136}
137
138/// Persisted HTTP bridge session is malformed or cryptographically inconsistent.
139#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
140pub enum HttpSessionError {
141    /// Persisted public and secret session keys do not match.
142    #[error(transparent)]
143    InvalidKeyPair(#[from] SessionKeyPairError),
144    /// SSE cursor contains characters forbidden by the `EventSource` model.
145    #[error("bridge event id must not contain null, CR, or LF characters")]
146    InvalidEventId,
147    /// Connected reducer state has no immutable account identity, or pending
148    /// state exposes one before connect succeeds.
149    #[error("persisted session account does not match its lifecycle phase")]
150    InvalidAccountBinding,
151}
152
153const fn validate_account_binding(
154    phase: WalletSessionPhase,
155    address: Option<RawAccountAddress>,
156) -> Result<(), HttpSessionError> {
157    match (phase, address) {
158        (WalletSessionPhase::PendingConnect, None)
159        | (WalletSessionPhase::Connected, Some(_))
160        | (WalletSessionPhase::Disconnected, None | Some(_)) => Ok(()),
161        (WalletSessionPhase::PendingConnect, Some(_)) | (WalletSessionPhase::Connected, None) => {
162            Err(HttpSessionError::InvalidAccountBinding)
163        }
164    }
165}
166
167fn validate_event_id(value: Option<&str>) -> Result<(), HttpSessionError> {
168    if value.is_some_and(|value| value.contains(['\0', '\r', '\n'])) {
169        Err(HttpSessionError::InvalidEventId)
170    } else {
171        Ok(())
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178    use crate::{WalletEventKind, WalletSessionState};
179
180    #[test]
181    fn serialized_session_restores_crypto_reducer_and_cursor()
182    -> Result<(), Box<dyn std::error::Error>> {
183        let local = SessionCrypto::generate()?;
184        let peer = SessionCrypto::generate()?;
185        let reducer = WalletSessionState::pending_connect()
186            .prepare_event(WalletEventKind::Connect)?
187            .into_state();
188        let persisted = PersistedHttpSession::new(
189            &local,
190            peer.client_id(),
191            HttpBridgeUrl::try_from("https://bridge.example/bridge")?,
192            reducer.clone(),
193            Some(RawAccountAddress::new(0, [9_u8; 32])),
194            Some("41".to_owned()),
195        )?;
196        let encoded = serde_json::to_vec(&persisted)?;
197        let decoded = serde_json::from_slice::<PersistedHttpSession>(&encoded)?;
198        let restored = decoded.restore_crypto()?;
199
200        assert_eq!(restored.client_id(), local.client_id());
201        assert_eq!(decoded.peer_client_id(), peer.client_id());
202        assert_eq!(decoded.reducer(), &reducer);
203        assert_eq!(
204            decoded.connected_address(),
205            Some(RawAccountAddress::new(0, [9_u8; 32]))
206        );
207        assert_eq!(decoded.last_bridge_event_id(), Some("41"));
208        assert_eq!(
209            decoded.bridge_url().as_str(),
210            "https://bridge.example/bridge"
211        );
212        Ok(())
213    }
214
215    #[test]
216    fn event_cursor_rejects_eventsource_control_characters()
217    -> Result<(), Box<dyn std::error::Error>> {
218        let local = SessionCrypto::generate()?;
219        let peer = SessionCrypto::generate()?;
220        let bridge = HttpBridgeUrl::try_from("https://bridge.example/bridge")?;
221        for invalid in ["a\0b", "a\rb", "a\nb"] {
222            assert!(matches!(
223                PersistedHttpSession::new(
224                    &local,
225                    peer.client_id(),
226                    bridge.clone(),
227                    WalletSessionState::pending_connect(),
228                    None,
229                    Some(invalid.to_owned()),
230                ),
231                Err(HttpSessionError::InvalidEventId)
232            ));
233        }
234        Ok(())
235    }
236
237    #[test]
238    fn connected_phase_requires_a_fixed_account() -> Result<(), Box<dyn std::error::Error>> {
239        let local = SessionCrypto::generate()?;
240        let peer = SessionCrypto::generate()?;
241        let connected = WalletSessionState::pending_connect()
242            .prepare_event(WalletEventKind::Connect)?
243            .into_state();
244        let bridge = HttpBridgeUrl::try_from("https://bridge.example/bridge")?;
245
246        assert!(matches!(
247            PersistedHttpSession::new(
248                &local,
249                peer.client_id(),
250                bridge.clone(),
251                connected,
252                None,
253                None
254            ),
255            Err(HttpSessionError::InvalidAccountBinding)
256        ));
257        assert!(matches!(
258            PersistedHttpSession::new(
259                &local,
260                peer.client_id(),
261                bridge,
262                WalletSessionState::pending_connect(),
263                Some(RawAccountAddress::new(0, [1_u8; 32])),
264                None,
265            ),
266            Err(HttpSessionError::InvalidAccountBinding)
267        ));
268        Ok(())
269    }
270
271    #[test]
272    fn failed_session_updates_do_not_corrupt_the_persisted_snapshot()
273    -> Result<(), Box<dyn std::error::Error>> {
274        let local = SessionCrypto::generate()?;
275        let peer = SessionCrypto::generate()?;
276        let bridge = HttpBridgeUrl::try_from("https://bridge.example/bridge")?;
277        let mut persisted = PersistedHttpSession::new(
278            &local,
279            peer.client_id(),
280            bridge,
281            WalletSessionState::pending_connect(),
282            None,
283            Some("7".to_owned()),
284        )?;
285
286        assert_eq!(
287            persisted.set_last_bridge_event_id(Some("bad\nvalue".to_owned())),
288            Err(HttpSessionError::InvalidEventId)
289        );
290        assert_eq!(persisted.last_bridge_event_id(), Some("7"));
291        persisted.set_last_bridge_event_id(Some("8".to_owned()))?;
292        assert_eq!(persisted.last_bridge_event_id(), Some("8"));
293
294        let connected = WalletSessionState::pending_connect()
295            .prepare_event(WalletEventKind::Connect)?
296            .into_state();
297        assert_eq!(
298            persisted.set_reducer(connected.clone(), None),
299            Err(HttpSessionError::InvalidAccountBinding)
300        );
301        assert_eq!(
302            persisted.reducer().phase(),
303            WalletSessionPhase::PendingConnect
304        );
305        assert_eq!(persisted.connected_address(), None);
306
307        let address = RawAccountAddress::new(0, [3_u8; 32]);
308        persisted.set_reducer(connected, Some(address))?;
309        assert_eq!(persisted.reducer().phase(), WalletSessionPhase::Connected);
310        assert_eq!(persisted.connected_address(), Some(address));
311        Ok(())
312    }
313}