Skip to main content

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}
147
148impl std::fmt::Debug for MessagingClient {
149    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150        f.debug_struct("MessagingClient")
151            .field("user_id", &self.identity.user_id().as_hex())
152            .field("device_id", &self.local_device.device_id.as_hex())
153            .field("conversation_count", &self.conversations.read().len())
154            .finish()
155    }
156}
157
158impl MessagingClient {
159    /// Initialise. Creates a new local device if none is recorded in storage; otherwise rehydrates.
160    pub async fn init(cfg: ClientConfig) -> Result<Arc<Self>> {
161        // [CR-4] OpenMLS provider is now pluggable. For `StorageBackend::Memory` this
162        // behaves like the old `OpenMlsRustCrypto::default()`. For `Sqlite`, the
163        // working set is hydrated from the on-disk blob; subsequent `checkpoint` calls
164        // flush it back. iOS NSE / web SW cold-start lives here.
165        //
166        // Use `open_async` so the WASM `StorageBackend::IndexedDb` variant can read
167        // its snapshot blob through the host-supplied `AsyncBlobStore` before
168        // returning — without this, the provider's `MemoryStorage` would be empty
169        // and `MlsGroup::load` would silently return `None` for every group on
170        // cold restart, breaking chat persistence across reloads. Native targets
171        // (Memory + Sqlite) delegate to the sync path under the hood, so the
172        // `.await` is free there.
173        let crypto = PersistentMlsProvider::open_async(cfg.storage_backend.clone())
174            .await
175            .map_err(|e| Error::Storage(format!("provider open: {e}")))?;
176        let local_device = match cfg.storage.get("device", "local").await? {
177            Some(bytes) => decode_local_device(&bytes, cfg.identity.user_id().clone())?,
178            None => {
179                // First-init path. If the host supplied a signing secret
180                // (typically to align the device_id with their auth
181                // layer), use it; otherwise mint a fresh random key.
182                // Either way, the constructed `LocalDevice` is
183                // immediately persisted so future inits load from
184                // storage without consulting the override again.
185                let dev = match cfg.device_signing_secret_key.as_ref() {
186                    Some(secret) => LocalDevice::from_signing_secret(
187                        cfg.identity.user_id().clone(),
188                        cfg.device_label,
189                        cfg.now_ms,
190                        secret,
191                    ),
192                    None => LocalDevice::generate(
193                        cfg.identity.user_id().clone(),
194                        cfg.device_label,
195                        cfg.now_ms,
196                    ),
197                };
198                let bytes = encode_local_device(&dev)?;
199                cfg.storage.put("device", "local", bytes).await?;
200                dev
201            }
202        };
203
204        // [CR-4] MLS signing keypair MUST be stable across cold restarts — otherwise the
205        // leaf-key stored on disk no longer matches the per-client key on re-init, and any
206        // send-after-restart silently misroutes. We derive deterministically from the
207        // already-persistent `LocalDevice::signing` (Ed25519, 32 raw bytes), and the
208        // ciphersuite's signature scheme is Ed25519 too — so the device signing key and the
209        // MLS leaf signing key are the same bytes. The MLS storage provider also receives
210        // a copy via `store()` so OpenMLS-internal lookups (process_message, etc.) succeed.
211        let signing = {
212            let sk_bytes = local_device.signing.to_bytes().to_vec();
213            let pk_bytes = local_device.signing.verifying_key().to_bytes().to_vec();
214            let kp = SignatureKeyPair::from_raw(
215                DEFAULT_CIPHERSUITE.signature_algorithm(),
216                sk_bytes,
217                pk_bytes,
218            );
219            kp.store(crypto.storage()).map_err(Error::mls)?;
220            Arc::new(kp)
221        };
222
223        let client = Arc::new(Self {
224            identity: cfg.identity,
225            local_device,
226            crypto,
227            signing,
228            storage: cfg.storage,
229            transport: cfg.transport,
230            conversations: RwLock::new(HashMap::new()),
231        });
232
233        client.rehydrate_conversations(cfg.now_ms).await?;
234
235        // [CR-10] Ensure the DeviceGroup exists at init, not lazily inside
236        // build_linking_ticket. Single-device users need somewhere to write
237        // personal events (drafts, read pointers, notes, vault wrapper)
238        // even before they pair a second device. Lazy creation in
239        // build_linking_ticket left them with no DG → no place for
240        // personal state to land.
241        //
242        // Idempotent — re-init after a cold restart finds the DG via
243        // rehydrate_conversations and this becomes a no-op.
244        client.ensure_device_group(cfg.now_ms).await?;
245
246        Ok(client)
247    }
248
249    /// [CR-10] Idempotently ensures this user's DeviceGroup exists in
250    /// `self.conversations`. Called from `init` (so single-device users
251    /// have a DG immediately) and from `build_linking_ticket` (the legacy
252    /// lazy path; still safe to call when the DG already exists, since
253    /// rehydrate_conversations would have re-attached it before init
254    /// returned).
255    ///
256    /// The DeviceGroup is a one-leaf MLS group at creation time —
257    /// `add_members` (called by `build_linking_ticket` when a second
258    /// device pairs in) is what grows it. We persist the snapshot so a
259    /// cold restart picks it up before this function runs again.
260    pub(crate) async fn ensure_device_group(self: &Arc<Self>, now_ms: u64) -> Result<()> {
261        let dg_id = device_group_id_for(self.identity.user_id());
262        if self.conversations.read().contains_key(&dg_id) {
263            return Ok(());
264        }
265        let mut new_dg = Conversation::create(
266            dg_id,
267            Some("device-group".into()),
268            self.local_device.device_id.clone(),
269            self.identity.user_id(),
270            self.crypto.clone(),
271            self.signing.clone(),
272            self.storage.clone(),
273            now_ms,
274        )?;
275        new_dg.meta.is_device_group = true;
276        new_dg.snapshot_to_storage().await?;
277        self.conversations.write().insert(dg_id, new_dg);
278        Ok(())
279    }
280
281    pub fn user_id(&self) -> UserId {
282        self.identity.user_id().clone()
283    }
284    pub fn device_id(&self) -> DeviceId {
285        self.local_device.device_id.clone()
286    }
287    pub fn device_info(&self, now_ms: u64) -> DeviceInfo {
288        self.local_device.info(now_ms)
289    }
290
291    /// Generate a fresh KeyPackage to publish to the directory. Hosts call this when registering
292    /// a device or topping up the directory.
293    ///
294    /// `build()` writes the private init + encryption keys into the storage
295    /// provider's working set, but ON ITS OWN that write is NOT durable: on the
296    /// WASM/AsyncBlob backend the working set only reaches IndexedDB at the next
297    /// `checkpoint_async`, so a page reload before the next state-changing op
298    /// loses the private keys while the PUBLIC KeyPackage has already been
299    /// published. Any Welcome later bound to that KeyPackage then fails with
300    /// "No matching key package was found in the key store" (breaking calls and
301    /// every invite to this device). So we checkpoint HERE, before returning the
302    /// bytes the host will publish — the published KeyPackage is durable the
303    /// instant it leaves this function. Hence `async`.
304    pub async fn fresh_key_package(&self) -> Result<Vec<u8>> {
305        let credential_with_key = CredentialWithKey {
306            credential: BasicCredential::new(self.identity.user_id().0.clone()).into(),
307            signature_key: self.signing.public().to_vec().into(),
308        };
309        let bundle = KeyPackageBuilder::new()
310            .build(
311                DEFAULT_CIPHERSUITE,
312                self.crypto.as_ref(),
313                self.signing.as_ref(),
314                credential_with_key,
315            )
316            .map_err(Error::mls)?;
317        // Durably persist the freshly-generated private keys BEFORE the public
318        // KeyPackage is handed to the host to publish (see doc comment).
319        self.crypto
320            .checkpoint_async()
321            .await
322            .map_err(|e| Error::Storage(format!("key package checkpoint: {e}")))?;
323        // KeyPackages are serialized as MlsMessage(KeyPackage) per the MLS framing spec.
324        let msg: MlsMessageOut = bundle.key_package().clone().into();
325        msg.tls_serialize_detached().map_err(Error::mls)
326    }
327
328    /// Create a new conversation owned by this client (and seeded with a single member: this device).
329    pub async fn create_conversation(
330        self: &Arc<Self>,
331        name: Option<String>,
332        now_ms: u64,
333    ) -> Result<ConversationId> {
334        let id = ConversationId::new();
335        let convo = Conversation::create(
336            id,
337            name,
338            self.local_device.device_id.clone(),
339            self.identity.user_id(),
340            self.crypto.clone(),
341            self.signing.clone(),
342            self.storage.clone(),
343            now_ms,
344        )?;
345        convo.snapshot_to_storage().await?;
346        self.conversations.write().insert(id, convo);
347        Ok(id)
348    }
349
350    /// Join via a Welcome bundled in a [`MessageEnvelope`] of kind `Welcome`.
351    pub async fn join_conversation(
352        self: &Arc<Self>,
353        welcome_envelope: &MessageEnvelope,
354        now_ms: u64,
355    ) -> Result<ConversationId> {
356        if welcome_envelope.kind != MessageKind::Welcome {
357            return Err(Error::Invalid("expected Welcome envelope".into()));
358        }
359        let convo = Conversation::join(
360            &welcome_envelope.payload,
361            self.local_device.device_id.clone(),
362            self.crypto.clone(),
363            self.signing.clone(),
364            self.storage.clone(),
365            now_ms,
366        )?;
367        let id = convo.id();
368        convo.snapshot_to_storage().await?;
369        self.conversations.write().insert(id, convo);
370        Ok(id)
371    }
372
373    pub fn list_conversations(&self) -> Vec<ConversationMeta> {
374        self.conversations
375            .read()
376            .values()
377            .map(|c| c.meta.clone())
378            .collect()
379    }
380
381    /// Member roster for a conversation, recovered locally from the MLS
382    /// group's leaf credentials. Empty if the conversation is unknown to
383    /// this client. Lets any device (including one that just joined via a
384    /// linking Welcome) resolve a 1:1 peer's `UserId` without the
385    /// out-of-band `ping.profile` re-send.
386    pub fn members(&self, conv_id: ConversationId) -> Vec<MemberInfo> {
387        self.conversations
388            .read()
389            .get(&conv_id)
390            .map(|c| c.members())
391            .unwrap_or_default()
392    }
393
394    /// Send an application message. Returns once the envelope has been handed to the transport.
395    pub async fn send(
396        &self,
397        conv_id: ConversationId,
398        plaintext: Vec<u8>,
399        now_ms: u64,
400    ) -> Result<MessageEnvelope> {
401        let envelope = {
402            let mut guard = self.conversations.write();
403            let convo = guard
404                .get_mut(&conv_id)
405                .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
406            convo.send_application(&plaintext, now_ms)?
407        };
408        self.transport.send(envelope.clone()).await?;
409        // The OpenMLS sender ratchet advances on every Application message — `seq` + `hlc`
410        // are bumped on the conversation, and the underlying group keystore stores new
411        // generation keys. Without a checkpoint here, a reload rolls back to the pre-send
412        // state and the next send re-uses an already-consumed generation that receivers
413        // silently drop. Mirrors the snapshot calls after every Commit/Welcome op.
414        //
415        // Capture the snapshot inputs UNDER the read guard, then DROP the
416        // guard (end of the `let` statement) before the async flush — never
417        // hold a `parking_lot` guard across `.await` (see
418        // `Conversation::snapshot_inputs`).
419        let snap = self
420            .conversations
421            .read()
422            .get(&conv_id)
423            .map(|c| c.snapshot_inputs())
424            .transpose()?;
425        if let Some(snap) = snap {
426            snap.flush().await?;
427        }
428        Ok(envelope)
429    }
430
431    /// Add members. The Commit goes on the wire; the Welcome should be delivered to the new
432    /// devices' inboxes (the host transport implements that — typically as a separate addressed
433    /// envelope).
434    ///
435    /// [CR-2] Each entry is `(DeviceId, KeyPackage_bytes)`. The host typically gets the
436    /// device_id from the directory at the same time it gets the KeyPackage; we use it to
437    /// record a per-conversation `device_id → leaf_index` map so [`Self::revoke_device`]
438    /// can later locate the leaf without a fresh directory lookup. The SDK does not
439    /// cryptographically verify the host's device-id claim — that's a directory policy
440    /// concern.
441    //
442    // The `conversations` lock is taken only for the SYNCHRONOUS MLS work
443    // (the add commit) and the synchronous snapshot capture, then dropped
444    // BEFORE every `.await`. We must never hold a `parking_lot` guard
445    // across an await — see `Conversation::snapshot_inputs` for why (the
446    // single-threaded wasm worker would panic in `parking_lot`'s parker
447    // stub). `parking_lot/send_guard` is still set so any guard that DOES
448    // briefly cross a yield-free boundary stays `Send`.
449    pub async fn add_members(
450        &self,
451        conv_id: ConversationId,
452        entries: Vec<(DeviceId, Vec<u8>)>,
453        now_ms: u64,
454    ) -> Result<()> {
455        // Phase 1 — stage the Commit WITHOUT merging (local epoch unchanged).
456        let staged = {
457            let mut guard = self.conversations.write();
458            let convo = guard
459                .get_mut(&conv_id)
460                .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
461            convo.stage_add_members(entries, now_ms)?
462        };
463
464        // Phase 2 — send the Commit FIRST, then merge only if the server accepts
465        // it (send-then-merge). A Commit the server REJECTS is rolled back, so the
466        // local epoch can never run ahead of the server — the desync that
467        // permanently bricks a group (every later Commit 409s; peers can't decrypt
468        // our epoch). A network failure with NO response is ambiguous (the server
469        // may have applied it), so there we merge to match a possible masked
470        // success rather than strand ourselves a step behind.
471        if let Err(send_err) = self.transport.send(staged.commit.clone()).await {
472            let merged = {
473                let mut guard = self.conversations.write();
474                match guard.get_mut(&conv_id) {
475                    Some(convo) if is_definite_rejection(&send_err) => {
476                        let _ = convo.abort_staged();
477                        false
478                    }
479                    Some(convo) => {
480                        convo.confirm_staged(&staged, now_ms)?;
481                        true
482                    }
483                    None => false,
484                }
485            };
486            if merged {
487                self.flush_conversation(&conv_id).await?;
488            }
489            return Err(send_err);
490        }
491
492        // Phase 3 — Commit accepted: merge locally + persist (so the advanced
493        // epoch survives a crash even if the Welcome below fails).
494        {
495            let mut guard = self.conversations.write();
496            let convo = guard
497                .get_mut(&conv_id)
498                .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
499            convo.confirm_staged(&staged, now_ms)?;
500        }
501        self.flush_conversation(&conv_id).await?;
502
503        // Phase 4 — deliver the Welcome to the new members. Best-effort: they are
504        // in the group server-side now; a failed Welcome is recoverable
505        // (re-invite) and must NOT roll back the merged Commit.
506        if let Some(welcome) = staged.welcome {
507            self.transport.send(welcome).await?;
508        }
509        Ok(())
510    }
511
512    /// Snapshot + flush a conversation's persistable state. Captures the snapshot
513    /// synchronously under the read guard, drops the guard, then awaits the flush
514    /// (never hold a `parking_lot` guard across an await — wasm parker panics).
515    async fn flush_conversation(&self, conv_id: &ConversationId) -> Result<()> {
516        let snap = self
517            .conversations
518            .read()
519            .get(conv_id)
520            .map(|c| c.snapshot_inputs())
521            .transpose()?;
522        if let Some(snap) = snap {
523            snap.flush().await?;
524        }
525        Ok(())
526    }
527
528    /// Admits `new_device_id` to every conversation in `kps_per_chat` via
529    /// the standard MLS `add_members` flow — one Commit + one Welcome per
530    /// chat. This is the SDK-side replacement for the host's previous
531    /// per-chat reconciler loop after device linking; centralising it
532    /// here means iOS/Android/web hosts all share the orchestration and
533    /// the transport's Welcome-recipient priming is automatic.
534    ///
535    /// Inputs:
536    /// - `new_device_id`: the device being admitted (matches the
537    ///   `device_binding_sig` recipient in the linking ticket).
538    /// - `kps_per_chat`: one freshly-claimed KeyPackage per chat. The
539    ///   host claims these via the auth-layer's per-account KP pool
540    ///   (`GET /v1/devices/{accountId}`) AFTER the new device's
541    ///   bootstrap has uploaded its KP batch.
542    /// - `now_ms`: wall-clock used to stamp HLCs on the emitted
543    ///   envelopes.
544    ///
545    /// Per-chat failures (unknown conversation, MLS error, transport
546    /// error, etc.) are CAPTURED in the returned vec rather than
547    /// short-circuiting the whole call — losing one chat shouldn't
548    /// strand the new device on every other chat. The caller decides
549    /// whether to retry the failed entries (e.g. with a fresh KP).
550    pub async fn admit_device_to_chats(
551        &self,
552        new_device_id: DeviceId,
553        kps_per_chat: Vec<(ConversationId, Vec<u8>)>,
554        now_ms: u64,
555    ) -> Result<Vec<AdmitChatOutcome>> {
556        let mut outcomes = Vec::with_capacity(kps_per_chat.len());
557        for (conv_id, kp_bytes) in kps_per_chat {
558            // Belt-and-braces: skip the DeviceGroup. The DG was already
559            // welcomed via the linking ticket — re-adding the new
560            // device there would produce a duplicate-add Commit that
561            // BE de-dups, but the noise is avoidable.
562            let is_dg = self
563                .conversations
564                .read()
565                .get(&conv_id)
566                .map(|c| c.meta().is_device_group)
567                .unwrap_or(false);
568            if is_dg {
569                outcomes.push(AdmitChatOutcome {
570                    conversation_id: conv_id,
571                    status: AdmitChatStatus::Skipped {
572                        reason: "device_group".to_string(),
573                    },
574                });
575                continue;
576            }
577
578            // Prime the host transport with the welcome recipient BEFORE
579            // we mutate MLS state. If priming fails (non-web hosts use
580            // the default no-op), continue — the host's transport will
581            // either route some other way or surface a 4xx on the
582            // welcome send and we'll catch it below.
583            let _ = self
584                .transport
585                .set_next_welcome_recipients(conv_id, vec![new_device_id.clone()])
586                .await;
587
588            let entry = (new_device_id.clone(), kp_bytes);
589            let outcome_result = {
590                let mut guard = self.conversations.write();
591                match guard.get_mut(&conv_id) {
592                    Some(convo) => convo.add_members(vec![entry], now_ms),
593                    None => Err(Error::UnknownConversation(conv_id.as_hex())),
594                }
595            };
596
597            let outcome = match outcome_result {
598                Ok(o) => o,
599                Err(e) => {
600                    outcomes.push(AdmitChatOutcome {
601                        conversation_id: conv_id,
602                        status: AdmitChatStatus::Failed {
603                            error: e.to_string(),
604                        },
605                    });
606                    continue;
607                }
608            };
609
610            if let Err(e) = self.transport.send(outcome.commit).await {
611                outcomes.push(AdmitChatOutcome {
612                    conversation_id: conv_id,
613                    status: AdmitChatStatus::Failed {
614                        error: format!("commit send: {e}"),
615                    },
616                });
617                continue;
618            }
619            if let Err(e) = self.transport.send(outcome.welcome).await {
620                outcomes.push(AdmitChatOutcome {
621                    conversation_id: conv_id,
622                    status: AdmitChatStatus::Failed {
623                        error: format!("welcome send: {e}"),
624                    },
625                });
626                continue;
627            }
628
629            // Capture the snapshot under the read guard, drop it, then
630            // flush async (never hold the lock across `.await`).
631            let snap_result = self
632                .conversations
633                .read()
634                .get(&conv_id)
635                .map(|c| c.snapshot_inputs())
636                .transpose();
637            let flush_result = match snap_result {
638                Ok(Some(snap)) => snap.flush().await,
639                Ok(None) => Ok(()),
640                Err(e) => Err(e),
641            };
642            if let Err(e) = flush_result {
643                // Snapshot failure is non-fatal for the join — the MLS adds
644                // already shipped — but record it so the host can decide
645                // whether to retry. The next successful send/process will
646                // re-snapshot anyway.
647                outcomes.push(AdmitChatOutcome {
648                    conversation_id: conv_id,
649                    status: AdmitChatStatus::Failed {
650                        error: format!("snapshot: {e}"),
651                    },
652                });
653                continue;
654            }
655
656            outcomes.push(AdmitChatOutcome {
657                conversation_id: conv_id,
658                status: AdmitChatStatus::Admitted,
659            });
660        }
661        Ok(outcomes)
662    }
663
664    pub async fn remove_members(
665        &self,
666        conv_id: ConversationId,
667        leaf_indexes: Vec<u32>,
668        now_ms: u64,
669    ) -> Result<()> {
670        // Send-then-merge — see `add_members` for the full rationale.
671        let staged = {
672            let mut guard = self.conversations.write();
673            let convo = guard
674                .get_mut(&conv_id)
675                .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
676            convo.stage_remove_members(leaf_indexes, now_ms)?
677        };
678
679        if let Err(send_err) = self.transport.send(staged.commit.clone()).await {
680            let merged = {
681                let mut guard = self.conversations.write();
682                match guard.get_mut(&conv_id) {
683                    Some(convo) if is_definite_rejection(&send_err) => {
684                        let _ = convo.abort_staged();
685                        false
686                    }
687                    Some(convo) => {
688                        convo.confirm_staged(&staged, now_ms)?;
689                        true
690                    }
691                    None => false,
692                }
693            };
694            if merged {
695                self.flush_conversation(&conv_id).await?;
696            }
697            return Err(send_err);
698        }
699
700        {
701            let mut guard = self.conversations.write();
702            let convo = guard
703                .get_mut(&conv_id)
704                .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
705            convo.confirm_staged(&staged, now_ms)?;
706        }
707        self.flush_conversation(&conv_id).await?;
708        Ok(())
709    }
710
711    /// Process an inbound envelope coming from the transport's subscribe callback or a sync pull.
712    /// Returns `Some` for application traffic, `None` for handshake messages (already merged).
713    pub async fn process_envelope(
714        &self,
715        env: &MessageEnvelope,
716        now_ms: u64,
717    ) -> Result<Option<IncomingMessage>> {
718        // Welcome envelopes for unknown conversations are routed to `join_conversation` by the
719        // caller. Here we only handle traffic for already-open groups.
720        //
721        // Do the MLS processing AND capture the snapshot synchronously
722        // under the write guard, then DROP the guard before the async
723        // flush. Previously the write guard was held across
724        // `snapshot_to_storage().await`; on the single-threaded wasm
725        // worker a concurrent `list_conversations()` (or any reader) that
726        // landed while a writer was waiting made `parking_lot` park →
727        // panic "Parking not supported". This is the method the crash
728        // stack pointed at (sync / Welcome ingestion).
729        let (out, snap) = {
730            let mut guard = self.conversations.write();
731            let convo = match guard.get_mut(&env.conversation_id) {
732                Some(c) => c,
733                None => return Err(Error::UnknownConversation(env.conversation_id.as_hex())),
734            };
735            let out = convo.process(env, now_ms)?;
736            // Cheap snapshot — only mutates KV the size of the cursor.
737            let snap = convo.snapshot_inputs()?;
738            (out, snap)
739        };
740        snap.flush().await?;
741        Ok(out)
742    }
743
744    /// Catch-up sync: pull missing events for every open conversation since its cursor.
745    /// Returns the list of newly-decrypted application messages, in apply order.
746    pub async fn sync_conversations(&self, now_ms: u64) -> Result<Vec<IncomingMessage>> {
747        let pending: Vec<(ConversationId, SyncCursor)> = self
748            .conversations
749            .read()
750            .iter()
751            .map(|(id, c)| (*id, c.cursor.clone()))
752            .collect();
753
754        let mut delivered = Vec::new();
755        for (conv_id, cursor) in pending {
756            loop {
757                let batch = self
758                    .transport
759                    .fetch_since(conv_id, cursor.clone(), 256)
760                    .await?;
761                if batch.is_empty() {
762                    break;
763                }
764                for env in &batch {
765                    if let Some(msg) = self.process_envelope(env, now_ms).await? {
766                        delivered.push(msg);
767                    }
768                }
769                if batch.len() < 256 {
770                    break;
771                } // partial page → caught up
772            }
773        }
774        Ok(delivered)
775    }
776
777    /// Rehydrate conversations from storage on startup ([CR-4]).
778    ///
779    /// Walks the host-side `groups` namespace for meta records, pairs each with its
780    /// cursor + device→leaf map, and asks `Conversation::load` to re-attach to the
781    /// underlying OpenMLS group state. The MLS state itself was persisted by the
782    /// SQLite-backed `PersistentMlsProvider` on the previous run; this method
783    /// reconciles the SDK-side caches with what's on disk.
784    async fn rehydrate_conversations(self: &Arc<Self>, now_ms: u64) -> Result<()> {
785        let metas = self.storage.list_keys("groups", "").await?;
786        for path in metas {
787            // path looks like "{convId}/meta"
788            let Some((id_hex, suffix)) = path.split_once('/') else {
789                continue;
790            };
791            if suffix != "meta" {
792                continue;
793            }
794            let Some(meta_bytes) = self.storage.get("groups", &path).await? else {
795                continue;
796            };
797            let meta: ConversationMeta = match codec::decode(&meta_bytes) {
798                Ok(m) => m,
799                Err(_) => continue,
800            };
801            let cursor_bytes = self
802                .storage
803                .get("cursors", id_hex)
804                .await?
805                .unwrap_or_default();
806            let cursor = if cursor_bytes.is_empty() {
807                SyncCursor::default()
808            } else {
809                SyncCursor::decode(&cursor_bytes).unwrap_or_default()
810            };
811
812            // [CR-2] device→leaf map was persisted alongside meta + cursor.
813            let device_leaves_bytes = self
814                .storage
815                .get("device_leaves", id_hex)
816                .await?
817                .unwrap_or_default();
818            let device_leaves: std::collections::BTreeMap<DeviceId, u32> =
819                if device_leaves_bytes.is_empty() {
820                    std::collections::BTreeMap::new()
821                } else {
822                    let pairs: Vec<(DeviceId, u32)> =
823                        codec::decode(&device_leaves_bytes).unwrap_or_default();
824                    pairs.into_iter().collect()
825                };
826
827            match Conversation::load(
828                meta.id,
829                meta.clone(),
830                cursor,
831                device_leaves,
832                self.local_device.device_id.clone(),
833                self.crypto.clone(),
834                self.signing.clone(),
835                self.storage.clone(),
836                now_ms,
837            ) {
838                Ok(Some(convo)) => {
839                    tracing::debug!(
840                        target: "ping_core::client",
841                        convo = %id_hex,
842                        epoch = meta.epoch,
843                        "rehydrated conversation from disk"
844                    );
845                    self.conversations.write().insert(meta.id, convo);
846                }
847                Ok(None) => {
848                    tracing::warn!(
849                        target: "ping_core::client",
850                        convo = %id_hex,
851                        "host-side meta present but OpenMLS state missing — skipping"
852                    );
853                }
854                Err(e) => {
855                    tracing::warn!(
856                        target: "ping_core::client",
857                        convo = %id_hex,
858                        error = %e,
859                        "Conversation::load failed — skipping"
860                    );
861                }
862            }
863        }
864        Ok(())
865    }
866
867    // ------------------- Multi-device API -------------------
868
869    /// Build a [`LinkingTicket`] for a new device. The caller obtains `new_device_kp` from the
870    /// new device (e.g., via QR-encoded handshake) and is responsible for sealing the returned
871    /// ticket against the new device's ephemeral X25519 pubkey before transmission via
872    /// [`ping_link::seal_ticket`].
873    ///
874    /// [CR-13] `last_app_events` is a host-supplied list of `(conversation_id, app_event_bytes)`
875    /// for the new device's "what you missed" UI. The SDK adds its own metas + (currently-
876    /// empty) per-conversation MLS state and bundles everything into
877    /// [`device::CatchupSnapshot`], CBOR-encoded into the ticket's `catchup_snapshot` field.
878    /// Pass an empty `Vec` to suppress catchup data (the new device sees an empty
879    /// conversation list until normal sync runs).
880    pub async fn build_linking_ticket(
881        self: &Arc<Self>,
882        new_device_id: DeviceId,
883        new_device_kp: Vec<u8>,
884        last_app_events: Vec<(ConversationId, Vec<u8>)>,
885        now_ms: u64,
886    ) -> Result<LinkingTicket> {
887        let device_binding_sig = self.identity.sign_device_binding(&new_device_id.0);
888        let dg_id = device_group_id_for(self.identity.user_id());
889
890        // [CR-10] DG is eagerly created at init now, but call ensure here too so
891        // hosts that bypass `MessagingClient::init` (mocked tests, legacy upgrade
892        // paths) keep working.
893        self.ensure_device_group(now_ms).await?;
894
895        // Admit the new device to the DeviceGroup.
896        let outcome = {
897            let mut conversations = self.conversations.write();
898            let dg = conversations
899                .get_mut(&dg_id)
900                .expect("DeviceGroup ensured above");
901            // [CR-2] Record the new device's leaf in the DG so future `revoke_device`
902            // can find it. The new_device_id we got as a parameter is the inviter's
903            // own assertion — same trust model as the rest of `add_members`.
904            dg.add_members(vec![(new_device_id.clone(), new_device_kp)], now_ms)?
905        };
906
907        // [CR-13] Assemble the catchup snapshot: SDK-known conversation metadata + host-
908        // supplied last-known plaintext per conversation. [CR-7] now populates
909        // `group_state_bytes` with each group's MLS state so the new device can decrypt
910        // historical traffic without re-Welcoming. An empty `group_state_bytes` would
911        // mean either a group with no exportable state (shouldn't happen) or an
912        // encoder failure (we let those propagate as errors below).
913        let catchup_snapshot = if last_app_events.is_empty() && self.conversations.read().is_empty()
914        {
915            // Cheap path: nothing to snapshot, skip the encode round-trip.
916            Vec::new()
917        } else {
918            let conversation_metas: Vec<CatchupConversationEntry> = self
919                .conversations
920                .read()
921                .values()
922                .map(|c| -> Result<CatchupConversationEntry> {
923                    // CR-7: per-group state. We deliberately keep the export bytes
924                    // inside the (HPKE-sealed-by-CR-3) LinkingTicket; the receiver
925                    // calls `import_state_snapshot` with these bytes after `consume_linking_ticket`.
926                    let group_bytes = c.export_state_snapshot(now_ms)?.to_vec();
927                    Ok(CatchupConversationEntry {
928                        conversation_id: c.id(),
929                        meta: c.meta().clone(),
930                        group_state_bytes: group_bytes,
931                    })
932                })
933                .collect::<Result<_>>()?;
934            let last_app_events_per_conv: Vec<CatchupAppEventEntry> = last_app_events
935                .into_iter()
936                .map(|(conversation_id, app_event_bytes)| CatchupAppEventEntry {
937                    conversation_id,
938                    app_event_bytes,
939                })
940                .collect();
941            CatchupSnapshot {
942                v: CATCHUP_SNAPSHOT_VERSION,
943                conversation_metas,
944                last_app_events_per_conv,
945            }
946            .encode()?
947        };
948
949        Ok(LinkingTicket {
950            v: 1,
951            user_id: self.identity.user_id().clone(),
952            user_pubkey: self.identity.public_key().to_bytes().to_vec(),
953            new_device_id,
954            device_binding_sig,
955            device_group_welcome: outcome.welcome.payload,
956            catchup_snapshot,
957        })
958    }
959
960    /// Apply a received linking ticket. Joins the user's DeviceGroup; the catch-up snapshot
961    /// (if any) is decrypted by the host using the standard per-conversation channel afterwards.
962    pub async fn consume_linking_ticket(
963        self: &Arc<Self>,
964        ticket: &LinkingTicket,
965        now_ms: u64,
966    ) -> Result<()> {
967        // Verify the binding the existing device made for us. (Ed25519 public keys are 32 bytes.)
968        let pk_bytes: [u8; 32] = ticket
969            .user_pubkey
970            .as_slice()
971            .try_into()
972            .map_err(|_| Error::Identity("user_pubkey must be 32 bytes".into()))?;
973        let user_pk = ed25519_dalek::VerifyingKey::from_bytes(&pk_bytes)
974            .map_err(|e| Error::Identity(format!("bad user pubkey: {e}")))?;
975        Identity::verify_device_binding(
976            &user_pk,
977            &ticket.user_id,
978            &ticket.new_device_id.0,
979            &ticket.device_binding_sig,
980        )?;
981        if ticket.new_device_id != self.local_device.device_id {
982            return Err(Error::Invalid(
983                "ticket addressed to a different device".into(),
984            ));
985        }
986
987        let dummy_env = MessageEnvelope::new(
988            ConversationId(device_group_id_for(&ticket.user_id).0),
989            0,
990            MessageKind::Welcome,
991            self.local_device.device_id.clone(),
992            0,
993            crate::clock::Hlc::ZERO,
994            ticket.device_group_welcome.clone(),
995        );
996        self.join_conversation(&dummy_env, now_ms).await?;
997        Ok(())
998    }
999
1000    /// [CR-7] Export the MLS state snapshot for one open conversation.
1001    ///
1002    /// Thin pass-through to [`Conversation::export_state_snapshot`]. Returned bytes
1003    /// are wrapped in `Zeroizing` because they contain past epoch secrets.
1004    pub fn export_conversation_state_snapshot(
1005        &self,
1006        conv_id: ConversationId,
1007        now_ms: u64,
1008    ) -> Result<zeroize::Zeroizing<Vec<u8>>> {
1009        let guard = self.conversations.read();
1010        let convo = guard
1011            .get(&conv_id)
1012            .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
1013        convo.export_state_snapshot(now_ms)
1014    }
1015
1016    /// [CR-7] Import a `GroupStateSnapshot` produced by another device's
1017    /// [`Conversation::export_state_snapshot`].
1018    ///
1019    /// Replays the snapshot's entries into this client's OpenMLS provider, then
1020    /// reconstructs the `Conversation` handle via `MlsGroup::load`. After return,
1021    /// the conversation is in `list_conversations()` and `send`/`process_envelope`
1022    /// work against it normally.
1023    ///
1024    /// **Scope.** This is for the *same-user* hand-off (linking, recovery). The
1025    /// snapshot exposes the exporter's view of past epoch secrets for the target
1026    /// group; only call this when the receiving device has been authenticated to
1027    /// the same user identity (mnemonic, QR-handshake). Cross-user history transfer
1028    /// uses HPKE-sealed AppEvent re-shares (umbrella §15.6), not this method.
1029    ///
1030    /// **Sanity.** Refuses snapshots whose `group_id` doesn't match the bytes the
1031    /// receiver intends to claim — guards against host bugs that shuffle snapshots
1032    /// between groups. Refuses mismatched OpenMLS storage versions outright; no
1033    /// silent forward/back compatibility.
1034    pub async fn import_state_snapshot(
1035        self: &Arc<Self>,
1036        snapshot_bytes: &[u8],
1037        now_ms: u64,
1038    ) -> Result<ConversationId> {
1039        use crate::device::GroupStateSnapshot;
1040        let snap = GroupStateSnapshot::decode(snapshot_bytes)
1041            .map_err(|e| Error::Invalid(format!("snapshot decode: {e}")))?;
1042
1043        if snap.openmls_storage_version != openmls_traits::storage::CURRENT_VERSION {
1044            return Err(Error::Invalid(format!(
1045                "snapshot openmls_storage_version={} not supported (this SDK supports v={})",
1046                snap.openmls_storage_version,
1047                openmls_traits::storage::CURRENT_VERSION
1048            )));
1049        }
1050
1051        let conv_id = snap.group_id;
1052
1053        // Refuse if we already have an active handle for this conv — the host should
1054        // close it first, otherwise import silently overwrites in-memory state and
1055        // the existing handle becomes stale.
1056        if self.conversations.read().contains_key(&conv_id) {
1057            return Err(Error::Invalid(format!(
1058                "conversation {} already open; close before importing snapshot",
1059                conv_id.as_hex()
1060            )));
1061        }
1062
1063        // Replay raw KV pairs into the provider's working set.
1064        let entries: Vec<(Vec<u8>, Vec<u8>)> =
1065            snap.entries.into_iter().map(|e| (e.key, e.value)).collect();
1066        self.crypto
1067            .import_entries(entries)
1068            .map_err(|e| Error::Storage(format!("import entries: {e}")))?;
1069
1070        // Reconstruct the Conversation handle. `Conversation::load` will return
1071        // `Ok(None)` if OpenMLS still can't find the group — i.e. our snapshot was
1072        // incomplete or for a different storage version.
1073        let meta = ConversationMeta {
1074            id: conv_id,
1075            name: None,
1076            epoch: 0, // will be overwritten from the loaded group state in process()
1077            member_count: 0,
1078            is_device_group: false, // host can flip this via meta update if needed
1079            created_at_ms: now_ms,
1080        };
1081        let convo = Conversation::load(
1082            conv_id,
1083            meta,
1084            SyncCursor::default(),
1085            std::collections::BTreeMap::new(),
1086            self.local_device.device_id.clone(),
1087            self.crypto.clone(),
1088            self.signing.clone(),
1089            self.storage.clone(),
1090            now_ms,
1091        )?
1092        .ok_or_else(|| {
1093            Error::Invalid(
1094                "snapshot imported but OpenMLS could not load the group — snapshot may be incomplete or storage version mismatched"
1095                    .into(),
1096            )
1097        })?;
1098
1099        // Pull the live epoch + member count from the loaded group so the meta we
1100        // just stubbed is consistent with what we'll observe on subsequent process_envelope.
1101        let live_epoch = convo.epoch();
1102        let live_members = convo.group.members().count() as u32;
1103        let mut convo = convo;
1104        convo.meta.epoch = live_epoch;
1105        convo.meta.member_count = live_members;
1106        convo.snapshot_to_storage().await?;
1107
1108        self.conversations.write().insert(conv_id, convo);
1109        Ok(conv_id)
1110    }
1111
1112    /// Export a derived secret from one conversation's MLS exporter ([CR-8]).
1113    ///
1114    /// Thin pass-through to [`Conversation::export_secret`]. See that method's doc comment
1115    /// for the contract on `label`, `context`, length validation, and zeroization. The
1116    /// returned `Zeroizing<Vec<u8>>` is automatically wiped when dropped.
1117    pub fn export_conversation_secret(
1118        &self,
1119        conv_id: ConversationId,
1120        label: &str,
1121        context: &[u8],
1122        length: usize,
1123    ) -> Result<Zeroizing<Vec<u8>>> {
1124        let guard = self.conversations.read();
1125        let convo = guard
1126            .get(&conv_id)
1127            .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
1128        convo.export_secret(label, context, length)
1129    }
1130
1131    /// Revoke a device by removing its leaf from every conversation where we know its
1132    /// position ([CR-2]).
1133    ///
1134    /// Returns one Commit envelope per conversation the device was a leaf in. The host
1135    /// broadcasts each envelope to the affected conversation; the SDK has also already
1136    /// handed them to the transport via `transport.send` (idempotent broadcast is the
1137    /// host's call).
1138    ///
1139    /// **Scope.** The SDK can only resolve leaves it recorded itself — either when it
1140    /// admitted the device via [`Self::add_members`] or when this device joined as the
1141    /// target via Welcome. For peer-admitted devices the leaf index isn't locally known;
1142    /// those conversations are silently skipped. The host can fall back to
1143    /// `remove_members(leaf_index)` directly using a transport-side directory lookup if
1144    /// it needs to revoke from those conversations too. See
1145    /// `docs/architecture/multi-device.md §Device removal` for the broader flow.
1146    ///
1147    /// Conversations with no entry for `device_id` produce no envelope; an empty `Vec`
1148    /// return is a valid outcome (e.g. the device was already revoked, or was never
1149    /// added by this client).
1150    #[allow(clippy::await_holding_lock)] // see add_members for rationale
1151    pub async fn revoke_device(
1152        &self,
1153        device_id: DeviceId,
1154        now_ms: u64,
1155    ) -> Result<Vec<MessageEnvelope>> {
1156        // 1. Walk every open conversation and gather (conv_id, leaf_index) pairs where
1157        //    we know `device_id` controls a leaf. Done under a read lock so we don't hold
1158        //    the write lock across the per-conversation remove path.
1159        let targets: Vec<(ConversationId, u32)> = self
1160            .conversations
1161            .read()
1162            .iter()
1163            .filter_map(|(id, c)| c.leaf_index_of(&device_id).map(|leaf| (*id, leaf)))
1164            .collect();
1165
1166        // 2. For each target, emit a remove_members commit. We do this sequentially: each
1167        //    one is a separate MLS epoch advance on its own group, and they don't share
1168        //    state, so parallel issuance is safe but adds complexity we don't need for v1.
1169        let mut envelopes = Vec::with_capacity(targets.len());
1170        for (conv_id, leaf_index) in targets {
1171            let envelope = {
1172                let mut guard = self.conversations.write();
1173                let convo = guard
1174                    .get_mut(&conv_id)
1175                    .ok_or_else(|| Error::UnknownConversation(conv_id.as_hex()))?;
1176                convo.remove_members(vec![leaf_index], now_ms)?
1177            };
1178            self.transport.send(envelope.clone()).await?;
1179            if let Some(c) = self.conversations.read().get(&conv_id) {
1180                c.snapshot_to_storage().await?;
1181            }
1182            envelopes.push(envelope);
1183        }
1184
1185        // 3. Notify the auth-layer server so it can invalidate the
1186        //    revoked device's KeyPackage pool, mark `auth.devices.revoked_at`,
1187        //    and refuse any future envelope signed by the revoked device's
1188        //    JWT. Done AFTER the MLS Commits so peers learn via MLS first
1189        //    (the canonical path) and the auth layer is the eventual-
1190        //    consistency cleanup. Transport failures bubble up so callers
1191        //    can retry — but the MLS-side work has already shipped, so
1192        //    the device is functionally revoked in every group; only the
1193        //    auth-layer KeyPackage purge is pending.
1194        self.transport.revoke_device_remote(device_id).await?;
1195        Ok(envelopes)
1196    }
1197}
1198
1199fn device_group_id_for(user_id: &UserId) -> ConversationId {
1200    // Deterministic 16-byte ID derived from the user's id, prefixed so it cannot collide with
1201    // a randomly-generated ULID in normal use (ULIDs start with a millisecond timestamp).
1202    let mut bytes = [0u8; 16];
1203    bytes[0] = 0xFF;
1204    bytes[1] = 0xDC; // "DeviCe" group sentinel
1205    let h = codec::sha256(&user_id.0);
1206    bytes[2..].copy_from_slice(&h[..14]);
1207    ConversationId(bytes)
1208}
1209
1210fn encode_local_device(d: &LocalDevice) -> Result<Vec<u8>> {
1211    use serde::Serialize;
1212    #[derive(Serialize)]
1213    struct Persisted<'a> {
1214        device_id: &'a DeviceId,
1215        label: &'a str,
1216        created_at_ms: u64,
1217        #[serde(with = "serde_bytes")]
1218        signing_seed: &'a [u8],
1219    }
1220    codec::encode(&Persisted {
1221        device_id: &d.device_id,
1222        label: &d.label,
1223        created_at_ms: d.created_at_ms,
1224        signing_seed: d.signing.as_bytes(),
1225    })
1226}
1227
1228fn decode_local_device(bytes: &[u8], user_id: UserId) -> Result<LocalDevice> {
1229    use serde::Deserialize;
1230    #[derive(Deserialize)]
1231    struct Persisted {
1232        device_id: DeviceId,
1233        label: String,
1234        created_at_ms: u64,
1235        #[serde(with = "serde_bytes")]
1236        signing_seed: Vec<u8>,
1237    }
1238    let p: Persisted = codec::decode(bytes)?;
1239    let seed: [u8; 32] = p
1240        .signing_seed
1241        .as_slice()
1242        .try_into()
1243        .map_err(|_| Error::Invalid("device signing seed must be 32 bytes".into()))?;
1244    let signing = ed25519_dalek::SigningKey::from_bytes(&seed);
1245    Ok(LocalDevice {
1246        device_id: p.device_id,
1247        user_id,
1248        label: p.label,
1249        signing,
1250        created_at_ms: p.created_at_ms,
1251    })
1252}