mailcycle 0.2.0

Rust client for the Mailcycle API. Create addresses that receive mail, read and decrypt it on your machine, send, and listen for events.
Documentation
//! Account identity derived from a recovery phrase.
//!
//! Everything below comes out of one 64-byte root seed, which never leaves
//! this machine. The split matters, so it is spelled out rather than left
//! implicit:
//!
//! | Field | | What it is |
//! |---|---|---|
//! | `account_id` | public | the ONLY identifier the server learns. An opaque hash. It carries no email, no name, no device, and nothing that links two accounts to one person. |
//! | `auth_secret` | private | the old proof of possession. Still derived, because an account created before the keypair existed was registered with its hash. |
//! | `auth_key` | private | the X25519 key that proves this account now. Only its public half is ever uploaded, once. |
//! | `vault_key` | private | encrypts mail, address labels and device names. Never transmitted in any form. Lose the phrase and the mail is gone; nobody at Mailcycle can help. |
//!
//! The domain-separation strings are part of the format. Changing one changes
//! every account id and every key derived after it.

use crate::encoding::to_b64u;

use super::mnemonic::phrase_to_seed;
use super::primitives::{hmac_sha256, public_key_from, sha256};

const LABEL_PREFIX: &str = "mailcycle/v1/";
const LABEL_PREFIX_V2: &str = "mailcycle/v2/";
const MAX_EPOCH: u32 = (1 << 31) - 1;

/// A labelled subkey of a seed. The labels are part of the format.
pub fn subkey(seed: &[u8], label: &str, length: usize) -> Vec<u8> {
    let first = hmac_sha256(seed, format!("{LABEL_PREFIX}{label}").as_bytes());
    if length <= first.len() {
        return first[..length].to_vec();
    }
    let second = hmac_sha256(seed, format!("{LABEL_PREFIX}{label}/2").as_bytes());
    let mut out = first.to_vec();
    out.extend_from_slice(&second);
    out.truncate(length);
    out
}

/// A labelled subkey under the version 2 derivation: HKDF-Expand-SHA256 (RFC
/// 5869) with the key as the PRK and `mailcycle/v2/<label>` as the info.
///
/// [`subkey`] concatenates its label and makes its second block by appending
/// `/2`, so one label's second block can be another label's first. Here the
/// counter sits outside the label, so two labels share output only if they are
/// the same label. Only new kinds of key use it, so no account id or existing
/// key changes. `None` for a length outside 1 to 8160 bytes.
pub fn subkey_v2(key: &[u8], label: &str, length: usize) -> Option<Vec<u8>> {
    if !(1..=255 * 32).contains(&length) {
        return None;
    }
    let hkdf = hkdf::Hkdf::<sha2::Sha256>::from_prk(key).ok()?;
    let mut out = vec![0u8; length];
    hkdf.expand(format!("{LABEL_PREFIX_V2}{label}").as_bytes(), &mut out).ok()?;
    Some(out)
}

/// Refuses an identifier that could reshape the derivation label around it.
///
/// [`subkey`] builds its second block by appending `/2`, and the label is
/// concatenated rather than length-prefixed. So for an id `X`, the MAC half of
/// `address_key(X)` is also the ENCRYPTION half of `address_key("X/2")`. A
/// server that handed one account the ids `X` and `X/2` could recover
/// keystream from the second and hold the first's MAC key.
///
/// Length-prefixing inside [`subkey`] is the deeper fix and would change every
/// key this product has ever derived, account ids included. Rejecting the
/// characters that make the collision reachable costs nothing and closes it,
/// because the attack needs a separator inside the id.
fn is_safe_label(id: &str) -> bool {
    !id.is_empty()
        && id.len() <= 64
        && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}

#[derive(Clone)]
pub struct AccountIdentity {
    pub account_id: String,
    pub auth_secret: Vec<u8>,
    pub auth_key: Vec<u8>,
    pub auth_public_key: String,
    pub vault_key: Vec<u8>,
}

