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