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