ferogram-mtproto 0.3.8

MTProto 2.0 session management, message framing, DH key exchange and transport abstractions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
//
// ferogram: async Telegram MTProto client in Rust
// https://github.com/ankit-chaubey/ferogram
//
// Licensed under either the MIT License or the Apache License 2.0.
// See the LICENSE-MIT or LICENSE-APACHE file in this repository:
// https://github.com/ankit-chaubey/ferogram
//
// Feel free to use, modify, and share this code.
// Please keep this notice when redistributing.

use std::collections::{HashSet, VecDeque};
use std::time::{SystemTime, UNIX_EPOCH};

use ferogram_crypto::{AuthKey, DequeBuffer, decrypt_data_v2, encrypt_data_v2};
use ferogram_tl_types::RemoteCall;

/// Rolling deduplication buffer for server msg_ids.
const SEEN_MSG_IDS_MAX: usize = 500;

/// Errors that can occur when decrypting a server message.
#[derive(Debug)]
pub enum DecryptError {
    /// The underlying crypto layer rejected the message.
    Crypto(ferogram_crypto::DecryptError),
    /// The decrypted inner message was too short to contain a valid header.
    FrameTooShort,
    /// Session-ID mismatch (possible replay or wrong connection).
    SessionMismatch,
    /// Server msg_id is outside the allowed time window (-300s / +30s).
    MsgIdTimeWindow,
    /// This msg_id was already seen in the rolling 500-entry buffer.
    DuplicateMsgId,
    /// Server msg_id has even parity; server messages must have odd msg_id.
    InvalidMsgId,
}

impl std::fmt::Display for DecryptError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Crypto(e) => write!(f, "crypto: {e}"),
            Self::FrameTooShort => write!(f, "inner plaintext too short"),
            Self::SessionMismatch => write!(f, "session_id mismatch"),
            Self::MsgIdTimeWindow => write!(f, "server msg_id outside -300s/+30s time window"),
            Self::DuplicateMsgId => write!(f, "duplicate server msg_id (replay)"),
            Self::InvalidMsgId => write!(f, "server msg_id has even parity (must be odd)"),
        }
    }
}
impl std::error::Error for DecryptError {}

/// The inner payload extracted from a successfully decrypted server frame.
pub struct DecryptedMessage {
    /// `salt` sent by the server.
    pub salt: i64,
    /// The `session_id` from the frame.
    pub session_id: i64,
    /// The `msg_id` of the inner message.
    pub msg_id: i64,
    /// `seq_no` of the inner message.
    pub seq_no: i32,
    /// TL-serialized body of the inner message.
    pub body: Vec<u8>,
}

/// Shared, persistent dedup ring for server msg_ids.
///
/// `VecDeque` provides O(1) push/pop for eviction order; `HashSet` provides
/// O(1) membership checks, replacing the previous O(n) `VecDeque::contains`
/// scan that became a serialisation bottleneck under 12 concurrent workers.
///
/// Outlives individual `EncryptedSession` objects so that replayed frames
/// from a prior connection cycle are still rejected after reconnect.
pub type SeenMsgIds = std::sync::Arc<std::sync::Mutex<(VecDeque<i64>, HashSet<i64>)>>;

/// Allocate a fresh seen-msg_id ring.
pub fn new_seen_msg_ids() -> SeenMsgIds {
    std::sync::Arc::new(std::sync::Mutex::new((
        VecDeque::with_capacity(SEEN_MSG_IDS_MAX),
        HashSet::with_capacity(SEEN_MSG_IDS_MAX),
    )))
}

/// MTProto 2.0 encrypted session state.
pub struct EncryptedSession {
    auth_key: AuthKey,
    session_id: i64,
    sequence: i32,
    last_msg_id: i64,
    /// Current server salt to include in outgoing messages.
    pub salt: i64,
    /// Clock skew in seconds vs. server.
    pub time_offset: i32,
    /// Rolling 500-entry dedup buffer of seen server msg_ids.
    /// Shared with the owning DcConnection so it survives reconnects.
    seen_msg_ids: SeenMsgIds,
}

impl EncryptedSession {
    /// Create a new encrypted session from the output of `authentication::finish`.
    ///
    /// `seen_msg_ids` should be the persistent ring owned by the `DcConnection`
    /// (or any other owner that outlives individual sessions).  Pass
    /// `new_seen_msg_ids()` for the very first connection on a slot.
    pub fn new(auth_key: [u8; 256], first_salt: i64, time_offset: i32) -> Self {
        Self::with_seen(auth_key, first_salt, time_offset, new_seen_msg_ids())
    }

