Cotton code
88 lines · 3.3 KB · RustRaw
//! base64url over bytes, by hand. The port of//! `packages/core/src/device/base64url.ts`.//!//! The device id (32 public-key bytes) and every signature (64 bytes) travel//! base64url, UNPADDED. The TypeScript spells the codec out by hand because//! the phone has no `Buffer` and Hermes has no `btoa`; this port spells it out//! for a different reason — the alphabet and the trailing-bit rule below are//! the identity grammar three implementations have to agree on (the phone's,//! Node's `base64url` on the server, and this), and a crate off the shelf is//! free to be more forgiving about the last character than Node's strict//! reading is./// The url alphabet, in value order: `-` is 62 and `_` is 63, and no `=`/// padding is ever written or accepted.const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";/// The value of one alphabet character, or `None` for anything else.////// Non-ASCII input fails here byte by byte, which is what the TypeScript's/// `/^[A-Za-z0-9_-]*$/` does to the whole string.const fn value_of(byte: u8) -> Option<u8> {    match byte {        b'A'..=b'Z' => Some(byte - b'A'),        b'a'..=b'z' => Some(byte - b'a' + 26),        b'0'..=b'9' => Some(byte - b'0' + 52),        b'-' => Some(62),        b'_' => Some(63),        _ => None,    }}/// The bytes as unpadded base64url — byte for byte what Node's/// `Buffer.from(bytes).toString("base64url")` answers.pub fn base64url_encode(bytes: &[u8]) -> String {    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);    let mut index = 0usize;    while index < bytes.len() {        let a = bytes[index];        let b = bytes.get(index + 1).copied();        let c = bytes.get(index + 2).copied();        let triple =            (u32::from(a) << 16) | (u32::from(b.unwrap_or(0)) << 8) | u32::from(c.unwrap_or(0));        out.push(ALPHABET[((triple >> 18) & 63) as usize] as char);        out.push(ALPHABET[((triple >> 12) & 63) as usize] as char);        if b.is_some() {            out.push(ALPHABET[((triple >> 6) & 63) as usize] as char);        }        if c.is_some() {            out.push(ALPHABET[(triple & 63) as usize] as char);        }        index += 3;    }    out}/// The bytes a base64url string names.////// `None` for anything outside the alphabet, for a length no byte string/// encodes to (`len % 4 == 1`), and — the rule that matters for identity — for/// non-canonical trailing bits. The leftover bits after the last whole byte/// must be zero: one byte string has ONE encoding, and a device id that/// differs only in those bits is a different string naming the same key, which/// is a second name for one identity.pub fn base64url_decode(value: &str) -> Option<Vec<u8>> {    let bytes = value.as_bytes();    if bytes.len() % 4 == 1 {        return None;    }    let mut out: Vec<u8> = Vec::with_capacity(bytes.len() * 3 / 4);    let mut buffer: u32 = 0;    let mut bits: u32 = 0;    for byte in bytes {        buffer = (buffer << 6) | u32::from(value_of(*byte)?);        bits += 6;        if bits >= 8 {            bits -= 8;            out.push(((buffer >> bits) & 255) as u8);        }    }    if bits > 0 && (buffer & ((1 << bits) - 1)) != 0 {        return None;    }    Some(out)}#[cfg(test)]#[path = "base64url_tests.rs"]mod tests;