garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

.. /crates/e2ee/src/lib.rs

raw

//! End-to-end encrypted private chats (`docs/notes/encrypted-chat.md`).
//!
//! One [`Device`] per installation per account: its signing key, the MLS state of
//! every private chat it is in, and the calls that turn plaintext into sealed
//! bytes and back. It does no I/O. What goes over the wire, and when, is the
//! caller's business — the client's resource sends what this returns and feeds
//! this what arrives — which is what lets the tests below run three devices
//! against each other with a `Vec` standing in for the server.
//!
//! # The server's part, and why it is small
//!
//! The simulator is an MLS *delivery service*: it keeps a directory of key
//! packages (the one-use public keys a device publishes so others can add it to
//! a chat), an ordered log of sealed messages per chat, and a list of which
//! accounts are in which chat so it knows whom to deliver to. It never holds a
//! key that opens anything. Two things follow and both are load-bearing:
//!
//! - **Commits must be applied in one order by everyone**, so the server orders
//!   them: a commit is accepted only if it was made in the chat's current epoch
//!   ([`Outgoing::epoch`]), and the second of two simultaneous commits is
//!   refused. The refused sender calls [`Device::discard_pending`] and tries
//!   again after catching up. Application messages carry no such constraint.
//! - **A device does not read its own entries back.** MLS does not hand a
//!   sender its own application message as a message (openmls answers with a
//!   variant this crate refuses), and its own commit was already applied by
//!   [`Device::confirm_pending`]. The log replays everything to everyone, so a
//!   device skips entries whose sender is itself ([`Device::is_me`]) and shows
//!   what it sent from its own copy. The one exception is its own commit when
//!   the server's answer to it was lost: [`Device::own_commit`] recognises it,
//!   and the device applies it from the log instead.
//!
//! # Identity
//!
//! A member's credential is its full address (`name@server`, protocol 37) and
//! device id, joined by a NUL. The server vouches for the address at sign-in;
//! nothing here verifies it further. That is the known limit of shipping
//! without identity proofs, and the note says so. A full address rather than
//! a username because a credential lasts as long as the device, and chats are
//! meant to reach other servers one day (`cartopolis_core::address`).

use std::collections::BTreeMap;

use openmls::prelude::tls_codec::{Deserialize as _, Serialize as _};
use openmls::prelude::*;
use openmls_basic_credential::SignatureKeyPair;
use openmls_rust_crypto::OpenMlsRustCrypto;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// X25519, AES-128-GCM, SHA-256, Ed25519: MLS's mandatory-to-implement suite,
/// and the one every other implementation is guaranteed to speak.
const CIPHERSUITE: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519;

/// Past epochs whose keys are kept, so a message sent just before a membership
/// change and delivered just after it still opens. Every epoch kept is key
/// material a stolen device would still hold, so it is small.
const MAX_PAST_EPOCHS: usize = 3;

/// Version of [`Device::save`]'s format. Bumped when the layout changes; an
/// older blob is refused rather than half-read, because a device that
/// misreads its own keys is worse than one that starts again.
///
/// 2 (protocol 37): identities are full addresses. A version-1 device's
/// credential holds a bare username for as long as it exists, so it is refused
/// and the client starts a new device.
const SAVE_VERSION: u8 = 2;

#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Anything the MLS library refused, with its own words. Kept as text so
    /// the storage provider's error type does not leak into every caller.
    #[error("{0}")]
    Mls(String),
    #[error("not in that chat")]
    UnknownGroup,
    #[error("unreadable bytes: {0}")]
    Decode(String),
    #[error("saved state is from a different version ({0})")]
    WrongVersion(u8),
}

fn mls(e: impl std::fmt::Debug) -> Error {
    Error::Mls(format!("{e:?}"))
}

/// Who sent something: the account and which of its devices.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Identity {
    pub address: String,
    pub device: Uuid,
}

impl Identity {
    fn to_bytes(&self) -> Vec<u8> {
        let mut out = self.address.as_bytes().to_vec();
        out.push(0);
        out.extend_from_slice(self.device.as_bytes());
        out
    }

    fn from_bytes(b: &[u8]) -> Option<Self> {
        let split = b.iter().position(|&c| c == 0)?;
        let address = String::from_utf8(b[..split].to_vec()).ok()?;
        let device = Uuid::from_slice(b.get(split + 1..)?).ok()?;
        Some(Self { address, device })
    }

    fn from_credential(c: &Credential) -> Option<Self> {
        BasicCredential::try_from(c.clone())
            .ok()
            .and_then(|b| Self::from_bytes(b.identity()))
    }
}

/// What a device hands the server after changing a chat's membership.
#[derive(Debug, Clone)]
pub struct Outgoing {
    /// Group id, as the server keys it.
    pub group: Vec<u8>,
    /// The epoch the message was made in. For a commit the server accepts it
    /// only if this is the chat's current epoch.
    pub epoch: u64,
    /// The sealed message for the chat's log.
    pub message: Vec<u8>,
    /// For a commit that adds devices: the invitation, addressed to them.
    pub welcome: Option<Vec<u8>>,
}

/// What reading one log entry produced.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Received {
    /// Somebody said something. The bytes are a [`Payload`] (see
    /// [`Payload::decode`]); kept raw here so a newer message type this build
    /// cannot read is still *received* — advancing the ratchet — and only
    /// fails at display.
    Message { from: Identity, bytes: Vec<u8> },
    /// Membership changed; [`Device::members`] has the new list.
    Membership { by: Identity },
}

/// One of a device's own log entries, seen from the device ([`Device::own_commit`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OwnCommit {
    /// Not a commit (or not readable as one): skip it, as every own entry.
    NotACommit,
    /// A commit this device has already applied.
    Applied,
    /// The commit this device is waiting to hear about: the server took it,
    /// so apply it ([`Device::confirm_pending`]).
    Pending,
    /// A commit of this device's in its current epoch that it no longer
    /// holds (it was discarded as refused, and was not). The chat moved on
    /// without this device, which cannot follow it.
    Lost,
}