    /// Like `new` but reuses an existing seen-msg_id ring (reconnect path).
    pub fn with_seen(
        auth_key: [u8; 256],
        first_salt: i64,
        time_offset: i32,
        seen_msg_ids: SeenMsgIds,
    ) -> Self {
        let mut rnd = [0u8; 8];
        getrandom::getrandom(&mut rnd).expect("getrandom");
        Self {
            auth_key: AuthKey::from_bytes(auth_key),
            session_id: i64::from_le_bytes(rnd),
            sequence: 0,
            last_msg_id: 0,
            salt: first_salt,
            time_offset,
            seen_msg_ids,
        }
    }

    /// Return a clone of the shared seen-msg_id ring for passing to a
    /// replacement session on reconnect.
    pub fn seen_msg_ids(&self) -> SeenMsgIds {
        std::sync::Arc::clone(&self.seen_msg_ids)
    }

    /// Compute the next message ID (based on corrected server time).
    fn next_msg_id(&mut self) -> i64 {
        let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
        // Keep arithmetic in u64: seconds since epoch with time_offset applied.
        let secs = now.as_secs().wrapping_add(self.time_offset as i64 as u64);
        let nanos = now.subsec_nanos() as u64;
        let mut id = ((secs << 32) | (nanos << 2)) as i64;
        // Spec requires lower 32 bits to be non-zero ("must present a
        // fractional part").  On coarse-grained clocks (e.g. some Android/Termux
        // environments) subsec_nanos() can be exactly 0, making the lower half 0.
        // Set the minimum valid bit (bit 2, step = 4) when lower half is zero.
        if (id as u64 & 0xFFFF_FFFF) == 0 {
            id |= 4;
        }
        if self.last_msg_id >= id {
            id = self.last_msg_id + 4;
        }
        self.last_msg_id = id;
        id
    }

    /// Next content-related seq_no (odd) and advance the counter.
    /// Used for all regular RPC requests.
    fn next_seq_no(&mut self) -> i32 {
        let n = self.sequence * 2 + 1;
        self.sequence += 1;
        n
    }

    /// Return the current even seq_no WITHOUT advancing the counter.
    ///
    /// Service messages (MsgsAck, containers, etc.) MUST use an even seqno
    /// per the MTProto spec so the server does not expect a reply.
    pub fn next_seq_no_ncr(&self) -> i32 {
        self.sequence * 2
    }

    /// Handle `bad_msg_notification` codes 32/33 (seq_no too low / too high).
    ///
    /// The previous implementation used magic offsets (+64 / -16) that have no
    /// basis in the MTProto spec. These caused ping-pong loops: +64 triggered
    /// code 33 (now too high), -16 triggered code 32 (now too low), repeating
    /// until the connection was dropped, which then hit the session_id reset bug.
    ///
    /// The spec-correct recovery is a full session reset (new session_id, seq_no=0).
    /// This is what TDesktop does. The caller (`dc_pool::rpc_call`) must then resend
    /// using the new session context.
    pub fn correct_seq_no(&mut self, _code: u32) {
        // Full session reset: new session_id, seq_no = 0.
        // The server will see a brand-new session and accept seq_no starting from 1.
        self.reset_session();
        log::debug!("[ferogram] seq_no desync (code {_code}): performed full session reset");
    }

    /// Undo the last `next_seq_no` increment.
    ///
    /// Called before retrying a request after `bad_server_salt` so the resent
    /// message uses the same seq_no slot rather than advancing the counter a
    /// second time (which would produce seq_no too high → bad_msg_notification
    /// code 33 → server closes TCP → early eof).
    pub fn undo_seq_no(&mut self) {
        self.sequence = self.sequence.saturating_sub(1);
    }

