mailcycle 0.6.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
//! base64url without padding, decoded strictly.
//!
//! The permissive decoders accept several spellings of the same bytes, which
//! matters here: these strings are compared, stored and fed to a MAC, and a
//! server picks how they are spelled. So unknown characters are an error,
//! padding is an error, a length that cannot come from whole bytes is an
//! error, and the unused low bits of the final character must be zero. This is
//! `fromBase64Url` in the app's `src/crypto/bytes.ts`, rule for rule.

use crate::error::{Error, Result};

const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
const STANDARD_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

fn encode(data: &[u8], alphabet: &[u8; 64], pad: bool) -> String {
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
    for chunk in data.chunks(3) {
        let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
        let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
        let take = chunk.len() + 1;
        for i in 0..take {
            out.push(alphabet[((n >> (18 - 6 * i)) & 0x3f) as usize] as char);
        }
        if pad {
            for _ in take..4 {
                out.push('=');
            }
        }
    }
    out
}

/// Bytes to base64url, unpadded.
pub fn to_b64u(data: &[u8]) -> String {
    encode(data, ALPHABET, false)
}

/// Bytes to standard, padded base64, as a file's content goes to the API.
pub fn to_b64(data: &[u8]) -> String {
    encode(data, STANDARD_ALPHABET, true)
}

fn value_of(byte: u8) -> Option<u32> {
    match byte {
        b'A'..=b'Z' => Some((byte - b'A') as u32),
        b'a'..=b'z' => Some((byte - b'a') as u32 + 26),
        b'0'..=b'9' => Some((byte - b'0') as u32 + 52),
        b'-' => Some(62),
        b'_' => Some(63),
        _ => None,
    }
}

/// base64url to bytes, refusing anything non-canonical.
pub fn from_b64u(value: &str) -> Result<Vec<u8>> {
    // One leftover character cannot encode any whole byte.
    if value.len() % 4 == 1 {
        return Err(Error::Base64Url("truncated"));
    }

    let mut out = Vec::with_capacity(value.len() * 6 / 8);
    let mut buffer: u32 = 0;
    let mut bits: u32 = 0;
    for byte in value.as_bytes() {
        let Some(index) = value_of(*byte) else {
            return Err(Error::Base64Url("unexpected character"));
        };
        buffer = (buffer << 6) | index;
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            out.push(((buffer >> bits) & 0xff) as u8);
            buffer &= (1 << bits) - 1;
        }
    }

    // Whatever is left is padding bits, and in a canonical encoding they are
    // zero. Non-zero means two strings would decode to the same bytes.
    if bits > 0 && buffer != 0 {
        return Err(Error::Base64Url("non-canonical trailing bits"));
    }
    Ok(out)
}

/// Eight bytes, big-endian: the additional data's length, in a MAC input.
pub fn be64(value: usize) -> [u8; 8] {
    (value as u64).to_be_bytes()
}

/// Lowercase hex, for a webhook signature.
pub fn to_hex(data: &[u8]) -> String {
    data.iter().map(|byte| format!("{byte:02x}")).collect()
}

/// Lowercase hex back to bytes, or `None` if it is not exactly that.
pub fn from_hex(value: &str) -> Option<Vec<u8>> {
    if value.len() % 2 != 0 || !value.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
        return None;
    }
    (0..value.len()).step_by(2).map(|i| u8::from_str_radix(&value[i..i + 2], 16).ok()).collect()
}