Skip to main content

ton_connect_core/
session.rs

1use std::fmt;
2
3use crypto_box::{Nonce, PublicKey, SalsaBox, SecretKey, aead::Aead};
4use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
5use thiserror::Error;
6use zeroize::{Zeroize, Zeroizing};
7
8use crate::ClientId;
9
10const KEY_LENGTH: usize = 32;
11const NONCE_LENGTH: usize = 24;
12const AUTHENTICATION_TAG_LENGTH: usize = 16;
13const MIN_ENCRYPTED_MESSAGE_LENGTH: usize = NONCE_LENGTH + AUTHENTICATION_TAG_LENGTH;
14
15/// A failure to restore persisted TON Connect session key material.
16#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
17pub enum SessionKeyPairError {
18    /// The serialized secret key was not exactly 32 lowercase-hex bytes.
19    #[error("session secret key must be exactly 64 lowercase hexadecimal characters")]
20    InvalidSecretKey,
21    /// The persisted public key does not correspond to the persisted secret key.
22    #[error("persisted session public and secret keys do not match")]
23    PublicKeyMismatch,
24}
25
26/// A session encryption or decryption failure.
27#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
28pub enum SessionCryptoError {
29    /// The platform cryptographically secure random source was unavailable.
30    #[error("platform secure random source is unavailable")]
31    EntropyUnavailable,
32    /// Encryption failed.
33    #[error("TON Connect session encryption failed")]
34    EncryptionFailed,
35    /// The message cannot contain a nonce and an authentication tag.
36    #[error("TON Connect encrypted message is truncated")]
37    TruncatedMessage,
38    /// Authentication failed because the key, nonce, or ciphertext is invalid.
39    #[error("TON Connect encrypted message authentication failed")]
40    AuthenticationFailed,
41}
42
43struct SecretKeyBytes([u8; KEY_LENGTH]);
44
45impl SecretKeyBytes {
46    fn from_hex(value: &str) -> Result<Self, SessionKeyPairError> {
47        if value.len() != KEY_LENGTH.saturating_mul(2)
48            || !value
49                .as_bytes()
50                .iter()
51                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(byte))
52        {
53            return Err(SessionKeyPairError::InvalidSecretKey);
54        }
55
56        let mut bytes = [0_u8; KEY_LENGTH];
57        hex::decode_to_slice(value, &mut bytes)
58            .map_err(|_| SessionKeyPairError::InvalidSecretKey)?;
59        Ok(Self(bytes))
60    }
61}
62
63impl Drop for SecretKeyBytes {
64    fn drop(&mut self) {
65        self.0.zeroize();
66    }
67}
68
69impl Serialize for SecretKeyBytes {
70    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
71    where
72        S: Serializer,
73    {
74        let encoded = Zeroizing::new(hex::encode(self.0));
75        serializer.serialize_str(encoded.as_str())
76    }
77}
78
79impl<'de> Deserialize<'de> for SecretKeyBytes {
80    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
81    where
82        D: Deserializer<'de>,
83    {
84        let encoded = Zeroizing::new(String::deserialize(deserializer)?);
85        Self::from_hex(encoded.as_str()).map_err(de::Error::custom)
86    }
87}
88
89/// Serializable key material required to resume one HTTP-bridge session.
90///
91/// This type intentionally does not implement `Debug` or `Clone`: its
92/// `secretKey` grants the ability to decrypt and impersonate the session.
93#[derive(Deserialize, Serialize)]
94#[serde(rename_all = "camelCase", deny_unknown_fields)]
95pub struct PersistedSessionKeyPair {
96    public_key: ClientId,
97    secret_key: SecretKeyBytes,
98}
99
100impl PersistedSessionKeyPair {
101    /// Returns the public bridge client identifier.
102    #[must_use]
103    pub const fn client_id(&self) -> ClientId {
104        self.public_key
105    }
106}
107
108/// `NaCl` `crypto_box` session cryptography used by the TON Connect HTTP bridge.
109///
110/// The bridge remains untrusted: every message is authenticated and encrypted
111/// end-to-end with `X25519`, `XSalsa20`, and `Poly1305`.
112pub struct SessionCrypto {
113    client_id: ClientId,
114    secret_key: SecretKeyBytes,
115}
116
117impl SessionCrypto {
118    /// Generates a fresh session keypair with the operating system CSPRNG.
119    pub fn generate() -> Result<Self, SessionCryptoError> {
120        let mut bytes = [0_u8; KEY_LENGTH];
121        getrandom::fill(&mut bytes).map_err(|_| SessionCryptoError::EntropyUnavailable)?;
122        Ok(Self::from_secret_key(bytes))
123    }
124
125    /// Restores a session and verifies that both persisted keys match.
126    pub fn from_persisted(
127        persisted: &PersistedSessionKeyPair,
128    ) -> Result<Self, SessionKeyPairError> {
129        let secret_bytes = persisted.secret_key.0;
130        let restored = Self::from_secret_key(secret_bytes);
131        if restored.client_id != persisted.public_key {
132            return Err(SessionKeyPairError::PublicKeyMismatch);
133        }
134        Ok(restored)
135    }
136
137    fn from_secret_key(bytes: [u8; KEY_LENGTH]) -> Self {
138        let secret_key = SecretKey::from(bytes);
139        let client_id = ClientId::from_bytes(secret_key.public_key().to_bytes());
140        Self {
141            client_id,
142            secret_key: SecretKeyBytes(bytes),
143        }
144    }
145
146    /// Returns the lowercase-hex public key used as bridge `client_id`.
147    #[must_use]
148    pub const fn client_id(&self) -> ClientId {
149        self.client_id
150    }
151
152    /// Copies the keypair into the explicit persistence representation.
153    ///
154    /// The returned value must be stored as confidential session material.
155    #[must_use]
156    pub fn persisted_keypair(&self) -> PersistedSessionKeyPair {
157        PersistedSessionKeyPair {
158            public_key: self.client_id,
159            secret_key: SecretKeyBytes(self.secret_key.0),
160        }
161    }
162
163    /// Encrypts bytes for a peer and returns `nonce || ciphertext`.
164    ///
165    /// A fresh 24-byte nonce is generated by the operating system CSPRNG for
166    /// every call, as required by the session protocol.
167    pub fn encrypt(&self, peer: ClientId, plaintext: &[u8]) -> Result<Vec<u8>, SessionCryptoError> {
168        let mut nonce = [0_u8; NONCE_LENGTH];
169        getrandom::fill(&mut nonce).map_err(|_| SessionCryptoError::EntropyUnavailable)?;
170        self.encrypt_with_nonce(peer, plaintext, nonce)
171    }
172
173    fn encrypt_with_nonce(
174        &self,
175        peer: ClientId,
176        plaintext: &[u8],
177        nonce_bytes: [u8; NONCE_LENGTH],
178    ) -> Result<Vec<u8>, SessionCryptoError> {
179        let peer_key = PublicKey::from(peer.to_bytes());
180        let secret_key = SecretKey::from(self.secret_key.0);
181        let cipher = SalsaBox::new(&peer_key, &secret_key);
182        let nonce = Nonce::from(nonce_bytes);
183        let ciphertext = cipher
184            .encrypt(&nonce, plaintext)
185            .map_err(|_| SessionCryptoError::EncryptionFailed)?;
186
187        let mut result = Vec::new();
188        result.extend_from_slice(&nonce_bytes);
189        result.extend_from_slice(&ciphertext);
190        Ok(result)
191    }
192
193    /// Authenticates and decrypts a `nonce || ciphertext` bridge payload.
194    ///
195    /// Invalid messages are returned as an opaque error and never exposed as
196    /// plaintext. Errors intentionally contain no key or message material.
197    pub fn decrypt(&self, peer: ClientId, encrypted: &[u8]) -> Result<Vec<u8>, SessionCryptoError> {
198        if encrypted.len() < MIN_ENCRYPTED_MESSAGE_LENGTH {
199            return Err(SessionCryptoError::TruncatedMessage);
200        }
201
202        let nonce_slice = encrypted
203            .get(..NONCE_LENGTH)
204            .ok_or(SessionCryptoError::TruncatedMessage)?;
205        let ciphertext = encrypted
206            .get(NONCE_LENGTH..)
207            .ok_or(SessionCryptoError::TruncatedMessage)?;
208        let nonce_bytes: [u8; NONCE_LENGTH] = nonce_slice
209            .try_into()
210            .map_err(|_| SessionCryptoError::TruncatedMessage)?;
211
212        let peer_key = PublicKey::from(peer.to_bytes());
213        let secret_key = SecretKey::from(self.secret_key.0);
214        let cipher = SalsaBox::new(&peer_key, &secret_key);
215        cipher
216            .decrypt(&Nonce::from(nonce_bytes), ciphertext)
217            .map_err(|_| SessionCryptoError::AuthenticationFailed)
218    }
219}
220
221impl fmt::Debug for SessionCrypto {
222    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
223        formatter
224            .debug_struct("SessionCrypto")
225            .field("client_id", &self.client_id)
226            .field("secret_key", &"[REDACTED]")
227            .finish()
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use std::error::Error;
234
235    use base64::{Engine as _, engine::general_purpose::STANDARD};
236    use proptest::prelude::*;
237
238    use super::*;
239
240    const ALICE_SECRET: [u8; 32] = [
241        0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16, 0xc1, 0x72, 0x51, 0xb2, 0x66,
242        0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, 0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9,
243        0x2c, 0x2a,
244    ];
245    const BOB_SECRET: [u8; 32] = [
246        0x5d, 0xab, 0x08, 0x7e, 0x62, 0x4a, 0x8a, 0x4b, 0x79, 0xe1, 0x7f, 0x8b, 0x83, 0x80, 0x0e,
247        0xe6, 0x6f, 0x3b, 0xb1, 0x29, 0x26, 0x18, 0xb6, 0xfd, 0x1c, 0x2f, 0x8b, 0x27, 0xff, 0x88,
248        0xe0, 0xeb,
249    ];
250    const NONCE: [u8; 24] = [
251        0x69, 0x69, 0x6e, 0xe9, 0x55, 0xb6, 0x2b, 0x73, 0xcd, 0x62, 0xbd, 0xa8, 0x75, 0xfc, 0x73,
252        0xd6, 0x82, 0x19, 0xe0, 0x03, 0x6b, 0x7a, 0x0b, 0x37,
253    ];
254
255    #[test]
256    fn peers_round_trip_binary_payloads() {
257        let alice = SessionCrypto::from_secret_key(ALICE_SECRET);
258        let bob = SessionCrypto::from_secret_key(BOB_SECRET);
259        let encrypted = alice.encrypt(bob.client_id(), b"\0TON Connect\xff");
260        assert_eq!(
261            encrypted.and_then(|message| bob.decrypt(alice.client_id(), &message)),
262            Ok(b"\0TON Connect\xff".to_vec())
263        );
264    }
265
266    /// Ported from the official TypeScript protocol
267    /// `session-crypto.spec.ts` at
268    /// `beb31b373e0d9db4b7d0bfd55a1ab0d0a439b74a`.
269    #[test]
270    fn typescript_session_crypto_cases_round_trip() -> Result<(), Box<dyn Error>> {
271        let first = SessionCrypto::generate()?;
272        let second = SessionCrypto::generate()?;
273        assert_ne!(first.client_id(), second.client_id());
274
275        let persisted = first.persisted_keypair();
276        assert_eq!(persisted.client_id(), first.client_id());
277        let restored = SessionCrypto::from_persisted(&persisted)?;
278        assert_eq!(restored.client_id(), first.client_id());
279        let debug = format!("{restored:?}");
280        assert!(debug.contains("[REDACTED]"));
281        assert!(!debug.contains(&hex::encode(persisted.secret_key.0)));
282
283        let plaintext = b"some protocol message: { method_params: [1, 2, null] }";
284        let encrypted = first.encrypt(second.client_id(), plaintext)?;
285        assert_eq!(second.decrypt(first.client_id(), &encrypted)?, plaintext);
286        Ok(())
287    }
288
289    #[test]
290    fn encryption_matches_tweetnacl_golden_vector() {
291        // Generated independently with tweetnacl 1.0.3. This locks the exact
292        // X25519 + XSalsa20-Poly1305 construction and nonce-prefix framing.
293        let alice = SessionCrypto::from_secret_key(ALICE_SECRET);
294        let bob = SessionCrypto::from_secret_key(BOB_SECRET);
295        let expected = hex::decode(
296            "69696ee955b62b73cd62bda875fc73d68219e0036b7a0b37\
297             4f143feef2ba7f7dabdcb006973180de64d12a7a37868ec868e1378cba7808d0",
298        );
299        assert_eq!(
300            alice.encrypt_with_nonce(bob.client_id(), b"TON Connect core", NONCE),
301            expected.map_err(|_| SessionCryptoError::EncryptionFailed)
302        );
303        assert_eq!(
304            alice.client_id().to_string(),
305            "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"
306        );
307        assert_eq!(
308            bob.client_id().to_string(),
309            "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"
310        );
311    }
312
313    /// Generated by `XaBbl4/pytonconnect` `SessionCrypto` at
314    /// `15ec6997be196ff63677e3ccc5720f058cda3d98` with fixed keys and nonce.
315    #[test]
316    fn encryption_matches_python_session_crypto_vector() -> Result<(), Box<dyn Error>> {
317        let alice = SessionCrypto::from_secret_key(ALICE_SECRET);
318        let bob = SessionCrypto::from_secret_key(BOB_SECRET);
319        let plaintext = b"some protocol message: { method_params: [1, 2, null] }";
320        let expected = STANDARD.decode(concat!(
321            "aWlu6VW2K3PNYr2odfxz1oIZ4ANregs3C5To1mTCuJA5314JDiX0Q0PxCT9UmZLJ",
322            "ee0gw7U3F9BpaIrqPxV9CyxkWSo96jPJVVIJssYSp0EMUfTlgAiINWhiklOY2g=="
323        ))?;
324        assert_eq!(
325            alice.encrypt_with_nonce(bob.client_id(), plaintext, NONCE)?,
326            expected
327        );
328        assert_eq!(bob.decrypt(alice.client_id(), &expected)?, plaintext);
329        Ok(())
330    }
331
332    #[test]
333    fn tampered_ciphertext_is_never_returned_as_plaintext() {
334        let alice = SessionCrypto::from_secret_key(ALICE_SECRET);
335        let bob = SessionCrypto::from_secret_key(BOB_SECRET);
336        let encrypted = alice.encrypt_with_nonce(bob.client_id(), b"request", NONCE);
337        let mut tampered = encrypted.unwrap_or_default();
338        if let Some(byte) = tampered.last_mut() {
339            *byte ^= 1;
340        }
341        assert_eq!(
342            bob.decrypt(alice.client_id(), &tampered),
343            Err(SessionCryptoError::AuthenticationFailed)
344        );
345    }
346
347    #[test]
348    fn persisted_public_key_is_verified() {
349        let alice = SessionCrypto::from_secret_key(ALICE_SECRET);
350        let mut serialized = serde_json::to_value(alice.persisted_keypair()).unwrap_or_default();
351        if let Some(public_key) = serialized.get_mut("publicKey") {
352            *public_key = serde_json::Value::String("00".repeat(32));
353        }
354        let pair = serde_json::from_value::<PersistedSessionKeyPair>(serialized)
355            .expect("valid persisted key-pair shape");
356        assert!(matches!(
357            SessionCrypto::from_persisted(&pair),
358            Err(SessionKeyPairError::PublicKeyMismatch)
359        ));
360    }
361
362    proptest! {
363        #[test]
364        fn authenticated_encryption_round_trips_arbitrary_bytes(plaintext in proptest::collection::vec(any::<u8>(), 0..2048)) {
365            let alice = SessionCrypto::from_secret_key(ALICE_SECRET);
366            let bob = SessionCrypto::from_secret_key(BOB_SECRET);
367            let encrypted = alice.encrypt_with_nonce(bob.client_id(), &plaintext, NONCE);
368            let decrypted = encrypted.and_then(|message| bob.decrypt(alice.client_id(), &message));
369            prop_assert_eq!(decrypted, Ok(plaintext));
370        }
371    }
372}