    /// Re-derive the clock skew from a server-provided `msg_id`.
    ///
    /// Called on `bad_msg_notification` error codes 16 (msg_id too low) and
    /// 17 (msg_id too high) so clock drift is corrected at any point in the
    /// session, not only at connect time.
    ///
    pub fn correct_time_offset(&mut self, server_msg_id: i64) {
        // Upper 32 bits of msg_id = Unix seconds on the server
        let server_time = (server_msg_id >> 32) as i32;
        let local_now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i32;
        let new_offset = server_time.wrapping_sub(local_now);
        log::debug!(
            "[ferogram] time_offset correction: {} → {} (server_time={server_time})",
            self.time_offset,
            new_offset
        );
        self.time_offset = new_offset;
        // Seed last_msg_id from the server's msg_id (bits 1-0 cleared to 0b00)
        // so the next next_msg_id() call produces a strictly larger value.
        self.last_msg_id = (server_msg_id & !0x3i64).max(self.last_msg_id);
    }

    /// Allocate a fresh `(msg_id, seqno)` pair for an inner container message
    /// WITHOUT encrypting anything.
    ///
    /// `content_related = true`  → odd seqno, advances counter  (regular RPCs)
    /// `content_related = false` → even seqno, no advance       (MsgsAck, container)
    ///
    pub fn alloc_msg_seqno(&mut self, content_related: bool) -> (i64, i32) {
        let msg_id = self.next_msg_id();
        let seqno = if content_related {
            self.next_seq_no()
        } else {
            self.next_seq_no_ncr()
        };
        (msg_id, seqno)
    }

    /// Encrypt a pre-serialized TL body into a wire-ready MTProto frame.
    ///
    /// `content_related` controls whether the seqno is odd (content, advances
    /// the counter) or even (service, no advance).
    ///
    /// Returns `(encrypted_wire_bytes, msg_id)`.
    /// Used for (bad_msg re-send) and (container inner messages).
    pub fn pack_body_with_msg_id(&mut self, body: &[u8], content_related: bool) -> (Vec<u8>, i64) {
        let msg_id = self.next_msg_id();
        let seq_no = if content_related {
            self.next_seq_no()
        } else {
            self.next_seq_no_ncr()
        };

        let inner_len = 8 + 8 + 8 + 4 + 4 + body.len();
        let mut buf = DequeBuffer::with_capacity(inner_len, 32);
        buf.extend(self.salt.to_le_bytes());
        buf.extend(self.session_id.to_le_bytes());
        buf.extend(msg_id.to_le_bytes());
        buf.extend(seq_no.to_le_bytes());
        buf.extend((body.len() as u32).to_le_bytes());
        buf.extend(body.iter().copied());

        encrypt_data_v2(&mut buf, &self.auth_key);
        (buf.as_ref().to_vec(), msg_id)
    }

    /// Encrypt a pre-built `msg_container` body (the container itself is
    /// a non-content-related message with an even seqno).
    ///
    /// Returns `(encrypted_wire_bytes, container_msg_id)`.
    /// The container_msg_id is needed so callers can map it back to inner
    /// requests when a bad_msg_notification or bad_server_salt arrives for
    /// the container rather than the individual inner message.
    ///
    pub fn pack_container(&mut self, container_body: &[u8]) -> (Vec<u8>, i64) {
        self.pack_body_with_msg_id(container_body, false)
    }

    /// Encrypt `body` using a **caller-supplied** `msg_id` instead of generating one.
    ///
    /// Required by `auth.bindTempAuthKey`, which must use the same `msg_id`
    /// in both the outer MTProto envelope and the inner `bind_auth_key_inner`.
    pub fn pack_body_at_msg_id(&mut self, body: &[u8], msg_id: i64) -> Vec<u8> {
        let seq_no = self.next_seq_no();
        let inner_len = 8 + 8 + 8 + 4 + 4 + body.len();
        let mut buf = DequeBuffer::with_capacity(inner_len, 32);
        buf.extend(self.salt.to_le_bytes());
        buf.extend(self.session_id.to_le_bytes());
        buf.extend(msg_id.to_le_bytes());
        buf.extend(seq_no.to_le_bytes());
        buf.extend((body.len() as u32).to_le_bytes());
        buf.extend(body.iter().copied());
        encrypt_data_v2(&mut buf, &self.auth_key);
        buf.as_ref().to_vec()
    }

