ping-openmls-sdk-core 0.5.2

Platform-agnostic OpenMLS-based messaging engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//! Conversation state — wraps an OpenMLS `MlsGroup`.
//!
//! Each external conversation maps 1:1 to an MLS group whose leaves are devices. The DeviceGroup
//! (one per user, devices only) is just a special-cased conversation with the same wrapper.
//!
//! Persistence: we snapshot the `MlsGroup` after every state-changing operation under
//! `groups/{conversation_id}` and cache the result in-memory.

use openmls::{
    framing::{MlsMessageOut, ProcessedMessageContent},
    group::{MlsGroup, MlsGroupCreateConfig, MlsGroupJoinConfig},
    prelude::{
        tls_codec::{Deserialize as TlsDeserialize, Serialize as TlsSerialize},
        BasicCredential, Ciphersuite, CredentialWithKey, MlsMessageBodyIn, MlsMessageIn,
        ProcessedMessage, ProtocolMessage, ProtocolVersion,
    },
};
use openmls_basic_credential::SignatureKeyPair;
use openmls_traits::OpenMlsProvider;
use ping_mls_store::PersistentMlsProvider;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::sync::Arc;
use ulid::Ulid;
use zeroize::Zeroizing;

use crate::{
    clock::Hlc,
    codec,
    device::{DeviceId, GroupSnapshotEntry, GroupStateSnapshot, GROUP_SNAPSHOT_VERSION},
    error::{Error, Result},
    identity::UserId,
    message::{IncomingMessage, MessageEnvelope, MessageKind},
    storage::Storage,
    sync::SyncCursor,
};

const DEFAULT_CIPHERSUITE: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519;

/// 16-byte conversation identifier (ULID encoded). Stable across epochs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ConversationId(#[serde(with = "serde_bytes_array16")] pub [u8; 16]);

impl ConversationId {
    pub fn new() -> Self {
        Self(Ulid::new().to_bytes())
    }
    pub fn as_hex(&self) -> String {
        hex::encode(self.0)
    }
}

impl Default for ConversationId {
    fn default() -> Self {
        Self::new()
    }
}

mod serde_bytes_array16 {
    use serde::{Deserializer, Serializer};
    pub fn serialize<S: Serializer>(b: &[u8; 16], s: S) -> Result<S::Ok, S::Error> {
        serde_bytes::serialize(b.as_slice(), s)
    }
    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; 16], D::Error> {
        let v: Vec<u8> = serde_bytes::deserialize(d)?;
        v.try_into()
            .map_err(|_| serde::de::Error::custom("expected 16 bytes"))
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversationMeta {
    pub id: ConversationId,
    pub name: Option<String>,
    pub epoch: u64,
    pub member_count: u32,
    pub is_device_group: bool,
    pub created_at_ms: u64,
}

/// In-memory conversation handle. Holds the OpenMLS group plus our wire-level cursor.
pub struct Conversation {
    pub(crate) id: ConversationId,
    pub(crate) meta: ConversationMeta,
    pub(crate) group: MlsGroup,
    pub(crate) crypto: Arc<PersistentMlsProvider>,
    pub(crate) signing: Arc<SignatureKeyPair>,
    pub(crate) own_device: DeviceId,
    pub(crate) seq: u64,
    pub(crate) hlc: Hlc,
    pub(crate) cursor: SyncCursor,
    pub(crate) storage: Arc<dyn Storage>,
    /// Local device→leaf-index map for [CR-2] revocation.
    ///
    /// Populated when this device either (a) admits a peer via [`Self::add_members`] —
    /// every entry in the `Vec<(DeviceId, KeyPackage)>` is recorded after the commit
    /// merges — or (b) joins as the receiving device via [`Self::join`], at which point
    /// we record our own leaf. Pruned when [`Self::remove_members`] is called.
    ///
    /// Not authoritative for *peers' devices we didn't admit*: those are visible in
    /// `group.members()` but their device_ids are opaque to this client. `revoke_device`
    /// is therefore best-effort across conversations we ourselves invited the device
    /// into; see [`MessagingClient::revoke_device`] for the documented scope.
    pub(crate) device_leaves: BTreeMap<DeviceId, u32>,
}

impl std::fmt::Debug for Conversation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Conversation")
            .field("id", &self.id.as_hex())
            .field("meta", &self.meta)
            .finish()
    }
}

