iwlink 0.1.1

IntelliWallet Link - encrypted phone to computer protocol for IntelliWallet for Browser
Documentation
//! The pairing QR code, and the confirmation code both screens show.
//!
//! # QR payload
//!
//! `iwlink:` followed by unpadded base64url of:
//!
//! ```text
//! u8   format (1)
//! u16  highest protocol version the helper speaks, big endian
//! 16   helper install id
//! 32   helper static public key
//! 32   one-time pre-shared key
//! i64  expiry, unix seconds, big endian
//! u8   name length in bytes (at most 64)
//! ..   computer name, UTF-8
//! ```
//!
//! Binary rather than JSON because a QR code grows with every byte, and a
//! smaller code scans faster from a laptop screen.
//!
//! The pre-shared key is what stops a helper that did not show this QR code
//! from completing the pairing handshake, and it is valid for
//! [`OFFER_TTL_SECS`] only. The confirmation code covers the remaining case: a
//! photographed QR code used by someone else within those two minutes.

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use zeroize::Zeroizing;

use crate::error::{LinkError, Result};
use crate::keys::{KEY_LEN, PublicKey};
use crate::random;

/// URI scheme prefix of the QR payload.
pub const OFFER_PREFIX: &str = "iwlink:";

/// How long a pairing offer stays valid.
pub const OFFER_TTL_SECS: i64 = 120;

/// Longest computer name carried in an offer, in bytes.
pub const MAX_NAME_BYTES: usize = 64;

/// Length of the pre-shared key.
pub const PSK_LEN: usize = 32;

const FORMAT: u8 = 1;
const FIXED_LEN: usize = 1 + 2 + HelperId::LEN + KEY_LEN + PSK_LEN + 8 + 1;

/// Random identifier of one helper install. Stable across reboots, replaced
/// only if the helper's keys are reset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HelperId(pub [u8; HelperId::LEN]);

impl HelperId {
    pub const LEN: usize = 16;

    pub fn generate() -> Result<HelperId> {
        Ok(HelperId(random::bytes()?))
    }

    /// Lowercase hex, for storage keys and logs.
    pub fn to_hex(&self) -> String {
        self.0.iter().map(|b| format!("{b:02x}")).collect()
    }

    /// Parse the output of [`HelperId::to_hex`].
    pub fn from_hex(text: &str) -> Result<HelperId> {
        if text.len() != Self::LEN * 2 || !text.is_ascii() {
            return Err(LinkError::InvalidKey("helper id"));
        }
        let mut out = [0u8; Self::LEN];
        for (i, byte) in out.iter_mut().enumerate() {
            *byte = u8::from_str_radix(&text[i * 2..i * 2 + 2], 16)
                .map_err(|_| LinkError::InvalidKey("helper id"))?;
        }
        Ok(HelperId(out))
    }
}

/// Everything the phone needs to start pairing with a helper.
#[derive(Clone, PartialEq, Eq)]
pub struct PairingOffer {
    /// Highest protocol version the helper speaks.
    pub version: u16,
    pub helper_id: HelperId,
    pub helper_public: PublicKey,
    pub psk: Zeroizing<[u8; PSK_LEN]>,
    /// Unix seconds after which the helper refuses this offer.
    pub expires_at: i64,
    /// Display name of the computer, shown on the phone.
    pub name: String,
}

impl PairingOffer {
    /// A new offer with a fresh pre-shared key, valid for [`OFFER_TTL_SECS`].
    pub fn create(
        helper_id: HelperId,
        helper_public: PublicKey,
        name: &str,
        now: i64,
    ) -> Result<PairingOffer> {
        Ok(PairingOffer {
            version: crate::version::PROTOCOL_VERSION,
            helper_id,
            helper_public,
            psk: Zeroizing::new(random::bytes()?),
            expires_at: now.saturating_add(OFFER_TTL_SECS),
            name: truncate_name(name),
        })
    }

    pub fn is_expired(&self, now: i64) -> bool {
        now >= self.expires_at
    }

    /// The text to put in the QR code.
    pub fn to_uri(&self) -> String {
        let name = self.name.as_bytes();
        let mut raw = Zeroizing::new(Vec::with_capacity(FIXED_LEN + name.len()));
        raw.push(FORMAT);
        raw.extend_from_slice(&self.version.to_be_bytes());
        raw.extend_from_slice(&self.helper_id.0);
        raw.extend_from_slice(self.helper_public.as_bytes());
        raw.extend_from_slice(self.psk.as_ref());
        raw.extend_from_slice(&self.expires_at.to_be_bytes());
        // `name` was truncated to MAX_NAME_BYTES on the way in, so it fits a u8.
        raw.push(name.len() as u8);
        raw.extend_from_slice(name);
        format!("{OFFER_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw.as_slice()))
    }

    /// Parse a scanned QR code. Does not check expiry; see
    /// [`PairingOffer::is_expired`].
    pub fn parse(uri: &str) -> Result<PairingOffer> {
        let encoded = uri
            .strip_prefix(OFFER_PREFIX)
            .ok_or(LinkError::InvalidOffer("not an IntelliWallet pairing code"))?;
        let raw = Zeroizing::new(
            URL_SAFE_NO_PAD
                .decode(encoded.trim())
                .map_err(|_| LinkError::InvalidOffer("encoding"))?,
        );
        if raw.len() < FIXED_LEN {
            return Err(LinkError::InvalidOffer("too short"));
        }
        if raw[0] != FORMAT {
            return Err(LinkError::InvalidOffer("unknown format"));
        }

        let mut at = 1;
        let mut take = |n: usize| {
            let slice = &raw[at..at + n];
            at += n;
            slice
        };
        let version = u16::from_be_bytes(take(2).try_into().expect("2 bytes"));
        let helper_id = HelperId(take(HelperId::LEN).try_into().expect("16 bytes"));
        let helper_public = PublicKey::from_slice(take(KEY_LEN))?;
        let psk = Zeroizing::new(<[u8; PSK_LEN]>::try_from(take(PSK_LEN)).expect("32 bytes"));
        let expires_at = i64::from_be_bytes(take(8).try_into().expect("8 bytes"));
        let name_len = take(1)[0] as usize;

        if name_len > MAX_NAME_BYTES || raw.len() != FIXED_LEN + name_len {
            return Err(LinkError::InvalidOffer("name length"));
        }
        let name = std::str::from_utf8(&raw[FIXED_LEN..])
            .map_err(|_| LinkError::InvalidOffer("name encoding"))?
            .to_owned();
        if version == 0 {
            return Err(LinkError::InvalidOffer("version"));
        }

        Ok(PairingOffer {
            version,
            helper_id,
            helper_public,
            psk,
            expires_at,
            name,
        })
    }
}

impl std::fmt::Debug for PairingOffer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PairingOffer")
            .field("version", &self.version)
            .field("helper_id", &self.helper_id.to_hex())
            .field("expires_at", &self.expires_at)
            .field("name", &self.name)
            .finish_non_exhaustive()
    }
}