    /// Serialize and encrypt a TL function into a wire-ready byte vector.
    pub fn pack_serializable<S: ferogram_tl_types::Serializable>(&mut self, call: &S) -> Vec<u8> {
        let body = call.to_bytes();
        let msg_id = self.next_msg_id();
        let seq_no = self.next_seq_no();

        let inner_len = 8 + 8 + 8 + 4 + 4 + body.len();
        let mut buf = DequeBuffer::with_capacity(inner_len, 32);
        buf.extend(self.salt.to_le_bytes());
        buf.extend(self.session_id.to_le_bytes());
        buf.extend(msg_id.to_le_bytes());
        buf.extend(seq_no.to_le_bytes());
        buf.extend((body.len() as u32).to_le_bytes());
        buf.extend(body.iter().copied());

        encrypt_data_v2(&mut buf, &self.auth_key);
        buf.as_ref().to_vec()
    }

    /// Like `pack_serializable` but also returns the `msg_id`.
    pub fn pack_serializable_with_msg_id<S: ferogram_tl_types::Serializable>(
        &mut self,
        call: &S,
    ) -> (Vec<u8>, i64) {
        let body = call.to_bytes();
        let msg_id = self.next_msg_id();
        let seq_no = self.next_seq_no();
        let inner_len = 8 + 8 + 8 + 4 + 4 + body.len();
        let mut buf = DequeBuffer::with_capacity(inner_len, 32);
        buf.extend(self.salt.to_le_bytes());
        buf.extend(self.session_id.to_le_bytes());
        buf.extend(msg_id.to_le_bytes());
        buf.extend(seq_no.to_le_bytes());
        buf.extend((body.len() as u32).to_le_bytes());
        buf.extend(body.iter().copied());
        encrypt_data_v2(&mut buf, &self.auth_key);
        (buf.as_ref().to_vec(), msg_id)
    }

    /// Like [`pack`] but also returns the `msg_id` allocated for this message.
    pub fn pack_with_msg_id<R: RemoteCall>(&mut self, call: &R) -> (Vec<u8>, i64) {
        let body = call.to_bytes();
        let msg_id = self.next_msg_id();
        let seq_no = self.next_seq_no();
        let inner_len = 8 + 8 + 8 + 4 + 4 + body.len();
        let mut buf = DequeBuffer::with_capacity(inner_len, 32);
        buf.extend(self.salt.to_le_bytes());
        buf.extend(self.session_id.to_le_bytes());
        buf.extend(msg_id.to_le_bytes());
        buf.extend(seq_no.to_le_bytes());
        buf.extend((body.len() as u32).to_le_bytes());
        buf.extend(body.iter().copied());
        encrypt_data_v2(&mut buf, &self.auth_key);
        (buf.as_ref().to_vec(), msg_id)
    }

    /// Encrypt and frame a [`RemoteCall`] into a ready-to-send MTProto message.
    pub fn pack<R: RemoteCall>(&mut self, call: &R) -> Vec<u8> {
        let body = call.to_bytes();
        let msg_id = self.next_msg_id();
        let seq_no = self.next_seq_no();

        let inner_len = 8 + 8 + 8 + 4 + 4 + body.len();
        let mut buf = DequeBuffer::with_capacity(inner_len, 32);
        buf.extend(self.salt.to_le_bytes());
        buf.extend(self.session_id.to_le_bytes());
        buf.extend(msg_id.to_le_bytes());
        buf.extend(seq_no.to_le_bytes());
        buf.extend((body.len() as u32).to_le_bytes());
        buf.extend(body.iter().copied());

        encrypt_data_v2(&mut buf, &self.auth_key);
        buf.as_ref().to_vec()
    }

