Skip to main content

ping_core/
conversation.rs

1//! Conversation state — wraps an OpenMLS `MlsGroup`.
2//!
3//! Each external conversation maps 1:1 to an MLS group whose leaves are devices. The DeviceGroup
4//! (one per user, devices only) is just a special-cased conversation with the same wrapper.
5//!
6//! Persistence: we snapshot the `MlsGroup` after every state-changing operation under
7//! `groups/{conversation_id}` and cache the result in-memory.
8
9use openmls::{
10    framing::{MlsMessageOut, ProcessedMessageContent},
11    group::{MlsGroup, MlsGroupCreateConfig, MlsGroupJoinConfig},
12    prelude::{
13        tls_codec::{Deserialize as TlsDeserialize, Serialize as TlsSerialize},
14        BasicCredential, Capabilities, Ciphersuite, CredentialWithKey, Extension, ExtensionType,
15        Extensions, MlsMessageBodyIn, MlsMessageIn, ProcessedMessage, ProtocolMessage,
16        ProtocolVersion, RequiredCapabilitiesExtension, UnknownExtension,
17    },
18};
19use openmls_basic_credential::SignatureKeyPair;
20use openmls_traits::OpenMlsProvider;
21use ping_mls_store::PersistentMlsProvider;
22use serde::{Deserialize, Serialize};
23use std::collections::BTreeMap;
24use std::sync::Arc;
25use ulid::Ulid;
26use zeroize::Zeroizing;
27
28use crate::{
29    clock::Hlc,
30    codec,
31    device::{DeviceId, GroupSnapshotEntry, GroupStateSnapshot, GROUP_SNAPSHOT_VERSION},
32    error::{Error, Result},
33    identity::UserId,
34    message::{IncomingMessage, MessageEnvelope, MessageKind},
35    storage::Storage,
36    sync::SyncCursor,
37};
38
39const DEFAULT_CIPHERSUITE: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519;
40
41/// Map an OpenMLS `WelcomeError` to a typed [`Error`]. The two variants that
42/// mean "the KeyPackage this Welcome was bound to (or its private init key) is
43/// no longer in our keystore" — i.e. the KeyPackage was already consumed
44/// (single-use reuse) or never persisted — become [`Error::KeyPackageNotFound`]
45/// so the host can top up KeyPackages and retry rather than treating it as an
46/// opaque MLS failure. Everything else stays a generic MLS error.
47fn map_welcome_error<S: std::fmt::Display>(e: openmls::group::WelcomeError<S>) -> Error {
48    use openmls::group::WelcomeError;
49    match e {
50        WelcomeError::NoMatchingKeyPackage | WelcomeError::PrivateInitKeyNotFound => {
51            Error::KeyPackageNotFound
52        }
53        other => Error::mls(other),
54    }
55}
56
57/// MLS GroupContext extension type carrying the human conversation `name`.
58///
59/// Stored in the group context so the name is part of shared MLS group state and
60/// therefore present on EVERY device that holds the group — including a device
61/// that joins via a Welcome. Without this the name was creator-local and a
62/// joiner/linked device saw `None`. A private-use `Unknown` extension type
63/// (not a GREASE `0x?A?A` value, not a registered type 0x0001–0x0005).
64///
65/// It is added WITHOUT a `RequiredCapabilities` extension, so openmls imposes no
66/// per-member capability check — existing KeyPackages keep working and no
67/// re-link is required. The value is UTF-8 bytes of the name.
68const GROUP_NAME_EXTENSION_TYPE: u16 = 0xFF00;
69
70/// Read the conversation `name` from a group's GroupContext extensions, if set.
71fn group_name_from_extensions(extensions: &Extensions) -> Option<String> {
72    extensions.iter().find_map(|ext| match ext {
73        Extension::Unknown(ext_type, data) if *ext_type == GROUP_NAME_EXTENSION_TYPE => {
74            String::from_utf8(data.0.clone())
75                .ok()
76                .filter(|s| !s.is_empty())
77        }
78        _ => None,
79    })
80}
81
82/// Build the GroupContext extensions carrying `name` (empty when `name` is
83/// `None`/blank), for `MlsGroupCreateConfig::with_group_context_extensions`.
84fn group_context_extensions_for_name(name: Option<&str>) -> Extensions {
85    match name {
86        Some(n) if !n.is_empty() => Extensions::single(Extension::Unknown(
87            GROUP_NAME_EXTENSION_TYPE,
88            UnknownExtension(n.as_bytes().to_vec()),
89        )),
90        _ => Extensions::empty(),
91    }
92}
93
94/// Leaf [`Capabilities`] advertising support for the group-name GroupContext
95/// extension ([`GROUP_NAME_EXTENSION_TYPE`]) ON TOP OF the MLS defaults.
96///
97/// Required so a later [`Conversation::set_name`] (rename / avatar-id change via
98/// `update_group_context_extensions`) passes openmls' GCE-proposal validation:
99/// that path demands every group-context extension be listed in a
100/// `RequiredCapabilities`, and that every member's leaf advertise those
101/// extension types. The CREATE path does not need this (genesis extensions skip
102/// the proposal validator), but a post-create UPDATE does. New KeyPackages and
103/// the creator's own leaf carry this; existing devices must RE-LINK once to pick
104/// it up (a pre-production-acceptable cost, aligned with the shared-identity
105/// re-link).
106pub(crate) fn ping_leaf_capabilities() -> Capabilities {
107    ping_leaf_capabilities_for(false)
108}
109
110/// Leaf capabilities, optionally also advertising the `LastResort` extension.
111///
112/// A KeyPackage marked last-resort (`mark_as_last_resort`) carries the
113/// `LastResort` extension on its leaf; openmls' KeyPackage validation rejects
114/// any leaf whose capabilities do not advertise every extension the leaf
115/// actually carries ("A key package extension is not supported in the leaf's
116/// capabilities"). So last-resort KeyPackages MUST list `LastResort` here, while
117/// ordinary KeyPackages must NOT (they don't carry it).
118pub(crate) fn ping_leaf_capabilities_for(last_resort: bool) -> Capabilities {
119    let extensions = if last_resort {
120        vec![
121            ExtensionType::Unknown(GROUP_NAME_EXTENSION_TYPE),
122            ExtensionType::LastResort,
123        ]
124    } else {
125        vec![ExtensionType::Unknown(GROUP_NAME_EXTENSION_TYPE)]
126    };
127    Capabilities::new(None, None, Some(&extensions), None, None)
128}
129
130/// GroupContext extensions for a NAME UPDATE commit (`set_name`), as opposed to
131/// genesis ([`group_context_extensions_for_name`]). The GCE-proposal validator
132/// requires every group-context extension to appear in a `RequiredCapabilities`,
133/// so we attach one listing [`GROUP_NAME_EXTENSION_TYPE`] alongside the name
134/// extension. Clearing the name (`None`/blank) keeps the `RequiredCapabilities`
135/// (harmless: required caps may list a type that isn't currently present).
136fn group_context_extensions_for_name_update(name: Option<&str>) -> Extensions {
137    let required = Extension::RequiredCapabilities(RequiredCapabilitiesExtension::new(
138        &[ExtensionType::Unknown(GROUP_NAME_EXTENSION_TYPE)],
139        &[],
140        &[],
141    ));
142    match name {
143        Some(n) if !n.is_empty() => Extensions::from_vec(vec![
144            Extension::Unknown(
145                GROUP_NAME_EXTENSION_TYPE,
146                UnknownExtension(n.as_bytes().to_vec()),
147            ),
148            required,
149        ])
150        // Two distinct extension types — `from_vec` only rejects duplicates.
151        .expect("name + required-capabilities are distinct extension types"),
152        _ => Extensions::single(required),
153    }
154}
155
156/// 16-byte conversation identifier (ULID encoded). Stable across epochs.
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
158pub struct ConversationId(#[serde(with = "serde_bytes_array16")] pub [u8; 16]);
159
160impl ConversationId {
161    pub fn new() -> Self {
162        Self(Ulid::new().to_bytes())
163    }
164    pub fn as_hex(&self) -> String {
165        hex::encode(self.0)
166    }
167}
168
169impl Default for ConversationId {
170    fn default() -> Self {
171        Self::new()
172    }
173}
174
175mod serde_bytes_array16 {
176    use serde::{Deserializer, Serializer};
177    pub fn serialize<S: Serializer>(b: &[u8; 16], s: S) -> Result<S::Ok, S::Error> {
178        serde_bytes::serialize(b.as_slice(), s)
179    }
180    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; 16], D::Error> {
181        let v: Vec<u8> = serde_bytes::deserialize(d)?;
182        v.try_into()
183            .map_err(|_| serde::de::Error::custom("expected 16 bytes"))
184    }
185}
186
187#[derive(Debug, Clone, Serialize, Deserialize)]
188pub struct ConversationMeta {
189    pub id: ConversationId,
190    pub name: Option<String>,
191    pub epoch: u64,
192    pub member_count: u32,
193    pub is_device_group: bool,
194    pub created_at_ms: u64,
195}
196
197/// One member leaf of a conversation's MLS group: the member's [`UserId`]
198/// (recovered from the leaf's `BasicCredential`) and its ratchet-tree leaf
199/// index. A user with multiple devices appears once **per device leaf** —
200/// callers that want a per-user roster should dedup by `user_id`.
201#[derive(Debug, Clone, Serialize, Deserialize)]
202pub struct MemberInfo {
203    pub user_id: UserId,
204    /// SHA-256 of this member's leaf signature public key — identical to the
205    /// value `Client::device_id()` reports for that device. Lets the host tell
206    /// WHICH device owns each leaf, e.g. to skip re-admitting a device that is
207    /// already a member (a plain Add of a duplicate signature key is rejected by
208    /// RFC 9420 leaf validation, so a recovery/re-admit pass must detect it).
209    pub device_id: DeviceId,
210    pub leaf_index: u32,
211}
212
213/// In-memory conversation handle. Holds the OpenMLS group plus our wire-level cursor.
214pub struct Conversation {
215    pub(crate) id: ConversationId,
216    pub(crate) meta: ConversationMeta,
217    pub(crate) group: MlsGroup,
218    pub(crate) crypto: Arc<PersistentMlsProvider>,
219    pub(crate) signing: Arc<SignatureKeyPair>,
220    pub(crate) own_device: DeviceId,
221    pub(crate) seq: u64,
222    pub(crate) hlc: Hlc,
223    pub(crate) cursor: SyncCursor,
224    pub(crate) storage: Arc<dyn Storage>,
225    /// Local device→leaf-index map for [CR-2] revocation.
226    ///
227    /// Populated when this device either (a) admits a peer via [`Self::add_members`] —
228    /// every entry in the `Vec<(DeviceId, KeyPackage)>` is recorded after the commit
229    /// merges — or (b) joins as the receiving device via [`Self::join`], at which point
230    /// we record our own leaf. Pruned when [`Self::remove_members`] is called.
231    ///
232    /// Not authoritative for *peers' devices we didn't admit*: those are visible in
233    /// `group.members()` but their device_ids are opaque to this client. `revoke_device`
234    /// is therefore best-effort across conversations we ourselves invited the device
235    /// into; see [`MessagingClient::revoke_device`] for the documented scope.
236    pub(crate) device_leaves: BTreeMap<DeviceId, u32>,
237}
238
239impl std::fmt::Debug for Conversation {
240    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241        f.debug_struct("Conversation")
242            .field("id", &self.id.as_hex())
243            .field("meta", &self.meta)
244            .finish()
245    }
246}
247
248impl Conversation {
249    pub fn id(&self) -> ConversationId {
250        self.id
251    }
252    pub fn meta(&self) -> &ConversationMeta {
253        &self.meta
254    }
255
256    /// Current member roster, recovered locally from the MLS group's leaf
257    /// credentials — no network and no out-of-band `ping.profile` message.
258    /// Each `BasicCredential` was built from the member's `UserId`
259    /// (`BasicCredential::new(own_user.0.clone())` in [`Self::create`] /
260    /// [`Self::join`]), so we round-trip it back here. Each entry is one
261    /// leaf; a multi-device user appears once per device leaf.
262    pub fn members(&self) -> Vec<MemberInfo> {
263        self.group
264            .members()
265            .filter_map(|m| {
266                // Derive the device id the same way `Client::device_id()` does —
267                // SHA-256 of the (signature) public key — so the host can match a
268                // member against a known device id.
269                let device_id = DeviceId(codec::sha256(m.signature_key.as_slice()).to_vec());
270                let basic = BasicCredential::try_from(m.credential).ok()?;
271                Some(MemberInfo {
272                    user_id: UserId(basic.identity().to_vec()),
273                    device_id,
274                    leaf_index: m.index.u32(),
275                })
276            })
277            .collect()
278    }
279
280    /// Leaf indexes of current members whose MLS signature key EQUALS the
281    /// incoming KeyPackage's — the "phrase-restore" duplicate: a device restored
282    /// from a recovery phrase keeps the SAME long-term signing key, so its dead
283    /// pre-wipe leaf (logout never emits an MLS Remove) still carries that key,
284    /// and RFC 9420 leaf validation would reject an Add that duplicates it. The
285    /// caller ([`Client::re_admit_device`]) evicts these BEFORE the Add.
286    ///
287    /// Read-only. The KeyPackage is validated exactly as [`Self::stage_add_members`]
288    /// validates it (never trust an unvalidated `KeyPackageIn`). Comparing the
289    /// PUBLIC leaf signature keys with `==` is the same content comparison
290    /// [`Self::confirm_staged`] already performs to resolve added leaves — not a
291    /// secret comparison. A healthy SIBLING device has a different signing key, so
292    /// it can never match here and is never evicted.
293    pub(crate) fn duplicate_signature_key_leaves(
294        &self,
295        key_package_bytes: &[u8],
296    ) -> Result<Vec<u32>> {
297        let mls_in = MlsMessageIn::tls_deserialize_exact(key_package_bytes).map_err(Error::mls)?;
298        let kp_in = match mls_in.extract() {
299            MlsMessageBodyIn::KeyPackage(kp) => kp,
300            _ => return Err(Error::Invalid("expected KeyPackage".into())),
301        };
302        let kp = kp_in
303            .validate(self.crypto.crypto(), ProtocolVersion::default())
304            .map_err(Error::mls)?;
305        let new_sig = kp.leaf_node().signature_key().as_slice().to_vec();
306        Ok(self
307            .group
308            .members()
309            .filter(|m| m.signature_key.as_slice() == new_sig.as_slice())
310            .map(|m| m.index.u32())
311            .collect())
312    }
313
314    pub fn epoch(&self) -> u64 {
315        self.group.epoch().as_u64()
316    }
317
318    /// True while the local device is still a member. Becomes false once we
319    /// process a Commit that removes our own leaf — OpenMLS transitions the group
320    /// to `MlsGroupState::Inactive`. The client uses this to tear the group down
321    /// on self-removal so a later re-invite Welcome is a clean first-join.
322    pub(crate) fn is_active(&self) -> bool {
323        self.group.is_active()
324    }
325
326    /// Delete this group's OpenMLS state from persistent storage. Called when the
327    /// local device has been removed from the group, so a subsequent re-invite
328    /// Welcome re-joins from CLEAN storage. OpenMLS keys group state by
329    /// `group_id`; a lingering removed group would (a) make the conversation look
330    /// "already joined" so the host drops the re-invite Welcome, and (b) collide
331    /// with the fresh `StagedWelcome::into_group` on re-join.
332    pub(crate) fn delete_group_state(&mut self) -> Result<()> {
333        self.group
334            .delete(self.crypto.storage())
335            .map_err(|e| Error::Storage(e.to_string()))
336    }
337
338    pub fn cursor(&self) -> &SyncCursor {
339        &self.cursor
340    }
341
342    /// Create a new conversation, with `self` as the only initial member.
343    // 8 args is a lot, but they're all needed for an internal constructor and a builder
344    // would be over-engineered for v0.1.
345    #[allow(clippy::too_many_arguments)]
346    pub(crate) fn create(
347        id: ConversationId,
348        name: Option<String>,
349        own_device: DeviceId,
350        own_user: &UserId,
351        crypto: Arc<PersistentMlsProvider>,
352        signing: Arc<SignatureKeyPair>,
353        storage: Arc<dyn Storage>,
354        now_ms: u64,
355    ) -> Result<Self> {
356        let credential = BasicCredential::new(own_user.0.clone());
357        let credential_with_key = CredentialWithKey {
358            credential: credential.into(),
359            signature_key: signing.public().into(),
360        };
361        // Carry the conversation name in the GroupContext so it travels in the
362        // Welcome to every joiner (see `GROUP_NAME_EXTENSION_TYPE`). No
363        // RequiredCapabilities is added, so this imposes no member capability
364        // check and stays compatible with existing KeyPackages.
365        let cfg = MlsGroupCreateConfig::builder()
366            .ciphersuite(DEFAULT_CIPHERSUITE)
367            .use_ratchet_tree_extension(true)
368            // Advertise the group-name extension capability on the creator's leaf
369            // so a later `set_name` (rename / avatar change) passes the GCE
370            // capability check. See `ping_leaf_capabilities`.
371            .capabilities(ping_leaf_capabilities())
372            .with_group_context_extensions(group_context_extensions_for_name(name.as_deref()))
373            .map_err(Error::mls)?
374            .build();
375        let group = MlsGroup::new_with_group_id(
376            crypto.as_ref(),
377            signing.as_ref(),
378            &cfg,
379            openmls::group::GroupId::from_slice(&id.0),
380            credential_with_key,
381        )
382        .map_err(Error::mls)?;
383
384        let meta = ConversationMeta {
385            id,
386            name,
387            epoch: 0,
388            member_count: 1,
389            is_device_group: false,
390            created_at_ms: now_ms,
391        };
392        // [CR-2] Group creator is always leaf 0; record so revoke_device can target it.
393        let mut device_leaves = BTreeMap::new();
394        device_leaves.insert(own_device.clone(), group.own_leaf_index().u32());
395        Ok(Self {
396            id,
397            meta,
398            group,
399            crypto,
400            signing,
401            own_device,
402            seq: 0,
403            hlc: Hlc::ZERO.tick(now_ms),
404            cursor: SyncCursor::default(),
405            storage,
406            device_leaves,
407        })
408    }
409
410    /// Join an existing conversation from a Welcome message.
411    ///
412    /// Maps the OpenMLS `WelcomeError` for a missing KeyPackage / init key to
413    /// the typed [`Error::KeyPackageNotFound`] (see `map_welcome_error`) so the
414    /// host can react (top up KeyPackages) instead of treating it as an opaque
415    /// MLS failure.
416    pub(crate) fn join(
417        welcome_bytes: &[u8],
418        own_device: DeviceId,
419        crypto: Arc<PersistentMlsProvider>,
420        signing: Arc<SignatureKeyPair>,
421        storage: Arc<dyn Storage>,
422        now_ms: u64,
423    ) -> Result<Self> {
424        let mls_in = MlsMessageIn::tls_deserialize_exact(welcome_bytes).map_err(Error::mls)?;
425        let welcome = match mls_in.extract() {
426            MlsMessageBodyIn::Welcome(w) => w,
427            _ => return Err(Error::Invalid("expected Welcome".into())),
428        };
429        let cfg = MlsGroupJoinConfig::builder()
430            .use_ratchet_tree_extension(true)
431            .build();
432        let staged =
433            openmls::group::StagedWelcome::new_from_welcome(crypto.as_ref(), &cfg, welcome, None)
434                .map_err(map_welcome_error)?;
435        let group = staged.into_group(crypto.as_ref()).map_err(Error::mls)?;
436
437        let id_bytes: [u8; 16] = group
438            .group_id()
439            .as_slice()
440            .try_into()
441            .map_err(|_| Error::Invalid("group id must be 16 bytes".into()))?;
442        let id = ConversationId(id_bytes);
443        // The creator stamped the name into the GroupContext, which is part of
444        // the shared group state the Welcome reconstructs — so a joining device
445        // recovers the real name here instead of starting with `None`.
446        let name = group_name_from_extensions(group.extensions());
447        let meta = ConversationMeta {
448            id,
449            name,
450            epoch: group.epoch().as_u64(),
451            member_count: group.members().count() as u32,
452            is_device_group: false,
453            created_at_ms: now_ms,
454        };
455
456        // Seed the cursor at the join epoch so subsequent fetches skip pre-join Commits
457        // (notably the Add commit that produced this Welcome — it lives in the conversation
458        // log at `epoch - 1`, which the joiner must not try to apply on top of its
459        // already-advanced group state).
460        let join_epoch = group.epoch().as_u64();
461        // [CR-2] Record our own (device_id → leaf_index) so the host can later revoke us
462        // via the standard `revoke_device` flow. `own_leaf_index()` is stable for the
463        // lifetime of this group membership.
464        let own_leaf = group.own_leaf_index().u32();
465        let mut device_leaves = BTreeMap::new();
466        device_leaves.insert(own_device.clone(), own_leaf);
467        Ok(Self {
468            id,
469            meta,
470            group,
471            crypto,
472            signing,
473            own_device,
474            seq: 0,
475            hlc: Hlc::ZERO.tick(now_ms),
476            cursor: SyncCursor {
477                epoch: join_epoch,
478                ..Default::default()
479            },
480            storage,
481            device_leaves,
482        })
483    }
484
485    /// The conversation name recovered from MLS GroupContext state (set at
486    /// creation, carried in the Welcome to every joiner). `None` if unnamed.
487    pub(crate) fn name_from_group_state(&self) -> Option<String> {
488        group_name_from_extensions(self.group.extensions())
489    }
490
491    /// [CR-4] Rehydrate a previously-persisted conversation on cold restart.
492    ///
493    /// Loads the OpenMLS group state via `MlsGroup::load` (which reads from the
494    /// provider's storage — populated by the SQLite-backed checkpoint on the
495    /// previous run). Pairs the loaded MLS state with the meta + cursor + device→leaf
496    /// map the host-side `Storage` trait kept for us. Returns `Ok(None)` if OpenMLS
497    /// finds no state for `id` — the host's `groups` namespace had a stale entry.
498    #[allow(clippy::too_many_arguments)]
499    pub(crate) fn load(
500        id: ConversationId,
501        meta: ConversationMeta,
502        cursor: SyncCursor,
503        device_leaves: BTreeMap<DeviceId, u32>,
504        own_device: DeviceId,
505        crypto: Arc<PersistentMlsProvider>,
506        signing: Arc<SignatureKeyPair>,
507        storage: Arc<dyn Storage>,
508        now_ms: u64,
509    ) -> Result<Option<Self>> {
510        use openmls::group::GroupId;
511        let group_id = GroupId::from_slice(&id.0);
512        let group = match MlsGroup::load(crypto.storage(), &group_id).map_err(Error::mls)? {
513            Some(g) => g,
514            None => return Ok(None),
515        };
516        // Restore the local outgoing-send counter from the persisted cursor. The cursor
517        // tracks the highest applied (epoch, sender, seq) for every device — including
518        // our own — so we can recover `self.seq` from `cursor.last_seq_per_device[own]`.
519        // Without this, the next `send_application()` re-uses an already-consumed seq
520        // and receivers silently dedupe (cursor.is_new returns false on their side).
521        let seq = cursor
522            .last_seq_per_device
523            .get(&own_device)
524            .copied()
525            .unwrap_or(0);
526        Ok(Some(Self {
527            id,
528            meta,
529            group,
530            crypto,
531            signing,
532            own_device,
533            seq,
534            hlc: Hlc::ZERO.tick(now_ms),
535            cursor,
536            storage,
537            device_leaves,
538        }))
539    }
540
541    /// Encrypt an application message and produce a wire envelope ready for transport.
542    ///
543    /// Uses the [CR-6] plaintext content_hash path: the envelope's `content_hash` is
544    /// `SHA-256(plaintext)`, not the MLS ciphertext. This is what makes rebase clean
545    /// and gives cross-binding hash parity.
546    pub fn send_application(&mut self, plaintext: &[u8], now_ms: u64) -> Result<MessageEnvelope> {
547        let out = self
548            .group
549            .create_message(self.crypto.as_ref(), self.signing.as_ref(), plaintext)
550            .map_err(Error::mls)?;
551
552        self.seq += 1;
553        self.hlc = self.hlc.tick(now_ms);
554        let bytes = out.tls_serialize_detached().map_err(Error::mls)?;
555        let env = MessageEnvelope::new_application(
556            self.id,
557            self.epoch(),
558            self.own_device.clone(),
559            self.seq,
560            self.hlc,
561            bytes,
562            plaintext,
563        );
564        // Advance the local cursor past our own send so a subsequent catch-up sync doesn't
565        // pull this envelope back to us (we've already applied it locally — re-processing
566        // would either fail or duplicate-deliver).
567        self.cursor.advance(
568            env.epoch,
569            self.own_device.clone(),
570            self.seq,
571            self.hlc,
572            now_ms,
573        );
574        Ok(env)
575    }
576
577    /// Add members by KeyPackage. Produces the Commit envelope to broadcast plus the Welcome
578    /// envelope(s) to deliver out-of-band to the newly-added devices.
579    ///
580    /// [CR-2] takes a `Vec<(DeviceId, KeyPackage)>` instead of a bare `Vec<KeyPackage>`. The
581    /// `DeviceId` for each entry is the *caller's* assertion of which device owns that
582    /// KeyPackage — hosts typically get it from the directory service alongside the
583    /// KeyPackage itself. The mapping is persisted per-conversation so [`MessagingClient::revoke_device`]
584    /// can later locate the leaf to remove without a fresh directory lookup. The SDK does
585    /// not cryptographically verify the device claim; that's a host policy concern
586    /// (typically: the directory authenticates the key_package_id → device_id mapping).
587    pub fn add_members(
588        &mut self,
589        entries: Vec<(DeviceId, Vec<u8>)>,
590        now_ms: u64,
591    ) -> Result<AddOutcome> {
592        // All-in-one (stage + immediate merge) for callers that commit and
593        // persist synchronously with NO networked rollback window — e.g. the
594        // device-group / device-linking paths. The networked group path in
595        // `client.rs` instead uses `stage_add_members` + `confirm_staged` /
596        // `abort_staged`, so a Commit the server REJECTS can be rolled back
597        // rather than leaving the local epoch ahead of the server (the desync
598        // that permanently bricks a group: every later Commit then 409s and
599        // peers can't decrypt our epoch).
600        let staged = self.stage_add_members(entries, now_ms)?;
601        self.confirm_staged(&staged, now_ms)?;
602        let StagedCommit {
603            commit, welcome, ..
604        } = staged;
605        let welcome =
606            welcome.ok_or_else(|| Error::Invalid("add_members produced no Welcome".into()))?;
607        Ok(AddOutcome { commit, welcome })
608    }
609
610    /// Stage an add-members Commit WITHOUT merging it — the group keeps a
611    /// *pending* commit and the local epoch is UNCHANGED. Returns the Commit +
612    /// Welcome envelopes to send. The caller MUST follow with exactly one of
613    /// [`Self::confirm_staged`] (server accepted the Commit → merge locally) or
614    /// [`Self::abort_staged`] (server rejected it → discard, epoch never moves).
615    ///
616    /// This is what makes the local epoch advance *only after* the server
617    /// accepts the Commit (send-then-merge), so a rejected/conflicting Commit
618    /// can't desync the group. Safe because the JS worker serializes top-level
619    /// requests — nothing else touches this group during the send round-trip
620    /// between stage and confirm/abort (worker.ts "SERIALIZE … dispatch").
621    pub(crate) fn stage_add_members(
622        &mut self,
623        entries: Vec<(DeviceId, Vec<u8>)>,
624        now_ms: u64,
625    ) -> Result<StagedCommit> {
626        let mut kps = Vec::with_capacity(entries.len());
627        // Track signature_key → device_id so we can resolve leaf indices post-commit.
628        let mut sig_to_device: Vec<(Vec<u8>, DeviceId)> = Vec::with_capacity(entries.len());
629        for (device_id, raw) in &entries {
630            let mls_in = MlsMessageIn::tls_deserialize_exact(raw).map_err(Error::mls)?;
631            let kp_in = match mls_in.extract() {
632                MlsMessageBodyIn::KeyPackage(kp) => kp,
633                _ => return Err(Error::Invalid("expected KeyPackage".into())),
634            };
635            // KeyPackages on the wire are unvalidated (`KeyPackageIn`); validate against the
636            // crypto provider before handing them to OpenMLS.
637            let kp = kp_in
638                .validate(self.crypto.crypto(), ProtocolVersion::default())
639                .map_err(Error::mls)?;
640            let sig_key = kp.leaf_node().signature_key().as_slice().to_vec();
641            sig_to_device.push((sig_key, device_id.clone()));
642            kps.push(kp);
643        }
644
645        // The Commit's wire `epoch` is the *source* epoch (where it was crafted). The
646        // Welcome's `epoch` is the *post-commit* epoch. An MLS Commit advances the epoch by
647        // exactly 1, so we can name the post-commit epoch as `pre + 1` WITHOUT merging.
648        let pre_commit_epoch = self.epoch();
649        let post_commit_epoch = pre_commit_epoch + 1;
650
651        let (commit_out, welcome_out, _gi) = self
652            .group
653            .add_members(self.crypto.as_ref(), self.signing.as_ref(), &kps)
654            .map_err(Error::mls)?;
655        // NB: NO merge here — the pending commit is merged by `confirm_staged`
656        // only once the server has accepted the Commit send.
657
658        let next_seq = self.seq + 1;
659        let next_hlc = self.hlc.tick(now_ms);
660
661        let commit_bytes = mls_message_out_bytes(commit_out)?;
662        let commit_env = MessageEnvelope::new(
663            self.id,
664            pre_commit_epoch,
665            MessageKind::Commit,
666            self.own_device.clone(),
667            next_seq,
668            next_hlc,
669            commit_bytes,
670        );
671
672        let welcome_bytes = mls_message_out_bytes(welcome_out)?;
673        let welcome_env = MessageEnvelope::new(
674            self.id,
675            post_commit_epoch,
676            MessageKind::Welcome,
677            self.own_device.clone(),
678            next_seq,
679            next_hlc,
680            welcome_bytes,
681        );
682
683        Ok(StagedCommit {
684            commit: commit_env,
685            welcome: Some(welcome_env),
686            next_seq,
687            next_hlc,
688            leaf_update: StagedLeafUpdate::Add(sig_to_device),
689        })
690    }
691
692    pub fn remove_members(
693        &mut self,
694        leaf_indexes: Vec<u32>,
695        now_ms: u64,
696    ) -> Result<MessageEnvelope> {
697        // All-in-one (stage + immediate merge). See `add_members` for why the
698        // networked path uses stage/confirm/abort instead.
699        let staged = self.stage_remove_members(leaf_indexes, now_ms)?;
700        self.confirm_staged(&staged, now_ms)?;
701        let StagedCommit { commit, .. } = staged;
702        Ok(commit)
703    }
704
705    /// Stage a remove-members Commit WITHOUT merging it — see
706    /// [`Self::stage_add_members`]. No Welcome (removals don't admit anyone).
707    pub(crate) fn stage_remove_members(
708        &mut self,
709        leaf_indexes: Vec<u32>,
710        now_ms: u64,
711    ) -> Result<StagedCommit> {
712        use openmls::prelude::LeafNodeIndex;
713        let leaves: Vec<LeafNodeIndex> = leaf_indexes
714            .iter()
715            .copied()
716            .map(LeafNodeIndex::new)
717            .collect();
718
719        let pre_commit_epoch = self.epoch();
720
721        let (commit_out, _welcome_opt, _gi) = self
722            .group
723            .remove_members(self.crypto.as_ref(), self.signing.as_ref(), &leaves)
724            .map_err(Error::mls)?;
725        // NB: NO merge here — see `stage_add_members`.
726
727        let next_seq = self.seq + 1;
728        let next_hlc = self.hlc.tick(now_ms);
729        let bytes = mls_message_out_bytes(commit_out)?;
730        let commit_env = MessageEnvelope::new(
731            self.id,
732            pre_commit_epoch,
733            MessageKind::Commit,
734            self.own_device.clone(),
735            next_seq,
736            next_hlc,
737            bytes,
738        );
739
740        let removed: std::collections::HashSet<u32> = leaf_indexes.iter().copied().collect();
741        Ok(StagedCommit {
742            commit: commit_env,
743            welcome: None,
744            next_seq,
745            next_hlc,
746            leaf_update: StagedLeafUpdate::Remove(removed),
747        })
748    }
749
750    /// Create a self-Remove PROPOSAL — "leave the group".
751    ///
752    /// MLS does not let a member commit their OWN removal, so leaving is a
753    /// two-step dance: this member broadcasts a Remove proposal for its own
754    /// leaf, and a DIFFERENT member commits it (see
755    /// [`Self::stage_commit_pending_proposals`]). A proposal does NOT advance
756    /// the epoch; we bump only our own seq/hlc and the caller then deletes the
757    /// conversation locally. Returns the proposal envelope
758    /// (`MessageKind::Proposal`) to broadcast on the conversation channel.
759    pub(crate) fn leave_group(&mut self, now_ms: u64) -> Result<MessageEnvelope> {
760        let proposal_out = self
761            .group
762            .leave_group(self.crypto.as_ref(), self.signing.as_ref())
763            .map_err(Error::mls)?;
764        let next_seq = self.seq + 1;
765        let next_hlc = self.hlc.tick(now_ms);
766        let bytes = mls_message_out_bytes(proposal_out)?;
767        let env = MessageEnvelope::new(
768            self.id,
769            self.epoch(),
770            MessageKind::Proposal,
771            self.own_device.clone(),
772            next_seq,
773            next_hlc,
774            bytes,
775        );
776        self.seq = next_seq;
777        self.hlc = next_hlc;
778        Ok(env)
779    }
780
781    /// True when OpenMLS has buffered pending proposals for this group (e.g. a
782    /// peer's leave proposal awaiting a Commit).
783    pub(crate) fn has_pending_proposals(&self) -> bool {
784        self.group.pending_proposals().next().is_some()
785    }
786
787    /// Stage a Commit covering all buffered pending proposals (the canonical
788    /// case: a peer's "leave" Remove proposal). Returns `None` when there is
789    /// nothing pending. Send-then-merge like add/remove so a server-rejected
790    /// Commit rolls back without desyncing the epoch. The removed leaves are
791    /// read off the pending Remove proposals so the device→leaf map is pruned
792    /// on confirm.
793    pub(crate) fn stage_commit_pending_proposals(
794        &mut self,
795        now_ms: u64,
796    ) -> Result<Option<StagedCommit>> {
797        use openmls::messages::proposals::Proposal;
798        let removed: std::collections::HashSet<u32> = self
799            .group
800            .pending_proposals()
801            .filter_map(|qp| match qp.proposal() {
802                Proposal::Remove(r) => Some(r.removed().u32()),
803                _ => None,
804            })
805            .collect();
806        if self.group.pending_proposals().next().is_none() {
807            return Ok(None);
808        }
809
810        let pre_commit_epoch = self.epoch();
811        let (commit_out, _welcome, _gi) = self
812            .group
813            .commit_to_pending_proposals(self.crypto.as_ref(), self.signing.as_ref())
814            .map_err(Error::mls)?;
815        // NB: NO merge here — confirm_staged merges once the server accepts.
816
817        let next_seq = self.seq + 1;
818        let next_hlc = self.hlc.tick(now_ms);
819        let bytes = mls_message_out_bytes(commit_out)?;
820        let commit_env = MessageEnvelope::new(
821            self.id,
822            pre_commit_epoch,
823            MessageKind::Commit,
824            self.own_device.clone(),
825            next_seq,
826            next_hlc,
827            bytes,
828        );
829
830        Ok(Some(StagedCommit {
831            commit: commit_env,
832            welcome: None,
833            next_seq,
834            next_hlc,
835            leaf_update: StagedLeafUpdate::Remove(removed),
836        }))
837    }
838
839    /// Change the conversation `name` carried in the GroupContext (RFC 9420
840    /// GroupContextExtensions commit). Unlike a hydration broadcast, this rides
841    /// MLS group STATE, so every member — and every future joiner via the
842    /// ratchet-tree/GroupInfo — converges on the new name. Hosts use this to make
843    /// a rename or an embedded avatar-media-id change BULLETPROOF (the name field
844    /// carries the `ping:meta:v1:` blob).
845    ///
846    /// Produces a Commit to broadcast; NO Welcome (membership is unchanged). All
847    /// members must advertise the group-name extension capability
848    /// ([`ping_leaf_capabilities`]) — i.e. have re-linked since that shipped —
849    /// else openmls rejects the commit (`RequiredExtensionNotSupportedByAllMembers`).
850    ///
851    /// All-in-one (stage + immediate merge). The networked group path uses
852    /// [`Self::stage_set_name`] + [`Self::confirm_staged`]/[`Self::abort_staged`]
853    /// so a server-rejected commit can roll back without desyncing the epoch.
854    pub fn set_name(&mut self, name: Option<String>, now_ms: u64) -> Result<MessageEnvelope> {
855        let staged = self.stage_set_name(name, now_ms)?;
856        self.confirm_staged(&staged, now_ms)?;
857        let StagedCommit { commit, .. } = staged;
858        Ok(commit)
859    }
860
861    /// Stage a name-update Commit WITHOUT merging it — see
862    /// [`Self::stage_add_members`]. No Welcome (no membership change). The local
863    /// epoch advances only on [`Self::confirm_staged`].
864    pub(crate) fn stage_set_name(
865        &mut self,
866        name: Option<String>,
867        now_ms: u64,
868    ) -> Result<StagedCommit> {
869        let pre_commit_epoch = self.epoch();
870        let extensions = group_context_extensions_for_name_update(name.as_deref());
871
872        let (commit_out, _welcome_opt, _gi) = self
873            .group
874            .update_group_context_extensions(
875                self.crypto.as_ref(),
876                extensions,
877                self.signing.as_ref(),
878            )
879            .map_err(Error::mls)?;
880        // NB: NO merge here — confirm_staged merges once the server accepts.
881
882        let next_seq = self.seq + 1;
883        let next_hlc = self.hlc.tick(now_ms);
884        let bytes = mls_message_out_bytes(commit_out)?;
885        let commit_env = MessageEnvelope::new(
886            self.id,
887            pre_commit_epoch,
888            MessageKind::Commit,
889            self.own_device.clone(),
890            next_seq,
891            next_hlc,
892            bytes,
893        );
894
895        Ok(StagedCommit {
896            commit: commit_env,
897            welcome: None,
898            next_seq,
899            next_hlc,
900            leaf_update: StagedLeafUpdate::None,
901        })
902    }
903
904    /// Merge a previously [staged](Self::stage_add_members) Commit into the local
905    /// group — call ONLY after the server has accepted the Commit send. Advances
906    /// the epoch, updates the roster + device→leaf map, bumps seq/hlc, and moves
907    /// the sync cursor past our own Commit so catch-up doesn't re-apply it.
908    pub(crate) fn confirm_staged(&mut self, staged: &StagedCommit, now_ms: u64) -> Result<()> {
909        self.group
910            .merge_pending_commit(self.crypto.as_ref())
911            .map_err(Error::mls)?;
912        self.meta.epoch = self.epoch();
913        self.meta.member_count = self.group.members().count() as u32;
914        // A GroupContextExtensions commit (e.g. `set_name`) changes the name
915        // carried in group state — refresh the cached meta name. Harmless for
916        // add/remove commits (the name is unchanged).
917        self.meta.name = self.name_from_group_state();
918
919        match &staged.leaf_update {
920            StagedLeafUpdate::Add(sig_to_device) => {
921                // [CR-2] Resolve leaf indexes for the devices we just added (match by the
922                // per-device MLS signature_key, unique per device).
923                for member in self.group.members() {
924                    if let Some((_, device_id)) = sig_to_device
925                        .iter()
926                        .find(|(sig, _)| sig.as_slice() == member.signature_key.as_slice())
927                    {
928                        self.device_leaves
929                            .insert(device_id.clone(), member.index.u32());
930                    }
931                }
932            }
933            StagedLeafUpdate::Remove(removed) => {
934                // [CR-2] Prune the device→leaf map for removed leaves. Other entries' leaf
935                // indexes are stable (OpenMLS reuses blank slots, doesn't reshuffle).
936                self.device_leaves.retain(|_, idx| !removed.contains(idx));
937            }
938            StagedLeafUpdate::None => {
939                // No membership change (name-update commit) — leaf map unchanged.
940            }
941        }
942
943        self.seq = staged.next_seq;
944        self.hlc = staged.next_hlc;
945        self.cursor.advance(
946            self.meta.epoch,
947            self.own_device.clone(),
948            self.seq,
949            self.hlc,
950            now_ms,
951        );
952        Ok(())
953    }
954
955    /// Discard a previously [staged](Self::stage_add_members) Commit — call when
956    /// the server REJECTED the Commit send. Clears the pending commit so the
957    /// local epoch stays exactly where it was (no desync) and the conversation
958    /// is operational again. Idempotent / safe if there is no pending commit.
959    pub(crate) fn abort_staged(&mut self) -> Result<()> {
960        self.group
961            .clear_pending_commit(self.crypto.storage())
962            .map_err(Error::mls)?;
963        Ok(())
964    }
965
966    /// Process an inbound envelope. Returns Some(IncomingMessage) for application traffic.
967    pub fn process(
968        &mut self,
969        env: &MessageEnvelope,
970        now_ms: u64,
971    ) -> Result<Option<IncomingMessage>> {
972        if !self.cursor.is_new(env.epoch, &env.sender_device, env.seq) {
973            return Ok(None); // dedupe: already applied
974        }
975        let mls_in = MlsMessageIn::tls_deserialize_exact(&env.payload).map_err(Error::mls)?;
976
977        // OpenMLS' `process_message` expects an `impl Into<ProtocolMessage>`. `MlsMessageIn`
978        // itself doesn't implement that; we have to extract the body and convert the inner
979        // private/public message. Welcomes are handled at the client level, not here.
980        let protocol_msg: ProtocolMessage = match mls_in.extract() {
981            MlsMessageBodyIn::PrivateMessage(m) => m.into(),
982            MlsMessageBodyIn::PublicMessage(m) => m.into(),
983            MlsMessageBodyIn::Welcome(_) => {
984                return Err(Error::Invalid(
985                    "Welcome must be handled at client level, not in-group".into(),
986                ));
987            }
988            _ => return Err(Error::Invalid("unsupported MLS message body".into())),
989        };
990
991        let processed: ProcessedMessage = self
992            .group
993            .process_message(self.crypto.as_ref(), protocol_msg)
994            .map_err(Error::mls)?;
995
996        // Recover the sender's account-level `UserId` from their authenticated
997        // leaf credential BEFORE `into_content()` consumes `processed`. Same
998        // round-trip as `members()`: the leaf was built as
999        // `BasicCredential::new(user.0)`, so `identity()` is the `UserId` bytes.
1000        // This lets the host attribute messages to the right account across
1001        // every linked device without any device→account side channel.
1002        let sender_user_id = BasicCredential::try_from(processed.credential().clone())
1003            .map(|c| UserId(c.identity().to_vec()))
1004            .unwrap_or_else(|_| UserId(Vec::new()));
1005
1006        let out = match processed.into_content() {
1007            ProcessedMessageContent::ApplicationMessage(app) => {
1008                let pt = app.into_bytes();
1009                // CR-6: for v=2 application envelopes the wire-contract validator can't
1010                // check `content_hash` (the hash is over plaintext, which it didn't have).
1011                // We can now: verify SHA-256(pt) == env.content_hash and reject mismatches.
1012                // For v=1 envelopes the wire-contract validator already checked the
1013                // ciphertext-based hash, so no extra work here.
1014                if env.v >= 2 {
1015                    let computed = crate::message::hash_application_plaintext(&pt);
1016                    if computed != env.content_hash {
1017                        return Err(Error::Invalid(
1018                            "v=2 application content_hash mismatch".into(),
1019                        ));
1020                    }
1021                }
1022                Some(IncomingMessage {
1023                    conversation_id: self.id,
1024                    sender_device: env.sender_device.clone(),
1025                    sender_user_id,
1026                    epoch: env.epoch,
1027                    hlc: env.hlc,
1028                    plaintext: pt,
1029                    content_hash: env.content_hash,
1030                })
1031            }
1032            ProcessedMessageContent::StagedCommitMessage(staged) => {
1033                self.group
1034                    .merge_staged_commit(self.crypto.as_ref(), *staged)
1035                    .map_err(Error::mls)?;
1036                self.meta.epoch = self.epoch();
1037                self.meta.member_count = self.group.members().count() as u32;
1038                // A remote `set_name` (GroupContextExtensions) commit changes the
1039                // name in group state — refresh the cached meta so this device
1040                // picks up the rename / avatar-id change WITHOUT a side broadcast.
1041                self.meta.name = self.name_from_group_state();
1042                None
1043            }
1044            ProcessedMessageContent::ProposalMessage(qp) => {
1045                // OpenMLS does NOT auto-buffer a processed proposal — the caller
1046                // must explicitly store it, or `pending_proposals()` stays empty
1047                // and `commit_to_pending_proposals` covers nothing. This is the
1048                // mechanism behind "leave": a peer's self-Remove proposal is
1049                // stored here so a remaining member can commit it (evicting the
1050                // leaver) via `commit_pending_proposals`.
1051                self.group
1052                    .store_pending_proposal(self.crypto.storage(), *qp)
1053                    .map_err(Error::mls)?;
1054                None
1055            }
1056            ProcessedMessageContent::ExternalJoinProposalMessage(_) => {
1057                // External-join proposals are not part of any current flow; drop.
1058                None
1059            }
1060        };
1061
1062        self.cursor.advance(
1063            env.epoch,
1064            env.sender_device.clone(),
1065            env.seq,
1066            env.hlc,
1067            now_ms,
1068        );
1069        Ok(out)
1070    }
1071
1072    /// Export a derived secret keyed to this group's current epoch ([CR-8]).
1073    ///
1074    /// Wraps `MlsGroup::export_secret` (the MLS exporter, RFC 9420 §8.5) and surfaces the
1075    /// bytes in a `Zeroizing<Vec<u8>>` so the local copy is wiped on drop. Used by the host
1076    /// to seed:
1077    ///   * the ephemeral channel (`ping/ephemeral`, §5.4 of the architecture)
1078    ///   * call media keys (`ping/calls/media/{call_id}`, §7.2)
1079    ///   * call-ephemeral framer keys (`ping/calls/ephemeral/{call_id}`, §7.5)
1080    ///
1081    /// `label` should use the documented `ping/*` namespacing convention. There is no
1082    /// runtime enforcement — cross-binding parity is enforced by conformance fixtures
1083    /// pinning specific label strings.
1084    ///
1085    /// Output is the secret. Callers MUST treat the buffer as a secret: never log, never
1086    /// persist unencrypted. The wrapper zeroes our local copy on drop; the caller is
1087    /// responsible for zeroing any copy they make.
1088    pub fn export_secret(
1089        &self,
1090        label: &str,
1091        context: &[u8],
1092        length: usize,
1093    ) -> Result<Zeroizing<Vec<u8>>> {
1094        if length == 0 {
1095            return Err(Error::Invalid("export_secret length must be > 0".into()));
1096        }
1097        // Soft cap to prevent runaway allocations from a malformed caller. Real labels never
1098        // need more than ~64 bytes (AES-256 key + 96-bit nonce + slack); 1 KiB is generous.
1099        if length > 1024 {
1100            return Err(Error::Invalid(
1101                "export_secret length exceeds 1024-byte cap".into(),
1102            ));
1103        }
1104        let bytes = self
1105            .group
1106            .export_secret(self.crypto.as_ref(), label, context, length)
1107            .map_err(Error::mls)?;
1108        Ok(Zeroizing::new(bytes))
1109    }
1110
1111    /// [CR-7] Export a portable snapshot of this group's MLS state.
1112    ///
1113    /// Walks the provider's working set, picks every entry whose key references this
1114    /// group's id, and bundles them with format metadata. Returns CBOR-encoded bytes
1115    /// suitable for inclusion in:
1116    ///   * `LinkingTicket.catchup_snapshot.conversation_metas[i].group_state_bytes`
1117    ///     (via [CR-13] — host calls this and passes the bytes through);
1118    ///   * `IdentityBackup.device_group_snapshot` (the Permissive-recovery path per
1119    ///     `docs/architecture/recovery.md`).
1120    ///
1121    /// Returns `Err` if the encoded snapshot exceeds [`GROUP_SNAPSHOT_HARD_CAP`].
1122    /// Output is wrapped in `Zeroizing` because the bytes contain past epoch secrets;
1123    /// the caller's copy on the FFI side is the host's responsibility to wipe.
1124    pub fn export_state_snapshot(&self, now_ms: u64) -> Result<Zeroizing<Vec<u8>>> {
1125        let entries = self.crypto.group_scoped_entries(&self.id.0);
1126        let snap = GroupStateSnapshot {
1127            v: GROUP_SNAPSHOT_VERSION,
1128            group_id: self.id,
1129            openmls_storage_version: openmls_traits::storage::CURRENT_VERSION,
1130            snapshot_created_at_ms: now_ms,
1131            entries: entries
1132                .into_iter()
1133                .map(|(key, value)| GroupSnapshotEntry { key, value })
1134                .collect(),
1135        };
1136        Ok(Zeroizing::new(snap.encode()?))
1137    }
1138
1139    /// Look up the leaf index this device controls, if known ([CR-2]).
1140    ///
1141    /// Returns the locally-tracked leaf for `device_id`. Only populated for devices we
1142    /// added via [`Self::add_members`] or for our own leaf via [`Self::create`] /
1143    /// [`Self::join`]. Devices a peer admitted on our behalf are not in this map.
1144    pub fn leaf_index_of(&self, device_id: &DeviceId) -> Option<u32> {
1145        self.device_leaves.get(device_id).copied()
1146    }
1147
1148    /// Synchronously capture everything [`ConversationSnapshot::flush`]
1149    /// needs to persist this conversation, so a caller can DROP the
1150    /// `conversations` lock BEFORE awaiting the async writes.
1151    ///
1152    /// Holding a `parking_lot` guard across `.await` is a latent bug: on
1153    /// the single-threaded wasm worker, a second client call that lands
1154    /// while the first is suspended (a waiting writer + a new reader)
1155    /// makes `parking_lot` try to PARK, and its wasm stub `panic!`s with
1156    /// "Parking not supported on this platform" — poisoning the module.
1157    /// Splitting the synchronous capture (under the lock) from the async
1158    /// flush (lock released) removes that hazard everywhere the snapshot
1159    /// runs for a conversation that lives inside the shared map. The
1160    /// capture is a consistent point-in-time view (cursor + meta + leaves
1161    /// + the Arc'd provider/storage handles).
1162    pub(crate) fn snapshot_inputs(&self) -> Result<ConversationSnapshot> {
1163        // [CR-2] Stable BTreeMap-of-pairs encoding → canonical CBOR so
1164        // every platform decodes identical bytes.
1165        let leaves_vec: Vec<(DeviceId, u32)> = self
1166            .device_leaves
1167            .iter()
1168            .map(|(d, i)| (d.clone(), *i))
1169            .collect();
1170        Ok(ConversationSnapshot {
1171            id: self.id,
1172            crypto: self.crypto.clone(),
1173            storage: self.storage.clone(),
1174            cursor: self.cursor.encode()?,
1175            meta: codec::encode(&self.meta)?,
1176            device_leaves: codec::encode(&leaves_vec)?,
1177        })
1178    }
1179
1180    /// Persist this conversation's state. Convenience wrapper used by
1181    /// call sites that hold an OWNED `Conversation` (not borrowed from the
1182    /// shared map) — e.g. just-created/just-joined conversations before
1183    /// they're inserted, where no lock is held across the await. Map-
1184    /// resident callers MUST instead use `snapshot_inputs()` + drop the
1185    /// guard + `flush().await` (see client.rs) to avoid the wasm parking
1186    /// panic described on `snapshot_inputs`.
1187    pub(crate) async fn snapshot_to_storage(&self) -> Result<()> {
1188        self.snapshot_inputs()?.flush().await
1189    }
1190}
1191
1192/// Point-in-time, lock-free snapshot of a [`Conversation`]'s persistable
1193/// state. Produced synchronously by [`Conversation::snapshot_inputs`] (so
1194/// the `conversations` lock can be dropped) and flushed asynchronously by
1195/// [`Self::flush`].
1196pub(crate) struct ConversationSnapshot {
1197    id: ConversationId,
1198    crypto: Arc<PersistentMlsProvider>,
1199    storage: Arc<dyn Storage>,
1200    cursor: Vec<u8>,
1201    meta: Vec<u8>,
1202    device_leaves: Vec<u8>,
1203}
1204
1205impl ConversationSnapshot {
1206    /// Flush the captured state to storage. Safe to `.await` with NO
1207    /// `conversations` lock held — it only touches the Arc'd provider +
1208    /// storage handles, never the shared map.
1209    pub(crate) async fn flush(self) -> Result<()> {
1210        // CRASH-CONSISTENCY ORDERING. The host `Storage` is a non-transactional
1211        // key-value store (iOS SQLCipher row, web IndexedDB slot, memory), so we
1212        // cannot make these four writes atomic without changing the host API on
1213        // every platform. Instead we order them so a crash between any two
1214        // leaves a SELF-HEALING state, never a permanent gap:
1215        //
1216        //   1. MLS working set (`checkpoint_async`) — the authoritative crypto
1217        //      state (epoch, ratchet keys). Written FIRST so the persisted MLS
1218        //      state is always >= what the cursor claims we've processed.
1219        //   2. meta (name / member_count) — cosmetic, re-derivable from group state.
1220        //   3. device→leaf map ([CR-2]) — needed by revoke_device after restart.
1221        //   4. cursor — the "processed up to here" gate, written LAST.
1222        //
1223        // Why cursor LAST is the key invariant: the cursor decides which events
1224        // we re-fetch on restart. If it committed BEFORE the MLS checkpoint, a
1225        // crash in between would leave the cursor ahead of the persisted MLS
1226        // state — we'd skip events the group never actually applied, a permanent
1227        // gap (the "stranded" condition). Writing MLS first and the cursor last
1228        // guarantees the cursor is never ahead of durable state: a crash just
1229        // means we re-fetch a few already-applied events, which `process` dedups
1230        // via `SyncCursor::is_new`. meta/device_leaves lagging the cursor is the
1231        // only residual skew and both are re-derivable from MLS group state.
1232        //
1233        // [CR-4] checkpoint MUST happen on every state-changing op so a cold
1234        // restart (iOS NSE, web SW) finds the latest epoch. `checkpoint_async`
1235        // is required for the WASM `IndexedDb` backend (IDB is async-only);
1236        // native Memory / Sqlite await trivially (their I/O is sync internally).
1237        self.crypto
1238            .checkpoint_async()
1239            .await
1240            .map_err(|e| Error::Storage(format!("checkpoint: {e}")))?;
1241
1242        let hex = self.id.as_hex();
1243        self.storage
1244            .put("groups", &format!("{hex}/meta"), self.meta)
1245            .await?;
1246        self.storage
1247            .put("device_leaves", &hex, self.device_leaves)
1248            .await?;
1249        // Cursor written LAST — see the ordering rationale above.
1250        self.storage.put("cursors", &hex, self.cursor).await?;
1251        Ok(())
1252    }
1253}
1254
1255/// Both halves of an Add commit. The Commit goes on the conversation channel; the Welcome is
1256/// delivered to the new members via whatever out-of-band path the host uses (often the same
1257/// transport, addressed to the new device's mailbox).
1258#[derive(Debug, Clone)]
1259pub struct AddOutcome {
1260    pub commit: MessageEnvelope,
1261    pub welcome: MessageEnvelope,
1262}
1263
1264/// The local-state mutation a staged Commit will apply on
1265/// [`Conversation::confirm_staged`]. Captured at stage time so confirm can run
1266/// after the (async) Commit send without re-deriving anything.
1267pub(crate) enum StagedLeafUpdate {
1268    /// Add: signature_key → device_id for each added device, resolved to a leaf
1269    /// index against the merged tree in `confirm_staged`.
1270    Add(Vec<(Vec<u8>, DeviceId)>),
1271    /// Remove: the leaf indexes being dropped from the device→leaf map.
1272    Remove(std::collections::HashSet<u32>),
1273    /// No membership change (e.g. a GroupContextExtensions / name-update commit).
1274    /// The device→leaf map is untouched.
1275    None,
1276}
1277
1278/// A Commit produced but NOT yet merged (see [`Conversation::stage_add_members`]).
1279/// Held by the client across the Commit send; merged via
1280/// [`Conversation::confirm_staged`] on success or discarded via
1281/// [`Conversation::abort_staged`] on a server rejection. This is the unit of the
1282/// send-then-merge protocol that keeps the local epoch from ever running ahead of
1283/// the server.
1284pub(crate) struct StagedCommit {
1285    pub commit: MessageEnvelope,
1286    pub welcome: Option<MessageEnvelope>,
1287    next_seq: u64,
1288    next_hlc: Hlc,
1289    leaf_update: StagedLeafUpdate,
1290}
1291
1292fn mls_message_out_bytes(m: MlsMessageOut) -> Result<Vec<u8>> {
1293    m.tls_serialize_detached().map_err(Error::mls)
1294}