mailcycle 0.8.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
//! Proving an account without handing over its secret.
//!
//! The account holds an X25519 keypair derived from the seed. Only the public
//! half is uploaded, once, at account creation. Unlocking is a
//! challenge-response and the private half never leaves this machine:
//!
//! 1. The client asks for a challenge, naming the account id.
//! 2. The server mints a single-use nonce AND an ephemeral X25519 keypair,
//!    keeps the private half, and returns the nonce with the public half.
//! 3. The client computes `X25519(account_private, ephemeral_public)` and
//!    answers with an HMAC over the nonce under that shared secret.
//! 4. The server computes `X25519(ephemeral_private, account_public)`, which
//!    is the same value, and compares in constant time.
//!
//! Nothing secret is transmitted in either direction, and the answer is
//! worthless afterwards because the nonce is consumed and the ephemeral key
//! discarded.
//!
//! What is given up is third-party verifiability: an HMAC under a shared
//! secret proves possession to THIS server and to nobody else, because the
//! server can compute the same value. That is the correct shape for a login
//! and the wrong shape for a signature, so nothing here should ever be
//! repurposed as one.

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

use super::primitives::{hmac_sha256, is_all_zero, shared_secret};

pub const DOMAIN: &str = "mailcycle/v1/auth-proof";
/// Confirming the account's erasure, so an unlock proof cannot stand in for it.
pub const DELETE_DOMAIN: &str = "mailcycle/v1/delete-proof";

/// The answer to a challenge.
///
/// The account id is inside the MAC as well as the nonce, so a proof captured
/// for one account cannot be presented for another even if a server reused a
/// nonce across them.
pub fn prove_account(
    account_private_key: &[u8],
    ephemeral_public_key_b64u: &str,
    nonce: &str,
    account_id: &str,
    domain: &str,
) -> Result<String> {
    let ephemeral_public_key = from_b64u(ephemeral_public_key_b64u)
        .map_err(|_| Error::AuthProof("The server offered a malformed challenge key."))?;
    if ephemeral_public_key.len() != 32 {
        return Err(Error::AuthProof("The server offered a malformed challenge key."));
    }

    let shared = shared_secret(account_private_key, &ephemeral_public_key);
    // A server that sent a small-order point would get back a MAC under a
    // secret it already knows, which proves nothing and would let it accept
    // anyone.
    if is_all_zero(&shared) {
        return Err(Error::AuthProof("The server offered an unusable challenge key."));
    }

    Ok(to_b64u(&hmac_sha256(&shared, format!("{domain}:{nonce}:{account_id}").as_bytes())))
}