    /// Decrypt an encrypted server frame.
    pub fn unpack(&self, frame: &mut [u8]) -> Result<DecryptedMessage, DecryptError> {
        let plaintext = decrypt_data_v2(frame, &self.auth_key).map_err(DecryptError::Crypto)?;

        if plaintext.len() < 32 {
            return Err(DecryptError::FrameTooShort);
        }

        let salt = i64::from_le_bytes(plaintext[..8].try_into().unwrap());
        let session_id = i64::from_le_bytes(plaintext[8..16].try_into().unwrap());
        let msg_id = i64::from_le_bytes(plaintext[16..24].try_into().unwrap());
        let seq_no = i32::from_le_bytes(plaintext[24..28].try_into().unwrap());
        let body_len = u32::from_le_bytes(plaintext[28..32].try_into().unwrap()) as usize;

        if session_id != self.session_id {
            return Err(DecryptError::SessionMismatch);
        }

        // MTProto: server msg_id must be odd.
        if msg_id & 1 == 0 {
            return Err(DecryptError::InvalidMsgId);
        }

        // Time window is intentionally asymmetric: -300s past, +30s future.
        let server_secs = (msg_id as u64 >> 32) as i64;
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;
        let corrected = now + self.time_offset as i64;
        let skew = server_secs - corrected;
        if !(-300..=30).contains(&skew) {
            return Err(DecryptError::MsgIdTimeWindow);
        }

        // Rolling 500-entry dedup.
        {
            let mut seen = self.seen_msg_ids.lock().unwrap();
            if seen.1.contains(&msg_id) {
                return Err(DecryptError::DuplicateMsgId);
            }
            seen.0.push_back(msg_id);
            seen.1.insert(msg_id);
            if seen.0.len() > SEEN_MSG_IDS_MAX
                && let Some(old_id) = seen.0.pop_front()
            {
                seen.1.remove(&old_id);
            }
        }

        // Maximum body length: 16 MB.
        if body_len > 16 * 1024 * 1024 {
            return Err(DecryptError::FrameTooShort);
        }
        if 32 + body_len > plaintext.len() {
            return Err(DecryptError::FrameTooShort);
        }
        // TL payload must be 4-byte aligned.
        if !body_len.is_multiple_of(4) {
            return Err(DecryptError::FrameTooShort);
        }
        // MTProto 2.0: padding must be in range [12, 1024] bytes (Security Guidelines).
        let padding = plaintext.len() - 32 - body_len;
        if !(12..=1024).contains(&padding) {
            return Err(DecryptError::FrameTooShort);
        }
        let body = plaintext[32..32 + body_len].to_vec();

        Ok(DecryptedMessage {
            salt,
            session_id,
            msg_id,
            seq_no,
            body,
        })
    }

    /// Return the auth_key bytes (for persistence).
    pub fn auth_key_bytes(&self) -> [u8; 256] {
        self.auth_key.to_bytes()
    }

    /// Return the current session_id.
    pub fn session_id(&self) -> i64 {
        self.session_id
    }

    /// Reset session state: new random session_id, zeroed seq_no and last_msg_id.
    ///
    /// Use this for genuine new-session creation (e.g. reconnect after auth loss,
    /// or bad_msg_notification codes 32/33 seq_no desync).
    /// For `new_session_created` server notifications received mid-session, use
    /// `reset_seq_no_only()` which preserves the client session_id so that
    /// in-flight server responses still decrypt correctly.
    pub fn reset_session(&mut self) {
        let mut rnd = [0u8; 8];
        getrandom::getrandom(&mut rnd).expect("getrandom");
        let old_session = self.session_id;
        self.session_id = i64::from_le_bytes(rnd);
        self.sequence = 0;
        self.last_msg_id = 0;
        // Do not clear seen_msg_ids: the ring is shared with the owning
        // DcConnection and must survive session resets to reject replayed frames.
        log::debug!(
            "[ferogram] session reset: {:#018x} → {:#018x}",
            old_session,
            self.session_id
        );
    }

    /// Reset only the sequence counter and last_msg_id, keeping session_id intact.
    ///
    /// # Protocol basis
    /// When the server sends `new_session_created`, it has created fresh server-side
    /// state for the client's **existing** session_id. The client must reset seq_no
    /// to 0 (server expectation is now 0) but MUST NOT change session_id. Doing so
    /// would cause the server's pending response (encrypted with the old session_id)
    /// to fail decryption with `SessionMismatch`.
    ///
    /// Replaces the previous `reset_session()` call in the `new_session_created` handler.
    pub fn reset_seq_no_only(&mut self) {
        self.sequence = 0;
        self.last_msg_id = 0;
        log::debug!(
            "[ferogram] seq_no reset (session_id unchanged): {:#018x}",
            self.session_id
        );
    }
}

impl EncryptedSession {
    /// Like [`decrypt_frame`] but also performs seen-msg_id deduplication using the
    /// supplied ring. Pass `&self.inner.seen_msg_ids` from the client.
    ///
    /// Hard-codes `time_offset = 0`. On systems where the local clock differs from
    /// the server by more than 30 seconds, valid server messages are rejected with
    /// `MsgIdTimeWindow`. Prefer `decrypt_frame_dedup_with_offset` when the session's
    /// clock skew is known.
    pub fn decrypt_frame_dedup(
        auth_key: &[u8; 256],
        session_id: i64,
        frame: &mut [u8],
        seen: &SeenMsgIds,
    ) -> Result<DecryptedMessage, DecryptError> {
        Self::decrypt_frame_dedup_with_offset(auth_key, session_id, frame, seen, 0)
    }

