mailcycle 0.7.0

Rust email API client: create addresses that receive email, read and decrypt messages on your machine, send email, verify webhooks and stream events.
Documentation
//! Authenticated encryption: ChaCha20 for confidentiality, HMAC-SHA-256 for
//! integrity, composed encrypt-then-MAC.
//!
//! ChaCha20-Poly1305 would be the textbook pairing. Mailcycle does not use it
//! because the app's JavaScript cannot implement Poly1305 safely, and the
//! format is the format everywhere or it is nothing. Encrypt-then-MAC with
//! HMAC-SHA-256 is provably secure given independent keys, which is why one
//! 64-byte secret is split into an encryption key and a separate MAC key
//! rather than used for both.
//!
//! # Versions
//!
//! 1. The tag covers `nonce | ciphertext | additional data`, which does not
//!    say where the ciphertext ends, so bytes can be moved across that
//!    boundary and the tag still verifies.
//! 2. The additional data's length, eight bytes big-endian, is appended, which
//!    makes the split unambiguous.
//!
//! Every reader must open both. New boxes are written as version 2 since
//! 2026-09-19.

use serde::{Deserialize, Serialize};

use crate::encoding::{be64, from_b64u, to_b64u};
use crate::error::{Error, Result};

use super::primitives::{chacha20, constant_time_equal, hmac_sha256, random_bytes, NONCE_BYTES};

/// Which version new boxes are written as.
pub const SEAL_VERSION: u8 = 2;

/// A sealed payload, in the wire shape the API uses.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SealedBox {
    #[serde(default = "one")]
    pub v: u8,
    pub n: String,
    pub c: String,
    pub t: String,
}

fn one() -> u8 {
    1
}

impl SealedBox {
    /// The version this box says it is.
    ///
    /// A box claiming the wrong one computes a different tag and fails, so
    /// this is not something a server can talk a reader into.
    fn version(&self) -> u8 {
        if self.v == 2 {
            2
        } else {
            1
        }
    }
}

/// Splits a 64-byte secret into the two independent keys the scheme needs.
pub fn derive_subkeys(secret: &[u8]) -> Result<(&[u8], &[u8])> {
    if secret.len() != 64 {
        return Err(Error::Decryption);
    }
    Ok((&secret[..32], &secret[32..]))
}

/// What the tag covers, which is the only difference between the versions.
pub fn mac_input(nonce: &[u8], ciphertext: &[u8], aad: &[u8], version: u8) -> Vec<u8> {
    let mut out = Vec::with_capacity(nonce.len() + ciphertext.len() + aad.len() + 8);
    out.extend_from_slice(nonce);
    out.extend_from_slice(ciphertext);
    out.extend_from_slice(aad);
    if version != 1 {
        out.extend_from_slice(&be64(aad.len()));
    }
    out
}

pub fn seal(secret: &[u8], plaintext: &[u8], aad: &str, version: u8) -> Result<SealedBox> {
    let (encryption, mac) = derive_subkeys(secret)?;
    let nonce = random_bytes(NONCE_BYTES);
    let ciphertext = chacha20(encryption, &nonce, plaintext);
    let tag = hmac_sha256(mac, &mac_input(&nonce, &ciphertext, aad.as_bytes(), version));
    Ok(SealedBox { v: version, n: to_b64u(&nonce), c: to_b64u(&ciphertext), t: to_b64u(&tag) })
}

pub fn open(secret: &[u8], box_: &SealedBox, aad: &str) -> Result<Vec<u8>> {
    let (encryption, mac) = derive_subkeys(secret)?;

    let nonce = from_b64u(&box_.n).map_err(|_| Error::Decryption)?;
    let ciphertext = from_b64u(&box_.c).map_err(|_| Error::Decryption)?;
    let tag = from_b64u(&box_.t).map_err(|_| Error::Decryption)?;

    // Shape first, then authenticity, then decrypt. A wrong-length nonce could
    // not produce a valid tag anyway, but the cheap structural check belongs
    // before the cryptographic one rather than after it.
    if nonce.len() != NONCE_BYTES {
        return Err(Error::Decryption);
    }

    let expected = hmac_sha256(mac, &mac_input(&nonce, &ciphertext, aad.as_bytes(), box_.version()));
    // Verify before decrypting. Never act on unauthenticated ciphertext.
    if !constant_time_equal(&expected, &tag) {
        return Err(Error::Decryption);
    }
    Ok(chacha20(encryption, &nonce, &ciphertext))
}

pub fn seal_json<T: Serialize>(secret: &[u8], value: &T, aad: &str, version: u8) -> Result<SealedBox> {
    let text = serde_json::to_vec(value).map_err(|_| Error::Decryption)?;
    seal(secret, &text, aad, version)
}

/// A box whose plaintext is not JSON is unreadable, not a panic.
///
/// That is reachable without the key: in version 1 the MAC does not frame the
/// boundary between ciphertext and additional data, so a server can move bytes
/// across it and leave the plaintext malformed.
pub fn open_json<T: serde::de::DeserializeOwned>(secret: &[u8], box_: &SealedBox, aad: &str) -> Result<T> {
    serde_json::from_slice(&open(secret, box_, aad)?).map_err(|_| Error::Decryption)
}