Cotton code
111 lines · 5.4 KB · RustRaw
//! The asking side's arithmetic of a device approved from another one (the//! Worker's `askCommit`, `askSas` and `claimStatement`, apps/business/src///! approval.ts): the commit an asking device makes to its keys and nonce//! before the approver's nonce exists, the six digits both screens show, and//! the statement its claim signs. Shared by every asking device, the phones//! (crates/cotton-ffi signin_approval.rs) and the Mac (crates/cotton-mac//! approval.rs), so the two can never drift. Pure.use sha2::{Digest as _, Sha256};/// What the claim signs: the Worker's `claimStatement`.pub fn claim_statement(ask_id: &str, challenge: &str) -> String {    format!("cotton-approval-claim-v1\n{ask_id}\n{challenge}")}/// What the asking device commits to before the approver's nonce exists: the/// Worker's `askCommit`. A missing vault key is hashed as 32 zero bytes.pub fn commit_of(device_id: &[u8], vault_key: Option<&[u8]>, nonce: &[u8]) -> [u8; 32] {    let mut hash = Sha256::new();    hash.update(b"cotton-ask-commit-v1");    hash.update(device_id);    hash.update(vault_key.unwrap_or(&[0u8; 32]));    hash.update(nonce);    hash.finalize().into()}/// The six digits both screens show: the Worker's `askSas`.pub fn sas_of(device_id: &[u8], vault_key: Option<&[u8]>, nonce_a: &[u8], nonce_b: &[u8]) -> String {    let mut hash = Sha256::new();    hash.update(b"cotton-ask-sas-v1");    hash.update(device_id);    hash.update(vault_key.unwrap_or(&[0u8; 32]));    hash.update(nonce_a);    hash.update(nonce_b);    let digest: [u8; 32] = hash.finalize().into();    let n = u32::from_be_bytes([digest[0], digest[1], digest[2], digest[3]]) % 1_000_000;    format!("{n:06}")}/// The matching code as both screens draw it: six digits in two threes.pub fn shown_code(code: &str) -> String {    if code.len() == 6 && code.chars().all(|c| c.is_ascii_digit()) {        format!("{} {}", &code[..3], &code[3..])    } else {        code.to_string()    }}/// What the new device's square code says (assets/design/shared/GETTING-IN.md): the ask and the nonce it committed/// to. Read by the approving app's own camera, so it travels a channel the server never sees, and binds the approval/// to the screen in the person's hands as the six digits do (the Worker's `scanned`).////// NEVER A LINK. A URL would let a stranger's ask, made for this person's number, arrive by a tap on a message; this/// text means nothing to a phone's own camera, a browser or any app but Cotton's scanner.pub const SCAN_PREFIX: &str = "COTTON-IN:1:";/// The text the square code carries for an ask.pub fn scan_text(ask_id: &str, nonce: &[u8; 32]) -> String {    use base64::Engine as _;    format!("{SCAN_PREFIX}{ask_id}:{}", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(nonce))}/// The square code for an ask, as every screen draws it: the text, its size in modules, and one string per row of/// `1` (dark) and `0`, to be drawn with a quiet border of four modules. `None` only if the text could not be encoded.pub fn scan_symbol(ask_id: &str, nonce: &[u8; 32]) -> Option<serde_json::Value> {    let text = scan_text(ask_id, nonce);    let matrix = crate::qr::encode_qr(&text).ok()?;    let rows: Vec<String> = matrix.modules.iter().map(|row| row.iter().map(|dark| if *dark { '1' } else { '0' }).collect()).collect();    Some(serde_json::json!({ "text": text, "size": matrix.size, "rows": rows }))}/// The ask and nonce a scanned text carries, or `None` for anything that is not a Cotton square code.pub fn read_scan(text: &str) -> Option<(String, [u8; 32])> {    use base64::Engine as _;    let rest = text.trim().strip_prefix(SCAN_PREFIX)?;    let (ask_id, nonce) = rest.rsplit_once(':')?;    if ask_id.is_empty() || !ask_id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') {        return None;    }    let nonce: [u8; 32] = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(nonce).ok()?.try_into().ok()?;    Some((ask_id.to_string(), nonce))}#[cfg(test)]mod tests {    use super::*;    #[test]    fn the_code_is_six_digits_in_two_threes_and_moves_with_every_input() {        let code = sas_of(&[1u8; 32], Some(&[2u8; 32]), &[3u8; 32], &[4u8; 32]);        assert_eq!(code.len(), 6);        assert_eq!(shown_code(&code), format!("{} {}", &code[..3], &code[3..]));        assert_ne!(code, sas_of(&[1u8; 32], None, &[3u8; 32], &[4u8; 32]), "the vault key is in the code");        assert_ne!(commit_of(&[1u8; 32], None, &[3u8; 32]), commit_of(&[1u8; 32], Some(&[0u8; 32][..1]), &[3u8; 32]));        assert_eq!(claim_statement("a", "c"), "cotton-approval-claim-v1\na\nc");    }    #[test]    fn a_square_code_carries_its_ask_and_nonce_and_nothing_else_reads_as_one() {        let text = scan_text("cta_abc-DEF_123", &[7u8; 32]);        assert!(text.starts_with(SCAN_PREFIX));        assert!(!text.contains("://"), "never a link");        assert_eq!(read_scan(&text), Some(("cta_abc-DEF_123".to_string(), [7u8; 32])));        assert_eq!(read_scan(&format!(" {text}\n")), Some(("cta_abc-DEF_123".to_string(), [7u8; 32])));        assert_eq!(read_scan("https://cottondb.com/in#cta_x:AAAA"), None);        assert_eq!(read_scan("COTTON-IN:1:cta_x:short"), None);        assert_eq!(read_scan("COTTON-IN:1::AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"), None);        assert_eq!(read_scan("COTTON-IN:2:cta_x:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"), None);        assert_eq!(read_scan("123 456"), None);    }}