/// The plaintext inside an application message.
///
/// **Append-only**: postcard encodes a variant by its index, so a new kind goes
/// at the end and nothing is ever reordered or removed. An older build that
/// meets a variant it lacks gets a decode error and shows "a message this
/// version can't display" instead of guessing.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Payload {
    Text {
        body: String,
        sent_at_ms: u64,
    },
    /// An ActivityStreams object as JSON — today always a point
    /// (`cartopolis_core::point`). Carried as text rather than as a typed struct
    /// so this crate stays about sealing, and so a newer kind of object reaches
    /// an older build as "something it cannot show" rather than a decode error
    /// that looks like a broken chat.
    Object {
        json: String,
        sent_at_ms: u64,
    },
    /// Where the sender's *phone* is, shared with this chat until `until_ms`
    /// (Unix milliseconds). Sent repeatedly while the share lasts.
    ///
    /// **The end is enforced by the devices, not the server**, which cannot read
    /// this: the sender stops sending at `until_ms`, and every receiver drops the
    /// position at `until_ms` whatever it last heard — so a sender whose phone
    /// dies mid-share still disappears on time. Never federated and never an
    /// ActivityStreams object: a live position is not a post.
    Location {
        latitude: f64,
        longitude: f64,
        accuracy_m: f32,
        until_ms: u64,
        sent_at_ms: u64,
    },
    /// The sender stopped sharing before `until_ms`.
    LocationStopped {
        sent_at_ms: u64,
    },
    /// A group chat's name, set by whoever sent it last. Sealed like
    /// everything else, so the server never learns what a group is called.
    GroupName {
        name: String,
        sent_at_ms: u64,
    },
    /// A picture: where its ciphertext is stored (the simulator's picture
    /// store, by hash) and the key that opens it ([`seal_attachment`]).
    ///
    /// The picture itself is not in here because the server refuses a log
    /// entry over 64 KB, on purpose; the key is, because this message is the
    /// one thing only the chat's members can read. `width`/`height` are the
    /// picture's own, so a bubble can be laid out before it has arrived.
    Picture {
        hash: String,
        key: [u8; 32],
        nonce: [u8; 12],
        width: u32,
        height: u32,
        caption: String,
        sent_at_ms: u64,
    },

    // The four below are what a work chat needs on top of lines (the web UI's
    // workspaces, `docs/notes/web-chat.md`). Each names another message by its
    // place in the chat's log (`E2eeDeliver::seq`), which every member sees the
    // same: the server orders the log, and that order is the only id a message
    // has that nobody had to agree on separately.
    /// A line in the thread under the message at `parent`.
    Reply {
        parent: u64,
        body: String,
        sent_at_ms: u64,
    },
    /// An emoji reaction to the message at `target`; `remove` takes it back.
    React {
        target: u64,
        emoji: String,
        remove: bool,
        sent_at_ms: u64,
    },
    /// The sender's new text for a message of theirs at `target`. Receivers
    /// apply it only if the target's sender is the same person.
    Edit {
        target: u64,
        body: String,
        sent_at_ms: u64,
    },
    /// The sender takes back a message of theirs at `target`. Receivers apply
    /// it only if the target's sender is the same person.
    Delete {
        target: u64,
        sent_at_ms: u64,
    },
    /// What was said before somebody joined, for them: a sealed attachment
    /// (`seal_attachment`) holding up to a few hundred earlier messages, sent
    /// by the device that added them. Its contents are that device's claim,
    /// not the log's: receivers show it as history shared by `from`.
    History {
        hash: String,
        key: [u8; 32],
        nonce: [u8; 12],
        /// How many messages it holds.
        count: u32,
        sent_at_ms: u64,
    },
}

/// An attachment encrypted for upload, and what opens it.
#[derive(Debug, Clone)]
pub struct SealedAttachment {
    pub bytes: Vec<u8>,
    pub key: [u8; 32],
    pub nonce: [u8; 12],
}

/// Encrypt an attachment under a key made for it alone.
///
/// ChaCha20-Poly1305 through the same RustCrypto provider MLS runs on, so this
/// adds no dependency and no C. A fresh random key per attachment means the
/// nonce can never repeat under one key; it is random too, rather than zero,
/// only so nobody has to re-derive that argument.
pub fn seal_attachment(plain: &[u8]) -> Result<SealedAttachment, Error> {
    let provider = OpenMlsRustCrypto::default();
    let key: [u8; 32] = provider.rand().random_array().map_err(mls)?;
    let nonce: [u8; 12] = provider.rand().random_array().map_err(mls)?;
    let bytes = provider
        .crypto()
        .aead_encrypt(AeadType::ChaCha20Poly1305, &key, plain, &nonce, &[])
        .map_err(mls)?;
    Ok(SealedAttachment { bytes, key, nonce })
}

/// Open an attachment. Fails — never returns garbage — if a byte of it, the
/// key or the nonce is wrong: the tag is checked first.
pub fn open_attachment(sealed: &[u8], key: &[u8; 32], nonce: &[u8; 12]) -> Result<Vec<u8>, Error> {
    OpenMlsRustCrypto::default()
        .crypto()
        .aead_decrypt(AeadType::ChaCha20Poly1305, key, sealed, nonce, &[])
        .map_err(|e| Error::Decode(format!("attachment does not open: {e:?}")))
}

/// `N` bytes from the same random source the keys come from.
pub fn random_bytes<const N: usize>() -> Result<[u8; N], Error> {
    OpenMlsRustCrypto::default()
        .rand()
        .random_array()
        .map_err(mls)
}

/// The key a person's chat backup is sealed under, from the secret their
/// recovery key spells. HKDF-SHA256, not a slow password hash: the secret is
/// random and long enough that guessing it is hopeless however fast each
/// guess is, which a chosen password would not be.
pub fn backup_key(secret: &[u8]) -> Result<[u8; 32], Error> {
    let provider = OpenMlsRustCrypto::default();
    let crypto = provider.crypto();
    let prk = crypto
        .hkdf_extract(HashType::Sha2_256, b"cartopolis recovery key", secret)
        .map_err(mls)?;
    let okm = crypto
        .hkdf_expand(HashType::Sha2_256, prk.as_slice(), b"chat backup v1", 32)
        .map_err(mls)?;
    okm.as_slice()
        .try_into()
        .map_err(|_| Error::Decode("a short backup key".into()))
}

/// Seal `plain` under a key that is used again (a backup, re-sealed each time
/// it changes): a fresh random nonce each time, kept in front of the
/// ciphertext, since one key with a repeated nonce would give it away.
pub fn seal_with_key(key: &[u8; 32], plain: &[u8]) -> Result<Vec<u8>, Error> {
    let nonce: [u8; 12] = random_bytes()?;
    let sealed = OpenMlsRustCrypto::default()
        .crypto()
        .aead_encrypt(AeadType::ChaCha20Poly1305, key, plain, &nonce, &[])
        .map_err(mls)?;
    let mut out = nonce.to_vec();
    out.extend(sealed);
    Ok(out)
}

/// Open what [`seal_with_key`] sealed. Fails if the key is not the one.
pub fn open_with_key(key: &[u8; 32], sealed: &[u8]) -> Result<Vec<u8>, Error> {
    let (nonce, body) = sealed
        .split_at_checked(12)
        .ok_or_else(|| Error::Decode("too short to be sealed".into()))?;
    OpenMlsRustCrypto::default()
        .crypto()
        .aead_decrypt(AeadType::ChaCha20Poly1305, key, body, nonce, &[])
        .map_err(|e| Error::Decode(format!("does not open with that key: {e:?}")))
}

impl Payload {
    #[must_use]
    pub fn encode(&self) -> Vec<u8> {
        postcard::to_allocvec(self).unwrap_or_default()
    }

    pub fn decode(bytes: &[u8]) -> Result<Self, Error> {
        postcard::from_bytes(bytes).map_err(|e| Error::Decode(e.to_string()))
    }
}

#[derive(Serialize, Deserialize)]
struct Saved {
    version: u8,
    me: Identity,
    signer_public: Vec<u8>,
    groups: Vec<Vec<u8>>,
    storage: BTreeMap<Vec<u8>, Vec<u8>>,
}

/// One installation's keys and chats.
pub struct Device {
    me: Identity,
    provider: OpenMlsRustCrypto,
    signer: SignatureKeyPair,
    credential: CredentialWithKey,
    groups: BTreeMap<Vec<u8>, MlsGroup>,
}