pub fn identity_from_seed(seed: &[u8]) -> AccountIdentity {
    let auth_key = subkey(seed, "auth-key", 32);
    let id_bytes = subkey(seed, "account-id", 16);
    AccountIdentity {
        account_id: format!("acct_{}", crate::encoding::to_hex(&id_bytes)),
        auth_secret: subkey(seed, "auth", 32),
        auth_public_key: to_b64u(&public_key_from(&auth_key)),
        auth_key,
        vault_key: subkey(seed, "vault", 64),
    }
}

pub fn identity_from_phrase(phrase: &str, passphrase: &str) -> AccountIdentity {
    identity_from_seed(&phrase_to_seed(phrase, passphrase))
}

/// The verifier the server is allowed to store.
///
/// It is a hash, so a database dump does not let an attacker authenticate
/// anywhere else and cannot be run backwards into the phrase or the vault key.
pub fn auth_verifier(auth_secret: &[u8]) -> String {
    to_b64u(&sha256(auth_secret))
}

/// The symmetric key for one address, 64 bytes.
///
/// Per address, so a key handed to one device unlocks that device's mail and
/// nothing else, and removing a device does not mean re-encrypting the rest.
pub fn address_key(vault_key: &[u8], address_id: &str) -> Option<Vec<u8>> {
    is_safe_label(address_id).then(|| subkey(vault_key, &format!("inbox/{address_id}"), 64))
}

/// The address's X25519 (private, public) pair, derived and never stored.
///
/// Separate from [`address_key`] and under a different label: the symmetric
/// key seals mail the account's own devices deliver, and this pair is what
/// lets a mail server seal what arrives from outside without ever being able
/// to read it. One secret for both roles would mean handing a paired device a
/// key that also opens inbound mail for an address it was never assigned.
pub fn address_key_pair(vault_key: &[u8], address_id: &str) -> Option<(Vec<u8>, [u8; 32])> {
    if !is_safe_label(address_id) {
        return None;
    }
    let private_key = subkey(vault_key, &format!("inbox-sealing/{address_id}"), 32);
    let public_key = public_key_from(&private_key);
    Some((private_key, public_key))
}

/// The address's symmetric key at a key epoch.
///
/// Epoch 0 is [`address_key`], the key every address has had from the start.
/// Later epochs come from [`subkey_v2`]: under [`subkey`], `inbox/<id>/2`
/// would be the second half of epoch 0's key. Old epochs stay derivable, so
/// mail sealed under them still opens.
pub fn address_key_at(vault_key: &[u8], address_id: &str, epoch: u32) -> Option<Vec<u8>> {
    match epoch {
        0 => address_key(vault_key, address_id),
        e if e <= MAX_EPOCH && is_safe_label(address_id) => {
            subkey_v2(vault_key, &format!("inbox/{address_id}/{e}"), 64)
        }
        _ => None,
    }
}

/// The address's X25519 pair at a key epoch. Epoch 0 is [`address_key_pair`].
pub fn address_key_pair_at(vault_key: &[u8], address_id: &str, epoch: u32) -> Option<(Vec<u8>, [u8; 32])> {
    match epoch {
        0 => address_key_pair(vault_key, address_id),
        e if e <= MAX_EPOCH && is_safe_label(address_id) => {
            let private_key = subkey_v2(vault_key, &format!("inbox-sealing/{address_id}/{e}"), 32)?;
            let public_key = public_key_from(&private_key);
            Some((private_key, public_key))
        }
        _ => None,
    }
}

/// Short, human-comparable fingerprint, as the app shows when pairing.
pub fn fingerprint(account_id: &str) -> String {
    let digest = crate::encoding::to_hex(&sha256(account_id.as_bytes()))[..12].to_uppercase();
    format!("{}-{}-{}", &digest[0..4], &digest[4..8], &digest[8..12])
}