    /// Like [`decrypt_frame_dedup`] but applies the time-window check with the given
    /// `time_offset` (seconds, server_time − local_time).
    ///
    /// Callers that track the session's clock skew (from `correct_time_offset`) should
    /// use this variant to avoid falsely rejecting valid server frames on clock-skewed
    /// systems. Pass `enc.time_offset()` from the owning `EncryptedSession`.
    pub fn decrypt_frame_dedup_with_offset(
        auth_key: &[u8; 256],
        session_id: i64,
        frame: &mut [u8],
        seen: &SeenMsgIds,
        time_offset: i32,
    ) -> Result<DecryptedMessage, DecryptError> {
        let msg = Self::decrypt_frame_with_offset(auth_key, session_id, frame, time_offset)?;
        {
            let mut s = seen.lock().unwrap();
            if s.1.contains(&msg.msg_id) {
                return Err(DecryptError::DuplicateMsgId);
            }
            s.0.push_back(msg.msg_id);
            s.1.insert(msg.msg_id);
            if s.0.len() > SEEN_MSG_IDS_MAX
                && let Some(old_id) = s.0.pop_front()
            {
                s.1.remove(&old_id);
            }
        }
        Ok(msg)
    }

    /// Decrypt a frame using explicit key + session_id: no mutable state needed.
    /// Used by the split-reader task so it can decrypt without locking the writer.
    /// `time_offset` is the session's current clock skew (seconds); pass 0 if unknown.
    pub fn decrypt_frame(
        auth_key: &[u8; 256],
        session_id: i64,
        frame: &mut [u8],
    ) -> Result<DecryptedMessage, DecryptError> {
        Self::decrypt_frame_with_offset(auth_key, session_id, frame, 0)
    }

    /// Like [`decrypt_frame`] but applies the time-window check with the given
    /// `time_offset` (seconds, server_time − local_time).
    pub fn decrypt_frame_with_offset(
        auth_key: &[u8; 256],
        session_id: i64,
        frame: &mut [u8],
        time_offset: i32,
    ) -> Result<DecryptedMessage, DecryptError> {
        let key = AuthKey::from_bytes(*auth_key);
        let plaintext = decrypt_data_v2(frame, &key).map_err(DecryptError::Crypto)?;
        if plaintext.len() < 32 {
            return Err(DecryptError::FrameTooShort);
        }
        let salt = i64::from_le_bytes(plaintext[..8].try_into().unwrap());
        let sid = i64::from_le_bytes(plaintext[8..16].try_into().unwrap());
        let msg_id = i64::from_le_bytes(plaintext[16..24].try_into().unwrap());
        let seq_no = i32::from_le_bytes(plaintext[24..28].try_into().unwrap());
        let body_len = u32::from_le_bytes(plaintext[28..32].try_into().unwrap()) as usize;
        if sid != session_id {
            return Err(DecryptError::SessionMismatch);
        }
        // MTProto: server msg_id must be odd.
        if msg_id & 1 == 0 {
            return Err(DecryptError::InvalidMsgId);
        }
        // Time window is intentionally asymmetric: -300s past, +30s future.
        let server_secs = (msg_id as u64 >> 32) as i64;
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;
        let corrected = now + time_offset as i64;
        let skew = server_secs - corrected;
        if !(-300..=30).contains(&skew) {
            return Err(DecryptError::MsgIdTimeWindow);
        }
        // Maximum body length: 16 MB.
        if body_len > 16 * 1024 * 1024 {
            return Err(DecryptError::FrameTooShort);
        }
        if 32 + body_len > plaintext.len() {
            return Err(DecryptError::FrameTooShort);
        }
        // TL payload must be 4-byte aligned.
        if !body_len.is_multiple_of(4) {
            return Err(DecryptError::FrameTooShort);
        }
        // MTProto 2.0: padding must be in range [12, 1024] bytes (Security Guidelines).
        let padding = plaintext.len() - 32 - body_len;
        if !(12..=1024).contains(&padding) {
            return Err(DecryptError::FrameTooShort);
        }
        let body = plaintext[32..32 + body_len].to_vec();
        Ok(DecryptedMessage {
            salt,
            session_id: sid,
            msg_id,
            seq_no,
            body,
        })
    }
}