impl Device {
    /// A new device with a fresh signing key and no chats, for the person at
    /// `address` — a full `name@server`, never a bare username: it goes into
    /// the credential, which cannot change for as long as the device exists.
    pub fn new(address: &str, device: Uuid) -> Result<Self, Error> {
        match address.rsplit_once('@') {
            Some((name, server)) if !name.is_empty() && !server.is_empty() => {}
            _ => return Err(Error::Mls(format!("{address:?} is not a full address"))),
        }
        let provider = OpenMlsRustCrypto::default();
        let signer = SignatureKeyPair::new(CIPHERSUITE.signature_algorithm()).map_err(mls)?;
        signer.store(provider.storage()).map_err(mls)?;
        let me = Identity {
            address: address.to_lowercase(),
            device,
        };
        let credential = credential_for(&me, &signer);
        Ok(Self {
            me,
            provider,
            signer,
            credential,
            groups: BTreeMap::new(),
        })
    }

    #[must_use]
    pub fn identity(&self) -> &Identity {
        &self.me
    }

    /// Whether a log entry's sender is this very device.
    #[must_use]
    pub fn is_me(&self, address: &str, device: Uuid) -> bool {
        device == self.me.device && address.eq_ignore_ascii_case(&self.me.address)
    }

    /// Everything needed to come back after a restart, as one blob.
    ///
    /// It holds private keys. The caller stores it where the app keeps its own
    /// data and nowhere else — never in a cache that gets evicted, since losing
    /// it means losing every chat on this device.
    #[must_use]
    pub fn save(&self) -> Vec<u8> {
        let storage = self
            .provider
            .storage()
            .values
            .read()
            .map(|v| v.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
            .unwrap_or_default();
        let saved = Saved {
            version: SAVE_VERSION,
            me: self.me.clone(),
            signer_public: self.signer.public().to_vec(),
            groups: self.groups.keys().cloned().collect(),
            storage,
        };
        postcard::to_allocvec(&saved).unwrap_or_default()
    }

    pub fn load(bytes: &[u8]) -> Result<Self, Error> {
        let saved: Saved = postcard::from_bytes(bytes).map_err(|e| Error::Decode(e.to_string()))?;
        if saved.version != SAVE_VERSION {
            return Err(Error::WrongVersion(saved.version));
        }
        let provider = OpenMlsRustCrypto::default();
        if let Ok(mut values) = provider.storage().values.write() {
            values.extend(saved.storage);
        }
        let signer = SignatureKeyPair::read(
            provider.storage(),
            &saved.signer_public,
            CIPHERSUITE.signature_algorithm(),
        )
        .ok_or_else(|| Error::Mls("signing key missing from saved state".into()))?;
        let mut groups = BTreeMap::new();
        for id in saved.groups {
            if let Some(g) =
                MlsGroup::load(provider.storage(), &GroupId::from_slice(&id)).map_err(mls)?
            {
                groups.insert(id, g);
            }
        }
        let credential = credential_for(&saved.me, &signer);
        Ok(Self {
            me: saved.me,
            provider,
            signer,
            credential,
            groups,
        })
    }

    /// `n` fresh key packages for the server's directory. Each can be used once,
    /// by one person adding this device to one chat.
    pub fn key_packages(&mut self, n: usize) -> Result<Vec<Vec<u8>>, Error> {
        (0..n)
            .map(|_| {
                let bundle = KeyPackage::builder()
                    .build(
                        CIPHERSUITE,
                        &self.provider,
                        &self.signer,
                        self.credential.clone(),
                    )
                    .map_err(mls)?;
                bundle.key_package().tls_serialize_detached().map_err(mls)
            })
            .collect()
    }

    /// Start a chat with only this device in it. Returns its id.
    ///
    /// `id` is the caller's: it names the chat's home server
    /// (`cartopolis_core::address::group_id`), which is a decision about the
    /// network, not about keys.
    pub fn create_group(&mut self, id: &[u8]) -> Result<Vec<u8>, Error> {
        let config = MlsGroupCreateConfig::builder()
            .ciphersuite(CIPHERSUITE)
            .use_ratchet_tree_extension(true)
            .wire_format_policy(PURE_CIPHERTEXT_WIRE_FORMAT_POLICY)
            .max_past_epochs(MAX_PAST_EPOCHS)
            .build();
        let group = MlsGroup::new_with_group_id(
            &self.provider,
            &self.signer,
            &config,
            GroupId::from_slice(id),
            self.credential.clone(),
        )
        .map_err(mls)?;
        let id = group.group_id().as_slice().to_vec();
        self.groups.insert(id.clone(), group);
        Ok(id)
    }

    /// Add devices to a chat, from key packages the server handed out.
    ///
    /// The change is *pending* until the server accepts the commit: call
    /// [`Self::confirm_pending`] when it does and [`Self::discard_pending`] when
    /// it does not. Until then this device's view of the chat is unchanged.
    pub fn add(&mut self, group: &[u8], key_packages: &[Vec<u8>]) -> Result<Outgoing, Error> {
        self.add_replacing(group, key_packages, &[])
    }

    /// [`Self::add`], taking `replace` (leaves already in the chat) out in the
    /// same commit: how a device that fell out of step with a chat is let back
    /// in under its fresh key package (`encrypted-chat.md`, "A device that fell
    /// behind"). Pending like [`Self::add`].
    fn add_replacing(
        &mut self,
        group: &[u8],
        key_packages: &[Vec<u8>],
        replace: &[LeafNodeIndex],
    ) -> Result<Outgoing, Error> {
        let packages = key_packages
            .iter()
            .map(|b| {
                KeyPackageIn::tls_deserialize(&mut b.as_slice())
                    .map_err(|e| Error::Decode(e.to_string()))?
                    .validate(self.provider.crypto(), ProtocolVersion::Mls10)
                    .map_err(mls)
            })
            .collect::<Result<Vec<_>, _>>()?;
        let g = self.groups.get_mut(group).ok_or(Error::UnknownGroup)?;
        let epoch = g.epoch().as_u64();
        if replace.is_empty() {
            let (commit, welcome, _) = g
                .add_members(&self.provider, &self.signer, &packages)
                .map_err(mls)?;
            return Ok(Outgoing {
                group: group.to_vec(),
                epoch,
                message: commit.tls_serialize_detached().map_err(mls)?,
                welcome: Some(welcome.tls_serialize_detached().map_err(mls)?),
            });
        }
        // What openmls's own `swap_members` does, without its one-for-one rule:
        // removals and adds as one commit.
        let packages: Vec<KeyPackage> = packages.into_iter().map(|p| p.into()).collect();
        let bundle = g
            .commit_builder()
            .propose_removals(replace.iter().copied())
            .propose_adds(packages)
            .load_psks(self.provider.storage())
            .map_err(mls)?
            .build(
                self.provider.rand(),
                self.provider.crypto(),
                &self.signer,
                |_| true,
            )
            .map_err(mls)?
            .stage_commit(&self.provider)
            .map_err(mls)?;
        let (commit, welcome, _) = bundle.into_messages();
        let welcome = welcome.ok_or_else(|| Error::Mls("an add made no invitation".into()))?;
        Ok(Outgoing {
            group: group.to_vec(),
            epoch,
            message: commit.tls_serialize_detached().map_err(mls)?,
            welcome: Some(welcome.tls_serialize_detached().map_err(mls)?),
        })
    }

    /// Add more devices of people already in a chat, and nobody else: a key
    /// package naming somebody who is not a member, or a device that already
    /// is one, is left out. Answers `None` when nothing is left to add.
    ///
    /// This is the check that keeps a request from the server to "add this
    /// member's new phone" from being a way to add a stranger.
    pub fn add_member_devices(
        &mut self,
        group: &[u8],
        key_packages: &[Vec<u8>],
    ) -> Result<Option<(Outgoing, Vec<Identity>)>, Error> {
        let members = self.members(group);
        self.add_allowed(group, key_packages, |address| {
            members
                .iter()
                .any(|m| m.address.eq_ignore_ascii_case(address))
        })
    }

    /// Add the devices whose key packages name somebody `allowed` admits.
    /// Answers who was added, or `None` when nobody was left. The rule for
    /// *who* belongs is the caller's: the members already here
    /// ([`Self::add_member_devices`]), or the people of the community a topic
    /// belongs to.
    ///
    /// **A device already in the chat is replaced, not skipped**: its old leaf
    /// goes out in the same commit that adds the new package. The server asks
    /// for that only for a device that fell behind the chat and dropped it
    /// (`Refusal::Behind` there), and a key package carries the device's own
    /// signature, so the server cannot put a device of its choosing in. This
    /// device itself is never replaced.
    pub fn add_allowed(
        &mut self,
        group: &[u8],
        key_packages: &[Vec<u8>],
        allowed: impl Fn(&str) -> bool,
    ) -> Result<Option<(Outgoing, Vec<Identity>)>, Error> {
        let members = self.members(group);
        if members.is_empty() {
            return Err(Error::UnknownGroup);
        }
        let mut keep = Vec::new();
        let mut who: Vec<Identity> = Vec::new();
        for b in key_packages {
            let Ok(kp) = KeyPackageIn::tls_deserialize(&mut b.as_slice())
                .map_err(|e| Error::Decode(e.to_string()))
                .and_then(|k| {
                    k.validate(self.provider.crypto(), ProtocolVersion::Mls10)
                        .map_err(mls)
                })
            else {
                continue;
            };
            let Some(id) = Identity::from_credential(kp.leaf_node().credential()) else {
                continue;
            };
            let a_member = allowed(&id.address);
            let twice = who.iter().any(|m| m.device == id.device);
            let me = id.device == self.me.device;
            if a_member && !twice && !me {
                keep.push(b.clone());
                who.push(id);
            }
        }
        if keep.is_empty() {
            return Ok(None);
        }
        let g = self.groups.get(group).ok_or(Error::UnknownGroup)?;
        let mine = g.own_leaf_index();
        let replace: Vec<LeafNodeIndex> = g
            .members()
            .filter(|m| m.index != mine)
            .filter(|m| {
                Identity::from_credential(&m.credential)
                    .is_some_and(|id| who.iter().any(|w| w.device == id.device))
            })
            .map(|m| m.index)
            .collect();
        Ok(Some((self.add_replacing(group, &keep, &replace)?, who)))
    }

    /// Take every device of each of `addresses` out of a chat, with one commit.
    /// Pending like [`Self::add`]. `None` when none of them is in it.
    pub fn remove_people(
        &mut self,
        group: &[u8],
        addresses: &[String],
    ) -> Result<Option<Outgoing>, Error> {
        let g = self.groups.get_mut(group).ok_or(Error::UnknownGroup)?;
        let me = g.own_leaf_index();
        let leaves: Vec<LeafNodeIndex> = g
            .members()
            .filter(|m| m.index != me)
            .filter(|m| {
                Identity::from_credential(&m.credential).is_some_and(|id| {
                    addresses
                        .iter()
                        .any(|a| a.eq_ignore_ascii_case(&id.address))
                })
            })
            .map(|m| m.index)
            .collect();
        if leaves.is_empty() {
            return Ok(None);
        }
        let epoch = g.epoch().as_u64();
        let (commit, _welcome, _) = g
            .remove_members(&self.provider, &self.signer, &leaves)
            .map_err(mls)?;
        Ok(Some(Outgoing {
            group: group.to_vec(),
            epoch,
            message: commit.tls_serialize_detached().map_err(mls)?,
            welcome: None,
        }))
    }

    /// Move a chat to a new epoch without changing who is in it: a commit
    /// carrying only this device's fresh leaf key. Every key derived from the
    /// old epoch — a call's SFrame key among them — stops opening anything
    /// sealed after it. How a meeting's guests are shut out of the chat's next
    /// call (`calls.md`, "Guests, by link"). Pending like [`Self::add`].
    pub fn rotate(&mut self, group: &[u8]) -> Result<Outgoing, Error> {
        let g = self.groups.get_mut(group).ok_or(Error::UnknownGroup)?;
        let epoch = g.epoch().as_u64();
        let bundle = g
            .commit_builder()
            .force_self_update(true)
            .load_psks(self.provider.storage())
            .map_err(mls)?
            .build(
                self.provider.rand(),
                self.provider.crypto(),
                &self.signer,
                |_| true,
            )
            .map_err(mls)?
            .stage_commit(&self.provider)
            .map_err(mls)?;
        let (commit, _welcome, _) = bundle.into_messages();
        Ok(Outgoing {
            group: group.to_vec(),
            epoch,
            message: commit.tls_serialize_detached().map_err(mls)?,
            welcome: None,
        })
    }

    /// The server accepted this device's commit: apply it.
    pub fn confirm_pending(&mut self, group: &[u8]) -> Result<(), Error> {
        let g = self.groups.get_mut(group).ok_or(Error::UnknownGroup)?;
        g.merge_pending_commit(&self.provider).map_err(mls)
    }

    /// The server refused this device's commit (somebody else's won the epoch).
    pub fn discard_pending(&mut self, group: &[u8]) -> Result<(), Error> {
        let g = self.groups.get_mut(group).ok_or(Error::UnknownGroup)?;
        g.clear_pending_commit(self.provider.storage()).map_err(mls)
    }

    /// Whether this device made a commit to `group` that is neither confirmed
    /// nor discarded yet. While it is, the server's epoch is either the one
    /// this device is in or the one after it, and this device cannot tell
    /// which; nothing should be sealed until it can.
    #[must_use]
    pub fn has_pending(&self, group: &[u8]) -> bool {
        self.groups
            .get(group)
            .is_some_and(|g| g.pending_commit().is_some())
    }

    /// What one of this device's own log entries is, as a commit. The log
    /// replays a device's own entries to it, and its own commit is the one
    /// entry that cannot simply be skipped: if the server's answer to it was
    /// lost (the connection dropped first), the replayed entry is the only
    /// word this device will ever get that the commit was accepted.
    ///
    /// The server accepts one commit per epoch, and this device can make no
    /// second commit while one is pending, so its own commit in the epoch it
    /// is still in *is* the pending one.
    #[must_use]
    pub fn own_commit(&self, group: &[u8], message: &[u8]) -> OwnCommit {
        let Some(g) = self.groups.get(group) else {
            return OwnCommit::NotACommit;
        };
        let Ok(msg) = MlsMessageIn::tls_deserialize(&mut &message[..]) else {
            return OwnCommit::NotACommit;
        };
        let Ok(protocol) = msg.try_into_protocol_message() else {
            return OwnCommit::NotACommit;
        };
        if protocol.content_type() != ContentType::Commit {
            return OwnCommit::NotACommit;
        }
        let epoch = protocol.epoch();
        if epoch < g.epoch() {
            OwnCommit::Applied
        } else if epoch == g.epoch() && g.pending_commit().is_some() {
            OwnCommit::Pending
        } else {
            OwnCommit::Lost
        }
    }

    /// Seal a message for everyone else in the chat.
    pub fn encrypt(&mut self, group: &[u8], payload: &Payload) -> Result<Outgoing, Error> {
        let g = self.groups.get_mut(group).ok_or(Error::UnknownGroup)?;
        let epoch = g.epoch().as_u64();
        let out = g
            .create_message(&self.provider, &self.signer, &payload.encode())
            .map_err(mls)?;
        Ok(Outgoing {
            group: group.to_vec(),
            epoch,
            message: out.tls_serialize_detached().map_err(mls)?,
            welcome: None,
        })
    }

    /// Join a chat from an invitation. Returns the chat's id.
    pub fn join(&mut self, welcome: &[u8]) -> Result<Vec<u8>, Error> {
        let msg = MlsMessageIn::tls_deserialize(&mut &welcome[..])
            .map_err(|e| Error::Decode(e.to_string()))?;
        let MlsMessageBodyIn::Welcome(welcome) = msg.extract() else {
            return Err(Error::Decode("not an invitation".into()));
        };
        let config = MlsGroupJoinConfig::builder()
            .use_ratchet_tree_extension(true)
            .wire_format_policy(PURE_CIPHERTEXT_WIRE_FORMAT_POLICY)
            .max_past_epochs(MAX_PAST_EPOCHS)
            .build();
        let group = StagedWelcome::new_from_welcome(&self.provider, &config, welcome, None)
            .map_err(mls)?
            .into_group(&self.provider)
            .map_err(mls)?;
        let id = group.group_id().as_slice().to_vec();
        self.groups.insert(id.clone(), group);
        Ok(id)
    }

    /// Read one entry of a chat's log that another device wrote.
    pub fn receive(&mut self, group: &[u8], message: &[u8]) -> Result<Received, Error> {
        let msg = MlsMessageIn::tls_deserialize(&mut &message[..])
            .map_err(|e| Error::Decode(e.to_string()))?;
        let protocol = msg
            .try_into_protocol_message()
            .map_err(|e| Error::Decode(format!("{e:?}")))?;
        let g = self.groups.get_mut(group).ok_or(Error::UnknownGroup)?;
        let processed = g.process_message(&self.provider, protocol).map_err(mls)?;
        let from = Identity::from_credential(processed.credential())
            .ok_or_else(|| Error::Decode("sender has an unreadable identity".into()))?;
        match processed.into_content() {
            ProcessedMessageContent::ApplicationMessage(app) => Ok(Received::Message {
                from,
                bytes: app.into_bytes(),
            }),
            ProcessedMessageContent::StagedCommitMessage(staged) => {
                g.merge_staged_commit(&self.provider, *staged)
                    .map_err(mls)?;
                Ok(Received::Membership { by: from })
            }
            // A bare proposal is not something this client sends, and a device's
            // own entries are skipped before they get here. Either arriving means
            // the caller fed this the wrong thing, which must not be reported as
            // a membership change — it was, once, and that hid exactly this.
            _ => Err(Error::Mls(
                "not a message or a commit this client handles".into(),
            )),
        }
    }

    /// Drop a chat this device created and then abandoned (the server pointed
    /// at an existing one instead), keys and all.
    pub fn forget(&mut self, group: &[u8]) {
        if let Some(mut g) = self.groups.remove(group) {
            // A failed delete is not fatal: the group is gone from this
            // device's list either way, and `load` only restores listed groups.
            let _ = g.delete(self.provider.storage());
        }
    }

    /// The chats this device is in.
    pub fn groups(&self) -> impl Iterator<Item = &Vec<u8>> {
        self.groups.keys()
    }

    /// Who is in a chat, one entry per device.
    #[must_use]
    pub fn members(&self, group: &[u8]) -> Vec<Identity> {
        self.groups
            .get(group)
            .map(|g| {
                g.members()
                    .filter_map(|m| Identity::from_credential(&m.credential))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Whether this device is still in a chat it holds. False once a commit
    /// took it out: removed, or replaced because it fell behind.
    #[must_use]
    pub fn is_active(&self, group: &[u8]) -> bool {
        self.groups.get(group).is_some_and(MlsGroup::is_active)
    }

    /// The chat's current epoch, which the server checks commits against.
    #[must_use]
    pub fn epoch(&self, group: &[u8]) -> Option<u64> {
        self.groups.get(group).map(|g| g.epoch().as_u64())
    }

    /// What a call in this chat needs from its current epoch
    /// (`docs/notes/calls.md`): the SFrame base key every member computes and
    /// nobody else can, and which member sends under which leaf index.
    ///
    /// The key is the MLS exporter with RFC 9605 §5.2's label, so it changes
    /// with every membership change — somebody removed from the chat cannot
    /// hear the call after the commit that removed them. The caller keeps the
    /// previous epoch's answer for a moment, because frames sealed just before
    /// a commit arrive just after it and this device can no longer export for
    /// an epoch it has left.
    pub fn call_epoch(&self, group: &[u8], key_len: usize) -> Result<CallEpoch, Error> {
        let g = self.groups.get(group).ok_or(Error::UnknownGroup)?;
        let base_key = g
            .export_secret(self.provider.crypto(), CALL_KEY_LABEL, b"", key_len)
            .map_err(mls)?;
        Ok(CallEpoch {
            epoch: g.epoch().as_u64(),
            base_key,
            own_index: g.own_leaf_index().u32(),
            members: g
                .members()
                .filter_map(|m| Some((m.index.u32(), Identity::from_credential(&m.credential)?)))
                .collect(),
        })
    }
}

/// RFC 9605 §5.2's exporter label for an SFrame base key.
pub const CALL_KEY_LABEL: &str = "SFrame 1.0 Base Key";

/// One epoch of a chat, as a call sees it ([`Device::call_epoch`]).
#[derive(Clone, PartialEq, Eq)]
pub struct CallEpoch {
    pub epoch: u64,
    /// `MLS-Exporter(CALL_KEY_LABEL, "", key_len)`. Secret: never logged.
    pub base_key: Vec<u8>,
    /// This device's leaf index, which names its frames.
    pub own_index: u32,
    /// Every member device by leaf index, so a frame's sender can be named.
    pub members: Vec<(u32, Identity)>,
}

impl std::fmt::Debug for CallEpoch {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CallEpoch")
            .field("epoch", &self.epoch)
            .field("own_index", &self.own_index)
            .field("members", &self.members)
            .finish_non_exhaustive()
    }
}

fn credential_for(me: &Identity, signer: &SignatureKeyPair) -> CredentialWithKey {
    CredentialWithKey {
        credential: BasicCredential::new(me.to_bytes()).into(),
        signature_key: signer.public().into(),
    }
}

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

    #[test]
    fn an_attachment_opens_with_its_key_and_with_nothing_else() {
        let picture = b"\xff\xd8 pretend this is a jpeg".repeat(100);
        let sealed = seal_attachment(&picture).unwrap();
        assert_ne!(
            sealed.bytes[..picture.len()],
            picture[..],
            "it is encrypted"
        );
        assert_eq!(
            open_attachment(&sealed.bytes, &sealed.key, &sealed.nonce).unwrap(),
            picture
        );
        let mut wrong_key = sealed.key;
        wrong_key[0] ^= 1;
        assert!(open_attachment(&sealed.bytes, &wrong_key, &sealed.nonce).is_err());
        let mut tampered = sealed.bytes.clone();
        tampered[3] ^= 1;
        assert!(open_attachment(&tampered, &sealed.key, &sealed.nonce).is_err());
        // Two seals of one picture share nothing.
        let again = seal_attachment(&picture).unwrap();
        assert_ne!(again.key, sealed.key);
        assert_ne!(again.bytes, sealed.bytes);
    }

    #[test]
    fn a_picture_payload_round_trips_and_is_appended_last() {
        let p = Payload::Picture {
            hash: "ab".repeat(32),
            key: [7; 32],
            nonce: [9; 12],
            width: 1600,
            height: 900,
            caption: "the Vismarkt".into(),
            sent_at_ms: 42,
        };
        assert_eq!(Payload::decode(&p.encode()).unwrap(), p);
        // Postcard writes the variant index first: an older build must meet a
        // variant it lacks, never a renumbered one it thinks it knows.
        assert_eq!(p.encode()[0], 5);
    }

    /// The server's chat log, reduced to what the ordering rule needs: entries
    /// in order, and the epoch a commit must have been made in.
    #[derive(Default)]
    struct Log {
        entries: Vec<(Identity, Vec<u8>)>,
        epoch: u64,
    }

    impl Log {
        /// The server's acceptance test for a commit.
        fn commit(&mut self, from: &Identity, out: &Outgoing) -> bool {
            if out.epoch != self.epoch {
                return false;
            }
            self.epoch += 1;
            self.entries.push((from.clone(), out.message.clone()));
            true
        }

        fn send(&mut self, from: &Identity, out: &Outgoing) {
            self.entries.push((from.clone(), out.message.clone()));
        }
    }

    /// Replay the log from `cursor`, skipping this device's own entries.
    fn catch_up(dev: &mut Device, group: &[u8], log: &Log, cursor: &mut usize) -> Vec<Received> {
        let mut got = Vec::new();
        while *cursor < log.entries.len() {
            let (from, bytes) = &log.entries[*cursor];
            *cursor += 1;
            if dev.is_me(&from.address, from.device) {
                continue;
            }
            got.push(dev.receive(group, bytes).expect("entry reads"));
        }
        got
    }

    fn text(got: &[Received]) -> Vec<String> {
        got.iter()
            .filter_map(|r| match r {
                Received::Message { bytes, .. } => match Payload::decode(bytes).ok()? {
                    Payload::Text { body, .. } => Some(body),
                    _ => None,
                },
                Received::Membership { .. } => None,
            })
            .collect()
    }

    /// A fresh chat id whose home is the test server.
    fn test_group() -> Vec<u8> {
        let mut id = b"test.example/".to_vec();
        id.extend_from_slice(Uuid::new_v4().as_bytes());
        id
    }

    fn say(body: &str) -> Payload {
        Payload::Text {
            body: body.into(),
            sent_at_ms: 0,
        }
    }

    #[test]
    fn two_people_talk_and_the_log_holds_only_sealed_bytes() {
        let mut alice = Device::new("alice@test.example", Uuid::new_v4()).unwrap();
        let mut bob = Device::new("bob@test.example", Uuid::new_v4()).unwrap();
        let mut log = Log::default();

        let g = alice.create_group(&test_group()).unwrap();
        let bob_kp = bob.key_packages(1).unwrap();
        let add = alice.add(&g, &bob_kp).unwrap();
        assert!(log.commit(alice.identity(), &add));
        alice.confirm_pending(&g).unwrap();
        let joined = bob.join(add.welcome.as_ref().unwrap()).unwrap();
        assert_eq!(joined, g);
        // Bob joined *after* the commit that added him, so his cursor starts past it.
        let mut bob_cursor = log.entries.len();
        let mut alice_cursor = log.entries.len();

        let secret = "meet at the café at seven";
        let m = alice.encrypt(&g, &say(secret)).unwrap();
        log.send(alice.identity(), &m);
        assert!(
            !m.message
                .windows(secret.len())
                .any(|w| w == secret.as_bytes()),
            "the server's copy must not contain the plaintext"
        );
        assert_eq!(
            text(&catch_up(&mut bob, &g, &log, &mut bob_cursor)),
            vec![secret]
        );

        let r = bob.encrypt(&g, &say("see you there")).unwrap();
        log.send(bob.identity(), &r);
        assert_eq!(
            text(&catch_up(&mut alice, &g, &log, &mut alice_cursor)),
            vec!["see you there"]
        );
    }

    #[test]
    fn every_member_derives_the_same_call_key_and_it_changes_with_the_group() {
        let mut alice = Device::new("alice@test.example", Uuid::new_v4()).unwrap();
        let mut bob = Device::new("bob@test.example", Uuid::new_v4()).unwrap();
        let mut carol = Device::new("carol@test.example", Uuid::new_v4()).unwrap();
        let g = alice.create_group(&test_group()).unwrap();
        let add = alice.add(&g, &bob.key_packages(1).unwrap()).unwrap();
        alice.confirm_pending(&g).unwrap();
        bob.join(add.welcome.as_ref().unwrap()).unwrap();

        let a = alice.call_epoch(&g, 16).unwrap();
        let b = bob.call_epoch(&g, 16).unwrap();
        assert_eq!(a.base_key, b.base_key);
        assert_eq!(a.base_key.len(), 16);
        assert_eq!(a.epoch, b.epoch);
        assert_ne!(a.own_index, b.own_index, "each sender has its own index");
        assert_eq!(a.members, b.members);
        let bob_index = a
            .members
            .iter()
            .find(|(_, id)| id.address == "bob@test.example")
            .map(|(i, _)| *i);
        assert_eq!(bob_index, Some(b.own_index));

        // Carol joins: a new epoch, so a new key Bob gets only by reading the commit.
        let add = alice.add(&g, &carol.key_packages(1).unwrap()).unwrap();
        alice.confirm_pending(&g).unwrap();
        carol.join(add.welcome.as_ref().unwrap()).unwrap();
        bob.receive(&g, &add.message).unwrap();
        let a2 = alice.call_epoch(&g, 16).unwrap();
        assert_ne!(a2.base_key, a.base_key);
        assert_eq!(a2.base_key, bob.call_epoch(&g, 16).unwrap().base_key);
        assert_eq!(a2.base_key, carol.call_epoch(&g, 16).unwrap().base_key);
        assert!(
            format!("{a2:?}").find("base_key").is_none(),
            "never printed"
        );
    }

    #[test]
    fn a_devices_own_entry_never_reads_back_as_a_message() {
        let mut alice = Device::new("alice@test.example", Uuid::new_v4()).unwrap();
        let mut bob = Device::new("bob@test.example", Uuid::new_v4()).unwrap();
        let g = alice.create_group(&test_group()).unwrap();
        let add = alice.add(&g, &bob.key_packages(1).unwrap()).unwrap();
        alice.confirm_pending(&g).unwrap();
        bob.join(add.welcome.as_ref().unwrap()).unwrap();
        let m = alice.encrypt(&g, &say("hi")).unwrap();
        // What the caller must never do is show it as something Bob said, or
        // as a second copy of Alice's own line.
        assert!(!matches!(
            alice.receive(&g, &m.message),
            Ok(Received::Message { .. })
        ));
    }

    #[test]
    fn a_commit_whose_answer_was_lost_is_recognised_in_the_log() {
        let mut alice = Device::new("alice@test.example", Uuid::new_v4()).unwrap();
        let mut bob = Device::new("bob@test.example", Uuid::new_v4()).unwrap();
        let mut phone = Device::new("bob@test.example", Uuid::new_v4()).unwrap();
        let g = alice.create_group(&test_group()).unwrap();
        let add = alice.add(&g, &bob.key_packages(1).unwrap()).unwrap();
        alice.confirm_pending(&g).unwrap();
        bob.join(add.welcome.as_ref().unwrap()).unwrap();
        assert!(!alice.has_pending(&g));
        let line = alice.encrypt(&g, &say("hi")).unwrap();
        assert_eq!(alice.own_commit(&g, &line.message), OwnCommit::NotACommit);
        assert_eq!(alice.own_commit(&g, &add.message), OwnCommit::Applied);

        // Alice adds Bob's phone; the server takes it, and its answer is lost.
        let add_phone = alice
            .add_member_devices(&g, &phone.key_packages(1).unwrap())
            .unwrap()
            .unwrap()
            .0;
        assert!(alice.has_pending(&g));
        phone.join(add_phone.welcome.as_ref().unwrap()).unwrap();
        // The replay brings the commit back: it is the pending one.
        assert_eq!(alice.own_commit(&g, &add_phone.message), OwnCommit::Pending);
        alice.confirm_pending(&g).unwrap();
        assert!(!alice.has_pending(&g));
        assert_eq!(alice.own_commit(&g, &add_phone.message), OwnCommit::Applied);
        // And what Alice says now, the phone can read.
        let m = alice.encrypt(&g, &say("welcome, phone")).unwrap();
        assert!(matches!(
            phone.receive(&g, &m.message),
            Ok(Received::Message { .. })
        ));
    }

    #[test]
    fn of_two_simultaneous_commits_the_server_takes_one_and_the_other_retries() {
        let mut alice = Device::new("alice@test.example", Uuid::new_v4()).unwrap();
        let mut bob = Device::new("bob@test.example", Uuid::new_v4()).unwrap();
        let mut carol = Device::new("carol@test.example", Uuid::new_v4()).unwrap();
        let mut dave = Device::new("dave@test.example", Uuid::new_v4()).unwrap();
        let mut log = Log::default();

        let g = alice.create_group(&test_group()).unwrap();
        let add_bob = alice.add(&g, &bob.key_packages(1).unwrap()).unwrap();
        assert!(log.commit(alice.identity(), &add_bob));
        alice.confirm_pending(&g).unwrap();
        bob.join(add_bob.welcome.as_ref().unwrap()).unwrap();
        let mut alice_cursor = log.entries.len();
        let mut bob_cursor = log.entries.len();

        // Both add somebody in the same epoch.
        let by_alice = alice.add(&g, &carol.key_packages(1).unwrap()).unwrap();
        let by_bob = bob.add(&g, &dave.key_packages(1).unwrap()).unwrap();
        assert!(log.commit(alice.identity(), &by_alice));
        assert!(!log.commit(bob.identity(), &by_bob), "same epoch: refused");
        alice.confirm_pending(&g).unwrap();
        carol.join(by_alice.welcome.as_ref().unwrap()).unwrap();

        // Bob drops his, catches up, and tries again in the new epoch.
        bob.discard_pending(&g).unwrap();
        catch_up(&mut bob, &g, &log, &mut bob_cursor);
        let retry = bob.add(&g, &dave.key_packages(1).unwrap()).unwrap();
        assert!(log.commit(bob.identity(), &retry));
        bob.confirm_pending(&g).unwrap();
        dave.join(retry.welcome.as_ref().unwrap()).unwrap();
        catch_up(&mut alice, &g, &log, &mut alice_cursor);

        let names = |d: &Device| {
            let mut v: Vec<String> = d.members(&g).into_iter().map(|i| i.address).collect();
            v.sort();
            v
        };
        assert_eq!(
            names(&alice),
            [
                "alice@test.example",
                "bob@test.example",
                "carol@test.example",
                "dave@test.example"
            ]
        );
        assert_eq!(names(&alice), names(&bob));
        assert_eq!(alice.epoch(&g), bob.epoch(&g));
    }

    #[test]
    fn a_saved_device_comes_back_able_to_read_its_chats() {
        let mut alice = Device::new("alice@test.example", Uuid::new_v4()).unwrap();
        let mut bob = Device::new("bob@test.example", Uuid::new_v4()).unwrap();
        let g = alice.create_group(&test_group()).unwrap();
        let add = alice.add(&g, &bob.key_packages(1).unwrap()).unwrap();
        alice.confirm_pending(&g).unwrap();
        bob.join(add.welcome.as_ref().unwrap()).unwrap();

        let mut bob = Device::load(&bob.save()).unwrap();
        let m = alice.encrypt(&g, &say("still there?")).unwrap();
        let Received::Message { from, bytes } = bob.receive(&g, &m.message).unwrap() else {
            panic!("expected a message");
        };
        assert_eq!(from.address, "alice@test.example");
        assert_eq!(Payload::decode(&bytes).unwrap(), say("still there?"));
        // And it can still speak, with the key it was saved with.
        let r = bob.encrypt(&g, &say("yes")).unwrap();
        assert!(matches!(
            alice.receive(&g, &r.message).unwrap(),
            Received::Message { .. }
        ));
    }

    #[test]
    fn a_key_package_opens_only_one_invitation() {
        let mut alice = Device::new("alice@test.example", Uuid::new_v4()).unwrap();
        let mut bob = Device::new("bob@test.example", Uuid::new_v4()).unwrap();
        let kp = bob.key_packages(1).unwrap();
        let g1 = alice.create_group(&test_group()).unwrap();
        let a1 = alice.add(&g1, &kp).unwrap();
        alice.confirm_pending(&g1).unwrap();
        let g2 = alice.create_group(&test_group()).unwrap();
        let a2 = alice.add(&g2, &kp).unwrap();
        alice.confirm_pending(&g2).unwrap();
        bob.join(a1.welcome.as_ref().unwrap()).unwrap();
        // The private half was consumed by the first join: this is why the
        // server hands each package out once and devices keep a stock of them.
        assert!(bob.join(a2.welcome.as_ref().unwrap()).is_err());
    }

    /// A bare username in a credential could never be told apart from the same
    /// name on another server, and a credential cannot be changed later.
    #[test]
    fn a_device_belongs_to_a_full_address() {
        assert!(Device::new("jeroen", Uuid::new_v4()).is_err());
        assert!(Device::new("@cartopolis.org", Uuid::new_v4()).is_err());
        let d = Device::new("Jeroen@Cartopolis.org", Uuid::new_v4()).unwrap();
        assert_eq!(d.identity().address, "jeroen@cartopolis.org");
    }

    #[test]
    fn identities_survive_the_credential_round_trip() {
        let me = Identity {
            address: "jeroen@cartopolis.org".into(),
            device: Uuid::new_v4(),
        };
        assert_eq!(Identity::from_bytes(&me.to_bytes()), Some(me));
        assert_eq!(Identity::from_bytes(b"no separator"), None);
    }

    /// The viberfox/jeroen chat of 2026-10-18: one device missed a commit, so
    /// everything it sealed was `TooDistantInThePast` to the others and
    /// nothing they sealed opened for it. Adding it again under a fresh key
    /// package replaces its old leaf, and the chat works for everyone.
    #[test]
    fn a_device_that_fell_behind_is_replaced_and_reads_again() {
        let mut ann = Device::new("ann@x", Uuid::new_v4()).unwrap();
        let mut bob = Device::new("bob@x", Uuid::new_v4()).unwrap();
        let mut ann_phone = Device::new("ann@x", Uuid::new_v4()).unwrap();
        let g = ann.create_group(b"x/chat").unwrap();
        let add = ann.add(&g, &bob.key_packages(1).unwrap()).unwrap();
        ann.confirm_pending(&g).unwrap();
        bob.join(&add.welcome.unwrap()).unwrap();

        // Ann adds her phone; bob never applies that commit.
        let (missed, _) = ann
            .add_member_devices(&g, &ann_phone.key_packages(1).unwrap())
            .unwrap()
            .unwrap();
        ann.confirm_pending(&g).unwrap();
        ann_phone.join(&missed.welcome.unwrap()).unwrap();
        let line = |d: &mut Device| {
            d.encrypt(
                &g,
                &Payload::Text {
                    body: "hi".into(),
                    sent_at_ms: 1,
                },
            )
            .unwrap()
            .message
        };
        // Bob cannot read the chat any more. (Ann can still read *him* for a
        // few epochs, MAX_PAST_EPOCHS; the chat of 2026-10-18 was further gone.)
        let from_ann = line(&mut ann);
        assert!(
            bob.receive(&g, &from_ann).is_err(),
            "bob is stuck in the old epoch"
        );

        // Bob drops the chat and is added back by the phone, replacing his leaf.
        bob.forget(&g);
        let (back, who) = ann_phone
            .add_member_devices(&g, &bob.key_packages(1).unwrap())
            .unwrap()
            .unwrap();
        assert_eq!(who, vec![bob.identity().clone()]);
        ann_phone.confirm_pending(&g).unwrap();
        assert!(ann.receive(&g, &back.message).is_ok());
        assert_eq!(bob.join(&back.welcome.unwrap()).unwrap(), g);
        assert_eq!(ann.members(&g).len(), 3, "replaced, not added twice");

        let from_bob = line(&mut bob);
        assert!(ann.receive(&g, &from_bob).is_ok());
        let from_ann = line(&mut ann);
        assert!(bob.receive(&g, &from_ann).is_ok());
    }

    /// The leaf a commit replaces stops being in the chat on its old device.
    #[test]
    fn a_replaced_device_sees_itself_taken_out() {
        let mut ann = Device::new("ann@x", Uuid::new_v4()).unwrap();
        let mut bob = Device::new("bob@x", Uuid::new_v4()).unwrap();
        let g = ann.create_group(b"x/chat").unwrap();
        let add = ann.add(&g, &bob.key_packages(1).unwrap()).unwrap();
        ann.confirm_pending(&g).unwrap();
        bob.join(&add.welcome.unwrap()).unwrap();
        assert!(bob.is_active(&g));
        let (swap, _) = ann
            .add_member_devices(&g, &bob.key_packages(1).unwrap())
            .unwrap()
            .unwrap();
        ann.confirm_pending(&g).unwrap();
        bob.receive(&g, &swap.message).unwrap();
        assert!(!bob.is_active(&g));
    }

    #[test]
    fn a_request_to_add_member_devices_cannot_bring_in_anybody_new() {
        let mut laptop = Device::new("alice@x", Uuid::new_v4()).unwrap();
        let mut bob = Device::new("bob@x", Uuid::new_v4()).unwrap();
        let mut phone = Device::new("alice@x", Uuid::new_v4()).unwrap();
        let mut carol = Device::new("carol@x", Uuid::new_v4()).unwrap();
        let g = laptop.create_group(b"x/chat").unwrap();
        let add = laptop.add(&g, &bob.key_packages(1).unwrap()).unwrap();
        laptop.confirm_pending(&g).unwrap();
        bob.join(&add.welcome.unwrap()).unwrap();

        // A stranger is left out, and so is this device itself.
        let mut offered = carol.key_packages(1).unwrap();
        assert!(laptop.add_member_devices(&g, &offered).unwrap().is_none());
        let own = laptop.key_packages(1).unwrap();
        assert!(laptop.add_member_devices(&g, &own).unwrap().is_none());

        // Alice's own other device goes in, and the stranger beside it does not.
        offered.extend(phone.key_packages(1).unwrap());
        let (out, who) = laptop.add_member_devices(&g, &offered).unwrap().unwrap();
        assert_eq!(who, vec![phone.identity().clone()]);
        laptop.confirm_pending(&g).unwrap();
        assert_eq!(phone.join(&out.welcome.unwrap()).unwrap(), g);
        assert_eq!(laptop.members(&g).len(), 3);
    }

    #[test]
    fn removing_somebody_takes_every_device_of_theirs_out_and_they_read_nothing_after() {
        let mut ann = Device::new("ann@x", Uuid::new_v4()).unwrap();
        let mut bob = Device::new("bob@x", Uuid::new_v4()).unwrap();
        let mut cas = Device::new("cas@x", Uuid::new_v4()).unwrap();
        let mut cas_phone = Device::new("cas@x", Uuid::new_v4()).unwrap();
        let g = ann.create_group(b"x/topic").unwrap();
        let mut packages = bob.key_packages(1).unwrap();
        packages.extend(cas.key_packages(1).unwrap());
        packages.extend(cas_phone.key_packages(1).unwrap());
        let add = ann.add(&g, &packages).unwrap();
        ann.confirm_pending(&g).unwrap();
        let welcome = add.welcome.unwrap();
        for d in [&mut bob, &mut cas, &mut cas_phone] {
            d.join(&welcome).unwrap();
        }

        assert!(ann
            .remove_people(&g, &["nobody@x".into()])
            .unwrap()
            .is_none());
        let out = ann.remove_people(&g, &["CAS@x".into()]).unwrap().unwrap();
        ann.confirm_pending(&g).unwrap();
        assert_eq!(ann.members(&g).len(), 2, "both of Cas's devices went");
        bob.receive(&g, &out.message).unwrap();

        let line = ann
            .encrypt(
                &g,
                &Payload::Text {
                    body: "after".into(),
                    sent_at_ms: 0,
                },
            )
            .unwrap();
        assert!(bob.receive(&g, &line.message).is_ok());
        assert!(
            cas.receive(&g, &line.message).is_err(),
            "a removed device must not read what is said after"
        );
    }

    #[test]
    fn a_rotation_changes_the_call_key_and_nobody_s_place_in_the_chat() {
        let mut ann = Device::new("ann@x", Uuid::new_v4()).unwrap();
        let mut bob = Device::new("bob@x", Uuid::new_v4()).unwrap();
        let g = ann.create_group(b"x/meeting").unwrap();
        let add = ann.add(&g, &bob.key_packages(1).unwrap()).unwrap();
        ann.confirm_pending(&g).unwrap();
        bob.join(&add.welcome.unwrap()).unwrap();
        // What a guest was handed during the meeting.
        let handed = ann.call_epoch(&g, 16).unwrap();

        let out = bob.rotate(&g).unwrap();
        assert!(out.welcome.is_none());
        assert!(bob.has_pending(&g), "pending until the server takes it");
        bob.confirm_pending(&g).unwrap();
        assert!(matches!(
            ann.receive(&g, &out.message).unwrap(),
            Received::Membership { .. }
        ));

        let ann_now = ann.call_epoch(&g, 16).unwrap();
        let bob_now = bob.call_epoch(&g, 16).unwrap();
        assert_eq!(ann_now.epoch, handed.epoch + 1);
        assert_eq!(
            ann_now.base_key, bob_now.base_key,
            "both still share one key"
        );
        assert_ne!(ann_now.base_key, handed.base_key, "and not the guest's");
        assert_eq!(ann.members(&g).len(), 2);
    }
}