grammpars 0.1.0

Offline conversion between Telegram Desktop tdata, Telethon, and grammers sessions
Documentation
use crate::error::{OpenteleError, Result};
use crate::qt_compat::QDataStream;
use std::fmt;
use std::io::Read;
use zeroize::Zeroize;

/// Size of Telegram authorization and local encryption keys.
pub const AUTH_KEY_LEN: usize = 256;

/// Origin and lifetime category of an authorization key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthKeyType {
    /// A newly generated permanent network key.
    Generated = 0,
    /// A temporary network key.
    Temporary = 1,
    /// A permanent network key loaded from a session.
    ReadFromFile = 2,
    /// A local-storage encryption key.
    Local = 3,
}

/// A validated 256-byte Telegram key with redacted debug output.
#[derive(Clone)]
pub struct AuthKey {
    key: Vec<u8>,
    key_type: AuthKeyType,
    dc_id: u32,
}

impl AuthKey {
    /// Constructs a validated 256-byte Telegram authorization key.
    ///
    /// # Errors
    ///
    /// Returns an error when `key` does not contain exactly 256 bytes.
    pub fn new(key: Vec<u8>, key_type: AuthKeyType, dc_id: u32) -> Result<Self> {
        if key.len() != AUTH_KEY_LEN {
            return Err(OpenteleError::InvalidArgument(format!(
                "auth key must contain {AUTH_KEY_LEN} bytes, got {}",
                key.len()
            )));
        }
        Ok(Self {
            key,
            key_type,
            dc_id,
        })
    }

    /// Reads a length-prefixed key from a Qt-compatible stream.
    ///
    /// # Errors
    ///
    /// Returns an error when the stream cannot be read or the decoded key does
    /// not contain exactly 256 bytes.
    pub fn from_stream<R: Read>(
        stream: &mut QDataStream<R>,
        key_type: AuthKeyType,
        dc_id: u32,
    ) -> Result<Self> {
        let key_data = stream.read_qbytearray()?;
        Self::new(key_data.data, key_type, dc_id)
    }

    /// Returns the raw 256 key bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.key
    }

    /// Returns the key's origin category.
    pub fn key_type(&self) -> AuthKeyType {
        self.key_type.clone()
    }

    /// Returns the associated data-center ID, or zero for local keys.
    pub fn dc_id(&self) -> u32 {
        self.dc_id
    }
}

impl fmt::Debug for AuthKey {
    /// Formats key metadata without exposing the secret key bytes.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("AuthKey")
            .field("key", &"[REDACTED]")
            .field("key_type", &self.key_type)
            .field("dc_id", &self.dc_id)
            .finish()
    }
}

impl Drop for AuthKey {
    /// Zeroizes the owned authorization key before its allocation is released.
    fn drop(&mut self) {
        self.key.zeroize();
    }
}