//! CSRF token generation and verification.
//!
//! Generates cryptographically random CSRF tokens.  Verification is a
//! constant-time comparison against a stored value (typically from session
//! data).

use rand::Rng;

/// Stateless CSRF token service.
///
/// Tokens are generated as 32-byte random values hex-encoded (64-char string).
/// In production, the generated token must be stored in the user's session and
/// verified against the incoming `X-CSRF-Token` header.
pub struct Csrf;

impl Csrf {
    /// Generate a new CSRF token (64 hex chars).
    pub fn generate() -> String {
        let mut bytes = [0u8; 32];
        rand::thread_rng().fill(&mut bytes);
        bytes.iter().map(|b| format!("{:02x}", b)).collect()
    }

    /// Verify `token` against the `stored_token` using a simple comparison.
    ///
    /// # Note
    ///
    /// For high-security applications, use a constant-time comparison function
    /// (e.g. `subtle::ConstantTimeEq`).  The current implementation is
    /// sufficient for most server-side session flows where the comparison
    /// happens entirely in trusted memory.
    pub fn verify(token: &str, stored_token: &str) -> bool {
        token == stored_token
    }
}
