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},
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#[derive(Debug)]
38pub struct ClientConfig {
39 pub identity: Identity,
40 pub device_label: String,
41 pub storage: Arc<dyn Storage>,
42 pub transport: Arc<dyn Transport>,
43 /// Wall clock in ms. Pulled from the host so we can use a synthetic clock in tests.
44 pub now_ms: u64,
45 /// [CR-4] OpenMLS-provider backend. Defaults to in-memory; iOS NSE and web SW
46 /// cold-start paths MUST pass `StorageBackend::Sqlite { path, encryption_key }`
47 /// (native) or `StorageBackend::IndexedDb { db_name }` (WASM, when that lands).
48 /// See `docs/design/CR4_CR7_PERSISTENCE.md`.
49 pub storage_backend: StorageBackend,
50 /// Optional 32-byte Ed25519 secret key the SDK should use as the
51 /// device signing key. When set AND no `LocalDevice` is yet
52 /// persisted in `storage`, the SDK constructs its first
53 /// `LocalDevice` from this key instead of generating a fresh
54 /// random one — so `device_id = SHA-256(public_key_of(secret))`
55 /// is fully determined by what the host provided.
56 ///
57 /// Use case: align the SDK's `device_id` (which it stamps into
58 /// every envelope's `sender_device` field) with an externally-
59 /// computed device id — typically `SHA-256(device_signing_pubkey)`
60 /// in the host's auth layer, where the JWT carries that same
61 /// value as its `device_id` claim. Without this alignment, a
62 /// server that validates `envelope.sender_device ==
63 /// jwt.device_id` would reject every send.
64 ///
65 /// Ignored on re-init (when storage already has a persisted
66 /// `LocalDevice`) so the device identity remains stable across
67 /// restarts.
68 pub device_signing_secret_key: Option<[u8; 32]>,
69}
70
71impl ClientConfig {
72 /// Construct a config with `StorageBackend::Memory` — convenient for tests and
73 /// the existing v0.1 in-memory flow.
74 pub fn new_in_memory(
75 identity: Identity,
76 device_label: String,
77 storage: Arc<dyn Storage>,
78 transport: Arc<dyn Transport>,
79 now_ms: u64,
80 ) -> Self {
81 Self {
82 identity,
83 device_label,
84 storage,
85 transport,
86 now_ms,
87 storage_backend: StorageBackend::Memory,
88 device_signing_secret_key: None,
89 }
90 }
91}
92
93pub struct MessagingClient {
94 pub(crate) identity: Identity,
95 pub(crate) local_device: LocalDevice,
96 pub(crate) crypto: Arc<PersistentMlsProvider>,
97 pub(crate) signing: Arc<SignatureKeyPair>,
98 pub(crate) storage: Arc<dyn Storage>,
99 pub(crate) transport: Arc<dyn Transport>,
100 conversations: RwLock<HashMap<ConversationId, Conversation>>,
101}
102
103impl std::fmt::Debug for MessagingClient {
104 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105 f.debug_struct("MessagingClient")
106 .field("user_id", &self.identity.user_id().as_hex())
107 .field("device_id", &self.local_device.device_id.as_hex())
108 .field("conversation_count", &self.conversations.read().len())
109 .finish()
110 }
111}
112
113impl MessagingClient {
114 /// Initialise. Creates a new local device if none is recorded in storage; otherwise rehydrates.
115 pub async fn init(cfg: ClientConfig) -> Result<Arc<Self>> {
116 // [CR-4] OpenMLS provider is now pluggable. For `StorageBackend::Memory` this
117 // behaves like the old `OpenMlsRustCrypto::default()`. For `Sqlite`, the
118 // working set is hydrated from the on-disk blob; subsequent `checkpoint` calls
119 // flush it back. iOS NSE / web SW cold-start lives here.
120 let crypto = PersistentMlsProvider::open(cfg.storage_backend.clone())
121 .map_err(|e| Error::Storage(format!("provider open: {e}")))?;
122 let local_device = match cfg.storage.get("device", "local").await? {
123 Some(bytes) => decode_local_device(&bytes, cfg.identity.user_id().clone())?,
124 None => {
125 // First-init path. If the host supplied a signing secret
126 // (typically to align the device_id with their auth
127 // layer), use it; otherwise mint a fresh random key.
128 // Either way, the constructed `LocalDevice` is
129 // immediately persisted so future inits load from
130 // storage without consulting the override again.
131 let dev = match cfg.device_signing_secret_key.as_ref() {
132 Some(secret) => LocalDevice::from_signing_secret(
133 cfg.identity.user_id().clone(),
134 cfg.device_label,
135 cfg.now_ms,
136 secret,
137 ),
138 None => LocalDevice::generate(
139 cfg.identity.user_id().clone(),
140 cfg.device_label,
141 cfg.now_ms,
142 ),
143 };
144 let bytes = encode_local_device(&dev)?;
145 cfg.storage.put("device", "local", bytes).await?;
146 dev
147 }
148 };
149
150 // [CR-4] MLS signing keypair MUST be stable across cold restarts — otherwise the
151 // leaf-key stored on disk no longer matches the per-client key on re-init, and any
152 // send-after-restart silently misroutes. We derive deterministically from the
153 // already-persistent `LocalDevice::signing` (Ed25519, 32 raw bytes), and the
154 // ciphersuite's signature scheme is Ed25519 too — so the device signing key and the
155 // MLS leaf signing key are the same bytes. The MLS storage provider also receives
156 // a copy via `store()` so OpenMLS-internal lookups (process_message, etc.) succeed.
157 let signing = {
158 let sk_bytes = local_device.signing.to_bytes().to_vec();
159 let pk_bytes = local_device.signing.verifying_key().to_bytes().to_vec();
160 let kp = SignatureKeyPair::from_raw(
161 DEFAULT_CIPHERSUITE.signature_algorithm(),
162 sk_bytes,
163 pk_bytes,
164 );
165 kp.store(crypto.storage()).map_err(Error::mls)?;
166 Arc::new(kp)
167 };
168
169 let client = Arc::new(Self {
170 identity: cfg.identity,
171 local_device,
172 crypto,
173 signing,
174 storage: cfg.storage,
175 transport: cfg.transport,
176 conversations: RwLock::new(HashMap::new()),
177 });
178
179 client.rehydrate_conversations(cfg.now_ms).await?;
180
181 // [CR-10] Ensure the DeviceGroup exists at init, not lazily inside
182 // build_linking_ticket. Single-device users need somewhere to write
183 // personal events (drafts, read pointers, notes, vault wrapper)
184 // even before they pair a second device. Lazy creation in
185 // build_linking_ticket left them with no DG → no place for
186 // personal state to land.
187 //
188 // Idempotent — re-init after a cold restart finds the DG via
189 // rehydrate_conversations and this becomes a no-op.
190 client.ensure_device_group(cfg.now_ms).await?;
191
192 Ok(client)
193 }
194
195 /// [CR-10] Idempotently ensures this user's DeviceGroup exists in
196 /// `self.conversations`. Called from `init` (so single-device users
197 /// have a DG immediately) and from `build_linking_ticket` (the legacy
198 /// lazy path; still safe to call when the DG already exists, since
199 /// rehydrate_conversations would have re-attached it before init
200 /// returned).
201 ///
202 /// The DeviceGroup is a one-leaf MLS group at creation time —
203 /// `add_members` (called by `build_linking_ticket` when a second
204 /// device pairs in) is what grows it. We persist the snapshot so a
205 /// cold restart picks it up before this function runs again.
206 pub(crate) async fn ensure_device_group(self: &Arc<Self>, now_ms: u64) -> Result<()> {
207 let dg_id = device_group_id_for(self.identity.user_id());
208 if self.conversations.read().contains_key(&dg_id) {
209 return Ok(());
210 }
211 let mut new_dg = Conversation::create(
212 dg_id,
213 Some("device-group".into()),
214 self.local_device.device_id.clone(),
215 self.identity.user_id(),
216 self.crypto.clone(),
217 self.signing.clone(),
218 self.storage.clone(),
219 now_ms,
220 )?;
221 new_dg.meta.is_device_group = true;
222 new_dg.snapshot_to_storage().await?;
223 self.conversations.write().insert(dg_id, new_dg);
224 Ok(())
225 }
226
227 pub fn user_id(&self) -> UserId {
228 self.identity.user_id().clone()
229 }
230 pub fn device_id(&self) -> DeviceId {
231 self.local_device.device_id.clone()
232 }
233 pub fn device_info(&self, now_ms: u64) -> DeviceInfo {
234 self.local_device.info(now_ms)
235 }
236
237 /// Generate a fresh KeyPackage to publish to the directory. Hosts call this when registering
238 /// a device or topping up the directory.
239 pub fn fresh_key_package(&self) -> Result<Vec<u8>> {
240 let credential_with_key = CredentialWithKey {
241 credential: BasicCredential::new(self.identity.user_id().0.clone()).into(),
242 signature_key: self.signing.public().to_vec().into(),
243 };
244 let bundle = KeyPackageBuilder::new()
245 .build(
246 DEFAULT_CIPHERSUITE,
247 self.crypto.as_ref(),
248 self.signing.as_ref(),
249 credential_with_key,
250 )
251 .map_err(Error::mls)?;
252 // KeyPackages are serialized as MlsMessage(KeyPackage) per the MLS framing spec.
253 let msg: MlsMessageOut = bundle.key_package().clone().into();
254 msg.tls_serialize_detached().map_err(Error::mls)
255 }
256
257 /// Create a new conversation owned by this client (and seeded with a single member: this device).
258 pub async fn create_conversation(
259 self: &Arc<Self>,
260 name: Option<String>,
261 now_ms: u64,
262 ) -> Result<ConversationId> {
263 let id = ConversationId::new();
264 let convo = Conversation::create(
265 id,
266 name,
267 self.local_device.device_id.clone(),
268 self.identity.user_id(),
269 self.crypto.clone(),
270 self.signing.clone(),
271 self.storage.clone(),
272 now_ms,
273 )?;
274 convo.snapshot_to_storage().await?;
275 self.conversations.write().insert(id, convo);
276 Ok(id)
277 }
278
279 /// Join via a Welcome bundled in a [`MessageEnvelope`] of kind `Welcome`.
280 pub async fn join_conversation(
281 self: &Arc<Self>,
282 welcome_envelope: &MessageEnvelope,
283 now_ms: u64,
284 ) -> Result<ConversationId> {
285 if welcome_envelope.kind != MessageKind::Welcome {
286 return Err(Error::Invalid("expected Welcome envelope".into()));
287 }
288 let convo = Conversation::join(
289 &welcome_envelope.payload,
290 self.local_device.device_id.clone(),
291 self.crypto.clone(),
292 self.signing.clone(),
293 self.storage.clone(),
294 now_ms,
295 )?;
296 let id = convo.id();
297 convo.snapshot_to_storage().await?;
298 self.conversations.write().insert(id, convo);
299 Ok(id)
300 }
301
302 pub fn list_conversations(&self) -> Vec<ConversationMeta> {
303 self.conversations
304 .read()
305 .values()
306 .map(|c| c.meta.clone())
307 .collect()
308 }
309
310 /// Send an application message. Returns once the envelope has been handed to the transport.
311 pub async fn send(
312 &self,
313 conv_id: ConversationId,
314 plaintext: Vec<u8>,
315 now_ms: u64,
316 ) -> Result<MessageEnvelope> {
317 let envelope = {
318 let mut guard = self.conversations.write();
319 let convo = guard
320 .get_mut(&conv_id)
321 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
322 convo.send_application(&plaintext, now_ms)?
323 };
324 self.transport.send(envelope.clone()).await?;
325 Ok(envelope)
326 }
327
328 /// Add members. The Commit goes on the wire; the Welcome should be delivered to the new
329 /// devices' inboxes (the host transport implements that — typically as a separate addressed
330 /// envelope).
331 ///
332 /// [CR-2] Each entry is `(DeviceId, KeyPackage_bytes)`. The host typically gets the
333 /// device_id from the directory at the same time it gets the KeyPackage; we use it to
334 /// record a per-conversation `device_id → leaf_index` map so [`Self::revoke_device`]
335 /// can later locate the leaf without a fresh directory lookup. The SDK does not
336 /// cryptographically verify the host's device-id claim — that's a directory policy
337 /// concern.
338 //
339 // We hold a `parking_lot` read guard across `.await` for `snapshot_to_storage` here. Clippy
340 // flags this; we keep it for v0.1 because the alternative is a structural refactor of
341 // Conversation::snapshot_to_storage to split sync prep from async writes — see
342 // docs/ASSUMPTIONS.md item "lock-during-async-I/O is suboptimal but acceptable for v0.1".
343 // The `parking_lot/send_guard` feature (in core/Cargo.toml) makes the guard `Send` so the
344 // future is still schedulable across tokio threads.
345 #[allow(clippy::await_holding_lock)]
346 pub async fn add_members(
347 &self,
348 conv_id: ConversationId,
349 entries: Vec<(DeviceId, Vec<u8>)>,
350 now_ms: u64,
351 ) -> Result<()> {
352 let outcome = {
353 let mut guard = self.conversations.write();
354 let convo = guard
355 .get_mut(&conv_id)
356 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
357 convo.add_members(entries, now_ms)?
358 };
359 self.transport.send(outcome.commit).await?;
360 self.transport.send(outcome.welcome).await?;
361 if let Some(c) = self.conversations.read().get(&conv_id) {
362 c.snapshot_to_storage().await?;
363 }
364 Ok(())
365 }
366
367 #[allow(clippy::await_holding_lock)] // see add_members for rationale
368 pub async fn remove_members(
369 &self,
370 conv_id: ConversationId,
371 leaf_indexes: Vec<u32>,
372 now_ms: u64,
373 ) -> Result<()> {
374 let envelope = {
375 let mut guard = self.conversations.write();
376 let convo = guard
377 .get_mut(&conv_id)
378 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
379 convo.remove_members(leaf_indexes, now_ms)?
380 };
381 self.transport.send(envelope).await?;
382 if let Some(c) = self.conversations.read().get(&conv_id) {
383 c.snapshot_to_storage().await?;
384 }
385 Ok(())
386 }
387
388 /// Process an inbound envelope coming from the transport's subscribe callback or a sync pull.
389 /// Returns `Some` for application traffic, `None` for handshake messages (already merged).
390 #[allow(clippy::await_holding_lock)] // see add_members for rationale
391 pub async fn process_envelope(
392 &self,
393 env: &MessageEnvelope,
394 now_ms: u64,
395 ) -> Result<Option<IncomingMessage>> {
396 // Welcome envelopes for unknown conversations are routed to `join_conversation` by the
397 // caller. Here we only handle traffic for already-open groups.
398 let mut guard = self.conversations.write();
399 let convo = match guard.get_mut(&env.conversation_id) {
400 Some(c) => c,
401 None => return Err(Error::UnknownConversation(env.conversation_id.as_hex())),
402 };
403 let out = convo.process(env, now_ms)?;
404 // Cheap snapshot — only mutates KV the size of the cursor.
405 convo.snapshot_to_storage().await?;
406 Ok(out)
407 }
408
409 /// Catch-up sync: pull missing events for every open conversation since its cursor.
410 /// Returns the list of newly-decrypted application messages, in apply order.
411 pub async fn sync_conversations(&self, now_ms: u64) -> Result<Vec<IncomingMessage>> {
412 let pending: Vec<(ConversationId, SyncCursor)> = self
413 .conversations
414 .read()
415 .iter()
416 .map(|(id, c)| (*id, c.cursor.clone()))
417 .collect();
418
419 let mut delivered = Vec::new();
420 for (conv_id, cursor) in pending {
421 loop {
422 let batch = self
423 .transport
424 .fetch_since(conv_id, cursor.clone(), 256)
425 .await?;
426 if batch.is_empty() {
427 break;
428 }
429 for env in &batch {
430 if let Some(msg) = self.process_envelope(env, now_ms).await? {
431 delivered.push(msg);
432 }
433 }
434 if batch.len() < 256 {
435 break;
436 } // partial page → caught up
437 }
438 }
439 Ok(delivered)
440 }
441
442 /// Rehydrate conversations from storage on startup ([CR-4]).
443 ///
444 /// Walks the host-side `groups` namespace for meta records, pairs each with its
445 /// cursor + device→leaf map, and asks `Conversation::load` to re-attach to the
446 /// underlying OpenMLS group state. The MLS state itself was persisted by the
447 /// SQLite-backed `PersistentMlsProvider` on the previous run; this method
448 /// reconciles the SDK-side caches with what's on disk.
449 async fn rehydrate_conversations(self: &Arc<Self>, now_ms: u64) -> Result<()> {
450 let metas = self.storage.list_keys("groups", "").await?;
451 for path in metas {
452 // path looks like "{convId}/meta"
453 let Some((id_hex, suffix)) = path.split_once('/') else {
454 continue;
455 };
456 if suffix != "meta" {
457 continue;
458 }
459 let Some(meta_bytes) = self.storage.get("groups", &path).await? else {
460 continue;
461 };
462 let meta: ConversationMeta = match codec::decode(&meta_bytes) {
463 Ok(m) => m,
464 Err(_) => continue,
465 };
466 let cursor_bytes = self
467 .storage
468 .get("cursors", id_hex)
469 .await?
470 .unwrap_or_default();
471 let cursor = if cursor_bytes.is_empty() {
472 SyncCursor::default()
473 } else {
474 SyncCursor::decode(&cursor_bytes).unwrap_or_default()
475 };
476
477 // [CR-2] device→leaf map was persisted alongside meta + cursor.
478 let device_leaves_bytes = self
479 .storage
480 .get("device_leaves", id_hex)
481 .await?
482 .unwrap_or_default();
483 let device_leaves: std::collections::BTreeMap<DeviceId, u32> =
484 if device_leaves_bytes.is_empty() {
485 std::collections::BTreeMap::new()
486 } else {
487 let pairs: Vec<(DeviceId, u32)> =
488 codec::decode(&device_leaves_bytes).unwrap_or_default();
489 pairs.into_iter().collect()
490 };
491
492 match Conversation::load(
493 meta.id,
494 meta.clone(),
495 cursor,
496 device_leaves,
497 self.local_device.device_id.clone(),
498 self.crypto.clone(),
499 self.signing.clone(),
500 self.storage.clone(),
501 now_ms,
502 ) {
503 Ok(Some(convo)) => {
504 tracing::debug!(
505 target: "ping_core::client",
506 convo = %id_hex,
507 epoch = meta.epoch,
508 "rehydrated conversation from disk"
509 );
510 self.conversations.write().insert(meta.id, convo);
511 }
512 Ok(None) => {
513 tracing::warn!(
514 target: "ping_core::client",
515 convo = %id_hex,
516 "host-side meta present but OpenMLS state missing — skipping"
517 );
518 }
519 Err(e) => {
520 tracing::warn!(
521 target: "ping_core::client",
522 convo = %id_hex,
523 error = %e,
524 "Conversation::load failed — skipping"
525 );
526 }
527 }
528 }
529 Ok(())
530 }
531
532 // ------------------- Multi-device API -------------------
533
534 /// Build a [`LinkingTicket`] for a new device. The caller obtains `new_device_kp` from the
535 /// new device (e.g., via QR-encoded handshake) and is responsible for sealing the returned
536 /// ticket against the new device's ephemeral X25519 pubkey before transmission via
537 /// [`ping_link::seal_ticket`].
538 ///
539 /// [CR-13] `last_app_events` is a host-supplied list of `(conversation_id, app_event_bytes)`
540 /// for the new device's "what you missed" UI. The SDK adds its own metas + (currently-
541 /// empty) per-conversation MLS state and bundles everything into
542 /// [`device::CatchupSnapshot`], CBOR-encoded into the ticket's `catchup_snapshot` field.
543 /// Pass an empty `Vec` to suppress catchup data (the new device sees an empty
544 /// conversation list until normal sync runs).
545 pub async fn build_linking_ticket(
546 self: &Arc<Self>,
547 new_device_id: DeviceId,
548 new_device_kp: Vec<u8>,
549 last_app_events: Vec<(ConversationId, Vec<u8>)>,
550 now_ms: u64,
551 ) -> Result<LinkingTicket> {
552 let device_binding_sig = self.identity.sign_device_binding(&new_device_id.0);
553 let dg_id = device_group_id_for(self.identity.user_id());
554
555 // [CR-10] DG is eagerly created at init now, but call ensure here too so
556 // hosts that bypass `MessagingClient::init` (mocked tests, legacy upgrade
557 // paths) keep working.
558 self.ensure_device_group(now_ms).await?;
559
560 // Admit the new device to the DeviceGroup.
561 let outcome = {
562 let mut conversations = self.conversations.write();
563 let dg = conversations
564 .get_mut(&dg_id)
565 .expect("DeviceGroup ensured above");
566 // [CR-2] Record the new device's leaf in the DG so future `revoke_device`
567 // can find it. The new_device_id we got as a parameter is the inviter's
568 // own assertion — same trust model as the rest of `add_members`.
569 dg.add_members(vec![(new_device_id.clone(), new_device_kp)], now_ms)?
570 };
571
572 // [CR-13] Assemble the catchup snapshot: SDK-known conversation metadata + host-
573 // supplied last-known plaintext per conversation. [CR-7] now populates
574 // `group_state_bytes` with each group's MLS state so the new device can decrypt
575 // historical traffic without re-Welcoming. An empty `group_state_bytes` would
576 // mean either a group with no exportable state (shouldn't happen) or an
577 // encoder failure (we let those propagate as errors below).
578 let catchup_snapshot = if last_app_events.is_empty() && self.conversations.read().is_empty()
579 {
580 // Cheap path: nothing to snapshot, skip the encode round-trip.
581 Vec::new()
582 } else {
583 let conversation_metas: Vec<CatchupConversationEntry> = self
584 .conversations
585 .read()
586 .values()
587 .map(|c| -> Result<CatchupConversationEntry> {
588 // CR-7: per-group state. We deliberately keep the export bytes
589 // inside the (HPKE-sealed-by-CR-3) LinkingTicket; the receiver
590 // calls `import_state_snapshot` with these bytes after `consume_linking_ticket`.
591 let group_bytes = c.export_state_snapshot(now_ms)?.to_vec();
592 Ok(CatchupConversationEntry {
593 conversation_id: c.id(),
594 meta: c.meta().clone(),
595 group_state_bytes: group_bytes,
596 })
597 })
598 .collect::<Result<_>>()?;
599 let last_app_events_per_conv: Vec<CatchupAppEventEntry> = last_app_events
600 .into_iter()
601 .map(|(conversation_id, app_event_bytes)| CatchupAppEventEntry {
602 conversation_id,
603 app_event_bytes,
604 })
605 .collect();
606 CatchupSnapshot {
607 v: CATCHUP_SNAPSHOT_VERSION,
608 conversation_metas,
609 last_app_events_per_conv,
610 }
611 .encode()?
612 };
613
614 Ok(LinkingTicket {
615 v: 1,
616 user_id: self.identity.user_id().clone(),
617 user_pubkey: self.identity.public_key().to_bytes().to_vec(),
618 new_device_id,
619 device_binding_sig,
620 device_group_welcome: outcome.welcome.payload,
621 catchup_snapshot,
622 })
623 }
624
625 /// Apply a received linking ticket. Joins the user's DeviceGroup; the catch-up snapshot
626 /// (if any) is decrypted by the host using the standard per-conversation channel afterwards.
627 pub async fn consume_linking_ticket(
628 self: &Arc<Self>,
629 ticket: &LinkingTicket,
630 now_ms: u64,
631 ) -> Result<()> {
632 // Verify the binding the existing device made for us. (Ed25519 public keys are 32 bytes.)
633 let pk_bytes: [u8; 32] = ticket
634 .user_pubkey
635 .as_slice()
636 .try_into()
637 .map_err(|_| Error::Identity("user_pubkey must be 32 bytes".into()))?;
638 let user_pk = ed25519_dalek::VerifyingKey::from_bytes(&pk_bytes)
639 .map_err(|e| Error::Identity(format!("bad user pubkey: {e}")))?;
640 Identity::verify_device_binding(
641 &user_pk,
642 &ticket.user_id,
643 &ticket.new_device_id.0,
644 &ticket.device_binding_sig,
645 )?;
646 if ticket.new_device_id != self.local_device.device_id {
647 return Err(Error::Invalid(
648 "ticket addressed to a different device".into(),
649 ));
650 }
651
652 let dummy_env = MessageEnvelope::new(
653 ConversationId(device_group_id_for(&ticket.user_id).0),
654 0,
655 MessageKind::Welcome,
656 self.local_device.device_id.clone(),
657 0,
658 crate::clock::Hlc::ZERO,
659 ticket.device_group_welcome.clone(),
660 );
661 self.join_conversation(&dummy_env, now_ms).await?;
662 Ok(())
663 }
664
665 /// [CR-7] Export the MLS state snapshot for one open conversation.
666 ///
667 /// Thin pass-through to [`Conversation::export_state_snapshot`]. Returned bytes
668 /// are wrapped in `Zeroizing` because they contain past epoch secrets.
669 pub fn export_conversation_state_snapshot(
670 &self,
671 conv_id: ConversationId,
672 now_ms: u64,
673 ) -> Result<zeroize::Zeroizing<Vec<u8>>> {
674 let guard = self.conversations.read();
675 let convo = guard
676 .get(&conv_id)
677 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
678 convo.export_state_snapshot(now_ms)
679 }
680
681 /// [CR-7] Import a `GroupStateSnapshot` produced by another device's
682 /// [`Conversation::export_state_snapshot`].
683 ///
684 /// Replays the snapshot's entries into this client's OpenMLS provider, then
685 /// reconstructs the `Conversation` handle via `MlsGroup::load`. After return,
686 /// the conversation is in `list_conversations()` and `send`/`process_envelope`
687 /// work against it normally.
688 ///
689 /// **Scope.** This is for the *same-user* hand-off (linking, recovery). The
690 /// snapshot exposes the exporter's view of past epoch secrets for the target
691 /// group; only call this when the receiving device has been authenticated to
692 /// the same user identity (mnemonic, QR-handshake). Cross-user history transfer
693 /// uses HPKE-sealed AppEvent re-shares (umbrella §15.6), not this method.
694 ///
695 /// **Sanity.** Refuses snapshots whose `group_id` doesn't match the bytes the
696 /// receiver intends to claim — guards against host bugs that shuffle snapshots
697 /// between groups. Refuses mismatched OpenMLS storage versions outright; no
698 /// silent forward/back compatibility.
699 pub async fn import_state_snapshot(
700 self: &Arc<Self>,
701 snapshot_bytes: &[u8],
702 now_ms: u64,
703 ) -> Result<ConversationId> {
704 use crate::device::GroupStateSnapshot;
705 let snap = GroupStateSnapshot::decode(snapshot_bytes)
706 .map_err(|e| Error::Invalid(format!("snapshot decode: {e}")))?;
707
708 if snap.openmls_storage_version != openmls_traits::storage::CURRENT_VERSION {
709 return Err(Error::Invalid(format!(
710 "snapshot openmls_storage_version={} not supported (this SDK supports v={})",
711 snap.openmls_storage_version,
712 openmls_traits::storage::CURRENT_VERSION
713 )));
714 }
715
716 let conv_id = snap.group_id;
717
718 // Refuse if we already have an active handle for this conv — the host should
719 // close it first, otherwise import silently overwrites in-memory state and
720 // the existing handle becomes stale.
721 if self.conversations.read().contains_key(&conv_id) {
722 return Err(Error::Invalid(format!(
723 "conversation {} already open; close before importing snapshot",
724 conv_id.as_hex()
725 )));
726 }
727
728 // Replay raw KV pairs into the provider's working set.
729 let entries: Vec<(Vec<u8>, Vec<u8>)> =
730 snap.entries.into_iter().map(|e| (e.key, e.value)).collect();
731 self.crypto
732 .import_entries(entries)
733 .map_err(|e| Error::Storage(format!("import entries: {e}")))?;
734
735 // Reconstruct the Conversation handle. `Conversation::load` will return
736 // `Ok(None)` if OpenMLS still can't find the group — i.e. our snapshot was
737 // incomplete or for a different storage version.
738 let meta = ConversationMeta {
739 id: conv_id,
740 name: None,
741 epoch: 0, // will be overwritten from the loaded group state in process()
742 member_count: 0,
743 is_device_group: false, // host can flip this via meta update if needed
744 created_at_ms: now_ms,
745 };
746 let convo = Conversation::load(
747 conv_id,
748 meta,
749 SyncCursor::default(),
750 std::collections::BTreeMap::new(),
751 self.local_device.device_id.clone(),
752 self.crypto.clone(),
753 self.signing.clone(),
754 self.storage.clone(),
755 now_ms,
756 )?
757 .ok_or_else(|| {
758 Error::Invalid(
759 "snapshot imported but OpenMLS could not load the group — snapshot may be incomplete or storage version mismatched"
760 .into(),
761 )
762 })?;
763
764 // Pull the live epoch + member count from the loaded group so the meta we
765 // just stubbed is consistent with what we'll observe on subsequent process_envelope.
766 let live_epoch = convo.epoch();
767 let live_members = convo.group.members().count() as u32;
768 let mut convo = convo;
769 convo.meta.epoch = live_epoch;
770 convo.meta.member_count = live_members;
771 convo.snapshot_to_storage().await?;
772
773 self.conversations.write().insert(conv_id, convo);
774 Ok(conv_id)
775 }
776
777 /// Export a derived secret from one conversation's MLS exporter ([CR-8]).
778 ///
779 /// Thin pass-through to [`Conversation::export_secret`]. See that method's doc comment
780 /// for the contract on `label`, `context`, length validation, and zeroization. The
781 /// returned `Zeroizing<Vec<u8>>` is automatically wiped when dropped.
782 pub fn export_conversation_secret(
783 &self,
784 conv_id: ConversationId,
785 label: &str,
786 context: &[u8],
787 length: usize,
788 ) -> Result<Zeroizing<Vec<u8>>> {
789 let guard = self.conversations.read();
790 let convo = guard
791 .get(&conv_id)
792 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
793 convo.export_secret(label, context, length)
794 }
795
796 /// Revoke a device by removing its leaf from every conversation where we know its
797 /// position ([CR-2]).
798 ///
799 /// Returns one Commit envelope per conversation the device was a leaf in. The host
800 /// broadcasts each envelope to the affected conversation; the SDK has also already
801 /// handed them to the transport via `transport.send` (idempotent broadcast is the
802 /// host's call).
803 ///
804 /// **Scope.** The SDK can only resolve leaves it recorded itself — either when it
805 /// admitted the device via [`Self::add_members`] or when this device joined as the
806 /// target via Welcome. For peer-admitted devices the leaf index isn't locally known;
807 /// those conversations are silently skipped. The host can fall back to
808 /// `remove_members(leaf_index)` directly using a transport-side directory lookup if
809 /// it needs to revoke from those conversations too. See
810 /// `docs/architecture/multi-device.md §Device removal` for the broader flow.
811 ///
812 /// Conversations with no entry for `device_id` produce no envelope; an empty `Vec`
813 /// return is a valid outcome (e.g. the device was already revoked, or was never
814 /// added by this client).
815 #[allow(clippy::await_holding_lock)] // see add_members for rationale
816 pub async fn revoke_device(
817 &self,
818 device_id: DeviceId,
819 now_ms: u64,
820 ) -> Result<Vec<MessageEnvelope>> {
821 // 1. Walk every open conversation and gather (conv_id, leaf_index) pairs where
822 // we know `device_id` controls a leaf. Done under a read lock so we don't hold
823 // the write lock across the per-conversation remove path.
824 let targets: Vec<(ConversationId, u32)> = self
825 .conversations
826 .read()
827 .iter()
828 .filter_map(|(id, c)| c.leaf_index_of(&device_id).map(|leaf| (*id, leaf)))
829 .collect();
830
831 // 2. For each target, emit a remove_members commit. We do this sequentially: each
832 // one is a separate MLS epoch advance on its own group, and they don't share
833 // state, so parallel issuance is safe but adds complexity we don't need for v1.
834 let mut envelopes = Vec::with_capacity(targets.len());
835 for (conv_id, leaf_index) in targets {
836 let envelope = {
837 let mut guard = self.conversations.write();
838 let convo = guard
839 .get_mut(&conv_id)
840 .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
841 convo.remove_members(vec![leaf_index], now_ms)?
842 };
843 self.transport.send(envelope.clone()).await?;
844 if let Some(c) = self.conversations.read().get(&conv_id) {
845 c.snapshot_to_storage().await?;
846 }
847 envelopes.push(envelope);
848 }
849
850 // 3. Notify the auth-layer server so it can invalidate the
851 // revoked device's KeyPackage pool, mark `auth.devices.revoked_at`,
852 // and refuse any future envelope signed by the revoked device's
853 // JWT. Done AFTER the MLS Commits so peers learn via MLS first
854 // (the canonical path) and the auth layer is the eventual-
855 // consistency cleanup. Transport failures bubble up so callers
856 // can retry — but the MLS-side work has already shipped, so
857 // the device is functionally revoked in every group; only the
858 // auth-layer KeyPackage purge is pending.
859 self.transport.revoke_device_remote(device_id).await?;
860 Ok(envelopes)
861 }
862}
863
864fn device_group_id_for(user_id: &UserId) -> ConversationId {
865 // Deterministic 16-byte ID derived from the user's id, prefixed so it cannot collide with
866 // a randomly-generated ULID in normal use (ULIDs start with a millisecond timestamp).
867 let mut bytes = [0u8; 16];
868 bytes[0] = 0xFF;
869 bytes[1] = 0xDC; // "DeviCe" group sentinel
870 let h = codec::sha256(&user_id.0);
871 bytes[2..].copy_from_slice(&h[..14]);
872 ConversationId(bytes)
873}
874
875fn encode_local_device(d: &LocalDevice) -> Result<Vec<u8>> {
876 use serde::Serialize;
877 #[derive(Serialize)]
878 struct Persisted<'a> {
879 device_id: &'a DeviceId,
880 label: &'a str,
881 created_at_ms: u64,
882 #[serde(with = "serde_bytes")]
883 signing_seed: &'a [u8],
884 }
885 codec::encode(&Persisted {
886 device_id: &d.device_id,
887 label: &d.label,
888 created_at_ms: d.created_at_ms,
889 signing_seed: d.signing.as_bytes(),
890 })
891}
892
893fn decode_local_device(bytes: &[u8], user_id: UserId) -> Result<LocalDevice> {
894 use serde::Deserialize;
895 #[derive(Deserialize)]
896 struct Persisted {
897 device_id: DeviceId,
898 label: String,
899 created_at_ms: u64,
900 #[serde(with = "serde_bytes")]
901 signing_seed: Vec<u8>,
902 }
903 let p: Persisted = codec::decode(bytes)?;
904 let seed: [u8; 32] = p
905 .signing_seed
906 .as_slice()
907 .try_into()
908 .map_err(|_| Error::Invalid("device signing seed must be 32 bytes".into()))?;
909 let signing = ed25519_dalek::SigningKey::from_bytes(&seed);
910 Ok(LocalDevice {
911 device_id: p.device_id,
912 user_id,
913 label: p.label,
914 signing,
915 created_at_ms: p.created_at_ms,
916 })
917}