impl Conversation {
    pub fn id(&self) -> ConversationId {
        self.id
    }
    pub fn meta(&self) -> &ConversationMeta {
        &self.meta
    }
    pub fn epoch(&self) -> u64 {
        self.group.epoch().as_u64()
    }
    pub fn cursor(&self) -> &SyncCursor {
        &self.cursor
    }

    /// Create a new conversation, with `self` as the only initial member.
    // 8 args is a lot, but they're all needed for an internal constructor and a builder
    // would be over-engineered for v0.1.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn create(
        id: ConversationId,
        name: Option<String>,
        own_device: DeviceId,
        own_user: &UserId,
        crypto: Arc<PersistentMlsProvider>,
        signing: Arc<SignatureKeyPair>,
        storage: Arc<dyn Storage>,
        now_ms: u64,
    ) -> Result<Self> {
        let credential = BasicCredential::new(own_user.0.clone());
        let credential_with_key = CredentialWithKey {
            credential: credential.into(),
            signature_key: signing.public().into(),
        };
        let cfg = MlsGroupCreateConfig::builder()
            .ciphersuite(DEFAULT_CIPHERSUITE)
            .use_ratchet_tree_extension(true)
            .build();
        let group = MlsGroup::new_with_group_id(
            crypto.as_ref(),
            signing.as_ref(),
            &cfg,
            openmls::group::GroupId::from_slice(&id.0),
            credential_with_key,
        )
        .map_err(Error::mls)?;

        let meta = ConversationMeta {
            id,
            name,
            epoch: 0,
            member_count: 1,
            is_device_group: false,
            created_at_ms: now_ms,
        };
        // [CR-2] Group creator is always leaf 0; record so revoke_device can target it.
        let mut device_leaves = BTreeMap::new();
        device_leaves.insert(own_device.clone(), group.own_leaf_index().u32());
        Ok(Self {
            id,
            meta,
            group,
            crypto,
            signing,
            own_device,
            seq: 0,
            hlc: Hlc::ZERO.tick(now_ms),
            cursor: SyncCursor::default(),
            storage,
            device_leaves,
        })
    }

    /// Join an existing conversation from a Welcome message.
    pub(crate) fn join(
        welcome_bytes: &[u8],
        own_device: DeviceId,
        crypto: Arc<PersistentMlsProvider>,
        signing: Arc<SignatureKeyPair>,
        storage: Arc<dyn Storage>,
        now_ms: u64,
    ) -> Result<Self> {
        let mls_in = MlsMessageIn::tls_deserialize_exact(welcome_bytes).map_err(Error::mls)?;
        let welcome = match mls_in.extract() {
            MlsMessageBodyIn::Welcome(w) => w,
            _ => return Err(Error::Invalid("expected Welcome".into())),
        };
        let cfg = MlsGroupJoinConfig::builder()
            .use_ratchet_tree_extension(true)
            .build();
        let staged =
            openmls::group::StagedWelcome::new_from_welcome(crypto.as_ref(), &cfg, welcome, None)
                .map_err(Error::mls)?;
        let group = staged.into_group(crypto.as_ref()).map_err(Error::mls)?;

        let id_bytes: [u8; 16] = group
            .group_id()
            .as_slice()
            .try_into()
            .map_err(|_| Error::Invalid("group id must be 16 bytes".into()))?;
        let id = ConversationId(id_bytes);
        let meta = ConversationMeta {
            id,
            name: None,
            epoch: group.epoch().as_u64(),
            member_count: group.members().count() as u32,
            is_device_group: false,
            created_at_ms: now_ms,
        };

        // Seed the cursor at the join epoch so subsequent fetches skip pre-join Commits
        // (notably the Add commit that produced this Welcome — it lives in the conversation
        // log at `epoch - 1`, which the joiner must not try to apply on top of its
        // already-advanced group state).
        let join_epoch = group.epoch().as_u64();
        // [CR-2] Record our own (device_id → leaf_index) so the host can later revoke us
        // via the standard `revoke_device` flow. `own_leaf_index()` is stable for the
        // lifetime of this group membership.
        let own_leaf = group.own_leaf_index().u32();
        let mut device_leaves = BTreeMap::new();
        device_leaves.insert(own_device.clone(), own_leaf);
        Ok(Self {
            id,
            meta,
            group,
            crypto,
            signing,
            own_device,
            seq: 0,
            hlc: Hlc::ZERO.tick(now_ms),
            cursor: SyncCursor {
                epoch: join_epoch,
                ..Default::default()
            },
            storage,
            device_leaves,
        })
    }

    /// [CR-4] Rehydrate a previously-persisted conversation on cold restart.
    ///
    /// Loads the OpenMLS group state via `MlsGroup::load` (which reads from the
    /// provider's storage — populated by the SQLite-backed checkpoint on the
    /// previous run). Pairs the loaded MLS state with the meta + cursor + device→leaf
    /// map the host-side `Storage` trait kept for us. Returns `Ok(None)` if OpenMLS
    /// finds no state for `id` — the host's `groups` namespace had a stale entry.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn load(
        id: ConversationId,
        meta: ConversationMeta,
        cursor: SyncCursor,
        device_leaves: BTreeMap<DeviceId, u32>,
        own_device: DeviceId,
        crypto: Arc<PersistentMlsProvider>,
        signing: Arc<SignatureKeyPair>,
        storage: Arc<dyn Storage>,
        now_ms: u64,
    ) -> Result<Option<Self>> {
        use openmls::group::GroupId;
        let group_id = GroupId::from_slice(&id.0);
        let group = match MlsGroup::load(crypto.storage(), &group_id).map_err(Error::mls)? {
            Some(g) => g,
            None => return Ok(None),
        };
        Ok(Some(Self {
            id,
            meta,
            group,
            crypto,
            signing,
            own_device,
            seq: 0,
            hlc: Hlc::ZERO.tick(now_ms),
            cursor,
            storage,
            device_leaves,
        }))
    }

    /// Encrypt an application message and produce a wire envelope ready for transport.
    ///
    /// Uses the [CR-6] plaintext content_hash path: the envelope's `content_hash` is
    /// `SHA-256(plaintext)`, not the MLS ciphertext. This is what makes rebase clean
    /// and gives cross-binding hash parity.
    pub fn send_application(&mut self, plaintext: &[u8], now_ms: u64) -> Result<MessageEnvelope> {
        let out = self
            .group
            .create_message(self.crypto.as_ref(), self.signing.as_ref(), plaintext)
            .map_err(Error::mls)?;

        self.seq += 1;
        self.hlc = self.hlc.tick(now_ms);
        let bytes = out.tls_serialize_detached().map_err(Error::mls)?;
        let env = MessageEnvelope::new_application(
            self.id,
            self.epoch(),
            self.own_device.clone(),
            self.seq,
            self.hlc,
            bytes,
            plaintext,
        );
        // Advance the local cursor past our own send so a subsequent catch-up sync doesn't
        // pull this envelope back to us (we've already applied it locally — re-processing
        // would either fail or duplicate-deliver).
        self.cursor.advance(
            env.epoch,
            self.own_device.clone(),
            self.seq,
            self.hlc,
            now_ms,
        );
        Ok(env)
    }

    /// Add members by KeyPackage. Produces the Commit envelope to broadcast plus the Welcome
    /// envelope(s) to deliver out-of-band to the newly-added devices.
    ///
    /// [CR-2] takes a `Vec<(DeviceId, KeyPackage)>` instead of a bare `Vec<KeyPackage>`. The
    /// `DeviceId` for each entry is the *caller's* assertion of which device owns that
    /// KeyPackage — hosts typically get it from the directory service alongside the
    /// KeyPackage itself. The mapping is persisted per-conversation so [`MessagingClient::revoke_device`]
    /// can later locate the leaf to remove without a fresh directory lookup. The SDK does
    /// not cryptographically verify the device claim; that's a host policy concern
    /// (typically: the directory authenticates the key_package_id → device_id mapping).
    pub fn add_members(
        &mut self,
        entries: Vec<(DeviceId, Vec<u8>)>,
        now_ms: u64,
    ) -> Result<AddOutcome> {
        let mut kps = Vec::with_capacity(entries.len());
        // Track signature_key → device_id so we can resolve leaf indices post-commit.
        let mut sig_to_device: Vec<(Vec<u8>, DeviceId)> = Vec::with_capacity(entries.len());
        for (device_id, raw) in &entries {
            let mls_in = MlsMessageIn::tls_deserialize_exact(raw).map_err(Error::mls)?;
            let kp_in = match mls_in.extract() {
                MlsMessageBodyIn::KeyPackage(kp) => kp,
                _ => return Err(Error::Invalid("expected KeyPackage".into())),
            };
            // KeyPackages on the wire are unvalidated (`KeyPackageIn`); validate against the
            // crypto provider before handing them to OpenMLS.
            let kp = kp_in
                .validate(self.crypto.crypto(), ProtocolVersion::default())
                .map_err(Error::mls)?;
            let sig_key = kp.leaf_node().signature_key().as_slice().to_vec();
            sig_to_device.push((sig_key, device_id.clone()));
            kps.push(kp);
        }

        // The Commit's wire `epoch` field is the *source* epoch (the epoch the Commit was
        // crafted in, matching the epoch embedded in the inner MLS message bytes). The
        // Welcome's `epoch` is the *post-commit* epoch (it carries the new group state).
        // This split is what lets a joiner's sync cursor correctly filter pre-join Commits.
        let pre_commit_epoch = self.epoch();

        let (commit_out, welcome_out, _gi) = self
            .group
            .add_members(self.crypto.as_ref(), self.signing.as_ref(), &kps)
            .map_err(Error::mls)?;

        self.group
            .merge_pending_commit(self.crypto.as_ref())
            .map_err(Error::mls)?;
        self.meta.epoch = self.epoch();
        self.meta.member_count = self.group.members().count() as u32;

        // [CR-2] Resolve leaf indexes for the devices we just added. The Commit merged each
        // new KeyPackage's leaf into the tree; match by signature_key (unique per device's
        // MLS signing keypair) to recover the index.
        for member in self.group.members() {
            if let Some((_, device_id)) = sig_to_device
                .iter()
                .find(|(sig, _)| sig.as_slice() == member.signature_key.as_slice())
            {
                self.device_leaves
                    .insert(device_id.clone(), member.index.u32());
            }
        }

        self.seq += 1;
        self.hlc = self.hlc.tick(now_ms);

        let commit_bytes = mls_message_out_bytes(commit_out)?;
        let commit_env = MessageEnvelope::new(
            self.id,
            pre_commit_epoch,
            MessageKind::Commit,
            self.own_device.clone(),
            self.seq,
            self.hlc,
            commit_bytes,
        );

        let welcome_bytes = mls_message_out_bytes(welcome_out)?;
        let welcome_env = MessageEnvelope::new(
            self.id,
            self.meta.epoch,
            MessageKind::Welcome,
            self.own_device.clone(),
            self.seq,
            self.hlc,
            welcome_bytes,
        );

        // Advance the local cursor past our own Commit (at the post-commit epoch, since
        // we've already merged it locally) so catch-up sync doesn't try to re-apply it.
        self.cursor.advance(
            self.meta.epoch,
            self.own_device.clone(),
            self.seq,
            self.hlc,
            now_ms,
        );

        Ok(AddOutcome {
            commit: commit_env,
            welcome: welcome_env,
        })
    }

    pub fn remove_members(
        &mut self,
        leaf_indexes: Vec<u32>,
        now_ms: u64,
    ) -> Result<MessageEnvelope> {
        use openmls::prelude::LeafNodeIndex;
        let leaves: Vec<LeafNodeIndex> = leaf_indexes
            .iter()
            .copied()
            .map(LeafNodeIndex::new)
            .collect();

        // Capture the source epoch before merge — see add_members for the rationale.
        let pre_commit_epoch = self.epoch();

        let (commit_out, _welcome_opt, _gi) = self
            .group
            .remove_members(self.crypto.as_ref(), self.signing.as_ref(), &leaves)
            .map_err(Error::mls)?;
        self.group
            .merge_pending_commit(self.crypto.as_ref())
            .map_err(Error::mls)?;
        self.meta.epoch = self.epoch();
        self.meta.member_count = self.group.members().count() as u32;

        // [CR-2] Prune the device→leaf map for any devices we just removed. Other
        // entries' leaf indexes are stable across MLS adds/removes (OpenMLS reuses
        // blank slots, doesn't reshuffle live leaves).
        let removed: std::collections::HashSet<u32> = leaf_indexes.iter().copied().collect();
        self.device_leaves.retain(|_, idx| !removed.contains(idx));

        self.seq += 1;
        self.hlc = self.hlc.tick(now_ms);
        let bytes = mls_message_out_bytes(commit_out)?;
        let env = MessageEnvelope::new(
            self.id,
            pre_commit_epoch,
            MessageKind::Commit,
            self.own_device.clone(),
            self.seq,
            self.hlc,
            bytes,
        );
        // Advance the local cursor past our own Commit (at the post-commit epoch we've just
        // merged into) so catch-up sync doesn't try to re-apply it.
        self.cursor.advance(
            self.meta.epoch,
            self.own_device.clone(),
            self.seq,
            self.hlc,
            now_ms,
        );
        Ok(env)
    }

    /// Process an inbound envelope. Returns Some(IncomingMessage) for application traffic.
    pub fn process(
        &mut self,
        env: &MessageEnvelope,
        now_ms: u64,
    ) -> Result<Option<IncomingMessage>> {
        if !self.cursor.is_new(env.epoch, &env.sender_device, env.seq) {
            return Ok(None); // dedupe: already applied
        }
        let mls_in = MlsMessageIn::tls_deserialize_exact(&env.payload).map_err(Error::mls)?;

        // OpenMLS' `process_message` expects an `impl Into<ProtocolMessage>`. `MlsMessageIn`
        // itself doesn't implement that; we have to extract the body and convert the inner
        // private/public message. Welcomes are handled at the client level, not here.
        let protocol_msg: ProtocolMessage = match mls_in.extract() {
            MlsMessageBodyIn::PrivateMessage(m) => m.into(),
            MlsMessageBodyIn::PublicMessage(m) => m.into(),
            MlsMessageBodyIn::Welcome(_) => {
                return Err(Error::Invalid(
                    "Welcome must be handled at client level, not in-group".into(),
                ));
            }
            _ => return Err(Error::Invalid("unsupported MLS message body".into())),
        };

        let processed: ProcessedMessage = self
            .group
            .process_message(self.crypto.as_ref(), protocol_msg)
            .map_err(Error::mls)?;

        let out = match processed.into_content() {
            ProcessedMessageContent::ApplicationMessage(app) => {
                let pt = app.into_bytes();
                // CR-6: for v=2 application envelopes the wire-contract validator can't
                // check `content_hash` (the hash is over plaintext, which it didn't have).
                // We can now: verify SHA-256(pt) == env.content_hash and reject mismatches.
                // For v=1 envelopes the wire-contract validator already checked the
                // ciphertext-based hash, so no extra work here.
                if env.v >= 2 {
                    let computed = crate::message::hash_application_plaintext(&pt);
                    if computed != env.content_hash {
                        return Err(Error::Invalid(
                            "v=2 application content_hash mismatch".into(),
                        ));
                    }
                }
                Some(IncomingMessage {
                    conversation_id: self.id,
                    sender_device: env.sender_device.clone(),
                    epoch: env.epoch,
                    hlc: env.hlc,
                    plaintext: pt,
                    content_hash: env.content_hash,
                })
            }
            ProcessedMessageContent::StagedCommitMessage(staged) => {
                self.group
                    .merge_staged_commit(self.crypto.as_ref(), *staged)
                    .map_err(Error::mls)?;
                self.meta.epoch = self.epoch();
                self.meta.member_count = self.group.members().count() as u32;
                None
            }
            ProcessedMessageContent::ProposalMessage(_)
            | ProcessedMessageContent::ExternalJoinProposalMessage(_) => {
                // Proposals are buffered by OpenMLS until the next Commit; nothing to surface
                // to the application.
                None
            }
        };

        self.cursor.advance(
            env.epoch,
            env.sender_device.clone(),
            env.seq,
            env.hlc,
            now_ms,
        );
        Ok(out)
    }

    /// Export a derived secret keyed to this group's current epoch ([CR-8]).
    ///
    /// Wraps `MlsGroup::export_secret` (the MLS exporter, RFC 9420 §8.5) and surfaces the
    /// bytes in a `Zeroizing<Vec<u8>>` so the local copy is wiped on drop. Used by the host
    /// to seed:
    ///   * the ephemeral channel (`ping/ephemeral`, §5.4 of the architecture)
    ///   * call media keys (`ping/calls/media/{call_id}`, §7.2)
    ///   * call-ephemeral framer keys (`ping/calls/ephemeral/{call_id}`, §7.5)
    ///
    /// `label` should use the documented `ping/*` namespacing convention. There is no
    /// runtime enforcement — cross-binding parity is enforced by conformance fixtures
    /// pinning specific label strings.
    ///
    /// Output is the secret. Callers MUST treat the buffer as a secret: never log, never
    /// persist unencrypted. The wrapper zeroes our local copy on drop; the caller is
    /// responsible for zeroing any copy they make.
    pub fn export_secret(
        &self,
        label: &str,
        context: &[u8],
        length: usize,
    ) -> Result<Zeroizing<Vec<u8>>> {
        if length == 0 {
            return Err(Error::Invalid("export_secret length must be > 0".into()));
        }
        // Soft cap to prevent runaway allocations from a malformed caller. Real labels never
        // need more than ~64 bytes (AES-256 key + 96-bit nonce + slack); 1 KiB is generous.
        if length > 1024 {
            return Err(Error::Invalid(
                "export_secret length exceeds 1024-byte cap".into(),
            ));
        }
        let bytes = self
            .group
            .export_secret(self.crypto.as_ref(), label, context, length)
            .map_err(Error::mls)?;
        Ok(Zeroizing::new(bytes))
    }

    /// [CR-7] Export a portable snapshot of this group's MLS state.
    ///
    /// Walks the provider's working set, picks every entry whose key references this
    /// group's id, and bundles them with format metadata. Returns CBOR-encoded bytes
    /// suitable for inclusion in:
    ///   * `LinkingTicket.catchup_snapshot.conversation_metas[i].group_state_bytes`
    ///     (via [CR-13] — host calls this and passes the bytes through);
    ///   * `IdentityBackup.device_group_snapshot` (the Permissive-recovery path per
    ///     `docs/architecture/recovery.md`).
    ///
    /// Returns `Err` if the encoded snapshot exceeds [`GROUP_SNAPSHOT_HARD_CAP`].
    /// Output is wrapped in `Zeroizing` because the bytes contain past epoch secrets;
    /// the caller's copy on the FFI side is the host's responsibility to wipe.
    pub fn export_state_snapshot(&self, now_ms: u64) -> Result<Zeroizing<Vec<u8>>> {
        let entries = self.crypto.group_scoped_entries(&self.id.0);
        let snap = GroupStateSnapshot {
            v: GROUP_SNAPSHOT_VERSION,
            group_id: self.id,
            openmls_storage_version: openmls_traits::storage::CURRENT_VERSION,
            snapshot_created_at_ms: now_ms,
            entries: entries
                .into_iter()
                .map(|(key, value)| GroupSnapshotEntry { key, value })
                .collect(),
        };
        Ok(Zeroizing::new(snap.encode()?))
    }

    /// Look up the leaf index this device controls, if known ([CR-2]).
    ///
    /// Returns the locally-tracked leaf for `device_id`. Only populated for devices we
    /// added via [`Self::add_members`] or for our own leaf via [`Self::create`] /
    /// [`Self::join`]. Devices a peer admitted on our behalf are not in this map.
    pub fn leaf_index_of(&self, device_id: &DeviceId) -> Option<u32> {
        self.device_leaves.get(device_id).copied()
    }

    pub(crate) async fn snapshot_to_storage(&self) -> Result<()> {
        let blob = self
            .group
            .export_secret(self.crypto.as_ref(), "ping-snapshot-marker", &[], 32)
            .ok();
        // OpenMLS persists the group via its own keystore inside `crypto`. We only need to
        // record meta + cursor here; the group itself is recovered by re-opening with the
        // same provider on next launch.
        let _ = blob; // intentionally unused — present for future binary-snapshot path

        // [CR-4] Flush the MLS working set to the configured backend (no-op for
        // `StorageBackend::Memory`). MUST happen on every state-changing op so a cold
        // restart — iOS NSE, web SW — finds the latest epoch on disk.
        //
        // `checkpoint_async` is required for the WASM `IndexedDb` backend (IDB is
        // async-only); native Memory / Sqlite paths await trivially since their
        // I/O is sync internally.
        self.crypto
            .checkpoint_async()
            .await
            .map_err(|e| Error::Storage(format!("checkpoint: {e}")))?;

        let cursor = self.cursor.encode()?;
        self.storage
            .put("cursors", &self.id.as_hex(), cursor)
            .await?;
        let meta = codec::encode(&self.meta)?;
        self.storage
            .put("groups", &format!("{}/meta", self.id.as_hex()), meta)
            .await?;
        // [CR-2] Persist the device→leaf map so revoke_device works after a cold restart.
        // Use a stable BTreeMap-of-pairs encoding to guarantee canonical CBOR — every
        // platform that decodes this hits identical bytes.
        let leaves_vec: Vec<(DeviceId, u32)> = self
            .device_leaves
            .iter()
            .map(|(d, i)| (d.clone(), *i))
            .collect();
        let leaves_bytes = codec::encode(&leaves_vec)?;
        self.storage
            .put("device_leaves", &self.id.as_hex(), leaves_bytes)
            .await?;
        Ok(())
    }
}

/// Both halves of an Add commit. The Commit goes on the conversation channel; the Welcome is
/// delivered to the new members via whatever out-of-band path the host uses (often the same
/// transport, addressed to the new device's mailbox).
#[derive(Debug, Clone)]
pub struct AddOutcome {
    pub commit: MessageEnvelope,
    pub welcome: MessageEnvelope,
}

fn mls_message_out_bytes(m: MlsMessageOut) -> Result<Vec<u8>> {
    m.tls_serialize_detached().map_err(Error::mls)
}