ping_core/client.rs
1//! `MessagingClient` — top-level handle. Owns the OpenMLS provider, identity, local device,
2//! and the set of open conversations.
3//!
4//! All operations are `async`. The intent is that the FFI generators emit Swift `async`,
5//! Kotlin `suspend`, and the WASM glue exposes Promises.
6
7use openmls::framing::MlsMessageOut;
8use openmls::prelude::{
9 tls_codec::Serialize as TlsSerialize, BasicCredential, Ciphersuite, CredentialWithKey,
10 KeyPackageBuilder,
11};
12use openmls_basic_credential::SignatureKeyPair;
13use openmls_traits::OpenMlsProvider;
14use parking_lot::RwLock;
15use ping_mls_store::{PersistentMlsProvider, StorageBackend};
16use std::collections::HashMap;
17use std::sync::Arc;
18use zeroize::Zeroizing;
19
20use crate::{
21 codec,
22 conversation::{Conversation, ConversationId, ConversationMeta, MemberInfo},
23 device::{
24 CatchupAppEventEntry, CatchupConversationEntry, CatchupSnapshot, DeviceId, DeviceInfo,
25 LinkingTicket, LocalDevice, CATCHUP_SNAPSHOT_VERSION,
26 },
27 error::{Error, Result},
28 identity::{Identity, UserId},
29 message::{IncomingMessage, MessageEnvelope, MessageKind},
30 storage::Storage,
31 sync::SyncCursor,
32 transport::Transport,
33};
34
35const DEFAULT_CIPHERSUITE: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519;
36
37/// Whether a transport send failure is a DEFINITE server rejection (the server
38/// returned an HTTP error response) rather than an ambiguous network failure
39/// where the server may actually have applied the message.
40///
41/// This decides whether a staged Commit can be safely rolled back: only a
42/// definite rejection guarantees the server did NOT apply it. The host transport
43/// embeds the HTTP status in the error string (e.g. "network: http 409"); 4xx +
44/// known server error codes are definite, while timeouts / "fetch failed" / 5xx
45/// are ambiguous (could be a masked success). When unsure we treat it as
46/// ambiguous (return false) — merging on a masked success is recoverable, but
47/// rolling back a Commit the server DID apply strands us a step behind forever.
48fn is_definite_rejection(err: &Error) -> bool {
49 let Error::Transport(s) = err else {
50 return false;
51 };
52 let s = s.to_ascii_lowercase();
53 s.contains("http 4")
54 || s.contains("epoch_advanced")
55 || s.contains("invalid_request")
56 || s.contains("not_found")
57 || s.contains("conflict")
58 || s.contains("forbidden")
59 || s.contains("unauthorized")
60}
61
62/// Per-chat result reported by [`MessagingClient::admit_device_to_chats`].
63#[derive(Debug, Clone)]
64pub struct AdmitChatOutcome {
65 pub conversation_id: ConversationId,
66 pub status: AdmitChatStatus,
67}
68
69#[derive(Debug, Clone)]
70pub enum AdmitChatStatus {
71 /// The new device is now an MLS leaf in this chat. Both the Commit
72 /// and the addressed Welcome have been sent.
73 Admitted,
74 /// We chose not to admit (e.g. the conversation is a DeviceGroup,
75 /// which was already handled at linking-ticket build time).
76 Skipped { reason: String },
77 /// MLS or transport rejected the admission. `error` is the underlying
78 /// message — typically a `transport error: ...` or an OpenMLS error.
79 Failed { error: String },
80}
81
82#[derive(Debug)]
83pub struct ClientConfig {
84 pub identity: Identity,
85 pub device_label: String,
86 pub storage: Arc<dyn Storage>,
87 pub transport: Arc<dyn Transport>,
88 /// Wall clock in ms. Pulled from the host so we can use a synthetic clock in tests.
89 pub now_ms: u64,
90 /// [CR-4] OpenMLS-provider backend. Defaults to in-memory; iOS NSE and web SW
91 /// cold-start paths MUST pass `StorageBackend::Sqlite { path, encryption_key }`
92 /// (native) or `StorageBackend::IndexedDb { db_name }` (WASM, when that lands).
93 /// See `docs/design/CR4_CR7_PERSISTENCE.md`.
94 pub storage_backend: StorageBackend,
95 /// Optional 32-byte Ed25519 secret key the SDK should use as the
96 /// device signing key. When set AND no `LocalDevice` is yet
97 /// persisted in `storage`, the SDK constructs its first
98 /// `LocalDevice` from this key instead of generating a fresh
99 /// random one — so `device_id = SHA-256(public_key_of(secret))`
100 /// is fully determined by what the host provided.
101 ///
102 /// Use case: align the SDK's `device_id` (which it stamps into
103 /// every envelope's `sender_device` field) with an externally-
104 /// computed device id — typically `SHA-256(device_signing_pubkey)`
105 /// in the host's auth layer, where the JWT carries that same
106 /// value as its `device_id` claim. Without this alignment, a
107 /// server that validates `envelope.sender_device ==
108 /// jwt.device_id` would reject every send.
109 ///
110 /// Ignored on re-init (when storage already has a persisted
111 /// `LocalDevice`) so the device identity remains stable across
112 /// restarts.
113 pub device_signing_secret_key: Option<[u8; 32]>,
114}
115
116impl ClientConfig {
117 /// Construct a config with `StorageBackend::Memory` — convenient for tests and
118 /// the existing v0.1 in-memory flow.
119 pub fn new_in_memory(
120 identity: Identity,
121 device_label: String,
122 storage: Arc<dyn Storage>,
123 transport: Arc<dyn Transport>,
124 now_ms: u64,
125 ) -> Self {
126 Self {
127 identity,
128 device_label,
129 storage,
130 transport,
131 now_ms,
132 storage_backend: StorageBackend::Memory,
133 device_signing_secret_key: None,
134 }
135 }
136}
137
138pub struct MessagingClient {
139 pub(crate) identity: Identity,
140 pub(crate) local_device: LocalDevice,
141 pub(crate) crypto: Arc<PersistentMlsProvider>,
142 pub(crate) signing: Arc<SignatureKeyPair>,
143 pub(crate) storage: Arc<dyn Storage>,
144 pub(crate) transport: Arc<dyn Transport>,
145 conversations: RwLock<HashMap<ConversationId, Conversation>>,
146 /// Conversations detected as STRANDED during catch-up: a full page of
147 /// events was fetched but nothing could be applied (every envelope failed
148 /// to decrypt / was wrong-epoch), meaning a Commit was missed and the group
149 /// can no longer advance from local state. The host polls
150 /// [`MessagingClient::stranded_conversations`] after a sync and recovers
151 /// each (re-Welcome / same-user state snapshot). Cleared automatically once
152 /// the conversation makes progress again.
153 stranded: RwLock<std::collections::HashSet<ConversationId>>,
154}
155
156impl std::fmt::Debug for MessagingClient {
157 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158 f.debug_struct("MessagingClient")
159 .field("user_id", &self.identity.user_id().as_hex())
160 .field("device_id", &self.local_device.device_id.as_hex())
161 .field("conversation_count", &self.conversations.read().len())
162 .finish()
163 }
164}
165
166impl MessagingClient {
167 /// Initialise. Creates a new local device if none is recorded in storage; otherwise rehydrates.
168 pub async fn init(cfg: ClientConfig) -> Result<Arc<Self>> {
169 // [CR-4] OpenMLS provider is now pluggable. For `StorageBackend::Memory` this
170 // behaves like the old `OpenMlsRustCrypto::default()`. For `Sqlite`, the
171 // working set is hydrated from the on-disk blob; subsequent `checkpoint` calls
172 // flush it back. iOS NSE / web SW cold-start lives here.
173 //
174 // Use `open_async` so the WASM `StorageBackend::IndexedDb` variant can read
175 // its snapshot blob through the host-supplied `AsyncBlobStore` before
176 // returning — without this, the provider's `MemoryStorage` would be empty
177 // and `MlsGroup::load` would silently return `None` for every group on
178 // cold restart, breaking chat persistence across reloads. Native targets
179 // (Memory + Sqlite) delegate to the sync path under the hood, so the
180 // `.await` is free there.
181 let crypto = PersistentMlsProvider::open_async(cfg.storage_backend.clone())
182 .await
183 .map_err(|e| Error::Storage(format!("provider open: {e}")))?;
184 let local_device = match cfg.storage.get("device", "local").await? {
185 Some(bytes) => decode_local_device(&bytes, cfg.identity.user_id().clone())?,
186 None => {
187 // First-init path. If the host supplied a signing secret
188 // (typically to align the device_id with their auth
189 // layer), use it; otherwise mint a fresh random key.
190 // Either way, the constructed `LocalDevice` is
191 // immediately persisted so future inits load from
192 // storage without consulting the override again.
193 let dev = match cfg.device_signing_secret_key.as_ref() {
194 Some(secret) => LocalDevice::from_signing_secret(
195 cfg.identity.user_id().clone(),
196 cfg.device_label,
197 cfg.now_ms,
198 secret,
199 ),
200 None => LocalDevice::generate(
201 cfg.identity.user_id().clone(),
202 cfg.device_label,
203 cfg.now_ms,
204 ),
205 };
206 let bytes = encode_local_device(&dev)?;
207 cfg.storage.put("device", "local", bytes).await?;
208 dev
209 }
210 };
211
212 // [CR-4] MLS signing keypair MUST be stable across cold restarts — otherwise the
213 // leaf-key stored on disk no longer matches the per-client key on re-init, and any
214 // send-after-restart silently misroutes. We derive deterministically from the
215 // already-persistent `LocalDevice::signing` (Ed25519, 32 raw bytes), and the
216 // ciphersuite's signature scheme is Ed25519 too — so the device signing key and the
217 // MLS leaf signing key are the same bytes. The MLS storage provider also receives
218 // a copy via `store()` so OpenMLS-internal lookups (process_message, etc.) succeed.
219 let signing = {
220 let sk_bytes = local_device.signing.to_bytes().to_vec();
221 let pk_bytes = local_device.signing.verifying_key().to_bytes().to_vec();
222 let kp = SignatureKeyPair::from_raw(
223 DEFAULT_CIPHERSUITE.signature_algorithm(),
224 sk_bytes,
225 pk_bytes,
226 );
227 kp.store(crypto.storage()).map_err(Error::mls)?;
228 Arc::new(kp)
229 };
230
231 let client = Arc::new(Self {
232 identity: cfg.identity,
233 local_device,
234 crypto,
235 signing,
236 storage: cfg.storage,
237 transport: cfg.transport,
238 conversations: RwLock::new(HashMap::new()),
239 stranded: RwLock::new(std::collections::HashSet::new()),
240 });
241
242 client.rehydrate_conversations(cfg.now_ms).await?;
243
244 // [CR-10] Ensure the DeviceGroup exists at init, not lazily inside
245 // build_linking_ticket. Single-device users need somewhere to write
246 // personal events (drafts, read pointers, notes, vault wrapper)
247 // even before they pair a second device. Lazy creation in
248 // build_linking_ticket left them with no DG → no place for
249 // personal state to land.
250 //
251 // Idempotent — re-init after a cold restart finds the DG via
252 // rehydrate_conversations and this becomes a no-op.
253 client.ensure_device_group(cfg.now_ms).await?;
254
255 Ok(client)
256 }
257
258 /// [CR-10] Idempotently ensures this user's DeviceGroup exists in
259 /// `self.conversations`. Called from `init` (so single-device users
260 /// have a DG immediately) and from `build_linking_ticket` (the legacy
261 /// lazy path; still safe to call when the DG already exists, since
262 /// rehydrate_conversations would have re-attached it before init
263 /// returned).
264 ///
265 /// The DeviceGroup is a one-leaf MLS group at creation time —
266 /// `add_members` (called by `build_linking_ticket` when a second
267 /// device pairs in) is what grows it. We persist the snapshot so a
268 /// cold restart picks it up before this function runs again.
269 pub(crate) async fn ensure_device_group(self: &Arc<Self>, now_ms: u64) -> Result<()> {
270 let dg_id = device_group_id_for(self.identity.user_id());
271 if self.conversations.read().contains_key(&dg_id) {
272 return Ok(());
273 }
274 let mut new_dg = Conversation::create(
275 dg_id,
276 Some("device-group".into()),
277 self.local_device.device_id.clone(),
278 self.identity.user_id(),
279 self.crypto.clone(),
280 self.signing.clone(),
281 self.storage.clone(),
282 now_ms,
283 )?;
284 new_dg.meta.is_device_group = true;
285 new_dg.snapshot_to_storage().await?;
286 self.conversations.write().insert(dg_id, new_dg);
287 Ok(())
288 }
289
290 pub fn user_id(&self) -> UserId {
291 self.identity.user_id().clone()
292 }
293 /// Export this client's account identity (the Ed25519 seed, CBOR-wrapped —
294 /// same format `Identity::import` / `MessagingClient::init(identity_export)`
295 /// accept). SECRET. Hosts use this to TRANSFER the account identity to a
296 /// newly-linked device over the sealed linking channel, so every linked
297 /// device shares ONE `user_id` and `IncomingMessage.sender_user_id` equals
298 /// the local `user_id()` for any of the account's own devices — the basis
299 /// for cross-device self-attribution. Never log or persist in cleartext.
300 pub fn export_identity(&self) -> Zeroizing<Vec<u8>> {
301 self.identity.export()
302 }
303 pub fn device_id(&self) -> DeviceId {
304 self.local_device.device_id.clone()
305 }
306 pub fn device_info(&self, now_ms: u64) -> DeviceInfo {
307 self.local_device.info(now_ms)
308 }
309
310 /// Generate a fresh KeyPackage to publish to the directory. Hosts call this when registering
311 /// a device or topping up the directory.
312 ///
313 /// `build()` writes the private init + encryption keys into the storage
314 /// provider's working set, but ON ITS OWN that write is NOT durable: on the
315 /// WASM/AsyncBlob backend the working set only reaches IndexedDB at the next
316 /// `checkpoint_async`, so a page reload before the next state-changing op
317 /// loses the private keys while the PUBLIC KeyPackage has already been
318 /// published. Any Welcome later bound to that KeyPackage then fails with
319 /// "No matching key package was found in the key store" (breaking calls and
320 /// every invite to this device). So we checkpoint HERE, before returning the
321 /// bytes the host will publish — the published KeyPackage is durable the
322 /// instant it leaves this function. Hence `async`.
323 pub async fn fresh_key_package(&self) -> Result<Vec<u8>> {
324 self.build_key_package(false).await
325 }
326
327 /// Generate a fresh LAST-RESORT KeyPackage.
328 ///
329 /// A normal KeyPackage is single-use: once a Welcome consumes it, the
330 /// private init key is deleted and the directory entry is burned. When a
331 /// device's published pool runs dry, every invite to that device hard-fails
332 /// ("user unavailable") until it comes online and tops up — the classic
333 /// "I added them but they never got it" complaint.
334 ///
335 /// A last-resort KeyPackage (RFC 9420 §10) carries the `LastResort`
336 /// extension, signalling the server it may serve this KeyPackage MORE THAN
337 /// ONCE when no single-use KeyPackages remain. The host publishes exactly
338 /// one per device; the server keeps it as the always-available fallback so
339 /// an invite never fails purely because the pool emptied. Forward secrecy
340 /// for the joining epoch is slightly weaker (the init key is reused until
341 /// replenishment), which is the accepted RFC trade-off for availability.
342 pub async fn fresh_last_resort_key_package(&self) -> Result<Vec<u8>> {
343 self.build_key_package(true).await
344 }
345
346 async fn build_key_package(&self, last_resort: bool) -> Result<Vec<u8>> {
347 let credential_with_key = CredentialWithKey {
348 credential: BasicCredential::new(self.identity.user_id().0.clone()).into(),
349 signature_key: self.signing.public().to_vec().into(),
350 };
351 let mut builder = KeyPackageBuilder::new()
352 // Advertise the group-name extension capability so a later
353 // `set_name` (rename / avatar change via GroupContextExtensions)
354 // passes openmls' per-member capability check on every group this
355 // device joins. For a last-resort KeyPackage the leaf must also
356 // advertise the LastResort extension it carries, or openmls
357 // validation rejects the KeyPackage at add-member time. See
358 // `conversation::ping_leaf_capabilities_for`.
359 .leaf_node_capabilities(crate::conversation::ping_leaf_capabilities_for(last_resort));
360 if last_resort {
361 builder = builder.mark_as_last_resort();
362 }
363 let bundle = builder
364 .build(
365 DEFAULT_CIPHERSUITE,
366 self.crypto.as_ref(),
367 self.signing.as_ref(),
368 credential_with_key,
369 )
370 .map_err(Error::mls)?;
371 // Durably persist the freshly-generated private keys BEFORE the public
372 // KeyPackage is handed to the host to publish (see doc comment).
373 self.crypto
374 .checkpoint_async()
375 .await
376 .map_err(|e| Error::Storage(format!("key package checkpoint: {e}")))?;
377 // KeyPackages are serialized as MlsMessage(KeyPackage) per the MLS framing spec.
378 let msg: MlsMessageOut = bundle.key_package().clone().into();
379 msg.tls_serialize_detached().map_err(Error::mls)
380 }
381
382 /// Create a new conversation owned by this client (and seeded with a single member: this device).
383 pub async fn create_conversation(
384 self: &Arc<Self>,
385 name: Option<String>,
386 now_ms: u64,
387 ) -> Result<ConversationId> {
388 let id = ConversationId::new();
389 let convo = Conversation::create(
390 id,
391 name,
392 self.local_device.device_id.clone(),
393 self.identity.user_id(),
394 self.crypto.clone(),
395 self.signing.clone(),
396 self.storage.clone(),
397 now_ms,
398 )?;
399 convo.snapshot_to_storage().await?;
400 self.conversations.write().insert(id, convo);
401 Ok(id)
402 }
403
404 /// Join via a Welcome bundled in a [`MessageEnvelope`] of kind `Welcome`.
405 pub async fn join_conversation(
406 self: &Arc<Self>,
407 welcome_envelope: &MessageEnvelope,
408 now_ms: u64,
409 ) -> Result<ConversationId> {
410 if welcome_envelope.kind != MessageKind::Welcome {
411 return Err(Error::Invalid("expected Welcome envelope".into()));
412 }
413 let convo = Conversation::join(
414 &welcome_envelope.payload,
415 self.local_device.device_id.clone(),
416 self.crypto.clone(),
417 self.signing.clone(),
418 self.storage.clone(),
419 now_ms,
420 )?;
421 let id = convo.id();
422 convo.snapshot_to_storage().await?;
423 self.conversations.write().insert(id, convo);
424 // Joining (re-Welcome) recovers a previously-stranded conversation.
425 self.stranded.write().remove(&id);
426 Ok(id)
427 }
428
429 /// Conversations detected as STRANDED during catch-up — a Commit was missed
430 /// and the group can no longer advance from local state. The host should
431 /// recover each (re-Welcome from a peer, or a same-user state-snapshot
432 /// import) so messages start delivering again. The set self-clears as a
433 /// conversation makes progress or is re-joined.
434 pub fn stranded_conversations(&self) -> Vec<ConversationId> {
435 let mut ids: Vec<ConversationId> = self.stranded.read().iter().copied().collect();
436 ids.sort_by_key(|a| a.0);
437 ids
438 }
439
440 pub fn list_conversations(&self) -> Vec<ConversationMeta> {
441 self.conversations
442 .read()
443 .values()
444 .map(|c| c.meta.clone())
445 .collect()
446 }
447
448 /// Member roster for a conversation, recovered locally from the MLS
449 /// group's leaf credentials. Empty if the conversation is unknown to
450 /// this client. Lets any device (including one that just joined via a
451 /// linking Welcome) resolve a 1:1 peer's `UserId` without the
452 /// out-of-band `ping.profile` re-send.
453 pub fn members(&self, conv_id: ConversationId) -> Vec<MemberInfo> {
454 self.conversations
455 .read()
456 .get(&conv_id)
457 .map(|c| c.members())
458 .unwrap_or_default()
459 }
460
461 /// Send an application message. Returns once the envelope has been handed to the transport.
462 pub async fn send(
463 &self,
464 conv_id: ConversationId,
465 plaintext: Vec<u8>,
466 now_ms: u64,
467 ) -> Result<MessageEnvelope> {
468 // FAST-FAIL on a stranded conversation. A missed Commit forked our epoch,
469 // so anything we encrypt now is at a stale epoch: the server either 409s
470 // it (epoch occupied) or accepts a frame the peers can never decrypt — a
471 // durable-but-undelivered message. Surface `EpochStranded` immediately so
472 // the host renders "needs repair" (and recovers via
473 // `stranded_conversations()` → re-Welcome / snapshot import, which clears
474 // the mark) instead of silently 409-looping every send. Without this the
475 // SDK knew the conversation was forked but sent anyway.
476 if self.stranded.read().contains(&conv_id) {
477 return Err(Error::EpochStranded(conv_id.as_hex()));
478 }
479 let envelope = {
480 let mut guard = self.conversations.write();
481 let convo = guard
482 .get_mut(&conv_id)
483 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
484 convo.send_application(&plaintext, now_ms)?
485 };
486 self.transport.send(envelope.clone()).await?;
487 // The OpenMLS sender ratchet advances on every Application message — `seq` + `hlc`
488 // are bumped on the conversation, and the underlying group keystore stores new
489 // generation keys. Without a checkpoint here, a reload rolls back to the pre-send
490 // state and the next send re-uses an already-consumed generation that receivers
491 // silently drop. Mirrors the snapshot calls after every Commit/Welcome op.
492 //
493 // Capture the snapshot inputs UNDER the read guard, then DROP the
494 // guard (end of the `let` statement) before the async flush — never
495 // hold a `parking_lot` guard across `.await` (see
496 // `Conversation::snapshot_inputs`).
497 let snap = self
498 .conversations
499 .read()
500 .get(&conv_id)
501 .map(|c| c.snapshot_inputs())
502 .transpose()?;
503 if let Some(snap) = snap {
504 snap.flush().await?;
505 }
506 Ok(envelope)
507 }
508
509 /// Add members. The Commit goes on the wire; the Welcome should be delivered to the new
510 /// devices' inboxes (the host transport implements that — typically as a separate addressed
511 /// envelope).
512 ///
513 /// [CR-2] Each entry is `(DeviceId, KeyPackage_bytes)`. The host typically gets the
514 /// device_id from the directory at the same time it gets the KeyPackage; we use it to
515 /// record a per-conversation `device_id → leaf_index` map so [`Self::revoke_device`]
516 /// can later locate the leaf without a fresh directory lookup. The SDK does not
517 /// cryptographically verify the host's device-id claim — that's a directory policy
518 /// concern.
519 //
520 // The `conversations` lock is taken only for the SYNCHRONOUS MLS work
521 // (the add commit) and the synchronous snapshot capture, then dropped
522 // BEFORE every `.await`. We must never hold a `parking_lot` guard
523 // across an await — see `Conversation::snapshot_inputs` for why (the
524 // single-threaded wasm worker would panic in `parking_lot`'s parker
525 // stub). `parking_lot/send_guard` is still set so any guard that DOES
526 // briefly cross a yield-free boundary stays `Send`.
527 pub async fn add_members(
528 &self,
529 conv_id: ConversationId,
530 entries: Vec<(DeviceId, Vec<u8>)>,
531 now_ms: u64,
532 ) -> Result<()> {
533 // Phase 1 — stage the Commit WITHOUT merging (local epoch unchanged).
534 let staged = {
535 let mut guard = self.conversations.write();
536 let convo = guard
537 .get_mut(&conv_id)
538 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
539 convo.stage_add_members(entries, now_ms)?
540 };
541
542 // Phase 2 — send the Commit FIRST, then merge only if the server accepts
543 // it (send-then-merge). A Commit the server REJECTS is rolled back, so the
544 // local epoch can never run ahead of the server — the desync that
545 // permanently bricks a group (every later Commit 409s; peers can't decrypt
546 // our epoch). A network failure with NO response is ambiguous (the server
547 // may have applied it), so there we merge to match a possible masked
548 // success rather than strand ourselves a step behind.
549 if let Err(send_err) = self.transport.send(staged.commit.clone()).await {
550 let merged = {
551 let mut guard = self.conversations.write();
552 match guard.get_mut(&conv_id) {
553 Some(convo) if is_definite_rejection(&send_err) => {
554 let _ = convo.abort_staged();
555 false
556 }
557 Some(convo) => {
558 convo.confirm_staged(&staged, now_ms)?;
559 true
560 }
561 None => false,
562 }
563 };
564 if merged {
565 self.flush_conversation(&conv_id).await?;
566 }
567 return Err(send_err);
568 }
569
570 // Phase 3 — Commit accepted: merge locally + persist (so the advanced
571 // epoch survives a crash even if the Welcome below fails).
572 {
573 let mut guard = self.conversations.write();
574 let convo = guard
575 .get_mut(&conv_id)
576 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
577 convo.confirm_staged(&staged, now_ms)?;
578 }
579 self.flush_conversation(&conv_id).await?;
580
581 // Phase 4 — deliver the Welcome to the new members. Best-effort: they are
582 // in the group server-side now; a failed Welcome is recoverable
583 // (re-invite) and must NOT roll back the merged Commit.
584 if let Some(welcome) = staged.welcome {
585 self.transport.send(welcome).await?;
586 }
587 Ok(())
588 }
589
590 /// Change a conversation's `name` (carried in the GroupContext) and broadcast
591 /// the change to every member as an MLS GroupContextExtensions Commit. Unlike
592 /// a hydration broadcast, the new name rides MLS group STATE, so every member
593 /// — and every future joiner via the GroupInfo — converges on it. Hosts use
594 /// this to make a rename or an embedded avatar-media-id change bulletproof
595 /// (the `name` carries the `ping:meta:v1:` blob).
596 ///
597 /// No Welcome (membership is unchanged). Uses the same send-then-merge
598 /// rollback discipline as [`Self::add_members`] so a server-rejected Commit
599 /// never desyncs the local epoch. All members must have re-linked since the
600 /// group-name capability shipped (see `conversation::ping_leaf_capabilities`),
601 /// else openmls rejects the Commit.
602 pub async fn set_conversation_name(
603 &self,
604 conv_id: ConversationId,
605 name: Option<String>,
606 now_ms: u64,
607 ) -> Result<()> {
608 // Phase 1 — stage the Commit WITHOUT merging (local epoch unchanged).
609 let staged = {
610 let mut guard = self.conversations.write();
611 let convo = guard
612 .get_mut(&conv_id)
613 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
614 convo.stage_set_name(name, now_ms)?
615 };
616
617 // Phase 2 — send-then-merge (see `add_members` for the rollback rationale).
618 if let Err(send_err) = self.transport.send(staged.commit.clone()).await {
619 let merged = {
620 let mut guard = self.conversations.write();
621 match guard.get_mut(&conv_id) {
622 Some(convo) if is_definite_rejection(&send_err) => {
623 let _ = convo.abort_staged();
624 false
625 }
626 Some(convo) => {
627 convo.confirm_staged(&staged, now_ms)?;
628 true
629 }
630 None => false,
631 }
632 };
633 if merged {
634 self.flush_conversation(&conv_id).await?;
635 }
636 return Err(send_err);
637 }
638
639 // Phase 3 — Commit accepted: merge locally + persist.
640 {
641 let mut guard = self.conversations.write();
642 let convo = guard
643 .get_mut(&conv_id)
644 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
645 convo.confirm_staged(&staged, now_ms)?;
646 }
647 self.flush_conversation(&conv_id).await?;
648 Ok(())
649 }
650
651 /// Snapshot + flush a conversation's persistable state. Captures the snapshot
652 /// synchronously under the read guard, drops the guard, then awaits the flush
653 /// (never hold a `parking_lot` guard across an await — wasm parker panics).
654 async fn flush_conversation(&self, conv_id: &ConversationId) -> Result<()> {
655 let snap = self
656 .conversations
657 .read()
658 .get(conv_id)
659 .map(|c| c.snapshot_inputs())
660 .transpose()?;
661 if let Some(snap) = snap {
662 snap.flush().await?;
663 }
664 Ok(())
665 }
666
667 /// Admits `new_device_id` to every conversation in `kps_per_chat` via
668 /// the standard MLS `add_members` flow — one Commit + one Welcome per
669 /// chat. This is the SDK-side replacement for the host's previous
670 /// per-chat reconciler loop after device linking; centralising it
671 /// here means iOS/Android/web hosts all share the orchestration and
672 /// the transport's Welcome-recipient priming is automatic.
673 ///
674 /// Inputs:
675 /// - `new_device_id`: the device being admitted (matches the
676 /// `device_binding_sig` recipient in the linking ticket).
677 /// - `kps_per_chat`: one freshly-claimed KeyPackage per chat. The
678 /// host claims these via the auth-layer's per-account KP pool
679 /// (`GET /v1/devices/{accountId}`) AFTER the new device's
680 /// bootstrap has uploaded its KP batch.
681 /// - `now_ms`: wall-clock used to stamp HLCs on the emitted
682 /// envelopes.
683 ///
684 /// Per-chat failures (unknown conversation, MLS error, transport
685 /// error, etc.) are CAPTURED in the returned vec rather than
686 /// short-circuiting the whole call — losing one chat shouldn't
687 /// strand the new device on every other chat. The caller decides
688 /// whether to retry the failed entries (e.g. with a fresh KP).
689 pub async fn admit_device_to_chats(
690 &self,
691 new_device_id: DeviceId,
692 kps_per_chat: Vec<(ConversationId, Vec<u8>)>,
693 now_ms: u64,
694 ) -> Result<Vec<AdmitChatOutcome>> {
695 let mut outcomes = Vec::with_capacity(kps_per_chat.len());
696 for (conv_id, kp_bytes) in kps_per_chat {
697 // Belt-and-braces: skip the DeviceGroup. The DG was already
698 // welcomed via the linking ticket — re-adding the new
699 // device there would produce a duplicate-add Commit that
700 // BE de-dups, but the noise is avoidable.
701 let is_dg = self
702 .conversations
703 .read()
704 .get(&conv_id)
705 .map(|c| c.meta().is_device_group)
706 .unwrap_or(false);
707 if is_dg {
708 outcomes.push(AdmitChatOutcome {
709 conversation_id: conv_id,
710 status: AdmitChatStatus::Skipped {
711 reason: "device_group".to_string(),
712 },
713 });
714 continue;
715 }
716
717 // Prime the host transport with the welcome recipient BEFORE
718 // we mutate MLS state. If priming fails (non-web hosts use
719 // the default no-op), continue — the host's transport will
720 // either route some other way or surface a 4xx on the
721 // welcome send and we'll catch it below.
722 let _ = self
723 .transport
724 .set_next_welcome_recipients(conv_id, vec![new_device_id.clone()])
725 .await;
726
727 let entry = (new_device_id.clone(), kp_bytes);
728 let outcome_result = {
729 let mut guard = self.conversations.write();
730 match guard.get_mut(&conv_id) {
731 Some(convo) => convo.add_members(vec![entry], now_ms),
732 None => Err(Error::UnknownConversation(conv_id.as_hex())),
733 }
734 };
735
736 let outcome = match outcome_result {
737 Ok(o) => o,
738 Err(e) => {
739 outcomes.push(AdmitChatOutcome {
740 conversation_id: conv_id,
741 status: AdmitChatStatus::Failed {
742 error: e.to_string(),
743 },
744 });
745 continue;
746 }
747 };
748
749 if let Err(e) = self.transport.send(outcome.commit).await {
750 outcomes.push(AdmitChatOutcome {
751 conversation_id: conv_id,
752 status: AdmitChatStatus::Failed {
753 error: format!("commit send: {e}"),
754 },
755 });
756 continue;
757 }
758 if let Err(e) = self.transport.send(outcome.welcome).await {
759 outcomes.push(AdmitChatOutcome {
760 conversation_id: conv_id,
761 status: AdmitChatStatus::Failed {
762 error: format!("welcome send: {e}"),
763 },
764 });
765 continue;
766 }
767
768 // Capture the snapshot under the read guard, drop it, then
769 // flush async (never hold the lock across `.await`).
770 let snap_result = self
771 .conversations
772 .read()
773 .get(&conv_id)
774 .map(|c| c.snapshot_inputs())
775 .transpose();
776 let flush_result = match snap_result {
777 Ok(Some(snap)) => snap.flush().await,
778 Ok(None) => Ok(()),
779 Err(e) => Err(e),
780 };
781 if let Err(e) = flush_result {
782 // Snapshot failure is non-fatal for the join — the MLS adds
783 // already shipped — but record it so the host can decide
784 // whether to retry. The next successful send/process will
785 // re-snapshot anyway.
786 outcomes.push(AdmitChatOutcome {
787 conversation_id: conv_id,
788 status: AdmitChatStatus::Failed {
789 error: format!("snapshot: {e}"),
790 },
791 });
792 continue;
793 }
794
795 outcomes.push(AdmitChatOutcome {
796 conversation_id: conv_id,
797 status: AdmitChatStatus::Admitted,
798 });
799 }
800 Ok(outcomes)
801 }
802
803 pub async fn remove_members(
804 &self,
805 conv_id: ConversationId,
806 leaf_indexes: Vec<u32>,
807 now_ms: u64,
808 ) -> Result<()> {
809 // Send-then-merge — see `add_members` for the full rationale.
810 let staged = {
811 let mut guard = self.conversations.write();
812 let convo = guard
813 .get_mut(&conv_id)
814 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
815 convo.stage_remove_members(leaf_indexes, now_ms)?
816 };
817
818 if let Err(send_err) = self.transport.send(staged.commit.clone()).await {
819 let merged = {
820 let mut guard = self.conversations.write();
821 match guard.get_mut(&conv_id) {
822 Some(convo) if is_definite_rejection(&send_err) => {
823 let _ = convo.abort_staged();
824 false
825 }
826 Some(convo) => {
827 convo.confirm_staged(&staged, now_ms)?;
828 true
829 }
830 None => false,
831 }
832 };
833 if merged {
834 self.flush_conversation(&conv_id).await?;
835 }
836 return Err(send_err);
837 }
838
839 {
840 let mut guard = self.conversations.write();
841 let convo = guard
842 .get_mut(&conv_id)
843 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
844 convo.confirm_staged(&staged, now_ms)?;
845 }
846 self.flush_conversation(&conv_id).await?;
847 Ok(())
848 }
849
850 /// Re-admit a device, first evicting any existing leaf that duplicates the
851 /// new KeyPackage's signature key (the phrase-restore case — see
852 /// [`Conversation::duplicate_signature_key_leaves`] and
853 /// `docs/specs/re-admit-device.md`). Equivalent to [`Self::add_members`] when
854 /// there is no duplicate, so it is a strict superset — safe to prefer on the
855 /// recovery re-admission path.
856 ///
857 /// It composes the two conformance-tested membership primitives —
858 /// `remove_members` (evict the dead duplicate leaf, freeing its signing key)
859 /// then `add_members` (admit the fresh device + ship its Welcome) — each with
860 /// its own send-then-merge rollback, so a server-rejected Commit never leaves
861 /// the local epoch ahead of the server. Two Commits on the rare recovery path;
862 /// folding them into a single combined Remove+Add commit is a possible future
863 /// optimization (kept out of scope to reuse already-vetted primitives). If the
864 /// remove succeeds but the add fails, the device is simply un-admitted (no
865 /// worse than before) and the caller retries.
866 pub async fn re_admit_device(
867 &self,
868 conv_id: ConversationId,
869 entry: (DeviceId, Vec<u8>),
870 now_ms: u64,
871 ) -> Result<()> {
872 let dup_leaves = {
873 let guard = self.conversations.read();
874 let convo = guard
875 .get(&conv_id)
876 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
877 convo.duplicate_signature_key_leaves(&entry.1)?
878 };
879 if !dup_leaves.is_empty() {
880 self.remove_members(conv_id, dup_leaves, now_ms).await?;
881 }
882 self.add_members(conv_id, vec![entry], now_ms).await?;
883 Ok(())
884 }
885
886 /// Leave a conversation. Broadcasts a self-Remove PROPOSAL (MLS doesn't
887 /// allow committing your own removal — a remaining member commits it via
888 /// [`Self::commit_pending_proposals`]). After this returns, the host should
889 /// delete the conversation locally; the leaver remains a cryptographic
890 /// member only until a peer commits the proposal, at which point the server
891 /// stops delivering to this device.
892 pub async fn leave_conversation(&self, conv_id: ConversationId, now_ms: u64) -> Result<()> {
893 let proposal = {
894 let mut guard = self.conversations.write();
895 let convo = guard
896 .get_mut(&conv_id)
897 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
898 convo.leave_group(now_ms)?
899 };
900 // A proposal doesn't change the epoch, so there's nothing to roll back
901 // on a send failure — surface the error and let the host retry.
902 self.transport.send(proposal).await?;
903 self.flush_conversation(&conv_id).await?;
904 Ok(())
905 }
906
907 /// Drop a conversation's ENTIRE local state with **no** network side effect.
908 ///
909 /// Unlike [`Self::leave_conversation`] (which broadcasts a self-Remove
910 /// proposal so a remaining member evicts you), this is a purely LOCAL
911 /// teardown for a group the server does not back — e.g. an invite that minted
912 /// the MLS group locally but never completed server-side, so the backend
913 /// 404s `fetchSince` / 403s the member roster for it. The host detects that
914 /// authoritative "not a member" verdict and calls this so the dead group
915 /// stops rehydrating on every restart (and re-materialising as a ghost
916 /// conversation). No envelope is sent — there is no live group to send to.
917 ///
918 /// Deletes the OpenMLS group state AND the host-side snapshot rows
919 /// (`groups/{id}/…`, `cursors/{id}`, `device_leaves/{id}`) that
920 /// [`Self::rehydrate_conversations`] would otherwise reload, then drops the
921 /// in-memory handle + `stranded` marker. Idempotent: an unknown id still
922 /// best-effort purges any orphan storage rows, and calling it twice is safe.
923 pub async fn drop_conversation_local(&self, conv_id: ConversationId) -> Result<()> {
924 // Take the handle OUT of the map first, then delete its OpenMLS state via
925 // the owned value — mirrors the self-removal teardown in
926 // `process_envelope` and keeps no lock across the awaits below.
927 let existing = self.conversations.write().remove(&conv_id);
928 if let Some(mut convo) = existing {
929 if let Err(e) = convo.delete_group_state() {
930 // Best-effort: dropping the in-memory handle + purging the
931 // snapshot rows below already makes the group non-rehydratable.
932 tracing::warn!(error = %e, "drop_conversation_local: delete group state failed");
933 }
934 }
935 self.stranded.write().remove(&conv_id);
936
937 // Purge the host-side snapshot rows so a restart's
938 // `rehydrate_conversations` (which walks `groups/{id}/meta`) can't bring
939 // the group back. Best-effort — deleting an absent key is a no-op on
940 // every backend. Sweep the whole `groups/{id}/` prefix so any future
941 // sub-key is covered, then the known `cursors` + `device_leaves` rows.
942 let hex = conv_id.as_hex();
943 if let Ok(keys) = self.storage.list_keys("groups", &format!("{hex}/")).await {
944 for k in keys {
945 let _ = self.storage.delete("groups", &k).await;
946 }
947 }
948 let _ = self.storage.delete("cursors", &hex).await;
949 let _ = self.storage.delete("device_leaves", &hex).await;
950 Ok(())
951 }
952
953 /// Conversations with buffered pending proposals (e.g. a peer's leave
954 /// proposal awaiting a Commit). The host polls this after a sync and, if it
955 /// is the designated committer, calls [`Self::commit_pending_proposals`] to
956 /// evict the leaver. Sorted for determinism.
957 pub fn conversations_with_pending_proposals(&self) -> Vec<ConversationId> {
958 let guard = self.conversations.read();
959 let mut ids: Vec<ConversationId> = guard
960 .iter()
961 .filter(|(_, c)| c.has_pending_proposals())
962 .map(|(id, _)| *id)
963 .collect();
964 ids.sort_by_key(|a| a.0);
965 ids
966 }
967
968 /// Commit all buffered pending proposals for a conversation (evicts a peer
969 /// who left). No-op (Ok) when nothing is pending. Send-then-merge with
970 /// rollback like add/remove so a server-rejected Commit doesn't desync the
971 /// epoch — on an `epoch_advanced` rejection the host should re-sync (another
972 /// member already committed) and the pending proposal will have cleared.
973 pub async fn commit_pending_proposals(
974 &self,
975 conv_id: ConversationId,
976 now_ms: u64,
977 ) -> Result<()> {
978 let staged = {
979 let mut guard = self.conversations.write();
980 let convo = guard
981 .get_mut(&conv_id)
982 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
983 match convo.stage_commit_pending_proposals(now_ms)? {
984 Some(s) => s,
985 None => return Ok(()),
986 }
987 };
988
989 if let Err(send_err) = self.transport.send(staged.commit.clone()).await {
990 let merged = {
991 let mut guard = self.conversations.write();
992 match guard.get_mut(&conv_id) {
993 Some(convo) if is_definite_rejection(&send_err) => {
994 let _ = convo.abort_staged();
995 false
996 }
997 Some(convo) => {
998 convo.confirm_staged(&staged, now_ms)?;
999 true
1000 }
1001 None => false,
1002 }
1003 };
1004 if merged {
1005 self.flush_conversation(&conv_id).await?;
1006 }
1007 return Err(send_err);
1008 }
1009
1010 {
1011 let mut guard = self.conversations.write();
1012 let convo = guard
1013 .get_mut(&conv_id)
1014 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
1015 convo.confirm_staged(&staged, now_ms)?;
1016 }
1017 self.flush_conversation(&conv_id).await?;
1018 Ok(())
1019 }
1020
1021 /// Process an inbound envelope coming from the transport's subscribe callback or a sync pull.
1022 /// Returns `Some` for application traffic, `None` for handshake messages (already merged).
1023 ///
1024 /// LIVE path: applies the envelope to the in-memory MLS working set and then
1025 /// durably flushes THIS envelope before returning (per-envelope crash-safety
1026 /// for streaming). The catch-up drain (`sync_conversations`) instead applies a
1027 /// whole page in-memory and flushes ONCE per page — see `apply_envelope_in_memory`.
1028 pub async fn process_envelope(
1029 &self,
1030 env: &MessageEnvelope,
1031 now_ms: u64,
1032 ) -> Result<Option<IncomingMessage>> {
1033 let (out, removed) = self.apply_envelope_in_memory(env, now_ms)?;
1034 // A self-removal already deleted the group's storage; nothing to flush.
1035 if !removed {
1036 self.flush_conversation(&env.conversation_id).await?;
1037 }
1038 Ok(out)
1039 }
1040
1041 /// Apply an inbound envelope to the IN-MEMORY MLS working set and advance the
1042 /// in-memory cursor, WITHOUT the durable checkpoint flush. Returns the
1043 /// decrypted application message (if any) and whether the conversation was
1044 /// REMOVED (a Commit that removed our own leaf tears the group down and
1045 /// deletes its storage synchronously — a removed conversation needs no flush).
1046 ///
1047 /// The write guard is taken and dropped entirely within this synchronous
1048 /// helper — NO `.await` happens while it is held. That is the wasm
1049 /// parking-panic constraint: previously the write guard was held across
1050 /// `snapshot_to_storage().await`, and on the single-threaded wasm worker a
1051 /// concurrent reader that landed while a writer was waiting made `parking_lot`
1052 /// park → panic "Parking not supported". Callers `.await` the flush AFTER this
1053 /// returns (`process_envelope` per call; `sync_conversations` once per page).
1054 ///
1055 /// Batching the flush is the drain-wedge fix: `flush` writes a FULL-state
1056 /// checkpoint (the whole MLS store as one blob), so flushing per envelope made
1057 /// a backlog drain O(N × total_state) of synchronous serialization on the
1058 /// host's single serial queue — the stall the client saw as "messages
1059 /// delivered late". Crash-safety is unchanged: `flush` persists MLS state
1060 /// before the cursor (see `ConversationSnapshot::flush`), so a crash mid-page
1061 /// re-fetches the page and `SyncCursor::is_new` dedups the already-applied
1062 /// events.
1063 fn apply_envelope_in_memory(
1064 &self,
1065 env: &MessageEnvelope,
1066 now_ms: u64,
1067 ) -> Result<(Option<IncomingMessage>, bool)> {
1068 // Welcome envelopes for unknown conversations are routed to
1069 // `join_conversation` by the caller. Here we only handle traffic for
1070 // already-open groups.
1071 let mut guard = self.conversations.write();
1072 let convo = match guard.get_mut(&env.conversation_id) {
1073 Some(c) => c,
1074 None => return Err(Error::UnknownConversation(env.conversation_id.as_hex())),
1075 };
1076 let out = convo.process(env, now_ms)?;
1077 // SELF-REMOVAL: if this Commit removed our own leaf the group is now
1078 // Inactive. Tear it down — delete the OpenMLS state + drop the handle
1079 // — so the conversation becomes UNKNOWN to this client. A later
1080 // re-invite Welcome for the same group_id is then routed to
1081 // `join_conversation` (the host only joins UNKNOWN conversations) and
1082 // re-joins from clean storage, instead of being suppressed as an
1083 // "already-joined duplicate" (the cause of the stuck-un-joined re-invite).
1084 if !convo.is_active() {
1085 let conv_id = env.conversation_id;
1086 // Best-effort storage cleanup; even if it fails, dropping the
1087 // in-memory handle already makes the conversation re-joinable.
1088 if let Err(e) = convo.delete_group_state() {
1089 tracing::warn!(error = %e, "process_envelope: delete removed group state failed");
1090 }
1091 guard.remove(&conv_id);
1092 self.stranded.write().remove(&conv_id);
1093 return Ok((out, true));
1094 }
1095 Ok((out, false))
1096 }
1097
1098 /// Catch-up sync: pull missing events for every open conversation since its cursor.
1099 /// Returns the list of newly-decrypted application messages, in apply order.
1100 pub async fn sync_conversations(&self, now_ms: u64) -> Result<Vec<IncomingMessage>> {
1101 // Snapshot the conversation IDs ONLY — not their cursors. The cursor is
1102 // re-read fresh per fetch below. Two bugs this avoids:
1103 // 1. Stale-cursor pagination: `process_envelope` advances the
1104 // conversation's cursor as it applies each page, but the OLD code
1105 // kept fetching from the cursor captured up-front — so a chat with
1106 // more than one page (256+) of backlog re-fetched the SAME first
1107 // page forever and never paged past it (catch-up silently truncated
1108 // a freshly-linked device's history, incl. group-avatar/name
1109 // hydration that lands after the first page).
1110 // 2. Join-during-sync: reading IDs fresh here (and re-reading the map
1111 // each iteration) means a conversation the host joins via a live
1112 // Welcome right before/around this call is still covered.
1113 // Iterate a sorted, de-duplicated ID set for deterministic order.
1114 let conversation_ids: Vec<ConversationId> = {
1115 let guard = self.conversations.read();
1116 let mut ids: Vec<ConversationId> = guard.keys().copied().collect();
1117 ids.sort_by_key(|a| a.0);
1118 ids
1119 };
1120
1121 let mut delivered = Vec::new();
1122 for conv_id in conversation_ids {
1123 loop {
1124 // Re-read the LIVE cursor each iteration so pagination advances
1125 // as `process_envelope` consumes pages. If the conversation was
1126 // removed mid-sync (e.g. a wipe), stop cleanly.
1127 let cursor = match self.conversations.read().get(&conv_id) {
1128 Some(c) => c.cursor.clone(),
1129 None => break,
1130 };
1131 // PER-CONVERSATION ISOLATION: a transport error on ONE
1132 // conversation (a transient 5xx, a non-404 fetch failure) must
1133 // not abort catch-up for ALL the others. Previously a single
1134 // erroring conversation propagated `?` and failed the entire
1135 // `sync_conversations` — so on a freshly-linked device, one bad
1136 // conversation (e.g. the device group, or a group mid-churn)
1137 // blocked every chat from syncing, and group name/avatar
1138 // hydration broadcasts never arrived. Log + skip this
1139 // conversation instead.
1140 let batch = match self.transport.fetch_since(conv_id, cursor, 256).await {
1141 Ok(b) => b,
1142 Err(e) => {
1143 tracing::warn!(error = %e, "sync_conversations: fetch_since failed; skipping conversation");
1144 break;
1145 }
1146 };
1147 if batch.is_empty() {
1148 break;
1149 }
1150 let mut advanced = false;
1151 let mut removed = false;
1152 for env in &batch {
1153 // PER-ENVELOPE ISOLATION: a single undecryptable / malformed
1154 // / wrong-epoch envelope must not drop the rest of the page
1155 // (or fail the sync). Skip it; the live stream / a later
1156 // epoch advance can still deliver retriable ones.
1157 //
1158 // BATCHED CHECKPOINT (drain-wedge fix): apply each envelope to
1159 // the in-memory working set WITHOUT flushing, then persist the
1160 // whole page with ONE full-state checkpoint below. This turns a
1161 // backlog drain from O(N × total_state) synchronous
1162 // serializations into O(1) per page (~100-1000× less work on
1163 // the host's single serial queue) — the stall the client saw
1164 // as "messages delivered late".
1165 match self.apply_envelope_in_memory(env, now_ms) {
1166 Ok((msg, rm)) => {
1167 // Commits / handshakes advance the in-memory cursor too
1168 // (no app message surfaced) — treat them as progress so
1169 // we keep paging instead of re-fetching the same page.
1170 advanced = true;
1171 if let Some(msg) = msg {
1172 delivered.push(msg);
1173 }
1174 if rm {
1175 // A self-removal Commit deleted the conversation
1176 // mid-page; stop applying further envelopes to it.
1177 removed = true;
1178 break;
1179 }
1180 }
1181 Err(e) => {
1182 tracing::warn!(error = %e, "sync_conversations: process_envelope failed; skipping envelope");
1183 }
1184 }
1185 }
1186 if advanced {
1187 // Progress was made — this conversation is not stranded
1188 // (clear any prior stranded mark).
1189 self.stranded.write().remove(&conv_id);
1190 }
1191 // ONE durable checkpoint for the whole page. Skipped when the
1192 // conversation was self-removed (its storage was already deleted).
1193 // Crash-safety is preserved by `flush`'s state-before-cursor
1194 // ordering: a crash before/inside this flush re-fetches the page on
1195 // restart and `SyncCursor::is_new` dedups the already-applied events.
1196 if advanced && !removed {
1197 if let Err(e) = self.flush_conversation(&conv_id).await {
1198 tracing::warn!(error = %e, "sync_conversations: batch checkpoint failed; will re-fetch on next sync");
1199 break;
1200 }
1201 }
1202 if removed {
1203 break; // conversation gone; nothing more to page
1204 }
1205 if batch.len() < 256 {
1206 break; // partial page → caught up
1207 }
1208 if !advanced {
1209 // Full page but nothing advanced the cursor (every envelope
1210 // errored / was wrong-epoch). The group can no longer advance
1211 // from local state — a Commit was missed. Mark it STRANDED so
1212 // the host can recover it (re-Welcome / snapshot import) via
1213 // `stranded_conversations()`, and bail to avoid an infinite
1214 // re-fetch loop.
1215 tracing::warn!(
1216 "sync_conversations: full page made no progress; marking conversation stranded"
1217 );
1218 self.stranded.write().insert(conv_id);
1219 break;
1220 }
1221 }
1222 }
1223 Ok(delivered)
1224 }
1225
1226 /// Rehydrate conversations from storage on startup ([CR-4]).
1227 ///
1228 /// Walks the host-side `groups` namespace for meta records, pairs each with its
1229 /// cursor + device→leaf map, and asks `Conversation::load` to re-attach to the
1230 /// underlying OpenMLS group state. The MLS state itself was persisted by the
1231 /// SQLite-backed `PersistentMlsProvider` on the previous run; this method
1232 /// reconciles the SDK-side caches with what's on disk.
1233 async fn rehydrate_conversations(self: &Arc<Self>, now_ms: u64) -> Result<()> {
1234 let metas = self.storage.list_keys("groups", "").await?;
1235 for path in metas {
1236 // path looks like "{convId}/meta"
1237 let Some((id_hex, suffix)) = path.split_once('/') else {
1238 continue;
1239 };
1240 if suffix != "meta" {
1241 continue;
1242 }
1243 let Some(meta_bytes) = self.storage.get("groups", &path).await? else {
1244 continue;
1245 };
1246 let meta: ConversationMeta = match codec::decode(&meta_bytes) {
1247 Ok(m) => m,
1248 Err(_) => continue,
1249 };
1250 let cursor_bytes = self
1251 .storage
1252 .get("cursors", id_hex)
1253 .await?
1254 .unwrap_or_default();
1255 let cursor = if cursor_bytes.is_empty() {
1256 SyncCursor::default()
1257 } else {
1258 SyncCursor::decode(&cursor_bytes).unwrap_or_default()
1259 };
1260
1261 // [CR-2] device→leaf map was persisted alongside meta + cursor.
1262 let device_leaves_bytes = self
1263 .storage
1264 .get("device_leaves", id_hex)
1265 .await?
1266 .unwrap_or_default();
1267 let device_leaves: std::collections::BTreeMap<DeviceId, u32> =
1268 if device_leaves_bytes.is_empty() {
1269 std::collections::BTreeMap::new()
1270 } else {
1271 let pairs: Vec<(DeviceId, u32)> =
1272 codec::decode(&device_leaves_bytes).unwrap_or_default();
1273 pairs.into_iter().collect()
1274 };
1275
1276 match Conversation::load(
1277 meta.id,
1278 meta.clone(),
1279 cursor,
1280 device_leaves,
1281 self.local_device.device_id.clone(),
1282 self.crypto.clone(),
1283 self.signing.clone(),
1284 self.storage.clone(),
1285 now_ms,
1286 ) {
1287 Ok(Some(convo)) => {
1288 tracing::debug!(
1289 target: "ping_core::client",
1290 convo = %id_hex,
1291 epoch = meta.epoch,
1292 "rehydrated conversation from disk"
1293 );
1294 self.conversations.write().insert(meta.id, convo);
1295 }
1296 Ok(None) => {
1297 tracing::warn!(
1298 target: "ping_core::client",
1299 convo = %id_hex,
1300 "host-side meta present but OpenMLS state missing — skipping"
1301 );
1302 }
1303 Err(e) => {
1304 tracing::warn!(
1305 target: "ping_core::client",
1306 convo = %id_hex,
1307 error = %e,
1308 "Conversation::load failed — skipping"
1309 );
1310 }
1311 }
1312 }
1313 Ok(())
1314 }
1315
1316 // ------------------- Multi-device API -------------------
1317
1318 /// Build a [`LinkingTicket`] for a new device. The caller obtains `new_device_kp` from the
1319 /// new device (e.g., via QR-encoded handshake) and is responsible for sealing the returned
1320 /// ticket against the new device's ephemeral X25519 pubkey before transmission via
1321 /// [`ping_link::seal_ticket`].
1322 ///
1323 /// [CR-13] `last_app_events` is a host-supplied list of `(conversation_id, app_event_bytes)`
1324 /// for the new device's "what you missed" UI. The SDK adds its own metas + (currently-
1325 /// empty) per-conversation MLS state and bundles everything into
1326 /// [`device::CatchupSnapshot`], CBOR-encoded into the ticket's `catchup_snapshot` field.
1327 /// Pass an empty `Vec` to suppress catchup data (the new device sees an empty
1328 /// conversation list until normal sync runs).
1329 pub async fn build_linking_ticket(
1330 self: &Arc<Self>,
1331 new_device_id: DeviceId,
1332 new_device_kp: Vec<u8>,
1333 last_app_events: Vec<(ConversationId, Vec<u8>)>,
1334 now_ms: u64,
1335 ) -> Result<LinkingTicket> {
1336 let device_binding_sig = self.identity.sign_device_binding(&new_device_id.0);
1337 let dg_id = device_group_id_for(self.identity.user_id());
1338
1339 // [CR-10] DG is eagerly created at init now, but call ensure here too so
1340 // hosts that bypass `MessagingClient::init` (mocked tests, legacy upgrade
1341 // paths) keep working.
1342 self.ensure_device_group(now_ms).await?;
1343
1344 // Admit the new device to the DeviceGroup.
1345 let outcome = {
1346 let mut conversations = self.conversations.write();
1347 // `ensure_device_group` above creates it, but return a typed error
1348 // instead of panicking (which would unwind across FFI/wasm) on the
1349 // pathological case where it's still missing.
1350 let dg = conversations.get_mut(&dg_id).ok_or_else(|| {
1351 Error::Invalid("device group missing after ensure_device_group".into())
1352 })?;
1353 // [CR-2] Record the new device's leaf in the DG so future `revoke_device`
1354 // can find it. The new_device_id we got as a parameter is the inviter's
1355 // own assertion — same trust model as the rest of `add_members`.
1356 dg.add_members(vec![(new_device_id.clone(), new_device_kp)], now_ms)?
1357 };
1358
1359 // [CR-13] Assemble the catchup snapshot: SDK-known conversation metadata + host-
1360 // supplied last-known plaintext per conversation. [CR-7] now populates
1361 // `group_state_bytes` with each group's MLS state so the new device can decrypt
1362 // historical traffic without re-Welcoming. An empty `group_state_bytes` would
1363 // mean either a group with no exportable state (shouldn't happen) or an
1364 // encoder failure (we let those propagate as errors below).
1365 let catchup_snapshot = if last_app_events.is_empty() && self.conversations.read().is_empty()
1366 {
1367 // Cheap path: nothing to snapshot, skip the encode round-trip.
1368 Vec::new()
1369 } else {
1370 let conversation_metas: Vec<CatchupConversationEntry> = self
1371 .conversations
1372 .read()
1373 .values()
1374 .map(|c| -> Result<CatchupConversationEntry> {
1375 // CR-7: per-group state. We deliberately keep the export bytes
1376 // inside the (HPKE-sealed-by-CR-3) LinkingTicket; the receiver
1377 // calls `import_state_snapshot` with these bytes after `consume_linking_ticket`.
1378 let group_bytes = c.export_state_snapshot(now_ms)?.to_vec();
1379 Ok(CatchupConversationEntry {
1380 conversation_id: c.id(),
1381 meta: c.meta().clone(),
1382 group_state_bytes: group_bytes,
1383 })
1384 })
1385 .collect::<Result<_>>()?;
1386 let last_app_events_per_conv: Vec<CatchupAppEventEntry> = last_app_events
1387 .into_iter()
1388 .map(|(conversation_id, app_event_bytes)| CatchupAppEventEntry {
1389 conversation_id,
1390 app_event_bytes,
1391 })
1392 .collect();
1393 CatchupSnapshot {
1394 v: CATCHUP_SNAPSHOT_VERSION,
1395 conversation_metas,
1396 last_app_events_per_conv,
1397 }
1398 .encode()?
1399 };
1400
1401 Ok(LinkingTicket {
1402 v: 1,
1403 user_id: self.identity.user_id().clone(),
1404 user_pubkey: self.identity.public_key().to_bytes().to_vec(),
1405 new_device_id,
1406 device_binding_sig,
1407 device_group_welcome: outcome.welcome.payload,
1408 catchup_snapshot,
1409 })
1410 }
1411
1412 /// Apply a received linking ticket. Joins the user's DeviceGroup; the catch-up snapshot
1413 /// (if any) is decrypted by the host using the standard per-conversation channel afterwards.
1414 pub async fn consume_linking_ticket(
1415 self: &Arc<Self>,
1416 ticket: &LinkingTicket,
1417 now_ms: u64,
1418 ) -> Result<()> {
1419 // Verify the binding the existing device made for us. (Ed25519 public keys are 32 bytes.)
1420 let pk_bytes: [u8; 32] = ticket
1421 .user_pubkey
1422 .as_slice()
1423 .try_into()
1424 .map_err(|_| Error::Identity("user_pubkey must be 32 bytes".into()))?;
1425 let user_pk = ed25519_dalek::VerifyingKey::from_bytes(&pk_bytes)
1426 .map_err(|e| Error::Identity(format!("bad user pubkey: {e}")))?;
1427 Identity::verify_device_binding(
1428 &user_pk,
1429 &ticket.user_id,
1430 &ticket.new_device_id.0,
1431 &ticket.device_binding_sig,
1432 )?;
1433 if ticket.new_device_id != self.local_device.device_id {
1434 return Err(Error::Invalid(
1435 "ticket addressed to a different device".into(),
1436 ));
1437 }
1438
1439 let dummy_env = MessageEnvelope::new(
1440 ConversationId(device_group_id_for(&ticket.user_id).0),
1441 0,
1442 MessageKind::Welcome,
1443 self.local_device.device_id.clone(),
1444 0,
1445 crate::clock::Hlc::ZERO,
1446 ticket.device_group_welcome.clone(),
1447 );
1448 self.join_conversation(&dummy_env, now_ms).await?;
1449 Ok(())
1450 }
1451
1452 /// [CR-7] Export the MLS state snapshot for one open conversation.
1453 ///
1454 /// Thin pass-through to [`Conversation::export_state_snapshot`]. Returned bytes
1455 /// are wrapped in `Zeroizing` because they contain past epoch secrets.
1456 pub fn export_conversation_state_snapshot(
1457 &self,
1458 conv_id: ConversationId,
1459 now_ms: u64,
1460 ) -> Result<zeroize::Zeroizing<Vec<u8>>> {
1461 let guard = self.conversations.read();
1462 let convo = guard
1463 .get(&conv_id)
1464 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
1465 convo.export_state_snapshot(now_ms)
1466 }
1467
1468 /// [CR-7] Import a `GroupStateSnapshot` produced by another device's
1469 /// [`Conversation::export_state_snapshot`].
1470 ///
1471 /// Replays the snapshot's entries into this client's OpenMLS provider, then
1472 /// reconstructs the `Conversation` handle via `MlsGroup::load`. After return,
1473 /// the conversation is in `list_conversations()` and `send`/`process_envelope`
1474 /// work against it normally.
1475 ///
1476 /// **Scope.** This is for the *same-user* hand-off (linking, recovery). The
1477 /// snapshot exposes the exporter's view of past epoch secrets for the target
1478 /// group; only call this when the receiving device has been authenticated to
1479 /// the same user identity (mnemonic, QR-handshake). Cross-user history transfer
1480 /// uses HPKE-sealed AppEvent re-shares (umbrella §15.6), not this method.
1481 ///
1482 /// **Sanity.** Refuses snapshots whose `group_id` doesn't match the bytes the
1483 /// receiver intends to claim — guards against host bugs that shuffle snapshots
1484 /// between groups. Refuses mismatched OpenMLS storage versions outright; no
1485 /// silent forward/back compatibility.
1486 pub async fn import_state_snapshot(
1487 self: &Arc<Self>,
1488 snapshot_bytes: &[u8],
1489 now_ms: u64,
1490 ) -> Result<ConversationId> {
1491 use crate::device::GroupStateSnapshot;
1492 let snap = GroupStateSnapshot::decode(snapshot_bytes)
1493 .map_err(|e| Error::Invalid(format!("snapshot decode: {e}")))?;
1494
1495 if snap.openmls_storage_version != openmls_traits::storage::CURRENT_VERSION {
1496 return Err(Error::Invalid(format!(
1497 "snapshot openmls_storage_version={} not supported (this SDK supports v={})",
1498 snap.openmls_storage_version,
1499 openmls_traits::storage::CURRENT_VERSION
1500 )));
1501 }
1502
1503 let conv_id = snap.group_id;
1504
1505 // Refuse if we already have an active handle for this conv — the host should
1506 // close it first, otherwise import silently overwrites in-memory state and
1507 // the existing handle becomes stale.
1508 if self.conversations.read().contains_key(&conv_id) {
1509 return Err(Error::Invalid(format!(
1510 "conversation {} already open; close before importing snapshot",
1511 conv_id.as_hex()
1512 )));
1513 }
1514
1515 // Replay raw KV pairs into the provider's working set.
1516 let entries: Vec<(Vec<u8>, Vec<u8>)> =
1517 snap.entries.into_iter().map(|e| (e.key, e.value)).collect();
1518 self.crypto
1519 .import_entries(entries)
1520 .map_err(|e| Error::Storage(format!("import entries: {e}")))?;
1521
1522 // Reconstruct the Conversation handle. `Conversation::load` will return
1523 // `Ok(None)` if OpenMLS still can't find the group — i.e. our snapshot was
1524 // incomplete or for a different storage version.
1525 let meta = ConversationMeta {
1526 id: conv_id,
1527 name: None,
1528 epoch: 0, // will be overwritten from the loaded group state in process()
1529 member_count: 0,
1530 is_device_group: false, // host can flip this via meta update if needed
1531 created_at_ms: now_ms,
1532 };
1533 let convo = Conversation::load(
1534 conv_id,
1535 meta,
1536 SyncCursor::default(),
1537 std::collections::BTreeMap::new(),
1538 self.local_device.device_id.clone(),
1539 self.crypto.clone(),
1540 self.signing.clone(),
1541 self.storage.clone(),
1542 now_ms,
1543 )?
1544 .ok_or_else(|| {
1545 Error::Invalid(
1546 "snapshot imported but OpenMLS could not load the group — snapshot may be incomplete or storage version mismatched"
1547 .into(),
1548 )
1549 })?;
1550
1551 // Pull the live epoch + member count from the loaded group so the meta we
1552 // just stubbed is consistent with what we'll observe on subsequent process_envelope.
1553 let live_epoch = convo.epoch();
1554 let live_members = convo.group.members().count() as u32;
1555 let live_name = convo.name_from_group_state();
1556 let mut convo = convo;
1557 convo.meta.epoch = live_epoch;
1558 convo.meta.member_count = live_members;
1559 // Recover the name from the loaded GroupContext state (a snapshot import
1560 // is join-equivalent; the stubbed `name: None` would otherwise stick).
1561 convo.meta.name = live_name;
1562 convo.snapshot_to_storage().await?;
1563
1564 self.conversations.write().insert(conv_id, convo);
1565 Ok(conv_id)
1566 }
1567
1568 /// Export a derived secret from one conversation's MLS exporter ([CR-8]).
1569 ///
1570 /// Thin pass-through to [`Conversation::export_secret`]. See that method's doc comment
1571 /// for the contract on `label`, `context`, length validation, and zeroization. The
1572 /// returned `Zeroizing<Vec<u8>>` is automatically wiped when dropped.
1573 pub fn export_conversation_secret(
1574 &self,
1575 conv_id: ConversationId,
1576 label: &str,
1577 context: &[u8],
1578 length: usize,
1579 ) -> Result<Zeroizing<Vec<u8>>> {
1580 let guard = self.conversations.read();
1581 let convo = guard
1582 .get(&conv_id)
1583 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
1584 convo.export_secret(label, context, length)
1585 }
1586
1587 /// Revoke a device by removing its leaf from every conversation where we know its
1588 /// position ([CR-2]).
1589 ///
1590 /// Returns one Commit envelope per conversation the device was a leaf in. The host
1591 /// broadcasts each envelope to the affected conversation; the SDK has also already
1592 /// handed them to the transport via `transport.send` (idempotent broadcast is the
1593 /// host's call).
1594 ///
1595 /// **Scope.** The SDK can only resolve leaves it recorded itself — either when it
1596 /// admitted the device via [`Self::add_members`] or when this device joined as the
1597 /// target via Welcome. For peer-admitted devices the leaf index isn't locally known;
1598 /// those conversations are silently skipped. The host can fall back to
1599 /// `remove_members(leaf_index)` directly using a transport-side directory lookup if
1600 /// it needs to revoke from those conversations too. See
1601 /// `docs/architecture/multi-device.md §Device removal` for the broader flow.
1602 ///
1603 /// Conversations with no entry for `device_id` produce no envelope; an empty `Vec`
1604 /// return is a valid outcome (e.g. the device was already revoked, or was never
1605 /// added by this client).
1606 #[allow(clippy::await_holding_lock)] // see add_members for rationale
1607 pub async fn revoke_device(
1608 &self,
1609 device_id: DeviceId,
1610 now_ms: u64,
1611 ) -> Result<Vec<MessageEnvelope>> {
1612 // 1. Walk every open conversation and gather (conv_id, leaf_index) pairs where
1613 // we know `device_id` controls a leaf. Done under a read lock so we don't hold
1614 // the write lock across the per-conversation remove path.
1615 let targets: Vec<(ConversationId, u32)> = self
1616 .conversations
1617 .read()
1618 .iter()
1619 .filter_map(|(id, c)| c.leaf_index_of(&device_id).map(|leaf| (*id, leaf)))
1620 .collect();
1621
1622 // 2. For each target, emit a remove_members commit. We do this sequentially: each
1623 // one is a separate MLS epoch advance on its own group, and they don't share
1624 // state, so parallel issuance is safe but adds complexity we don't need for v1.
1625 let mut envelopes = Vec::with_capacity(targets.len());
1626 for (conv_id, leaf_index) in targets {
1627 let envelope = {
1628 let mut guard = self.conversations.write();
1629 let convo = guard
1630 .get_mut(&conv_id)
1631 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
1632 convo.remove_members(vec![leaf_index], now_ms)?
1633 };
1634 self.transport.send(envelope.clone()).await?;
1635 if let Some(c) = self.conversations.read().get(&conv_id) {
1636 c.snapshot_to_storage().await?;
1637 }
1638 envelopes.push(envelope);
1639 }
1640
1641 // 3. Notify the auth-layer server so it can invalidate the
1642 // revoked device's KeyPackage pool, mark `auth.devices.revoked_at`,
1643 // and refuse any future envelope signed by the revoked device's
1644 // JWT. Done AFTER the MLS Commits so peers learn via MLS first
1645 // (the canonical path) and the auth layer is the eventual-
1646 // consistency cleanup. Transport failures bubble up so callers
1647 // can retry — but the MLS-side work has already shipped, so
1648 // the device is functionally revoked in every group; only the
1649 // auth-layer KeyPackage purge is pending.
1650 self.transport.revoke_device_remote(device_id).await?;
1651 Ok(envelopes)
1652 }
1653}
1654
1655fn device_group_id_for(user_id: &UserId) -> ConversationId {
1656 // Deterministic 16-byte ID derived from the user's id, prefixed so it cannot collide with
1657 // a randomly-generated ULID in normal use (ULIDs start with a millisecond timestamp).
1658 let mut bytes = [0u8; 16];
1659 bytes[0] = 0xFF;
1660 bytes[1] = 0xDC; // "DeviCe" group sentinel
1661 let h = codec::sha256(&user_id.0);
1662 bytes[2..].copy_from_slice(&h[..14]);
1663 ConversationId(bytes)
1664}
1665
1666fn encode_local_device(d: &LocalDevice) -> Result<Vec<u8>> {
1667 use serde::Serialize;
1668 #[derive(Serialize)]
1669 struct Persisted<'a> {
1670 device_id: &'a DeviceId,
1671 label: &'a str,
1672 created_at_ms: u64,
1673 #[serde(with = "serde_bytes")]
1674 signing_seed: &'a [u8],
1675 }
1676 codec::encode(&Persisted {
1677 device_id: &d.device_id,
1678 label: &d.label,
1679 created_at_ms: d.created_at_ms,
1680 signing_seed: d.signing.as_bytes(),
1681 })
1682}
1683
1684fn decode_local_device(bytes: &[u8], user_id: UserId) -> Result<LocalDevice> {
1685 use serde::Deserialize;
1686 #[derive(Deserialize)]
1687 struct Persisted {
1688 device_id: DeviceId,
1689 label: String,
1690 created_at_ms: u64,
1691 #[serde(with = "serde_bytes")]
1692 signing_seed: Vec<u8>,
1693 }
1694 let p: Persisted = codec::decode(bytes)?;
1695 let seed: [u8; 32] = p
1696 .signing_seed
1697 .as_slice()
1698 .try_into()
1699 .map_err(|_| Error::Invalid("device signing seed must be 32 bytes".into()))?;
1700 let signing = ed25519_dalek::SigningKey::from_bytes(&seed);
1701 Ok(LocalDevice {
1702 device_id: p.device_id,
1703 user_id,
1704 label: p.label,
1705 signing,
1706 created_at_ms: p.created_at_ms,
1707 })
1708}