/// The 6 digit code both screens show after the pairing handshake.
///
/// Derived from the Noise handshake hash, which is identical on both sides
/// only if both saw exactly the same handshake: same keys, same pre-shared
/// key, no one in the middle. The hash is a BLAKE2s output, so its first four
/// bytes are uniformly distributed, and reducing them modulo one million has a
/// bias below one part in four thousand, which is irrelevant for a code a
/// human compares once.
pub fn confirmation_code(handshake_hash: &[u8]) -> String {
    let mut word = [0u8; 4];
    let n = handshake_hash.len().min(4);
    word[..n].copy_from_slice(&handshake_hash[..n]);
    format!("{:06}", u32::from_be_bytes(word) % 1_000_000)
}

/// Cut a name to at most [`MAX_NAME_BYTES`] bytes on a character boundary.
fn truncate_name(name: &str) -> String {
    let name = name.trim();
    if name.len() <= MAX_NAME_BYTES {
        return name.to_owned();
    }
    let mut end = MAX_NAME_BYTES;
    while !name.is_char_boundary(end) {
        end -= 1;
    }
    name[..end].to_owned()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn offer(name: &str) -> PairingOffer {
        PairingOffer::create(
            HelperId([7; HelperId::LEN]),
            PublicKey([9; KEY_LEN]),
            name,
            1_000,
        )
        .unwrap()
    }

    #[test]
    fn round_trips() {
        let original = offer("Studio MacBook");
        let parsed = PairingOffer::parse(&original.to_uri()).unwrap();
        assert_eq!(parsed, original);
        assert_eq!(parsed.expires_at, 1_000 + OFFER_TTL_SECS);
    }

    #[test]
    fn each_offer_has_a_fresh_psk() {
        assert_ne!(offer("a").psk, offer("a").psk);
    }

    #[test]
    fn expiry() {
        let o = offer("a");
        assert!(!o.is_expired(1_000 + OFFER_TTL_SECS - 1));
        assert!(o.is_expired(1_000 + OFFER_TTL_SECS));
    }

    #[test]
    fn long_names_are_cut_on_a_character_boundary() {
        let long = "ü".repeat(40); // 80 bytes
        let o = offer(&long);
        assert!(o.name.len() <= MAX_NAME_BYTES);
        assert!(o.name.chars().all(|c| c == 'ü'));
        assert_eq!(PairingOffer::parse(&o.to_uri()).unwrap().name, o.name);
    }

    #[test]
    fn rejects_malformed_input() {
        let good = offer("a").to_uri();
        let body = good.strip_prefix(OFFER_PREFIX).unwrap();

        assert!(PairingOffer::parse(body).is_err(), "missing prefix");
        assert!(PairingOffer::parse("iwlink:!!!").is_err(), "bad base64");
        assert!(PairingOffer::parse("iwlink:AAAA").is_err(), "too short");

        let mut raw = URL_SAFE_NO_PAD.decode(body).unwrap();
        raw[0] = 2;
        let bad_format = format!("{OFFER_PREFIX}{}", URL_SAFE_NO_PAD.encode(&raw));
        assert!(PairingOffer::parse(&bad_format).is_err(), "unknown format");

        let mut raw = URL_SAFE_NO_PAD.decode(body).unwrap();
        raw.push(b'x');
        let trailing = format!("{OFFER_PREFIX}{}", URL_SAFE_NO_PAD.encode(&raw));
        assert!(PairingOffer::parse(&trailing).is_err(), "trailing byte");
    }

    #[test]
    fn debug_does_not_print_the_psk() {
        let text = format!("{:?}", offer("a"));
        assert!(!text.contains("psk"), "{text}");
    }

    #[test]
    fn helper_id_hex_round_trips() {
        let id = HelperId::generate().unwrap();
        assert_eq!(HelperId::from_hex(&id.to_hex()).unwrap(), id);
        assert!(HelperId::from_hex("zz").is_err());
    }

    #[test]
    fn confirmation_code_is_six_digits_and_input_sensitive() {
        let a = confirmation_code(&[0xFF; 32]);
        assert_eq!(a.len(), 6);
        assert!(a.chars().all(|c| c.is_ascii_digit()));
        assert_eq!(confirmation_code(&[0; 32]), "000000");
        assert_ne!(
            confirmation_code(&[1, 2, 3, 4]),
            confirmation_code(&[1, 2, 3, 5])
        );
    }
}