Cotton code
233 lines · 10.4 KB · RustRaw
//! THIS MAC APPROVED FROM THE PERSON'S PHONE (22 Nov 2026).//!//! Since 19 Nov a device is let into the vault only through an approval ask//! whose code the person typed on a phone already signed in (signin-harden://! the Worker keeps no wrap onto another device's `vault_key` row without such//! an ask, and a phone's one-tap Approve is refused). A Mac that signed in by//! a code and published its key waited for an approval no phone could give;//! the recovery code was the only way in.//!//! So the Mac asks as a phone does (`apps/business/src/approval.ts`, the//! asking side of `crates/cotton-ffi/src/phone/signin_approval.rs`, the same//! bytes from `cotton_core::vault::approval`): its device id is the public//! half of an Ed25519 key it keeps in the login Keychain ([`DeviceKey`]); the//! ask names that id and this Mac's vault key and commits to a fresh nonce;//! once a phone opens the ask, the Mac reveals the nonce and shows six digits//! the person types on the phone; approved, the Mac claims its credential with//! a signature over the Worker's challenge. The phone's approval wrote the//! vault's key for this Mac's vault key onto this Mac's own row, so the first//! pass after it opens the vault: one step signs the Mac in and lets it in.//!//! Every word is the phones' own (`kits/shell/lines/signin.json`).use std::time::{Duration, Instant};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use cotton_core::rules::shell_lines::resolve;use cotton_core::vault::approval::{claim_statement, commit_of, sas_of, shown_code};use ed25519_dalek::{Signer as _, SigningKey};use rand::RngCore as _;use serde_json::{json, Value};use zeroize::Zeroizing;use crate::object::{ObjectClient, ObjectError};use crate::vault::Keyring;/// The open host's routes for the asking device.pub const ASK: &str = "/v1/approval/ask";pub const POLL: &str = "/v1/approval/poll";pub const REVEAL: &str = "/v1/approval/reveal";pub const CLAIM: &str = "/v1/approval/claim";/// How often the Mac polls while an ask stands, when the Worker names none.pub const POLL_SECONDS: u64 = 3;/// The login Keychain service this Mac's device key is kept under.pub const DEVICE_KEY_SERVICE: &str = "com.cottondb.mac.device-key";/// This Mac's device identity: an Ed25519 key whose public half, in base64url,/// is its device id everywhere (its sign-in, its device row, its vault row).pub struct DeviceKey {    signing: SigningKey,}impl std::fmt::Debug for DeviceKey {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("DeviceKey").field("id", &self.id()).finish_non_exhaustive()    }}impl DeviceKey {    /// The key `keyring` keeps, minted and kept there the first time.    pub fn load_or_mint(keyring: &dyn Keyring) -> Result<DeviceKey, String> {        if let Some(seed) = keyring.load()? {            return Ok(DeviceKey::from_seed(&seed));        }        let mut seed = Zeroizing::new([0u8; 32]);        rand::rngs::OsRng.fill_bytes(seed.as_mut());        keyring.store(&seed)?;        Ok(DeviceKey::from_seed(&seed))    }    pub fn from_seed(seed: &[u8; 32]) -> DeviceKey {        DeviceKey { signing: SigningKey::from_bytes(seed) }    }    /// The device id: the public half, 32 bytes of base64url.    pub fn id(&self) -> String {        URL_SAFE_NO_PAD.encode(self.signing.verifying_key().to_bytes())    }    fn public(&self) -> [u8; 32] {        self.signing.verifying_key().to_bytes()    }    pub fn sign(&self, message: &[u8]) -> [u8; 64] {        self.signing.sign(message).to_bytes()    }}/// This system's keyring for the device key under `account` (`device` for/// the app a person installs): the login Keychain on a Mac.pub fn system_device_keyring(account: &str) -> Box<dyn Keyring> {    #[cfg(target_os = "macos")]    return Box::new(crate::vault::LoginKeychain::for_service(DEVICE_KEY_SERVICE, account));    #[cfg(not(target_os = "macos"))]    {        let _ = account;        Box::new(crate::vault::NoKeyring)    }}fn say(line: &str, fills: &[(&str, &str)]) -> String {    resolve("signin", line, &[], fills).unwrap_or_default()}fn left_line(seconds: i64) -> String {    let minutes = if seconds <= 0 { 1 } else { (seconds + 59) / 60 };    say("asking.left", &[("n", &minutes.to_string())])}fn bytes32(text: &str) -> Option<[u8; 32]> {    URL_SAFE_NO_PAD.decode(text).ok().and_then(|bytes| bytes.try_into().ok())}/// The ask this Mac made: what it committed to, and the code once a phone/// opened it. Held in memory only: an app that quits mid-ask asks again.#[derive(Debug, Clone)]pub struct Asking {    pub ask_id: String,    pub phone: String,    deadline: Instant,    vault_key: Option<[u8; 32]>,    nonce: [u8; 32],    code: Option<String>,    pub poll_seconds: u64,}impl Asking {    fn left(&self) -> String {        left_line(self.deadline.saturating_duration_since(Instant::now()).as_secs() as i64)    }}/// Where an ask stands after one poll.#[derive(Debug, Clone, PartialEq)]pub enum Polled {    /// Nobody opened it yet (`code` none), or the person is to type `code`.    Waiting { code: Option<String> },    /// Approved and claimed: the credential, as `/v1/sign-in` hands one over.    Approved { credential: String, database_id: String, person: Value },    /// Refused, expired or used: the ask is over. `wrong`: three wrong codes ended it, not a person's No.    Ended { state: String, wrong: bool },}/// Ask to be approved from a signed-in phone of `phone`, naming this Mac's/// device key, its vault key (`vault_public`, base64url) and `device_name`.pub fn ask(object: &ObjectClient, device: &DeviceKey, phone: &str, device_name: &str, vault_public: Option<&str>) -> Result<Asking, ObjectError> {    let vault_key = vault_public.and_then(bytes32);    let mut nonce = [0u8; 32];    rand::rngs::OsRng.fill_bytes(&mut nonce);    let commit = commit_of(&device.public(), vault_key.as_ref().map(|k| k.as_slice()), &nonce);    let mut body = json!({ "phone": phone, "device_id": device.id(), "commit": URL_SAFE_NO_PAD.encode(commit), "device_name": device_name, "device_kind": "mac" });    if let Some(key) = &vault_key {        body["vault_key"] = json!(URL_SAFE_NO_PAD.encode(key));    }    let answer = object.post_route(ASK, &body)?;    let ask_id = answer["ask_id"].as_str().filter(|id| !id.is_empty()).ok_or_else(|| ObjectError::Decode("the Worker sent no ask".into()))?;    let expires_in = answer["expires_in"].as_i64().unwrap_or(0).max(0) as u64;    Ok(Asking {        ask_id: ask_id.to_string(),        phone: phone.to_string(),        deadline: Instant::now() + Duration::from_secs(expires_in),        vault_key,        nonce,        code: None,        poll_seconds: answer["poll_seconds"].as_u64().filter(|s| *s > 0).unwrap_or(POLL_SECONDS),    })}/// One poll of `asking`: once a phone opened it, this Mac reveals its nonce/// and works out the code; approved, it claims its credential.pub fn poll(object: &ObjectClient, device: &DeviceKey, asking: &mut Asking) -> Result<Polled, ObjectError> {    let answer = object.post_route(POLL, &json!({ "ask_id": asking.ask_id }))?;    match answer["state"].as_str().unwrap_or("expired") {        "waiting" => {            if asking.code.is_none() {                if let Some(nonce_b) = answer["nonce_b"].as_str().and_then(bytes32) {                    object.post_route(REVEAL, &json!({ "ask_id": asking.ask_id, "nonce": URL_SAFE_NO_PAD.encode(asking.nonce) }))?;                    asking.code = Some(sas_of(&device.public(), asking.vault_key.as_ref().map(|k| k.as_slice()), &asking.nonce, &nonce_b));                }            }            Ok(Polled::Waiting { code: asking.code.clone() })        }        "approved" => {            let challenge = answer["challenge"].as_str().filter(|c| !c.is_empty()).ok_or_else(|| ObjectError::Decode("the Worker sent no challenge".into()))?;            let sig = device.sign(claim_statement(&asking.ask_id, challenge).as_bytes());            let claimed = object.post_route(CLAIM, &json!({ "ask_id": asking.ask_id, "sig": URL_SAFE_NO_PAD.encode(sig) }))?;            let credential = claimed["credential"].as_str().filter(|c| !c.is_empty()).ok_or_else(|| ObjectError::Decode("the object granted no credential".into()))?;            let database_id = claimed["database_id"].as_str().filter(|id| !id.is_empty()).ok_or_else(|| ObjectError::Decode("the sign-in named no database".into()))?;            Ok(Polled::Approved { credential: credential.to_string(), database_id: database_id.to_string(), person: claimed["person"].clone() })        }        other => Ok(Polled::Ended { state: other.to_string(), wrong: answer["why"].as_str() == Some("wrong") }),    }}/// What the panel draws for `asking` after `polled` (assets/design/shared/GETTING-IN.md): the square code at once,/// the six digits once a phone opened the ask, Sign out always beside it. The words are the phones' `getting_in`.pub fn card(asking: &Asking, polled: &Polled) -> Value {    let g = |line: &str| say(&format!("getting_in.{line}"), &[]);    match polled {        Polled::Waiting { code } => json!({            "state": "waiting", "done": false, "heading": g("heading"),            "line": g("mac_line"),            "qr": cotton_core::vault::approval::scan_symbol(&asking.ask_id, &asking.nonce),            "code": code.as_deref().map(shown_code),            "codeLine": if code.is_some() { g("digits_line") } else { g("before_digits") },            "check": g("never"),            "left": asking.left(), "pollSeconds": asking.poll_seconds,            "noDevice": g("no_device"), "signOut": g("sign_out"),        }),        Polled::Approved { .. } => json!({ "state": "approved", "done": true, "line": g("approved") }),        Polled::Ended { state, wrong } => {            let line = match state.as_str() {                "refused" if *wrong => "ended",                "refused" => "refused",                "used" => "approved",                _ => "timed_out",            };            json!({ "state": state, "done": true, "line": g(line), "again": g("again"), "signOut": g("sign_out") })        }    }}/// The card for an ask this app no longer holds (it quit, or never asked).pub fn lost() -> Value {    json!({ "state": "expired", "done": true, "line": say("getting_in.timed_out", &[]), "again": say("getting_in.again", &[]), "signOut": say("getting_in.sign_out", &[]) })}/// The words of the button that starts an ask.pub fn ask_button() -> String {    say("ask", &[])}