//! THE INVITE LINK (KS5): what an admin hands the person they are admitting. //! //! `://join?i=`, where the payload is the //! length-prefixed fields below in order, under the tag `cotton-invite-link-v2`. //! One codec serves both ends — the serving Mac that makes the link and the //! device that claims it — so the two cannot drift. //! //! **A LINK IS FLAVOR-BOUND, TWICE.** Its scheme is the app's own //! ([`Flavor::url_scheme`]): a Cotton Dev link does not open in CottonDB and //! the reverse. And when its serving address is a relay name, that name must //! be the flavor's ([`Flavor::admits_relay_name`]): a dev link never carries a //! real household's address, and a dev build never dials one off a link. A //! LAN or Tailscale address names no household and passes either way. //! //! **WHAT THE LINK TELLS WHOEVER SEES IT**, and why that is acceptable in dev //! mode, is in the build file (KS5): the database's id and name, the serving //! Mac's address and key, the admitter's fingerprint and name, and the secret — which //! lets them claim first, which shows the admitter a device fingerprint the //! real joiner's screen does not, and the admitter refuses it. //! //! Every field is a length-prefixed string (`lp(x)`: a 4-byte big-endian //! length, then the bytes), the form every signed string of the keys design //! takes. There is no JSON here: a signature over fields is a signature over //! bytes, and the link is parsed by the same reader a signature check uses. use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine; use crate::device::pairing::relay_name_of; use crate::flavor::Flavor; /// The tag the payload opens with; a payload under another tag is not an /// invite link. pub const LINK_TAG: &str = "cotton-invite-link-v2"; /// The query key the payload rides under. pub const QUERY_KEY: &str = "i"; /// The path of the link: `://join?i=…`. pub const HOST: &str = "join"; /// The fields of an invite link, in the payload's order. #[derive(Debug, Clone, PartialEq, Eq)] pub struct InviteLink { pub database_id: String, pub database_name: String, /// The serving Mac's origin — `https://.relay.cottondb.com`, or a /// LAN / Tailscale origin while the dev relay is not in use. pub server_address: String, /// The serving Mac's device id, its Ed25519 public half: the joiner pins /// the Mac it reaches to this key before it sends anything. pub server_device_id: String, pub invite_id: String, /// The invite's secret, whose SHA-256 the `cotton_invites` row holds. pub secret: Vec, /// The admitter's person key fingerprint, which the joiner's screen shows. pub admitter_fingerprint: String, /// The admitter's name as the inviting database knows them, which the /// joiner's screen says while it waits ("waiting for Asha to admit /// you") — v2's field: v1 carried only the fingerprint, and the screen /// showed an id where a person was meant. Empty when the database knows /// no name for them. pub admitter_name: String, /// RFC 3339, UTC — the same text the `cotton_invites` row holds and the /// invite's `p_sig` covers. pub expires_at: String, } /// Why a string is not an invite link this app may act on. #[derive(Debug, Clone, PartialEq, Eq)] pub enum InviteLinkError { /// The scheme, host or query is not an invite link's at all. NotAnInviteLink, /// A well-formed invite link of the OTHER app: its scheme is that app's, or /// its serving address is a relay name only that app may dial. OtherApp { sentence: String }, /// The payload does not decode to the fields of this version. Malformed, } impl InviteLinkError { /// The sentence a screen shows. pub fn sentence(&self) -> String { match self { InviteLinkError::NotAnInviteLink => "this is not an invite link".to_string(), InviteLinkError::OtherApp { sentence } => sentence.clone(), InviteLinkError::Malformed => { "this invite link is damaged; ask for a new one".to_string() } } } } impl std::fmt::Display for InviteLinkError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.sentence()) } } impl std::error::Error for InviteLinkError {} /// `lp(x)`: a 4-byte big-endian length, then the bytes. pub fn lp(out: &mut Vec, field: &[u8]) { let len = u32::try_from(field.len()).expect("a field under 4 GiB"); out.extend_from_slice(&len.to_be_bytes()); out.extend_from_slice(field); } /// The next `lp` field, or `None` when the bytes do not hold one. fn read_lp<'a>(bytes: &mut &'a [u8]) -> Option<&'a [u8]> { let (len, rest) = bytes.split_first_chunk::<4>()?; let len = usize::try_from(u32::from_be_bytes(*len)).ok()?; let (field, rest) = rest.split_at_checked(len)?; *bytes = rest; Some(field) } fn read_text<'a>(bytes: &mut &'a [u8]) -> Option<&'a str> { std::str::from_utf8(read_lp(bytes)?).ok() } impl InviteLink { /// The payload bytes: the tag, then every field, each length-prefixed. pub fn payload(&self) -> Vec { let mut out = Vec::new(); lp(&mut out, LINK_TAG.as_bytes()); lp(&mut out, self.database_id.as_bytes()); lp(&mut out, self.database_name.as_bytes()); lp(&mut out, self.server_address.as_bytes()); lp(&mut out, self.server_device_id.as_bytes()); lp(&mut out, self.invite_id.as_bytes()); lp(&mut out, &self.secret); lp(&mut out, self.admitter_fingerprint.as_bytes()); lp(&mut out, self.admitter_name.as_bytes()); lp(&mut out, self.expires_at.as_bytes()); out } /// The link itself, under this app's scheme. /// /// A LINK IS MADE ONLY FOR AN ADDRESS THE FLAVOR MAY DIAL: making a Cotton /// Dev link that names the real household's relay is refused here, before /// anything is handed out, with the same sentence a parse would give. pub fn encode(&self, flavor: Flavor) -> Result { refuse_other_apps_address(flavor, &self.server_address)?; Ok(format!( "{}://{HOST}?{QUERY_KEY}={}", flavor.url_scheme(), URL_SAFE_NO_PAD.encode(self.payload()) )) } /// Whether this app may put `address` in a link — the same rule a parse /// holds the address to, asked before an invite is made. pub fn parse_address(address: &str, flavor: Flavor) -> Result<(), InviteLinkError> { refuse_other_apps_address(flavor, address) } /// The fields of a link, when it is this app's. /// /// THE ORDER IS THE PRIVACY ORDER: the scheme first, so a link of the /// other app is named as such before its payload is read; then the /// payload; then the address inside it, held to the flavor. pub fn parse(link: &str, flavor: Flavor) -> Result { let link = link.trim(); let (scheme, rest) = link.split_once("://").ok_or(InviteLinkError::NotAnInviteLink)?; let scheme = scheme.to_ascii_lowercase(); let rest = rest .strip_prefix(HOST) .and_then(|rest| rest.strip_prefix('/').or(Some(rest))) .ok_or(InviteLinkError::NotAnInviteLink)?; let query = rest.strip_prefix('?').ok_or(InviteLinkError::NotAnInviteLink)?; let encoded = query .split('&') .find_map(|pair| pair.strip_prefix(QUERY_KEY).and_then(|v| v.strip_prefix('='))) .ok_or(InviteLinkError::NotAnInviteLink)?; if scheme != flavor.url_scheme() { if scheme == flavor.other().url_scheme() { return Err(InviteLinkError::OtherApp { sentence: other_apps_link(flavor), }); } return Err(InviteLinkError::NotAnInviteLink); } let bytes = URL_SAFE_NO_PAD .decode(encoded) .map_err(|_| InviteLinkError::Malformed)?; let link = Self::from_payload(&bytes).ok_or(InviteLinkError::Malformed)?; refuse_other_apps_address(flavor, &link.server_address)?; Ok(link) } /// The fields off the payload bytes, or `None` for any other bytes. pub fn from_payload(mut bytes: &[u8]) -> Option { if read_lp(&mut bytes)? != LINK_TAG.as_bytes() { return None; } let link = InviteLink { database_id: read_text(&mut bytes)?.to_string(), database_name: read_text(&mut bytes)?.to_string(), server_address: read_text(&mut bytes)?.to_string(), server_device_id: read_text(&mut bytes)?.to_string(), invite_id: read_text(&mut bytes)?.to_string(), secret: read_lp(&mut bytes)?.to_vec(), admitter_fingerprint: read_text(&mut bytes)?.to_string(), admitter_name: read_text(&mut bytes)?.to_string(), expires_at: read_text(&mut bytes)?.to_string(), }; // Nothing after the last field: a payload with a tail is not this // version's, and reading it as if it were would admit a link whose // extra field somebody meant something by. if !bytes.is_empty() { return None; } if link.database_id.is_empty() || link.server_address.is_empty() || link.server_device_id.is_empty() || link.invite_id.is_empty() || link.secret.is_empty() || link.expires_at.is_empty() { return None; } Some(link) } } /// THE DEVICE STATEMENT'S BYTES (KS3's form): `lp(tag) ‖ lp(database id) ‖ /// lp(person key) ‖ lp(device key) ‖ lp(vault public key)`. The person key /// signs them under [`DEVICE_STATEMENT_TAG`] (`p_sig`) and the device under /// [`DEVICE_STATEMENT_CONSENT_TAG`] (`d_sig`); the claim carries both and the /// serving Mac checks both before it writes the statement. Declared here, beside /// the claim's codec, until KS3's `keys/` module lands and this moves there. pub fn device_statement_bytes( tag: &str, database_id: &str, person_key: &str, device_key: &str, vault_public_key: &str, ) -> Vec { let mut out = Vec::new(); lp(&mut out, tag.as_bytes()); lp(&mut out, database_id.as_bytes()); lp(&mut out, person_key.as_bytes()); lp(&mut out, device_key.as_bytes()); lp(&mut out, vault_public_key.as_bytes()); out } /// The tag the person key signs a device statement under. pub const DEVICE_STATEMENT_TAG: &str = "cotton-device-statement-v1"; /// The tag the named device signs its consent to a statement under. pub const DEVICE_STATEMENT_CONSENT_TAG: &str = "cotton-device-statement-consent-v1"; /// A relay name in the address that only the other app may dial is refused; /// an address naming no relay passes. fn refuse_other_apps_address(flavor: Flavor, address: &str) -> Result<(), InviteLinkError> { let Some(name) = relay_name_of(address) else { return Ok(()); }; match flavor.refusal_for_relay_name(name) { Some(sentence) => Err(InviteLinkError::OtherApp { sentence }), None => Ok(()), } } fn other_apps_link(flavor: Flavor) -> String { format!( "this invite is for {}, not {}", flavor.other().display_name(), flavor.display_name() ) } #[cfg(test)] #[path = "invite_link_tests.rs"] mod invite_link_tests; /// An invite refusal's words, shared by the link reader and the server: the /// protocol's own sentences, now that no shipped member definition carries /// them (72nd amendment, 21 Oct 2026). pub fn status_word(key: &str) -> &'static str { match key { "expired" => "Expired", "spent" => "Spent", "phone_required" => "Sign in by phone to join as staff.", "staff_not_configured" => "Staff invites are not set up for this business.", "staff_rights_invalid" => "Staff invite rights are not valid.", "staff_expiry_invalid" => "Staff invite expiry is not valid.", "key_required" => "Unlock your owner key to manage staff.", "revoked" => "this invite was withdrawn; ask for a new one", "wrong_secret" => "this is not the link that was made; ask for a new one", "person_signature" => "the person key did not sign this statement", "device_consent" => "the device did not consent to this statement", "recipient_required" => "Enter an international phone number starting with +.", "staff_invalid" => "The staff invitation is invalid.", "sign_in_again" => "Sign in again to join as staff.", _ => panic!("no invite word {key:?}"), } }