Cotton code
188 lines · 7.9 KB · RustRaw
//! What a device signs. The port of `packages/core/src/device/signature.ts`.//!//! The server owns the definition//! (`crates/cotton-server/src/devices/device_auth.rs`, `signed_string`) and the phone//! builds the same string a second time, because it cannot import `node:crypto`.//! This is now the THIRD spelling of it, so it is pinned the same way the other//! two are: [`the_signed_string_is_the_servers_byte_for_byte`] asserts the//! literal, and that literal is the one//! `crates/cotton-server/src/devices/device_auth_tests.rs` and//! `crates/cotton-client/src/identity.rs` both pin. A change to any//! side that forgets the others fails a test rather than a pairing.//!//!   "cotton-device-v1" ‖ origin ‖ METHOD ‖ path ‖ ts ‖ nonce ‖ sha256(body)//!   (newline joined)//!//! No bearer anywhere: the GoTrue session, while it still exists, rides as an//! `Authorization` header the bridge reads and the signature ignores. The path//! is `URL.pathname + URL.search`, RAW as sent — percent-encoded, the leading//! `?` when there is a query, no re-ordering, no decoding. The query is signed//! because an unsigned one would let a captured GET signature replay for 120 s//! against any query on the same path. The body hash is SHA-256 over the raw//! bytes AS SENT, lower-case hex — the serialised JSON string itself, never a//! re-serialisation — and an absent or empty body hashes as the empty byte//! string, so a GET and a bodyless POST sign the same way and no form is//! optional.use sha2::{Digest, Sha256};use crate::device::base64url::{base64url_decode, base64url_encode};/// The server's header names, restated (that module is Node-only).pub const DEVICE_HEADER: &str = "x-cotton-device";pub const DEVICE_SIG_HEADER: &str = "x-cotton-device-sig";pub const DEVICE_SIG_CONTEXT: &str = "cotton-device-v1";/// What the device says it IS — `"<platform>/<app version>"`, e.g. `ios/1.2.0`.////// **It is NOT signed, and it is not meant to be.** The signed string is frozen/// (`DEVICE_SIG_CONTEXT`): adding a field to it would refuse every device/// already in the field on its next request. What the signature proves is WHOSE/// row this lands on, and that is the whole of what matters here — the value is/// a device's own description of itself, it decides nothing and admits nobody,/// and the worst a tamperer on the path could achieve is a wrong version number/// beside a name on one screen. Over the relay the connection is TLS end to end/// to the Mac, so there is no such path anyway.////// **Absent means absent.** A build that sends nothing leaves the row's columns/// exactly as they are; nothing here can blank what an older build wrote.pub const DEVICE_APP_HEADER: &str = "x-cotton-device-app";/// The relay's window, reused (P-D2).pub const MAX_DEVICE_CLOCK_SKEW_SECONDS: i64 = 120;/// SHA-256 of zero bytes — what an absent or empty body signs as.pub const EMPTY_BODY_HASH: &str =    "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";/// A signature is 64 bytes, always: Ed25519 says so, and/// [`parse_device_sig_header`] refuses a header carrying any other length.pub const DEVICE_SIG_BYTES: usize = 64;/// The seven fields, before they are joined.////// `body` is the request body EXACTLY as it goes on the wire — the TypeScript/// takes `string | Uint8Array` and hashes a string's UTF-8 bytes, so one/// `Option<&[u8]>` says the same thing: `None` and an empty slice hash alike.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct DeviceSignedInput<'a> {    /// The origin the device addressed, no trailing slash. Not a header.    pub origin: &'a str,    pub method: &'a str,    /// [`signed_path`]: the pathname plus the raw search.    pub path: &'a str,    /// Unix seconds. The TypeScript's `String(ts)` over a non-integer would    /// print a fraction; the field is SECONDS and the verifier's `\d{1,12}`    /// refuses anything else, so the port takes an integer and cannot spell one.    pub ts: i64,    /// 22 chars of base64url on a write; the empty string on GET / HEAD.    pub nonce: &'a str,    /// The body as sent; `None` for none.    pub body: Option<&'a [u8]>,}/// Lower-case hex SHA-256 of the body as sent; the empty hash for none.pub fn body_hash_hex(body: Option<&[u8]>) -> String {    match body {        // An absent body and an empty one hash alike, so a GET and a bodyless        // POST sign the same way.        None | Some([]) => EMPTY_BODY_HASH.to_string(),        Some(bytes) => hex::encode(Sha256::digest(bytes)),    }}/// A URL the device could not address at all.////// The TypeScript throws here — `new URL(x)` on a string that is not a URL is/// a `TypeError: Invalid URL` — and the sentence is kept verbatim so a handler/// can pass it straight to the error envelope.#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]#[error("Invalid URL")]pub struct InvalidUrl;/// The `path` field for a URL, exactly as the server reads it back:/// `pathname + search`, encoded as sent. A fragment never travels; a bare `?`/// is no search at all.////// WHATWG semantics, not string surgery: `/v1/../x` is `/x`, a non-ASCII/// segment is percent-encoded (`/v1/café` → `/v1/caf%C3%A9`), and an origin/// with no path at all signs `/`. That is what `new URL` does, and the two are/// pinned against each other by vectors read out of Node.pub fn signed_path(url: &str) -> Result<String, InvalidUrl> {    let parsed = url::Url::parse(url).map_err(|_| InvalidUrl)?;    Ok(match parsed.query() {        // `URL.search` is the empty string when the query is empty, so a bare        // `?` signs as no query at all.        Some(query) if !query.is_empty() => format!("{}?{}", parsed.path(), query),        _ => parsed.path().to_string(),    })}/// The seven fields, newline joined — the string a device signs.pub fn device_signed_string(input: &DeviceSignedInput<'_>) -> String {    format!(        "{}\n{}\n{}\n{}\n{}\n{}\n{}",        DEVICE_SIG_CONTEXT,        input.origin,        input.method.to_uppercase(),        input.path,        input.ts,        input.nonce,        body_hash_hex(input.body),    )}/// The same string as the bytes an Ed25519 key actually signs.pub fn device_signed_message(input: &DeviceSignedInput<'_>) -> Vec<u8> {    device_signed_string(input).into_bytes()}/// `<ts>.<nonce>.<signature>` — the `x-cotton-device-sig` header's value.////// The TypeScript takes an object; three arguments say the same thing without/// forcing a caller who holds a `[u8; 64]` to build one.pub fn format_device_sig_header(ts: i64, nonce: &str, sig: &[u8]) -> String {    format!("{ts}.{nonce}.{}", base64url_encode(sig))}/// A parsed `x-cotton-device-sig`.////// `sig` is a fixed 64 bytes because [`parse_device_sig_header`] refuses any/// other length — the verifier downstream needs no second length check.#[derive(Debug, Clone, PartialEq, Eq)]pub struct DeviceSigHeader {    pub ts: i64,    pub nonce: String,    pub sig: [u8; DEVICE_SIG_BYTES],}/// `None` for anything that is not `<ts>.<nonce>.<64-byte signature>`.////// `ts` is one to twelve decimal digits — leading zeroes and all, since/// `Number("042")` is 42 — the nonce is base64url or empty, and the signature/// must decode to exactly 64 bytes.pub fn parse_device_sig_header(value: &str) -> Option<DeviceSigHeader> {    let parts: Vec<&str> = value.split('.').collect();    let [ts_raw, nonce, sig_raw] = parts[..] else {        return None;    };    if ts_raw.is_empty() || ts_raw.len() > 12 || !ts_raw.bytes().all(|b| b.is_ascii_digit()) {        return None;    }    if !nonce        .bytes()        .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')    {        return None;    }    let sig: [u8; DEVICE_SIG_BYTES] = base64url_decode(sig_raw)?.try_into().ok()?;    Some(DeviceSigHeader {        ts: ts_raw.parse().ok()?,        nonce: nonce.to_string(),        sig,    })}#[cfg(test)]#[path = "signature_tests.rs"]mod tests;