Skip to main content

ferogram_e2e/
chat.rs

1/*
2 * Copyright (c) 2026 Ankit Chaubey <ankitchaubey.dev@gmail.com>
3 * https://github.com/ankit-chaubey
4 *
5 * Project: ferogram
6 * Website: https://ferogram.dev
7 *
8 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
9 * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
10 * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
11 * This file may not be copied, modified, or distributed except according
12 * to those terms.
13 */
14
15//! High-level secret chat client ([`E2eClient`]): request, accept, send, receive, re-key.
16
17use std::path::PathBuf;
18use std::sync::Arc;
19
20use ferogram_tl_types as tl;
21use tokio::sync::{Mutex, broadcast};
22use tracing::{debug, warn};
23
24use crate::crypto::{
25    decrypt_message, encrypt_message, file_decrypt, file_encrypt, file_key_fingerprint,
26    key_fingerprint,
27};
28use crate::dh::{DEFAULT_LAYER, DhCacheEntry, DhContext, compute_shared_from_raw};
29use crate::error::E2eError;
30use crate::state::{ChatStore, RekeyingState, SecretChatState, TempChatState};
31use crate::tl::{
32    DecryptedAction, DecryptedMedia, DecryptedMessage, DecryptedMessageLayer, make_random_bytes,
33    serialize_layer8_service, serialize_message_layer,
34};
35use crate::transport::E2eTransport;
36use crate::update::E2eEvent;
37use crate::upload::upload_encrypted_file;
38
39/// High-level secret chat client.
40///
41/// Generic over the [`E2eTransport`] that sends RPCs; with `ferogram` enabled,
42/// use `ferogram::e2e::E2eClient`, which fixes `T` to `ferogram::Client`.
43///
44/// Cheap to clone: the chat store, DH cache and event channel are shared behind `Arc`.
45#[derive(Clone)]
46pub struct E2eClient<T: E2eTransport> {
47    pub(crate) client: T,
48    pub(crate) store: Arc<Mutex<ChatStore>>,
49    dh_cache: Arc<Mutex<Option<DhCacheEntry>>>,
50    // Broadcast channel for async events (TTL expiry, etc.)
51    event_tx: broadcast::Sender<E2eEvent>,
52}
53
54impl<T: E2eTransport> E2eClient<T> {
55    /// Create a client that keeps secret chat state in memory only.
56    ///
57    /// Chats are lost when the process exits; use [`Self::with_persistence`] to keep them.
58    pub fn new(client: T) -> Self {
59        let (event_tx, _) = broadcast::channel(256);
60        Self {
61            client,
62            store: Arc::new(Mutex::new(ChatStore::new())),
63            dh_cache: Arc::new(Mutex::new(None)),
64            event_tx,
65        }
66    }
67
68    /// Create a client that keeps secret chat state next to a session file.
69    ///
70    /// The store is `<session_name>.e2e`: the session path with its extension
71    /// replaced (`mybot.session` becomes `mybot.e2e`). See
72    /// [`with_persistence`](Self::with_persistence) for the details.
73    pub fn for_session(client: T, session: impl AsRef<std::path::Path>) -> std::io::Result<Self> {
74        Self::with_persistence(client, crate::state::store_path_for_session(session))
75    }
76
77    /// Create a client that persists secret chat state to the binary file at `path`.
78    ///
79    /// Previously saved chats are loaded on startup, and every change is written back
80    /// atomically. Loading fails with `InvalidData` if the file is corrupt or from an
81    /// unsupported version. The file holds each chat's `auth_key` unencrypted (it is
82    /// created with mode `0600` on Unix), so protect it accordingly.
83    pub fn with_persistence(client: T, path: impl Into<PathBuf>) -> std::io::Result<Self> {
84        let store = ChatStore::load(path.into())?;
85        let (event_tx, _) = broadcast::channel(256);
86        Ok(Self {
87            client,
88            store: Arc::new(Mutex::new(store)),
89            dh_cache: Arc::new(Mutex::new(None)),
90            event_tx,
91        })
92    }
93
94    /// Subscribe to asynchronous events that are not tied to an incoming update
95    /// (currently only [`E2eEvent::MessageExpired`] for self-destruct timers).
96    pub fn subscribe(&self) -> broadcast::Receiver<E2eEvent> {
97        self.event_tx.subscribe()
98    }
99
100    /// Spawn a background task that fires [`E2eEvent::MessageExpired`] after `ttl` seconds.
101    /// Does nothing if `ttl <= 0`.
102    fn schedule_expiry(&self, chat_id: i32, random_id: i64, ttl: i32) {
103        if ttl <= 0 {
104            return;
105        }
106        let tx = self.event_tx.clone();
107        let secs = ttl as u64;
108        tokio::spawn(async move {
109            tokio::time::sleep(std::time::Duration::from_secs(secs)).await;
110            let _ = tx.send(E2eEvent::MessageExpired { chat_id, random_id });
111        });
112    }
113
114    /// Fetch (and cache) the DH config from the server.
115    async fn get_dh_config(&self) -> Result<(u32, Vec<u8>), E2eError> {
116        let mut cache = self.dh_cache.lock().await;
117        let version = cache.as_ref().map(|c| c.version).unwrap_or(0);
118
119        let result = self
120            .client
121            .invoke(&tl::functions::messages::GetDhConfig {
122                version,
123                random_length: 0,
124            })
125            .await?;
126
127        match result {
128            tl::enums::messages::DhConfig::DhConfig(c) => {
129                let g = c.g as u32;
130                let p = c.p.clone();
131                *cache = Some(DhCacheEntry {
132                    g,
133                    p: p.clone(),
134                    version: c.version,
135                });
136                Ok((g, p))
137            }
138            tl::enums::messages::DhConfig::NotModified(_) => {
139                let cached = cache.as_ref().ok_or_else(|| {
140                    E2eError::InvalidState("DhConfigNotModified but no cache".into())
141                })?;
142                Ok((cached.g, cached.p.clone()))
143            }
144        }
145    }
146
147    /// Encrypt and send via `messages.sendEncryptedService`.
148    async fn do_send_service(
149        &self,
150        chat_id: i32,
151        access_hash: i64,
152        data: Vec<u8>,
153    ) -> Result<(), E2eError> {
154        let random_id = rand::random::<i64>();
155        self.client
156            .invoke(&tl::functions::messages::SendEncryptedService {
157                peer: tl::enums::InputEncryptedChat::InputEncryptedChat(
158                    tl::types::InputEncryptedChat {
159                        chat_id,
160                        access_hash,
161                    },
162                ),
163                random_id,
164                data,
165            })
166            .await?;
167        Ok(())
168    }
169
170    /// Encrypt and send via `messages.sendEncrypted`.
171    async fn do_send(&self, chat_id: i32, access_hash: i64, data: Vec<u8>) -> Result<(), E2eError> {
172        let random_id = rand::random::<i64>();
173        self.client
174            .invoke(&tl::functions::messages::SendEncrypted {
175                silent: false,
176                peer: tl::enums::InputEncryptedChat::InputEncryptedChat(
177                    tl::types::InputEncryptedChat {
178                        chat_id,
179                        access_hash,
180                    },
181                ),
182                random_id,
183                data,
184            })
185            .await?;
186        Ok(())
187    }
188
189    /// Re-send a buffered encrypted blob verbatim (for Resend handling).
190    async fn do_resend(
191        &self,
192        chat_id: i32,
193        access_hash: i64,
194        data: Vec<u8>,
195    ) -> Result<(), E2eError> {
196        let random_id = rand::random::<i64>();
197        self.client
198            .invoke(&tl::functions::messages::SendEncrypted {
199                silent: false,
200                peer: tl::enums::InputEncryptedChat::InputEncryptedChat(
201                    tl::types::InputEncryptedChat {
202                        chat_id,
203                        access_hash,
204                    },
205                ),
206                random_id,
207                data,
208            })
209            .await?;
210        Ok(())
211    }
212
213    /// Send the layer notification message immediately after chat establishment.
214    async fn notify_layer_inner(
215        &self,
216        chat_id: i32,
217        access_hash: i64,
218        auth_key: [u8; 256],
219        admin: bool,
220    ) -> Result<(), E2eError> {
221        let random_id = rand::random::<i64>();
222        let plaintext = serialize_layer8_service(
223            random_id,
224            &DecryptedAction::NotifyLayer {
225                layer: DEFAULT_LAYER,
226            },
227        )?;
228        let blob = encrypt_message(&auth_key, &plaintext, admin)?;
229        self.do_send_service(chat_id, access_hash, blob).await
230    }
231
232    /// The underlying transport (client) this E2E client sends through.
233    pub fn client(&self) -> &T {
234        &self.client
235    }
236
237    /// Initiate a secret chat with `user_id` / `access_hash`.
238    ///
239    /// This is the low-level form for clients that already hold the access hash.
240    /// With `ferogram`, prefer `E2eClientExt::request_secret_chat`, which looks it up.
241    pub async fn request_secret_chat_raw(
242        &self,
243        user_id: i64,
244        access_hash: i64,
245    ) -> Result<i32, E2eError> {
246        let (g, p_bytes) = self.get_dh_config().await?;
247        let ctx = DhContext::generate(g, &p_bytes)?;
248
249        let random_id = rand::random::<i32>();
250        let result = self
251            .client
252            .invoke(&tl::functions::messages::RequestEncryption {
253                user_id: tl::enums::InputUser::InputUser(tl::types::InputUser {
254                    user_id,
255                    access_hash,
256                }),
257                random_id,
258                g_a: ctx.public_value.clone(),
259            })
260            .await?;
261
262        let chat_id = match result {
263            tl::enums::EncryptedChat::Waiting(w) => w.id,
264            other => {
265                return Err(E2eError::InvalidState(format!(
266                    "unexpected chat state after requestEncryption: {:?}",
267                    other
268                )));
269            }
270        };
271
272        let mut store = self.store.lock().await;
273        store.insert_pending(TempChatState {
274            id: chat_id,
275            private_key_a: ctx.private_key,
276        });
277
278        debug!(chat_id, "secret chat requested");
279        Ok(chat_id)
280    }
281
282    /// Accept an incoming secret chat request (User B side).
283    pub async fn accept_secret_chat(
284        &self,
285        chat: &tl::types::EncryptedChatRequested,
286    ) -> Result<(), E2eError> {
287        let (g, p_bytes) = self.get_dh_config().await?;
288        let ctx = DhContext::generate(g, &p_bytes)?;
289        let auth_key = ctx.compute_shared_secret(&chat.g_a)?;
290        let fp = key_fingerprint(&auth_key);
291
292        self.client
293            .invoke(&tl::functions::messages::AcceptEncryption {
294                peer: tl::enums::InputEncryptedChat::InputEncryptedChat(
295                    tl::types::InputEncryptedChat {
296                        chat_id: chat.id,
297                        access_hash: chat.access_hash,
298                    },
299                ),
300                g_b: ctx.public_value.clone(),
301                key_fingerprint: fp,
302            })
303            .await?;
304
305        let state = SecretChatState::new(chat.id, chat.access_hash, auth_key, false, chat.admin_id);
306
307        {
308            let mut store = self.store.lock().await;
309            store.insert(state)?;
310        }
311
312        self.notify_layer_inner(chat.id, chat.access_hash, auth_key, false)
313            .await?;
314
315        debug!(chat_id = chat.id, "secret chat accepted");
316        Ok(())
317    }
318
319    /// Complete chat creation on the initiator side (User A) after peer accepts.
320    pub async fn finish_secret_chat(
321        &self,
322        chat: &tl::types::EncryptedChat,
323    ) -> Result<(), E2eError> {
324        let (_g, p_bytes) = self.get_dh_config().await?;
325
326        let temp = {
327            let mut store = self.store.lock().await;
328            store
329                .take_pending(chat.id)
330                .ok_or(E2eError::ChatNotFound(chat.id))?
331        };
332
333        let auth_key = compute_shared_from_raw(&temp.private_key_a, &chat.g_a_or_b, &p_bytes)?;
334
335        let computed_fp = key_fingerprint(&auth_key);
336        if computed_fp != chat.key_fingerprint {
337            self.client
338                .invoke(&tl::functions::messages::DiscardEncryption {
339                    delete_history: false,
340                    chat_id: chat.id,
341                })
342                .await?;
343            return Err(E2eError::KeyFingerprintMismatch);
344        }
345
346        let state = SecretChatState::new(
347            chat.id,
348            chat.access_hash,
349            auth_key,
350            true,
351            chat.participant_id,
352        );
353
354        {
355            let mut store = self.store.lock().await;
356            store.insert(state)?;
357        }
358
359        self.notify_layer_inner(chat.id, chat.access_hash, auth_key, true)
360            .await?;
361
362        debug!(chat_id = chat.id, "secret chat creation finished");
363        Ok(())
364    }
365
366    /// Send a text message to an established secret chat.
367    pub async fn send_text(&self, chat_id: i32, text: &str, ttl: i32) -> Result<(), E2eError> {
368        if text.len() > 512 * 1024 {
369            return Err(E2eError::MessageTooLarge);
370        }
371
372        let random_id = rand::random::<i64>();
373        let (blob, access_hash) = {
374            let mut store = self.store.lock().await;
375            let state = store.get_mut(chat_id)?;
376
377            let wire_seq_no = state.wire_out_seq_no();
378
379            let msg = DecryptedMessage::Text {
380                random_id,
381                ttl,
382                message: text.to_owned(),
383                media: DecryptedMedia::Empty,
384            };
385
386            let layer_msg = DecryptedMessageLayer {
387                random_bytes: make_random_bytes(),
388                layer: DEFAULT_LAYER,
389                in_seq_no: state.wire_in_seq_no(),
390                out_seq_no: wire_seq_no,
391                message: msg,
392            };
393
394            let plaintext = serialize_message_layer(&layer_msg)?;
395            if plaintext.len() > 512 * 1024 {
396                return Err(E2eError::MessageTooLarge);
397            }
398
399            let blob = encrypt_message(&state.auth_key, &plaintext, state.admin)?;
400            state.push_sent(wire_seq_no, blob.clone());
401            state.out_seq_no += 1;
402            state.ttr -= 1;
403            let access_hash = state.access_hash;
404            store.save();
405            (blob, access_hash)
406        };
407
408        self.maybe_rekey(chat_id).await?;
409        self.do_send(chat_id, access_hash, blob).await?;
410        self.schedule_expiry(chat_id, random_id, ttl);
411        Ok(())
412    }
413
414    /// Encrypt and send a file as a secret chat document message.
415    ///
416    /// `file_bytes` is the raw plaintext content.
417    /// `mime_type` e.g. "image/jpeg", "application/pdf".
418    /// `file_name` is the suggested filename shown to the recipient.
419    /// `caption` is optional (empty string = no caption).
420    /// `ttl` is self-destruct seconds (0 = no TTL).
421    ///
422    /// Returns the `random_id` of the sent message.
423    pub async fn send_file(
424        &self,
425        chat_id: i32,
426        file_bytes: &[u8],
427        mime_type: &str,
428        file_name: &str,
429        caption: &str,
430        ttl: i32,
431    ) -> Result<i64, E2eError> {
432        let (file_key, file_iv, ciphertext) = file_encrypt(file_bytes);
433        let fp = file_key_fingerprint(&file_key, &file_iv);
434
435        let input_file = upload_encrypted_file(&self.client, &ciphertext, fp).await?;
436
437        let random_id = rand::random::<i64>();
438
439        let media = DecryptedMedia::Document {
440            thumb: Vec::new(),
441            thumb_w: 0,
442            thumb_h: 0,
443            mime_type: mime_type.to_owned(),
444            size: file_bytes.len() as i64,
445            key: file_key.to_vec(),
446            iv: file_iv.to_vec(),
447            attributes: vec![crate::tl::DocumentAttribute::FileName {
448                file_name: file_name.to_owned(),
449            }],
450            caption: caption.to_owned(),
451        };
452
453        let msg = DecryptedMessage::Text {
454            random_id,
455            ttl,
456            message: String::new(),
457            media,
458        };
459
460        let (blob, access_hash) = {
461            let mut store = self.store.lock().await;
462            let state = store.get_mut(chat_id)?;
463
464            let wire_seq_no = state.wire_out_seq_no();
465
466            let layer_msg = DecryptedMessageLayer {
467                random_bytes: make_random_bytes(),
468                layer: DEFAULT_LAYER,
469                in_seq_no: state.wire_in_seq_no(),
470                out_seq_no: wire_seq_no,
471                message: msg,
472            };
473
474            let plaintext = serialize_message_layer(&layer_msg)?;
475            if plaintext.len() > 512 * 1024 {
476                return Err(E2eError::MessageTooLarge);
477            }
478
479            let blob = encrypt_message(&state.auth_key, &plaintext, state.admin)?;
480            state.push_sent(wire_seq_no, blob.clone());
481            state.out_seq_no += 1;
482            state.ttr -= 1;
483            let access_hash = state.access_hash;
484            store.save();
485            (blob, access_hash)
486        };
487
488        self.maybe_rekey(chat_id).await?;
489
490        self.client
491            .invoke(&tl::functions::messages::SendEncryptedFile {
492                silent: false,
493                peer: tl::enums::InputEncryptedChat::InputEncryptedChat(
494                    tl::types::InputEncryptedChat {
495                        chat_id,
496                        access_hash,
497                    },
498                ),
499                random_id,
500                data: blob,
501                file: input_file,
502            })
503            .await?;
504
505        self.schedule_expiry(chat_id, random_id, ttl);
506        Ok(random_id)
507    }
508
509    /// Send a photo to a secret chat.
510    ///
511    /// Uses `DecryptedMedia::Photo` (constructor 0x32798a8c), which is what
512    /// official clients send for inline photos. `w` and `h` are the image
513    /// dimensions in pixels; pass 0 if unknown. `ttl` is self-destruct seconds
514    /// (0 = no TTL). Returns the `random_id` of the sent message.
515    pub async fn send_photo(
516        &self,
517        chat_id: i32,
518        photo_bytes: &[u8],
519        w: i32,
520        h: i32,
521        caption: &str,
522        ttl: i32,
523    ) -> Result<i64, E2eError> {
524        let (file_key, file_iv, ciphertext) = file_encrypt(photo_bytes);
525        let fp = file_key_fingerprint(&file_key, &file_iv);
526
527        let input_file = upload_encrypted_file(&self.client, &ciphertext, fp).await?;
528
529        let random_id = rand::random::<i64>();
530
531        let media = DecryptedMedia::Photo {
532            thumb: Vec::new(),
533            thumb_w: 0,
534            thumb_h: 0,
535            w,
536            h,
537            size: photo_bytes.len() as i32,
538            key: file_key.to_vec(),
539            iv: file_iv.to_vec(),
540            caption: caption.to_owned(),
541        };
542
543        let msg = DecryptedMessage::Text {
544            random_id,
545            ttl,
546            message: String::new(),
547            media,
548        };
549
550        let (blob, access_hash) = {
551            let mut store = self.store.lock().await;
552            let state = store.get_mut(chat_id)?;
553
554            let wire_seq_no = state.wire_out_seq_no();
555
556            let layer_msg = DecryptedMessageLayer {
557                random_bytes: make_random_bytes(),
558                layer: DEFAULT_LAYER,
559                in_seq_no: state.wire_in_seq_no(),
560                out_seq_no: wire_seq_no,
561                message: msg,
562            };
563
564            let plaintext = serialize_message_layer(&layer_msg)?;
565            if plaintext.len() > 512 * 1024 {
566                return Err(E2eError::MessageTooLarge);
567            }
568
569            let blob = encrypt_message(&state.auth_key, &plaintext, state.admin)?;
570            state.push_sent(wire_seq_no, blob.clone());
571            state.out_seq_no += 1;
572            state.ttr -= 1;
573            let access_hash = state.access_hash;
574            store.save();
575            (blob, access_hash)
576        };
577
578        self.maybe_rekey(chat_id).await?;
579
580        self.client
581            .invoke(&tl::functions::messages::SendEncryptedFile {
582                silent: false,
583                peer: tl::enums::InputEncryptedChat::InputEncryptedChat(
584                    tl::types::InputEncryptedChat {
585                        chat_id,
586                        access_hash,
587                    },
588                ),
589                random_id,
590                data: blob,
591                file: input_file,
592            })
593            .await?;
594
595        self.schedule_expiry(chat_id, random_id, ttl);
596        Ok(random_id)
597    }
598
599    /// Download and decrypt an encrypted attachment received in a secret chat.
600    ///
601    /// `enc_file` comes from `E2eEvent::Message { file: Some(enc_file), .. }`.
602    /// `key` and `iv` come from the `DecryptedMedia` inside the same message.
603    /// `size` is the original plaintext length from the `DecryptedMedia` size field.
604    ///
605    /// Returns the decrypted plaintext bytes ready for forwarding or processing.
606    pub async fn download_decrypted_file(
607        &self,
608        enc_file: &tl::enums::EncryptedFile,
609        key: &[u8],
610        iv: &[u8],
611        size: usize,
612    ) -> Result<Vec<u8>, E2eError> {
613        let (id, access_hash, dc_id) = match enc_file {
614            tl::enums::EncryptedFile::EncryptedFile(f) => (f.id, f.access_hash, f.dc_id),
615            tl::enums::EncryptedFile::Empty => {
616                return Err(E2eError::Transport("encrypted file is empty".into()));
617            }
618        };
619
620        let location = tl::enums::InputFileLocation::InputEncryptedFileLocation(
621            tl::types::InputEncryptedFileLocation { id, access_hash },
622        );
623
624        let ciphertext = self.download_encrypted_bytes(location, dc_id).await?;
625
626        file_decrypt(&ciphertext, key, iv, size)
627    }
628
629    /// Fetch the raw (still encrypted) bytes of a secret-chat file from `dc_id`.
630    ///
631    /// Secret-chat files live on the DC named in `EncryptedFile::dc_id`, so the
632    /// chunks are pulled with `upload.getFile` through [`E2eTransport::invoke_on_dc`].
633    async fn download_encrypted_bytes(
634        &self,
635        location: tl::enums::InputFileLocation,
636        dc_id: i32,
637    ) -> Result<Vec<u8>, E2eError> {
638        // Offset must be a multiple of 4 KiB and limit a divisor of 1 MiB.
639        const CHUNK: i32 = 512 * 1024;
640        let mut bytes = Vec::new();
641        let mut offset: i64 = 0;
642        loop {
643            let req = tl::functions::upload::GetFile {
644                precise: true,
645                cdn_supported: false,
646                location: location.clone(),
647                offset,
648                limit: CHUNK,
649            };
650            match self.client.invoke_on_dc(dc_id, &req).await? {
651                tl::enums::upload::File::File(f) => {
652                    let done = (f.bytes.len() as i32) < CHUNK;
653                    bytes.extend_from_slice(&f.bytes);
654                    if done {
655                        break;
656                    }
657                    offset += CHUNK as i64;
658                }
659                tl::enums::upload::File::CdnRedirect(_) => {
660                    return Err(E2eError::Transport(
661                        "unexpected CDN redirect for encrypted file".into(),
662                    ));
663                }
664            }
665        }
666        Ok(bytes)
667    }
668
669    /// Send a service message to an established secret chat.
670    pub async fn send_service(
671        &self,
672        chat_id: i32,
673        action: DecryptedAction,
674    ) -> Result<(), E2eError> {
675        let random_id = rand::random::<i64>();
676        let (blob, access_hash) = {
677            let mut store = self.store.lock().await;
678            let state = store.get_mut(chat_id)?;
679
680            let wire_seq_no = state.wire_out_seq_no();
681
682            let msg = DecryptedMessage::Service { random_id, action };
683
684            let layer_msg = DecryptedMessageLayer {
685                random_bytes: make_random_bytes(),
686                layer: DEFAULT_LAYER,
687                in_seq_no: state.wire_in_seq_no(),
688                out_seq_no: wire_seq_no,
689                message: msg,
690            };
691
692            let plaintext = serialize_message_layer(&layer_msg)?;
693            let blob = encrypt_message(&state.auth_key, &plaintext, state.admin)?;
694            state.push_sent(wire_seq_no, blob.clone());
695            state.out_seq_no += 1;
696            state.ttr -= 1;
697            let access_hash = state.access_hash;
698            store.save();
699            (blob, access_hash)
700        };
701
702        self.do_send_service(chat_id, access_hash, blob).await
703    }
704
705    /// Discard (close) a secret chat.
706    pub async fn discard(&self, chat_id: i32, delete_history: bool) -> Result<(), E2eError> {
707        self.client
708            .invoke(&tl::functions::messages::DiscardEncryption {
709                delete_history,
710                chat_id,
711            })
712            .await?;
713
714        let mut store = self.store.lock().await;
715        store.remove(chat_id);
716
717        debug!(chat_id, "secret chat discarded");
718        Ok(())
719    }
720
721    /// Return the 64-bit key fingerprint of a chat's `auth_key`.
722    ///
723    /// A sanity check for the key exchange, not a user-facing verification code.
724    pub fn fingerprint(&self, chat_id: i32) -> Result<i64, E2eError> {
725        let store = self
726            .store
727            .try_lock()
728            .map_err(|_| E2eError::InvalidState("store lock contention".into()))?;
729        let state = store.get(chat_id)?;
730        Ok(key_fingerprint(&state.auth_key))
731    }
732
733    /// Return 4 emoji derived from the chat key, for comparing out of band.
734    ///
735    /// Both sides of the chat see the same 4 emoji (see
736    /// [`crate::crypto::emoji_fingerprint_indices`]); display them side by side and
737    /// let the users compare. A mismatch means the key exchange was tampered with.
738    pub fn emoji_fingerprint(&self, chat_id: i32) -> Result<[&'static str; 4], E2eError> {
739        let store = self
740            .store
741            .try_lock()
742            .map_err(|_| E2eError::InvalidState("store lock contention".into()))?;
743        let state = store.get(chat_id)?;
744        let indices = crate::crypto::emoji_fingerprint_indices(&state.auth_key);
745        Ok([
746            crate::crypto::EMOJI_FINGERPRINT_TABLE[indices[0]],
747            crate::crypto::EMOJI_FINGERPRINT_TABLE[indices[1]],
748            crate::crypto::EMOJI_FINGERPRINT_TABLE[indices[2]],
749            crate::crypto::EMOJI_FINGERPRINT_TABLE[indices[3]],
750        ])
751    }
752
753    /// Send a typing indicator to a secret chat.
754    pub async fn set_encrypted_typing(&self, chat_id: i32, typing: bool) -> Result<(), E2eError> {
755        let access_hash = {
756            let store = self.store.lock().await;
757            store.get(chat_id)?.access_hash
758        };
759        self.client
760            .invoke(&tl::functions::messages::SetEncryptedTyping {
761                peer: tl::enums::InputEncryptedChat::InputEncryptedChat(
762                    tl::types::InputEncryptedChat {
763                        chat_id,
764                        access_hash,
765                    },
766                ),
767                typing,
768            })
769            .await?;
770        Ok(())
771    }
772
773    /// Mark secret chat messages as read up to `max_date` (Unix timestamp).
774    pub async fn read_encrypted_history(
775        &self,
776        chat_id: i32,
777        max_date: i32,
778    ) -> Result<(), E2eError> {
779        let access_hash = {
780            let store = self.store.lock().await;
781            store.get(chat_id)?.access_hash
782        };
783        self.client
784            .invoke(&tl::functions::messages::ReadEncryptedHistory {
785                peer: tl::enums::InputEncryptedChat::InputEncryptedChat(
786                    tl::types::InputEncryptedChat {
787                        chat_id,
788                        access_hash,
789                    },
790                ),
791                max_date,
792            })
793            .await?;
794        Ok(())
795    }
796
797    /// Acknowledge the secret chat message queue up to `max_qts`.
798    pub async fn received_queue(&self, max_qts: i32) -> Result<(), E2eError> {
799        self.client
800            .invoke(&tl::functions::messages::ReceivedQueue { max_qts })
801            .await?;
802        Ok(())
803    }
804
805    /// Initiate a re-key exchange for a chat.
806    pub async fn initiate_rekey(&self, chat_id: i32) -> Result<(), E2eError> {
807        let (g, p_bytes) = self.get_dh_config().await?;
808        let ctx = DhContext::generate(g, &p_bytes)?;
809
810        let exchange_id = rand::random::<i64>();
811        let action = DecryptedAction::RequestKey {
812            exchange_id,
813            g_a: ctx.public_value.clone(),
814        };
815
816        {
817            let mut store = self.store.lock().await;
818            let state = store.get_mut(chat_id)?;
819            match state.rekeying_state {
820                RekeyingState::Idle => {}
821                _ => return Err(E2eError::RekeyInProgress),
822            }
823            state
824                .temp_rekey_map
825                .insert(exchange_id, ctx.private_key.to_vec());
826            state.rekeying_state = RekeyingState::Requested { exchange_id };
827        }
828
829        self.send_service(chat_id, action).await
830    }
831
832    /// Handle an incoming `RequestKey` rekey action.
833    pub async fn handle_rekey_request(
834        &self,
835        chat_id: i32,
836        action: &DecryptedAction,
837    ) -> Result<(), E2eError> {
838        let DecryptedAction::RequestKey { exchange_id, g_a } = action else {
839            return Ok(());
840        };
841        let exchange_id = *exchange_id;
842
843        let (g, p_bytes) = self.get_dh_config().await?;
844        let ctx = DhContext::generate(g, &p_bytes)?;
845        let auth_key = ctx.compute_shared_secret(g_a)?;
846        let fp = key_fingerprint(&auth_key);
847
848        let should_ignore = {
849            let store = self.store.lock().await;
850            let state = store.get(chat_id)?;
851            matches!(state.rekeying_state, RekeyingState::Requested { exchange_id: my_id } if my_id > exchange_id)
852        };
853
854        if should_ignore {
855            return Ok(());
856        }
857
858        let reply_action = DecryptedAction::AcceptKey {
859            exchange_id,
860            g_b: ctx.public_value.clone(),
861            key_fingerprint: fp,
862        };
863
864        {
865            let mut store = self.store.lock().await;
866            let state = store.get_mut(chat_id)?;
867            state.temp_rekey_map.insert(exchange_id, auth_key.to_vec());
868            state.rekeying_state = RekeyingState::Accepted { exchange_id };
869        }
870
871        self.send_service(chat_id, reply_action).await
872    }
873
874    /// Handle an incoming `AcceptKey` rekey action.
875    pub async fn handle_rekey_accept(
876        &self,
877        chat_id: i32,
878        action: &DecryptedAction,
879    ) -> Result<(), E2eError> {
880        let DecryptedAction::AcceptKey {
881            exchange_id,
882            g_b,
883            key_fingerprint: received_fp,
884        } = action
885        else {
886            return Ok(());
887        };
888        let exchange_id = *exchange_id;
889
890        let private_key_bytes = {
891            let store = self.store.lock().await;
892            let state = store.get(chat_id)?;
893            let RekeyingState::Requested { exchange_id: my_id } = state.rekeying_state else {
894                return Ok(());
895            };
896            if my_id != exchange_id {
897                return Ok(());
898            }
899            state
900                .temp_rekey_map
901                .get(&exchange_id)
902                .cloned()
903                .ok_or(E2eError::InvalidState("no temp rekey entry".into()))?
904        };
905
906        let (_, p) = self.get_dh_config().await?;
907
908        let mut key_arr = [0u8; 256];
909        if private_key_bytes.len() != 256 {
910            return Err(E2eError::InvalidState("bad private key length".into()));
911        }
912        key_arr.copy_from_slice(&private_key_bytes);
913
914        let new_auth_key = compute_shared_from_raw(&key_arr, g_b, &p)?;
915        let computed_fp = key_fingerprint(&new_auth_key);
916
917        if computed_fp != *received_fp {
918            let abort = DecryptedAction::AbortKey { exchange_id };
919            {
920                let mut store = self.store.lock().await;
921                let state = store.get_mut(chat_id)?;
922                state.temp_rekey_map.remove(&exchange_id);
923                state.rekeying_state = RekeyingState::Idle;
924            }
925            self.send_service(chat_id, abort).await?;
926            return Err(E2eError::SecurityError("rekey fingerprint mismatch".into()));
927        }
928
929        let commit = DecryptedAction::CommitKey {
930            exchange_id,
931            key_fingerprint: computed_fp,
932        };
933
934        {
935            let mut store = self.store.lock().await;
936            let state = store.get_mut(chat_id)?;
937            state.rotate_key(new_auth_key);
938            state.temp_rekey_map.remove(&exchange_id);
939            state.rekeying_state = RekeyingState::Idle;
940            store.save();
941        }
942
943        self.send_service(chat_id, commit).await
944    }
945
946    /// Handle an incoming `CommitKey` rekey action.
947    pub async fn handle_rekey_commit(
948        &self,
949        chat_id: i32,
950        action: &DecryptedAction,
951    ) -> Result<(), E2eError> {
952        let DecryptedAction::CommitKey {
953            exchange_id,
954            key_fingerprint: received_fp,
955        } = action
956        else {
957            return Ok(());
958        };
959        let exchange_id = *exchange_id;
960
961        let (new_auth_key, fp_ok) = {
962            let store = self.store.lock().await;
963            let state = store.get(chat_id)?;
964            let RekeyingState::Accepted { exchange_id: my_id } = state.rekeying_state else {
965                return Ok(());
966            };
967            if my_id != exchange_id {
968                return Ok(());
969            }
970            let key_bytes = state
971                .temp_rekey_map
972                .get(&exchange_id)
973                .cloned()
974                .ok_or(E2eError::InvalidState("no temp rekey entry".into()))?;
975            if key_bytes.len() != 256 {
976                return Err(E2eError::InvalidState("bad rekey auth_key length".into()));
977            }
978            let mut arr = [0u8; 256];
979            arr.copy_from_slice(&key_bytes);
980            let computed_fp = key_fingerprint(&arr);
981            (arr, computed_fp == *received_fp)
982        };
983
984        if !fp_ok {
985            let abort = DecryptedAction::AbortKey { exchange_id };
986            {
987                let mut store = self.store.lock().await;
988                let state = store.get_mut(chat_id)?;
989                state.temp_rekey_map.remove(&exchange_id);
990                state.rekeying_state = RekeyingState::Idle;
991            }
992            self.send_service(chat_id, abort).await?;
993            return Err(E2eError::SecurityError(
994                "commit fingerprint mismatch".into(),
995            ));
996        }
997
998        {
999            let mut store = self.store.lock().await;
1000            let state = store.get_mut(chat_id)?;
1001            state.rotate_key(new_auth_key);
1002            state.temp_rekey_map.remove(&exchange_id);
1003            state.rekeying_state = RekeyingState::Idle;
1004            store.save();
1005        }
1006
1007        self.send_service(chat_id, DecryptedAction::Noop).await
1008    }
1009
1010    /// Check if a re-key should be initiated and do so if needed.
1011    pub(crate) async fn maybe_rekey(&self, chat_id: i32) -> Result<(), E2eError> {
1012        let should_rekey = {
1013            let store = self.store.lock().await;
1014            let state = match store.get(chat_id) {
1015                Ok(s) => s,
1016                Err(_) => return Ok(()),
1017            };
1018            let idle = matches!(state.rekeying_state, RekeyingState::Idle);
1019            let ttr_expired = state.ttr <= 0;
1020            let time_expired = state.secs_since_update() > 7 * 24 * 3600;
1021            idle && (ttr_expired || time_expired)
1022        };
1023
1024        if should_rekey {
1025            self.initiate_rekey(chat_id).await?;
1026        }
1027        Ok(())
1028    }
1029
1030    /// Decrypt an incoming encrypted message blob and return the inner message.
1031    ///
1032    /// Validates the incoming seq_no and sends a Resend action if a gap is
1033    /// detected. Handles service actions internally; returns `None` for them.
1034    pub async fn receive(
1035        &self,
1036        chat_id: i32,
1037        data: &[u8],
1038    ) -> Result<Option<DecryptedMessage>, E2eError> {
1039        let (auth_key, admin) = {
1040            let store = self.store.lock().await;
1041            let state = store.get(chat_id)?;
1042            (state.auth_key, state.admin)
1043        };
1044
1045        let plaintext = decrypt_message(&auth_key, data, admin)?;
1046        let layer_msg = crate::tl::deserialize_message_layer(&plaintext)?;
1047
1048        let resend = {
1049            let mut store = self.store.lock().await;
1050            let state = store.get_mut(chat_id)?;
1051
1052            let expected = state.wire_in_seq_no();
1053            let got = layer_msg.out_seq_no;
1054
1055            let resend = if got > expected {
1056                warn!(
1057                    chat_id,
1058                    expected, got, "secret chat seq_no gap; requesting resend"
1059                );
1060                Some(DecryptedAction::Resend {
1061                    start_seq_no: expected,
1062                    end_seq_no: got - 2,
1063                })
1064            } else {
1065                None
1066            };
1067
1068            state.in_seq_no += 1;
1069            state.ttr -= 1;
1070            if layer_msg.layer > 0 {
1071                state.layer = layer_msg.layer;
1072            }
1073            store.save();
1074            resend
1075        };
1076
1077        if let Some(resend_action) = resend
1078            && let Err(e) = self.send_service(chat_id, resend_action).await
1079        {
1080            warn!(chat_id, "failed to send Resend action: {e}");
1081        }
1082
1083        self.maybe_rekey(chat_id).await?;
1084
1085        match &layer_msg.message {
1086            DecryptedMessage::Service { action, .. } => {
1087                self.dispatch_action(chat_id, action.clone()).await?;
1088                Ok(None)
1089            }
1090            DecryptedMessage::Unknown { ctor, .. } => {
1091                debug!(chat_id, ctor, "ignoring unknown decrypted message ctor");
1092                Ok(None)
1093            }
1094            msg => {
1095                // Schedule TTL expiry on the recipient side if the message has one.
1096                if let DecryptedMessage::Text { random_id, ttl, .. } = msg {
1097                    self.schedule_expiry(chat_id, *random_id, *ttl);
1098                }
1099                Ok(Some(msg.clone()))
1100            }
1101        }
1102    }
1103
1104    async fn dispatch_action(&self, chat_id: i32, action: DecryptedAction) -> Result<(), E2eError> {
1105        match &action {
1106            DecryptedAction::NotifyLayer { layer } => {
1107                let mut store = self.store.lock().await;
1108                if let Ok(state) = store.get_mut(chat_id) {
1109                    state.layer = *layer;
1110                    if *layer >= 73 {
1111                        state.mtproto = 2;
1112                    }
1113                }
1114            }
1115            DecryptedAction::SetTtl { ttl_seconds } => {
1116                let mut store = self.store.lock().await;
1117                if let Ok(state) = store.get_mut(chat_id) {
1118                    state.ttl = *ttl_seconds;
1119                }
1120            }
1121            DecryptedAction::RequestKey { .. } => {
1122                self.handle_rekey_request(chat_id, &action).await?;
1123            }
1124            DecryptedAction::AcceptKey { .. } => {
1125                self.handle_rekey_accept(chat_id, &action).await?;
1126            }
1127            DecryptedAction::CommitKey { .. } => {
1128                self.handle_rekey_commit(chat_id, &action).await?;
1129            }
1130            DecryptedAction::AbortKey { .. } => {
1131                let mut store = self.store.lock().await;
1132                if let Ok(state) = store.get_mut(chat_id) {
1133                    state.rekeying_state = RekeyingState::Idle;
1134                    state.temp_rekey_map.clear();
1135                }
1136            }
1137            DecryptedAction::Resend {
1138                start_seq_no,
1139                end_seq_no,
1140            } => {
1141                self.handle_resend(chat_id, *start_seq_no, *end_seq_no)
1142                    .await;
1143            }
1144            DecryptedAction::ReadMessages { .. }
1145            | DecryptedAction::DeleteMessages { .. }
1146            | DecryptedAction::ScreenshotMessages { .. }
1147            | DecryptedAction::FlushHistory
1148            | DecryptedAction::Typing { .. }
1149            | DecryptedAction::Noop
1150            | DecryptedAction::Unknown { .. } => {}
1151        }
1152        Ok(())
1153    }
1154
1155    async fn handle_resend(&self, chat_id: i32, start_wire: i32, end_wire: i32) {
1156        let (blobs, access_hash) = {
1157            let store = self.store.lock().await;
1158            let Ok(state) = store.get(chat_id) else {
1159                return;
1160            };
1161            (state.lookup_sent(start_wire, end_wire), state.access_hash)
1162        };
1163
1164        if blobs.is_empty() {
1165            warn!(
1166                chat_id,
1167                start_wire, end_wire, "Resend requested but no buffered blobs found"
1168            );
1169            return;
1170        }
1171
1172        for (seq, blob) in blobs {
1173            debug!(chat_id, seq, "replaying sent blob for Resend");
1174            if let Err(e) = self.do_resend(chat_id, access_hash, blob).await {
1175                warn!(chat_id, seq, "failed to resend blob: {e}");
1176            }
1177        }
1178    }
1179}