Skip to main content

sew_proto/e2ee/
wire.rs

1//! The JSON half of the call key wire:
2//! the key join, the KeyPackage upload, the per-call key routes (`/calls/{call_id}/keys/…`), the
3//! `call_keys_delivered` dispatch body ([`CallKeysMessage`]), the DS-signed [`LeafBindingTable`],
4//! the relayed recorder [`Release`] and the READY section ([`ReadyCallKeys`]).
5//!
6//! Requests refuse unknown fields; responses, records and dispatch bodies ignore them.
7//! Units: epochs `u64`, slots `u8`, leaves `u32`, ids [`Id`], `*_ms` `u64`. MLS objects are
8//! [`B64`] (base64url, no padding). Sizes, quotas and every MLS check are the server's:
9//! validators here bound strings and list lengths only.
10
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize};
13
14use super::CallScope;
15use super::b64::B64;
16use super::names::{CallId, JoinIdHex, LkIdentity};
17use super::tls::{self, BindingKey, LeafBindingEntry, LeafBindingTableTbs};
18use crate::error::{Validate, ValidationError, check_known};
19use crate::id::Id;
20
21/// The only MLS ciphersuite of v1: `MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519`.
22pub const CIPHERSUITE_V1: u16 = 0x0001;
23/// The only `kdf` value.
24pub const KDF_HKDF: &str = "hkdf";
25/// A `key_package_ref` is a 32-byte RFC 9420 `KeyPackageRef`.
26pub const KEY_PACKAGE_REF_BYTES: usize = 32;
27/// A `group_id` is 16 random bytes.
28pub const GROUP_ID_BYTES: usize = 16;
29/// Longest caps string (`sdk`, `sdk_version`, `browser`, `lib`).
30pub const CAPS_STRING_MAX: usize = 64;
31/// Most entries in `caps.ciphersuites`.
32pub const CAPS_CIPHERSUITES_MAX: usize = 16;
33/// Longest `gateway_session` (the READY `session_id` wire form).
34pub const GATEWAY_SESSION_MAX: usize = 128;
35/// KeyPackages per KeyPackage upload.
36pub const UPLOAD_KEY_PACKAGES_MAX: usize = 2;
37/// The report `details` cap, as serialized JSON.
38pub const REPORT_DETAILS_MAX_BYTES: usize = 256;
39
40fn check_len(field: &str, s: &str, min: usize, max: usize) -> Result<(), ValidationError> {
41    if s.len() < min || s.len() > max {
42        return Err(ValidationError::invalid(
43            field,
44            format!("{field} must be {min}–{max} bytes, got {}", s.len()),
45        ));
46    }
47    Ok(())
48}
49
50fn check_bytes(field: &str, b: &B64, len: usize) -> Result<(), ValidationError> {
51    if b.len() != len {
52        return Err(ValidationError::invalid(
53            field,
54            format!("{field} must be {len} bytes, got {}", b.len()),
55        ));
56    }
57    Ok(())
58}
59
60fn check_nonempty(field: &str, b: &B64) -> Result<(), ValidationError> {
61    if b.is_empty() {
62        return Err(ValidationError::invalid(
63            field,
64            format!("{field} must not be empty"),
65        ));
66    }
67    Ok(())
68}
69
70fn is_false(b: &bool) -> bool {
71    !*b
72}
73
74// ---------------------------------------------------------------- caps and joins
75
76/// What the joining client can do. The server refuses an
77/// incapable client with `422 e2ee_unsupported_client`, so the values themselves are
78/// not checked here, only their sizes.
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
80#[serde(deny_unknown_fields)]
81#[non_exhaustive]
82pub struct E2eeCaps {
83    /// The SDK can move its sender to a new key slot.
84    pub sender_key_index: bool,
85    /// `"hkdf"`.
86    pub kdf: String,
87    /// 64; anything else is refused at join.
88    pub key_ring_size: u32,
89    /// The SDK family (`js`, `rust`, …).
90    pub sdk: String,
91    /// The SDK version as its `ClientInfo` reports it.
92    pub sdk_version: String,
93    /// `chrome`, `firefox`, `safari` or `other` (web only).
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub browser: Option<String>,
96    /// `sew-e2ee/<version>`.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub lib: Option<String>,
99    /// MLS ciphersuites the client supports; must contain 1 when present.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub ciphersuites: Option<Vec<u16>>,
102}
103
104impl E2eeCaps {
105    /// An `E2eeCaps` with its required fields: every count 0, every flag `false` and every
106    /// optional field unset.
107    pub fn new(
108        kdf: impl Into<String>,
109        sdk: impl Into<String>,
110        sdk_version: impl Into<String>,
111    ) -> Self {
112        E2eeCaps {
113            sender_key_index: false,
114            kdf: kdf.into(),
115            key_ring_size: 0,
116            sdk: sdk.into(),
117            sdk_version: sdk_version.into(),
118            browser: None,
119            lib: None,
120            ciphersuites: None,
121        }
122    }
123}
124
125impl Validate for E2eeCaps {
126    fn validate(&self) -> Result<(), ValidationError> {
127        check_len("kdf", &self.kdf, 1, CAPS_STRING_MAX)?;
128        check_len("sdk", &self.sdk, 1, CAPS_STRING_MAX)?;
129        check_len("sdk_version", &self.sdk_version, 1, CAPS_STRING_MAX)?;
130        if let Some(b) = &self.browser {
131            check_len("browser", b, 1, CAPS_STRING_MAX)?;
132        }
133        if let Some(l) = &self.lib {
134            check_len("lib", l, 1, CAPS_STRING_MAX)?;
135        }
136        if let Some(c) = &self.ciphersuites
137            && (c.is_empty() || c.len() > CAPS_CIPHERSUITES_MAX)
138        {
139            return Err(ValidationError::invalid(
140                "ciphersuites",
141                format!("ciphersuites must hold 1–{CAPS_CIPHERSUITES_MAX} values"),
142            ));
143        }
144        Ok(())
145    }
146}
147
148/// The `e2ee` object of a voice or call join (`VoiceJoinRequest.e2ee`, and DM call
149/// joins).
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
151#[serde(deny_unknown_fields)]
152pub struct E2eeJoin {
153    /// The single-use ref the KeyPackage upload returned (32 bytes).
154    pub key_package_ref: B64,
155    /// The caller's gateway session: READY's `session_id`.
156    pub gateway_session: String,
157    /// What the client can do.
158    pub caps: E2eeCaps,
159}
160
161impl Validate for E2eeJoin {
162    fn validate(&self) -> Result<(), ValidationError> {
163        check_bytes(
164            "key_package_ref",
165            &self.key_package_ref,
166            KEY_PACKAGE_REF_BYTES,
167        )?;
168        check_len(
169            "gateway_session",
170            &self.gateway_session,
171            1,
172            GATEWAY_SESSION_MAX,
173        )?;
174        self.caps.validate().map_err(|e| e.nested("caps"))
175    }
176}
177
178/// K2 body: the key join after a move, with the Sew-minted `join_id` from
179/// `voice_server_updated`.
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
181#[serde(deny_unknown_fields)]
182pub struct KeyJoinRequest {
183    /// The join id Sew minted for the move.
184    pub join_id: JoinIdHex,
185    /// The caller's gateway session.
186    pub gateway_session: String,
187    /// A ref uploaded for the target channel's scope.
188    pub key_package_ref: B64,
189    /// What the client can do.
190    pub caps: E2eeCaps,
191}
192
193impl Validate for KeyJoinRequest {
194    fn validate(&self) -> Result<(), ValidationError> {
195        check_bytes(
196            "key_package_ref",
197            &self.key_package_ref,
198            KEY_PACKAGE_REF_BYTES,
199        )?;
200        check_len(
201            "gateway_session",
202            &self.gateway_session,
203            1,
204            GATEWAY_SESSION_MAX,
205        )?;
206        self.caps.validate().map_err(|e| e.nested("caps"))
207    }
208}
209
210/// The client timings and constants the server relays (READY `call_keys.params` and every
211/// [`CallKeysInit`]). The single source for client timings.
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
213#[non_exhaustive]
214pub struct CallKeysParams {
215    /// The ciphersuite every group uses (1).
216    pub ciphersuite: u16,
217    /// The ciphersuites the server accepts (`[1]` in v1).
218    pub ciphersuites: Vec<u16>,
219    /// Always 64.
220    pub key_ring_size: u32,
221    /// `"hkdf"`.
222    pub kdf: String,
223    /// The MLS exporter label of frame keys ([`tls::EXPORTER_LABEL`]).
224    pub exporter_label: String,
225    /// The recorder release `info` label ([`tls::RELEASE_INFO_LABEL`]).
226    pub release_info_label: String,
227    /// Receivers retire an old slot this long after `activate`.
228    pub retire_after_ms: u64,
229    /// A sender that acked but hears no `activate` switches after this long.
230    pub client_activate_fallback_ms: u64,
231    /// Longest KeyPackage lifetime the server accepts.
232    pub key_package_max_lifetime_s: u64,
233    /// Dispatches for a `call_id` the client does not know yet are buffered this long.
234    pub unknown_call_buffer_ms: u64,
235    /// "Securing…" shows only after this long.
236    pub securing_indicator_after_ms: u64,
237}
238
239impl CallKeysParams {
240    /// A `CallKeysParams` with its required fields: every count 0 and every list empty.
241    pub fn new(
242        kdf: impl Into<String>,
243        exporter_label: impl Into<String>,
244        release_info_label: impl Into<String>,
245    ) -> Self {
246        CallKeysParams {
247            ciphersuite: 0,
248            ciphersuites: Vec::new(),
249            key_ring_size: 0,
250            kdf: kdf.into(),
251            exporter_label: exporter_label.into(),
252            release_info_label: release_info_label.into(),
253            retire_after_ms: 0,
254            client_activate_fallback_ms: 0,
255            key_package_max_lifetime_s: 0,
256            unknown_call_buffer_ms: 0,
257            securing_indicator_after_ms: 0,
258        }
259    }
260}
261
262/// What a key join answers (the voice join's `VoiceJoinResponse.e2ee`, the key join, and
263/// the `init` dispatch).
264#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
265#[non_exhaustive]
266pub struct CallKeysInit {
267    /// The call: its `r_…` room.
268    pub call_id: CallId,
269    /// The caller's Sew-minted join id; every per-call key route's body carries it.
270    pub join_id: JoinIdHex,
271    /// The caller's engine identity (`p_` + base32 of `join_id`; the token's `sub`).
272    pub lk_identity: LkIdentity,
273    /// The call's scope, `call:<channel_id>`; members refuse leaves with another.
274    pub scope: CallScope,
275    /// The current group (16 bytes).
276    pub group_id: B64,
277    /// The group's epoch.
278    pub epoch: u64,
279    /// The caller creates the group now.
280    pub create: bool,
281    /// The creator activates epoch 0 at once (first joiner of a fresh call only).
282    pub activate_on_create: bool,
283    /// `slot(e) = (slot_base + e) mod 64`.
284    pub slot_base: u8,
285    /// TLS `ExternalSender` of the install's DS key.
286    pub external_sender: B64,
287    /// Client timings.
288    pub params: CallKeysParams,
289}
290
291impl CallKeysInit {
292    /// A `CallKeysInit` with its required fields: every count 0 and every flag `false`.
293    pub fn new(
294        call_id: CallId,
295        join_id: JoinIdHex,
296        lk_identity: LkIdentity,
297        scope: CallScope,
298        group_id: B64,
299        external_sender: B64,
300        params: CallKeysParams,
301    ) -> Self {
302        CallKeysInit {
303            call_id,
304            join_id,
305            lk_identity,
306            scope,
307            group_id,
308            epoch: 0,
309            create: false,
310            activate_on_create: false,
311            slot_base: 0,
312            external_sender,
313            params,
314        }
315    }
316}
317
318// ---------------------------------------------------------------- KeyPackage upload
319
320/// KeyPackage upload body: 1–2 KeyPackages uploaded before any join.
321#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
322#[serde(deny_unknown_fields)]
323pub struct KeyPackageUploadRequest {
324    /// TLS `MLSMessage(KeyPackage)` each.
325    pub key_packages: Vec<B64>,
326}
327
328impl Validate for KeyPackageUploadRequest {
329    fn validate(&self) -> Result<(), ValidationError> {
330        if self.key_packages.is_empty() || self.key_packages.len() > UPLOAD_KEY_PACKAGES_MAX {
331            return Err(ValidationError::invalid(
332                "key_packages",
333                format!("key_packages must hold 1–{UPLOAD_KEY_PACKAGES_MAX} packages"),
334            ));
335        }
336        for (i, kp) in self.key_packages.iter().enumerate() {
337            check_nonempty(&format!("key_packages[{i}]"), kp)?;
338        }
339        Ok(())
340    }
341}
342
343/// One uploaded KeyPackage's single-use ref.
344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
345pub struct KeyPackageRefItem {
346    /// RFC 9420 `KeyPackageRef` (`KeyPackage::hash_ref`, 32 bytes).
347    pub key_package_ref: B64,
348    /// When the ref expires (unix ms).
349    pub expires_at_ms: u64,
350}
351
352/// KeyPackage upload answer: one item per package, in request order.
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
354pub struct KeyPackageUploadResponse {
355    /// The refs.
356    pub items: Vec<KeyPackageRefItem>,
357}
358
359// ---------------------------------------------------------------- binding tables
360
361/// One `LeafBinding` entry in JSON: exactly one of `leaf` (key type 1) or `key_package_ref`
362/// (key type 2), the join id and its engine identity.
363#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
364pub struct LeafBindingEntryJson {
365    /// The leaf index (commit, welcome, state report reply, recorder tables).
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub leaf: Option<u32>,
368    /// The Add's `key_package_ref` (proposals).
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    pub key_package_ref: Option<B64>,
371    /// The join id.
372    pub join_id: JoinIdHex,
373    /// `p_` + base32 of `join_id` (not signed; clients recompute and compare).
374    pub lk_identity: LkIdentity,
375}
376
377/// The DS-signed leaf ↔ join id table. `sig` = Ed25519(`sew-call-ds`,
378/// `"sew call leaf binding v1"` ‖ TLS([`LeafBindingTableTbs`])).
379#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
380pub struct LeafBindingTable {
381    /// The call.
382    pub call_id: CallId,
383    /// The group (16 bytes).
384    pub group_id: B64,
385    /// The proposal epoch (key type 2) or the new epoch (key type 1).
386    pub epoch: u64,
387    /// Ascending by leaf or by ref; one key type per table.
388    pub entries: Vec<LeafBindingEntryJson>,
389    /// 64-byte Ed25519 signature.
390    pub sig: B64,
391}
392
393/// Why a JSON binding table does not match its signed form.
394#[derive(Debug, Clone, PartialEq, Eq)]
395pub enum BindingError {
396    /// An entry has both or neither of `leaf` and `key_package_ref` (its index is named).
397    EntryKey(usize),
398    /// An entry's `lk_identity` is not `p_` + base32 of its `join_id` (its index is named).
399    Identity(usize),
400    /// The TBS `call_id` is not an `r_…` room.
401    CallId,
402    /// The content rules ([`LeafBindingTableTbs::check`]).
403    Table(tls::TableError),
404}
405
406impl std::fmt::Display for BindingError {
407    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408        match self {
409            BindingError::EntryKey(i) => {
410                write!(f, "entry {i} needs exactly one of leaf and key_package_ref")
411            }
412            BindingError::Identity(i) => write!(f, "entry {i}: lk_identity does not match join_id"),
413            BindingError::CallId => f.write_str("call_id is not a room name"),
414            BindingError::Table(e) => write!(f, "{e}"),
415        }
416    }
417}
418
419impl std::error::Error for BindingError {}
420
421impl LeafBindingTable {
422    /// The signed structure: entries in their key form, checked against the content rules
423    /// (one key type, strictly ascending, unique join ids) and each `lk_identity`.
424    pub fn tbs(&self) -> Result<LeafBindingTableTbs, BindingError> {
425        let mut entries = Vec::with_capacity(self.entries.len());
426        for (i, e) in self.entries.iter().enumerate() {
427            let key = match (e.leaf, &e.key_package_ref) {
428                (Some(l), None) => BindingKey::Leaf(l),
429                (None, Some(r)) => BindingKey::KeyPackageRef(r.as_bytes().to_vec()),
430                _ => return Err(BindingError::EntryKey(i)),
431            };
432            if e.join_id.lk_identity() != e.lk_identity {
433                return Err(BindingError::Identity(i));
434            }
435            entries.push(LeafBindingEntry {
436                key,
437                join_id: e.join_id.bytes(),
438            });
439        }
440        let tbs = LeafBindingTableTbs {
441            call_id: self.call_id.as_str().as_bytes().to_vec(),
442            group_id: self.group_id.as_bytes().to_vec(),
443            epoch: self.epoch,
444            entries,
445        };
446        tbs.check().map_err(BindingError::Table)?;
447        Ok(tbs)
448    }
449
450    /// The JSON form of a signed structure (identities derived from the join ids).
451    pub fn from_tbs(
452        tbs: &LeafBindingTableTbs,
453        sig: Vec<u8>,
454    ) -> Result<LeafBindingTable, BindingError> {
455        tbs.check().map_err(BindingError::Table)?;
456        let call_id = std::str::from_utf8(&tbs.call_id)
457            .ok()
458            .and_then(|s| CallId::parse(s).ok())
459            .ok_or(BindingError::CallId)?;
460        let entries = tbs
461            .entries
462            .iter()
463            .map(|e| {
464                let join_id = JoinIdHex::from_bytes(e.join_id);
465                let (leaf, key_package_ref) = match &e.key {
466                    BindingKey::Leaf(l) => (Some(*l), None),
467                    BindingKey::KeyPackageRef(r) => (None, Some(B64::new(r.clone()))),
468                };
469                LeafBindingEntryJson {
470                    leaf,
471                    key_package_ref,
472                    lk_identity: join_id.lk_identity(),
473                    join_id,
474                }
475            })
476            .collect();
477        Ok(LeafBindingTable {
478            call_id,
479            group_id: B64::new(tbs.group_id.clone()),
480            epoch: tbs.epoch,
481            entries,
482            sig: B64::new(sig),
483        })
484    }
485}
486
487/// A full key-type-1 table of one committed epoch for the recorder
488/// (`RecorderSink::bindings`, the recorder's `/bindings`).
489#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
490pub struct BindingsUpdate {
491    /// The group.
492    pub group_id: B64,
493    /// The epoch the table is for.
494    pub epoch: u64,
495    /// The group's slot base.
496    pub slot_base: u8,
497    /// The signed table.
498    pub table: LeafBindingTable,
499}
500
501/// A public key and its id (`kid` = hex of the first 8 bytes of SHA-256 of the raw key).
502#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
503pub struct CallPublicKey {
504    /// 16 lowercase hex characters.
505    pub kid: String,
506    /// The raw 32-byte Ed25519 public key.
507    pub public_key: B64,
508}
509
510/// The install CA and DS public keys (`CallKeyService::public_keys`, for the recorder PUT).
511#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
512pub struct CallPublicKeys {
513    /// `sew-call-ca`.
514    pub ca: CallPublicKey,
515    /// `sew-call-ds`.
516    pub ds: CallPublicKey,
517}
518
519// ---------------------------------------------------------------- per-call key routes
520
521unit_enum! {
522    /// The state report's answer.
523    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
524    pub enum KeyStateStatus {
525        /// The leaf is bound and current.
526        InSync = "in_sync",
527        /// Repeat the call with `ratchet_tree`.
528        SendTree = "send_tree",
529        /// A rebuild is collecting reports; retry after `retry_after_ms`.
530        Rebuilding = "rebuilding",
531    }
532}
533
534/// State report body: the create report, a re-bind after a re-identify, or a rebuild report.
535#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
536#[serde(deny_unknown_fields)]
537pub struct KeyStateRequest {
538    /// The caller's join id.
539    pub join_id: JoinIdHex,
540    /// The caller's current gateway session.
541    pub gateway_session: String,
542    /// The group the client holds.
543    pub group_id: B64,
544    /// The reporter's own leaf index.
545    pub leaf: u32,
546    /// The client's epoch.
547    pub epoch: u64,
548    /// The client's active epoch.
549    pub active_epoch: u64,
550    /// The client's slot base.
551    pub slot_base: u8,
552    /// The client's tree hash.
553    pub tree_hash: B64,
554    /// SHA-256 of the TLS binding table the client holds.
555    pub bindings_hash: B64,
556    /// TLS `MLSMessage(GroupInfo)`.
557    pub group_info: B64,
558    /// TLS `RatchetTree`, only when the DS asked (`send_tree`).
559    #[serde(default, skip_serializing_if = "Option::is_none")]
560    pub ratchet_tree: Option<B64>,
561}
562
563impl Validate for KeyStateRequest {
564    fn validate(&self) -> Result<(), ValidationError> {
565        check_len(
566            "gateway_session",
567            &self.gateway_session,
568            1,
569            GATEWAY_SESSION_MAX,
570        )?;
571        check_bytes("group_id", &self.group_id, GROUP_ID_BYTES)?;
572        check_nonempty("tree_hash", &self.tree_hash)?;
573        check_bytes("bindings_hash", &self.bindings_hash, 32)?;
574        check_nonempty("group_info", &self.group_info)?;
575        if let Some(t) = &self.ratchet_tree {
576            check_nonempty("ratchet_tree", t)?;
577        }
578        Ok(())
579    }
580}
581
582/// State report answer.
583#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
584pub struct KeyStateResponse {
585    /// `in_sync`, `send_tree` or `rebuilding`.
586    pub status: KeyStateStatus,
587    /// With `rebuilding`: the rest of the rebuild window.
588    #[serde(default, skip_serializing_if = "Option::is_none")]
589    pub retry_after_ms: Option<u64>,
590    /// The full signed table when the client's `bindings_hash` differs from the DS's.
591    #[serde(default, skip_serializing_if = "Option::is_none")]
592    pub bindings: Option<LeafBindingTable>,
593}
594
595/// Commit body: the designated committer's commit.
596#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
597#[serde(deny_unknown_fields)]
598pub struct KeyCommitRequest {
599    /// The committer's join id.
600    pub join_id: JoinIdHex,
601    /// The group.
602    pub group_id: B64,
603    /// The epoch the commit is for (the proposals' epoch).
604    pub epoch: u64,
605    /// TLS `MLSMessage(PublicMessage commit)`.
606    pub commit: B64,
607    /// TLS `MLSMessage(Welcome)`; present iff the commit adds leaves.
608    #[serde(default, skip_serializing_if = "Option::is_none")]
609    pub welcome: Option<B64>,
610    /// TLS `MLSMessage(GroupInfo)` for `epoch + 1`.
611    pub group_info: B64,
612}
613
614impl Validate for KeyCommitRequest {
615    fn validate(&self) -> Result<(), ValidationError> {
616        check_bytes("group_id", &self.group_id, GROUP_ID_BYTES)?;
617        check_nonempty("commit", &self.commit)?;
618        if let Some(w) = &self.welcome {
619            check_nonempty("welcome", w)?;
620        }
621        check_nonempty("group_info", &self.group_info)
622    }
623}
624
625/// Commit `200` answer.
626#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
627pub struct KeyCommitAccepted {
628    /// Always `true`.
629    pub accepted: bool,
630    /// The new epoch.
631    pub epoch: u64,
632    /// Its slot.
633    pub slot: u8,
634}
635
636/// Ready report body: every remote sender's key for `epoch` is installed.
637#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
638#[serde(deny_unknown_fields)]
639pub struct KeyReadyRequest {
640    /// The caller's join id.
641    pub join_id: JoinIdHex,
642    /// The group.
643    pub group_id: B64,
644    /// The installed epoch.
645    pub epoch: u64,
646}
647
648impl Validate for KeyReadyRequest {
649    fn validate(&self) -> Result<(), ValidationError> {
650        check_bytes("group_id", &self.group_id, GROUP_ID_BYTES)
651    }
652}
653
654unit_enum! {
655    /// Why a client asks to be re-added.
656    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
657    pub enum InvalidReason {
658        /// A commit failed to process.
659        CommitFailed = "commit_failed",
660        /// A commit failed the member-side checks.
661        BadCommit = "bad_commit",
662        /// A proposal failed the member-side checks.
663        BadProposal = "bad_proposal",
664        /// A Welcome failed to process or check.
665        BadWelcome = "bad_welcome",
666        /// An epoch was missed.
667        MissedEpoch = "missed_epoch",
668        /// The recovery watchdog ran out.
669        RecoveryTimeout = "recovery_timeout",
670        /// The state report answered `e2ee_epoch_behind`, or a `resync{behind}`.
671        Behind = "behind",
672        /// The client lost its MLS state.
673        StateLost = "state_lost",
674    }
675}
676
677/// Invalid report body: re-add the caller's leaf with a fresh inline KeyPackage (one Replace
678/// commit).
679#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
680#[serde(deny_unknown_fields)]
681pub struct KeyInvalidRequest {
682    /// The caller's join id (kept by the new leaf).
683    pub join_id: JoinIdHex,
684    /// The group the client holds.
685    pub group_id: B64,
686    /// The client's epoch.
687    pub epoch: u64,
688    /// Why.
689    pub reason: InvalidReason,
690    /// TLS `MLSMessage(KeyPackage)`: same member, device and scope as the leaf.
691    pub key_package: B64,
692    /// The caller's current gateway session, when it re-identified while holding no group
693    /// (its Welcome went to the dead socket, or its join waited across a restart): the DS
694    /// re-binds the join to it (additive, KB).
695    #[serde(default, skip_serializing_if = "Option::is_none")]
696    pub gateway_session: Option<String>,
697}
698
699impl Validate for KeyInvalidRequest {
700    fn validate(&self) -> Result<(), ValidationError> {
701        check_bytes("group_id", &self.group_id, GROUP_ID_BYTES)?;
702        check_known("reason", self.reason)?;
703        if let Some(s) = &self.gateway_session {
704            check_len("gateway_session", s, 1, GATEWAY_SESSION_MAX)?;
705        }
706        check_nonempty("key_package", &self.key_package)
707    }
708}
709
710/// `key_package` body: a fresh inline KeyPackage for a resetting call's new group.
711#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
712#[serde(deny_unknown_fields)]
713pub struct KeyResetPackageRequest {
714    /// The caller's join id.
715    pub join_id: JoinIdHex,
716    /// The group being collected (from `reset`).
717    pub new_group_id: B64,
718    /// TLS `MLSMessage(KeyPackage)`.
719    pub key_package: B64,
720}
721
722impl Validate for KeyResetPackageRequest {
723    fn validate(&self) -> Result<(), ValidationError> {
724        check_bytes("new_group_id", &self.new_group_id, GROUP_ID_BYTES)?;
725        check_nonempty("key_package", &self.key_package)
726    }
727}
728
729/// Release body: the caller's own sender key for one epoch, sealed to the recorder.
730/// `enc` and `ct` sizes and `sender_identity` are the DS's routing checks (`422`), not shape
731/// checks.
732#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
733#[serde(deny_unknown_fields)]
734pub struct KeyReleaseRequest {
735    /// The caller's join id.
736    pub join_id: JoinIdHex,
737    /// The group.
738    pub group_id: B64,
739    /// The released epoch.
740    pub epoch: u64,
741    /// `slot(epoch)`.
742    pub slot: u8,
743    /// The live recording.
744    pub recording_id: Id,
745    /// The caller's leaf index in `epoch`.
746    pub leaf: u32,
747    /// The caller's engine identity.
748    pub sender_identity: String,
749    /// HPKE `enc` (32 bytes).
750    pub enc: B64,
751    /// HPKE ciphertext (48 bytes).
752    pub ct: B64,
753}
754
755impl Validate for KeyReleaseRequest {
756    fn validate(&self) -> Result<(), ValidationError> {
757        check_bytes("group_id", &self.group_id, GROUP_ID_BYTES)?;
758        check_len("sender_identity", &self.sender_identity, 1, CAPS_STRING_MAX)
759    }
760}
761
762/// A release as the DS relays it to the recorder (`RecorderSink::release`; the recorder opens it
763/// with the client library's `ReleaseOpener`, which rebuilds the `info` with `leaf`).
764#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
765pub struct Release {
766    /// The call.
767    pub call_id: CallId,
768    /// The recording.
769    pub recording_id: Id,
770    /// The group.
771    pub group_id: B64,
772    /// The epoch.
773    pub epoch: u64,
774    /// The sender's leaf index in `epoch`.
775    pub leaf: u32,
776    /// `slot(epoch)`.
777    pub slot: u8,
778    /// The sender's engine identity.
779    pub sender_identity: LkIdentity,
780    /// HPKE `enc` (32 bytes).
781    pub enc: B64,
782    /// HPKE ciphertext (48 bytes).
783    pub ct: B64,
784}
785
786impl Release {
787    /// The structure the HPKE `info` binds.
788    pub fn info(&self) -> tls::ReleaseInfo {
789        tls::ReleaseInfo {
790            call_id: self.call_id.as_str().as_bytes().to_vec(),
791            recording_id: self.recording_id.get(),
792            group_id: self.group_id.as_bytes().to_vec(),
793            epoch: self.epoch,
794            leaf_index: self.leaf,
795            slot: self.slot,
796            sender_identity: self.sender_identity.as_str().as_bytes().to_vec(),
797        }
798    }
799}
800
801unit_enum! {
802    /// Why a client asks for an immediate rekey.
803    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
804    pub enum RekeyReason {
805        /// The member withdrew recording consent.
806        ConsentWithdrawn = "consent_withdrawn",
807    }
808}
809
810/// Rekey body.
811#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
812#[serde(deny_unknown_fields)]
813pub struct KeyRekeyRequest {
814    /// The caller's join id.
815    pub join_id: JoinIdHex,
816    /// Why.
817    pub reason: RekeyReason,
818}
819
820impl Validate for KeyRekeyRequest {
821    fn validate(&self) -> Result<(), ValidationError> {
822        check_known("reason", self.reason)
823    }
824}
825
826unit_enum! {
827    /// What a report is about.
828    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
829    pub enum ReportKind {
830        /// A leaf whose member has no voice state in the channel.
831        LeafWithoutVoiceState = "leaf_without_voice_state",
832        /// Two leaves of one member outside a swap.
833        DuplicateMember = "duplicate_member",
834        /// An engine participant with no leaf past 5 s.
835        EngineParticipantWithoutLeaf = "engine_participant_without_leaf",
836        /// The group's external sender differs from READY's.
837        ExternalSenderMismatch = "external_sender_mismatch",
838        /// The CA key differs from the pinned one.
839        CaChanged = "ca_changed",
840        /// A binding table failed the client's checks.
841        LeafBindingInvalid = "leaf_binding_invalid",
842        /// A leaf's credential scope is empty or differs from the call's.
843        ScopeInvalid = "scope_invalid",
844        /// The reporter's own sender stays on a stale slot after one re-apply.
845        SenderIndexStuck = "sender_index_stuck",
846        /// Another leaf's frames do not decrypt (quorum only).
847        PeerUndecryptable = "peer_undecryptable",
848        /// A bridge saw an unencrypted track from the engine.
849        EngineUnencryptedTrack = "engine_unencrypted_track",
850        /// A bridge saw a non-empty `sif_trailer` from the engine.
851        EngineSifTrailer = "engine_sif_trailer",
852        /// A bridge saw an encryption downgrade from the engine.
853        EngineEncryptionDowngrade = "engine_encryption_downgrade",
854    }
855}
856
857impl ReportKind {
858    /// The roster kinds (audited `call.e2ee_roster_report`, alarm `e2ee_roster_mismatch`).
859    pub const fn is_roster(self) -> bool {
860        matches!(
861            self,
862            ReportKind::LeafWithoutVoiceState
863                | ReportKind::DuplicateMember
864                | ReportKind::EngineParticipantWithoutLeaf
865                | ReportKind::ExternalSenderMismatch
866                | ReportKind::CaChanged
867                | ReportKind::LeafBindingInvalid
868                | ReportKind::ScopeInvalid
869        )
870    }
871
872    /// The slot signals (`sender_index_stuck`, `peer_undecryptable`; their own count).
873    pub const fn is_slot_signal(self) -> bool {
874        matches!(
875            self,
876            ReportKind::SenderIndexStuck | ReportKind::PeerUndecryptable
877        )
878    }
879
880    /// The bridge detections of a misbehaving engine.
881    pub const fn is_engine(self) -> bool {
882        matches!(
883            self,
884            ReportKind::EngineUnencryptedTrack
885                | ReportKind::EngineSifTrailer
886                | ReportKind::EngineEncryptionDowngrade
887        )
888    }
889}
890
891/// Report `details` (≤ 256 bytes of JSON). Every field is optional; strings ≤ 64 bytes.
892#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
893#[serde(deny_unknown_fields)]
894pub struct ReportDetails {
895    /// The slot the sender should be on.
896    #[serde(default, skip_serializing_if = "Option::is_none")]
897    pub expected_slot: Option<u8>,
898    /// The slot the reporter saw.
899    #[serde(default, skip_serializing_if = "Option::is_none")]
900    pub observed_slot: Option<u8>,
901    /// For how long the condition held.
902    #[serde(default, skip_serializing_if = "Option::is_none")]
903    pub since_ms: Option<u64>,
904    /// Failed decrypts counted.
905    #[serde(default, skip_serializing_if = "Option::is_none")]
906    pub failures: Option<u32>,
907    /// Re-apply attempts.
908    #[serde(default, skip_serializing_if = "Option::is_none")]
909    pub attempts: Option<u32>,
910    /// The key index a receiver missed.
911    #[serde(default, skip_serializing_if = "Option::is_none")]
912    pub missing_index: Option<u8>,
913    /// A short reason (`missing_key`, `invalid_key`, …).
914    #[serde(default, skip_serializing_if = "Option::is_none")]
915    pub reason: Option<String>,
916    /// The reporter's SDK family.
917    #[serde(default, skip_serializing_if = "Option::is_none")]
918    pub sdk: Option<String>,
919    /// The reporter's SDK version.
920    #[serde(default, skip_serializing_if = "Option::is_none")]
921    pub sdk_version: Option<String>,
922}
923
924impl Validate for ReportDetails {
925    fn validate(&self) -> Result<(), ValidationError> {
926        for (field, v) in [
927            ("reason", &self.reason),
928            ("sdk", &self.sdk),
929            ("sdk_version", &self.sdk_version),
930        ] {
931            if let Some(s) = v {
932                check_len(field, s, 1, CAPS_STRING_MAX)?;
933            }
934        }
935        let n = serde_json::to_vec(self)
936            .map(|v| v.len())
937            .unwrap_or(usize::MAX);
938        if n > REPORT_DETAILS_MAX_BYTES {
939            return Err(ValidationError::too_large(
940                "details",
941                format!("details must be at most {REPORT_DETAILS_MAX_BYTES} bytes of JSON"),
942            ));
943        }
944        Ok(())
945    }
946}
947
948/// Report body: a ghost-member, slot or engine report.
949#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
950#[serde(deny_unknown_fields)]
951pub struct KeyReportRequest {
952    /// The reporter's join id.
953    pub join_id: JoinIdHex,
954    /// The group the reporter holds.
955    pub group_id: B64,
956    /// The reporter's epoch.
957    pub epoch: u64,
958    /// What is reported.
959    pub kind: ReportKind,
960    /// The leaf it is about (the reporter's own for `sender_index_stuck`).
961    #[serde(default, skip_serializing_if = "Option::is_none")]
962    pub leaf: Option<u32>,
963    /// Optional details.
964    #[serde(default, skip_serializing_if = "Option::is_none")]
965    pub details: Option<ReportDetails>,
966}
967
968impl Validate for KeyReportRequest {
969    fn validate(&self) -> Result<(), ValidationError> {
970        check_bytes("group_id", &self.group_id, GROUP_ID_BYTES)?;
971        check_known("kind", self.kind)?;
972        if let Some(d) = &self.details {
973            d.validate().map_err(|e| e.nested("details"))?;
974        }
975        Ok(())
976    }
977}
978
979// ---------------------------------------------------------------- the dispatch
980
981unit_enum! {
982    /// Why a transition started (`proposals.reason`).
983    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
984    pub enum TransitionReason {
985        /// Leaves joined.
986        Join = "join",
987        /// Leaves left or were removed.
988        Leave = "leave",
989        /// A device swap (Remove + Add of one member).
990        Swap = "swap",
991        /// A re-add after a missed epoch or a failed commit.
992        Readd = "readd",
993        /// A requested rekey.
994        Rekey = "rekey",
995        /// Recording consent was withdrawn.
996        Consent = "consent",
997        /// The recording stopped.
998        RecorderStop = "recorder_stop",
999        /// A device was revoked.
1000        Revoke = "revoke",
1001        /// The periodic rekey.
1002        Periodic = "periodic",
1003        /// A leaf-lifetime refresh.
1004        Refresh = "refresh",
1005        /// Leaves a rebuild could not match.
1006        RebuildOrphan = "rebuild_orphan",
1007        /// A sender stuck on a stale slot was removed.
1008        StuckSender = "stuck_sender",
1009    }
1010}
1011
1012unit_enum! {
1013    /// Why a call's group is reset (`reset.reason`).
1014    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1015    pub enum ResetReason {
1016        /// Every committer candidate was silent.
1017        CommitterTimeout = "committer_timeout",
1018        /// A removal was not activated by `remove_deadline_ms`.
1019        RemoveDeadline = "remove_deadline",
1020        /// A rebuild found two equally covered groups.
1021        RebuildConflict = "rebuild_conflict",
1022        /// Too many invalid commits in one generation.
1023        InvalidCommits = "invalid_commits",
1024        /// A state report broke a group invariant.
1025        Invariant = "invariant",
1026    }
1027}
1028
1029unit_enum! {
1030    /// Why a leaf is told to resync (`resync.reason`). `stale_slot` re-asserts the
1031    /// sender slot; every other reason is answered with an invalid report.
1032    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1033    pub enum KeyResyncReason {
1034        /// The leaf is behind the DS's epoch.
1035        Behind = "behind",
1036        /// The leaf holds another group.
1037        GroupMismatch = "group_mismatch",
1038        /// The leaf stopped acking.
1039        Lagging = "lagging",
1040        /// The engine sees the leaf sending on the wrong slot.
1041        StaleSlot = "stale_slot",
1042    }
1043}
1044
1045coded_enum! {
1046    /// Why a leaf left the key group (`removed.reason`; every voice leave reason plus
1047    /// the key service's and DM calls' own). Codes are stable for metrics and logs.
1048    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1049    pub enum RemoveReason {
1050        /// The member left.
1051        Left = "left" => 1,
1052        /// The media connection ended for good.
1053        Disconnected = "disconnected" => 2,
1054        /// Another device of the member took over (swap).
1055        Replaced = "replaced" => 3,
1056        /// The member moved or switched channel.
1057        Moved = "moved" => 4,
1058        /// A moderator disconnected the member.
1059        RemovedByModerator = "removed_by_moderator" => 5,
1060        /// The member lost CONNECT or VIEW.
1061        PermsLost = "perms_lost" => 6,
1062        /// The channel was archived.
1063        ChannelArchived = "channel_archived" => 7,
1064        /// The member left or was removed from the space.
1065        RemovedFromSpace = "removed_from_space" => 8,
1066        /// The member was timed out.
1067        TimedOut = "timed_out" => 9,
1068        /// The account was deprovisioned.
1069        AccountRemoved = "account_removed" => 10,
1070        /// The login session was revoked.
1071        SessionRevoked = "session_revoked" => 11,
1072        /// The device was revoked.
1073        DeviceRevoked = "device_revoked" => 12,
1074        /// The media outlived every socket.
1075        Orphaned = "orphaned" => 13,
1076        /// Alone in the call too long.
1077        AloneTimeout = "alone_timeout" => 14,
1078        /// Media never connected.
1079        ConnectTimeout = "connect_timeout" => 15,
1080        /// The engine restarted and the media did not come back.
1081        MediaRestarted = "media_restarted" => 16,
1082        /// Voice was turned off.
1083        VoiceDisabled = "voice_disabled" => 17,
1084        /// The sender stayed on a stale key slot.
1085        E2eeSenderIndexStuck = "e2ee_sender_index_stuck" => 18,
1086        /// The device stopped answering key requests (removed as unresponsive).
1087        Unresponsive = "unresponsive" => 19,
1088        /// A rebuild found no live entry for the leaf.
1089        RebuildOrphan = "rebuild_orphan" => 20,
1090        /// The creator's group was refused.
1091        CreateFailed = "create_failed" => 21,
1092        /// The DM call ended for everyone.
1093        CallEnded = "call_ended" => 22,
1094    }
1095}
1096
1097impl RemoveReason {
1098    /// A forced removal: audited `call.e2ee_member_removed`. Ordinary departures
1099    /// are not.
1100    pub const fn is_forced(self) -> bool {
1101        !matches!(
1102            self,
1103            RemoveReason::Left
1104                | RemoveReason::Disconnected
1105                | RemoveReason::Replaced
1106                | RemoveReason::Moved
1107                | RemoveReason::ConnectTimeout
1108                | RemoveReason::CallEnded
1109        )
1110    }
1111}
1112
1113/// The `call_keys_delivered` dispatch body, tagged by `kind`. Clients ignore kinds
1114/// they do not know ([`CallKeysMessage::Unknown`]).
1115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1116#[serde(tag = "kind", rename_all = "snake_case")]
1117pub enum CallKeysMessage {
1118    /// A creator failover or a reset creator: the [`CallKeysInit`] fields.
1119    Init(CallKeysInit),
1120    /// A transition starts.
1121    Proposals {
1122        /// The call.
1123        call_id: CallId,
1124        /// The group.
1125        group_id: B64,
1126        /// The epoch the proposals are for.
1127        epoch: u64,
1128        /// DS-signed external `MLSMessage`s (Add and Remove only); empty for a rekey.
1129        proposals: Vec<B64>,
1130        /// The designated committer's leaf.
1131        committer: u32,
1132        /// Why.
1133        reason: TransitionReason,
1134        /// One entry per Add, keyed by its `key_package_ref`.
1135        bindings: LeafBindingTable,
1136    },
1137    /// Failover to the next committer candidate.
1138    CommitRequest {
1139        /// The call.
1140        call_id: CallId,
1141        /// The group.
1142        group_id: B64,
1143        /// The epoch.
1144        epoch: u64,
1145        /// The candidate's leaf.
1146        committer: u32,
1147        /// 2 or 3.
1148        attempt: u32,
1149    },
1150    /// The accepted commit.
1151    Commit {
1152        /// The call.
1153        call_id: CallId,
1154        /// The group.
1155        group_id: B64,
1156        /// The epoch the commit leaves.
1157        epoch_from: u64,
1158        /// TLS `MLSMessage(PublicMessage commit)`.
1159        commit: B64,
1160        /// The slot of `epoch_from + 1`.
1161        slot: u8,
1162        /// The leaves this commit added, keyed by leaf, for `epoch_from + 1`.
1163        bindings: LeafBindingTable,
1164    },
1165    /// A joiner's Welcome.
1166    Welcome {
1167        /// The call.
1168        call_id: CallId,
1169        /// The group.
1170        group_id: B64,
1171        /// The joiner's join id.
1172        join_id: JoinIdHex,
1173        /// The epoch the Welcome joins.
1174        epoch: u64,
1175        /// TLS `MLSMessage(Welcome)`.
1176        welcome: B64,
1177        /// TLS `RatchetTree` of `epoch`.
1178        ratchet_tree: B64,
1179        /// The group's slot base.
1180        slot_base: u8,
1181        /// `slot(epoch)`.
1182        slot: u8,
1183        /// The full table of `epoch`.
1184        bindings: LeafBindingTable,
1185    },
1186    /// Every sender switches to `slot`.
1187    Activate {
1188        /// The call.
1189        call_id: CallId,
1190        /// The group.
1191        group_id: B64,
1192        /// The epoch.
1193        epoch: u64,
1194        /// Its slot.
1195        slot: u8,
1196    },
1197    /// The group is replaced; send a fresh KeyPackage.
1198    Reset {
1199        /// The call.
1200        call_id: CallId,
1201        /// The group being collected.
1202        new_group_id: B64,
1203        /// Why.
1204        reason: ResetReason,
1205        /// The new group's slot base.
1206        slot_base: u8,
1207        /// The collection window.
1208        collect_ms: u64,
1209    },
1210    /// The recorder: a certified key recipient, or `removed: true` (no key fields).
1211    Recorder {
1212        /// The call.
1213        call_id: CallId,
1214        /// The recording.
1215        recording_id: Id,
1216        /// TLS `RecorderCert`.
1217        #[serde(default, skip_serializing_if = "Option::is_none")]
1218        recorder_cert: Option<B64>,
1219        /// The recorder's X25519 public key (32 bytes).
1220        #[serde(default, skip_serializing_if = "Option::is_none")]
1221        hpke_pub: Option<B64>,
1222        /// The recorder's engine identity (`p_…`, from the voice service's `admit_recorder`).
1223        #[serde(default, skip_serializing_if = "Option::is_none")]
1224        lk_identity: Option<LkIdentity>,
1225        /// The recording stopped.
1226        #[serde(default, skip_serializing_if = "is_false")]
1227        removed: bool,
1228    },
1229    /// Device certificates were revoked.
1230    Revoked {
1231        /// The revoked serials.
1232        serials: Vec<Id>,
1233    },
1234    /// The leaf was removed; its last key message.
1235    Removed {
1236        /// The call.
1237        call_id: CallId,
1238        /// The group.
1239        group_id: B64,
1240        /// The removed join.
1241        join_id: JoinIdHex,
1242        /// Why.
1243        reason: RemoveReason,
1244    },
1245    /// The dispatch form of the state report's `409` answers, and `stale_slot`.
1246    Resync {
1247        /// The call.
1248        call_id: CallId,
1249        /// The leaf's join id.
1250        join_id: JoinIdHex,
1251        /// Why.
1252        reason: KeyResyncReason,
1253        /// With `stale_slot`: the slot the sender must use.
1254        #[serde(default, skip_serializing_if = "Option::is_none")]
1255        expected_slot: Option<u8>,
1256    },
1257    /// A kind this build does not know.
1258    #[serde(other)]
1259    #[schemars(skip)]
1260    Unknown,
1261}
1262
1263impl CallKeysMessage {
1264    /// The `kind` string (`"unknown"` for [`CallKeysMessage::Unknown`]); metrics label it.
1265    pub const fn kind(&self) -> &'static str {
1266        match self {
1267            CallKeysMessage::Init(_) => "init",
1268            CallKeysMessage::Proposals { .. } => "proposals",
1269            CallKeysMessage::CommitRequest { .. } => "commit_request",
1270            CallKeysMessage::Commit { .. } => "commit",
1271            CallKeysMessage::Welcome { .. } => "welcome",
1272            CallKeysMessage::Activate { .. } => "activate",
1273            CallKeysMessage::Reset { .. } => "reset",
1274            CallKeysMessage::Recorder { .. } => "recorder",
1275            CallKeysMessage::Revoked { .. } => "revoked",
1276            CallKeysMessage::Removed { .. } => "removed",
1277            CallKeysMessage::Resync { .. } => "resync",
1278            CallKeysMessage::Unknown => "unknown",
1279        }
1280    }
1281}
1282
1283// ---------------------------------------------------------------- READY, consent, status
1284
1285unit_enum! {
1286    /// Policy `calls.verification_code`: whether "Call info → Security code" is
1287    /// shown. `required` is reserved for a later mode and refused by the policy validator.
1288    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1289    pub enum VerificationCode {
1290        /// Shown on request, never modal (the default).
1291        Shown = "shown",
1292        /// Not shown.
1293        Hidden = "hidden",
1294        /// Reserved: "confirm before you speak" (refused in v1).
1295        Required = "required",
1296    }
1297}
1298
1299/// READY `call_keys`: the trust anchors and client parameters. Absent when voice is
1300/// disabled.
1301#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1302#[non_exhaustive]
1303pub struct ReadyCallKeys {
1304    /// TLS `ExternalSender` of every group.
1305    pub external_sender: B64,
1306    /// The raw 32-byte DS Ed25519 key, for pinning.
1307    pub ds_public_key: B64,
1308    /// The install CA.
1309    pub ca: CallPublicKey,
1310    /// Serials of revoked, unexpired device certificates (at most 5,000).
1311    pub crl: Vec<Id>,
1312    /// More revoked serials exist: page them with `GET /api/v1/devices/crl`.
1313    #[serde(default, skip_serializing_if = "is_false")]
1314    pub crl_partial: bool,
1315    /// Policy `calls.verification_code`.
1316    pub verification_code: VerificationCode,
1317    /// Client timings.
1318    pub params: CallKeysParams,
1319}
1320
1321impl ReadyCallKeys {
1322    /// A `ReadyCallKeys` with its required fields: every flag `false` and every list empty.
1323    pub fn new(
1324        external_sender: B64,
1325        ds_public_key: B64,
1326        ca: CallPublicKey,
1327        verification_code: VerificationCode,
1328        params: CallKeysParams,
1329    ) -> Self {
1330        ReadyCallKeys {
1331            external_sender,
1332            ds_public_key,
1333            ca,
1334            crl: Vec::new(),
1335            crl_partial: false,
1336            verification_code,
1337            params,
1338        }
1339    }
1340}
1341
1342unit_enum! {
1343    /// A member's consent for one recording (the key service's `ConsentSource`).
1344    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1345    pub enum ConsentState {
1346        /// Granted: releases are forwarded.
1347        Granted = "granted",
1348        /// Declined.
1349        Denied = "denied",
1350        /// Not answered yet.
1351        Pending = "pending",
1352    }
1353}
1354
1355/// `status.voice.e2ee`.
1356#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1357#[non_exhaustive]
1358pub struct StatusVoiceE2ee {
1359    /// Live key groups.
1360    pub calls: u32,
1361    /// Leaves across them.
1362    pub leaves: u32,
1363    /// Lagging leaves.
1364    pub lagging: u32,
1365    /// Calls rebuilding after a restart.
1366    pub rebuilding: u32,
1367    /// Group resets in the last hour.
1368    pub resets_1h: u32,
1369    /// Removals past their hard bound in the last hour.
1370    pub removal_overdue_1h: u32,
1371    /// Roster-kind reports in the last hour.
1372    pub roster_reports_1h: u32,
1373    /// The CA key id; absent when the key failed to load.
1374    #[serde(default, skip_serializing_if = "Option::is_none")]
1375    pub ca_kid: Option<String>,
1376    /// The DS key id; absent when the key failed to load.
1377    #[serde(default, skip_serializing_if = "Option::is_none")]
1378    pub ds_kid: Option<String>,
1379    /// Unrevoked enrolled devices.
1380    pub devices: u64,
1381    /// Serials in the in-memory CRL.
1382    pub crl_size: u64,
1383    /// One entry per live key group, sorted by `call_id` (Sew 0.7.1). No member, device, join
1384    /// id or key material: what K2 needs to diagnose a stuck call without the mgmt socket.
1385    #[serde(default)]
1386    pub per_call: Vec<StatusVoiceE2eeCall>,
1387}
1388
1389/// One call in `status.voice.e2ee.per_call` (Sew 0.7.1).
1390#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1391#[non_exhaustive]
1392pub struct StatusVoiceE2eeCall {
1393    /// The call (its room name, as the key routes carry it).
1394    pub call_id: CallId,
1395    /// Group resets so far (0 for the first group).
1396    pub generation: u32,
1397    /// The DS group's epoch.
1398    pub epoch: u64,
1399    /// The last activated epoch; absent before the first activation.
1400    #[serde(default, skip_serializing_if = "Option::is_none")]
1401    pub active_epoch: Option<u64>,
1402    /// Leaves by state.
1403    pub leaves_by_state: StatusVoiceE2eeLeaves,
1404    /// Admitted joins without a leaf yet.
1405    pub pending: u32,
1406    /// Queued changes.
1407    pub queue_len: u32,
1408    /// The call waits for its first joiner to create the group.
1409    pub awaiting_creator: bool,
1410    /// A group reset is in flight.
1411    pub resetting: bool,
1412    /// The call is rebuilding after a `sew` restart.
1413    pub rebuilding: bool,
1414    /// The call is in reset back-off.
1415    pub backoff: bool,
1416}
1417
1418impl StatusVoiceE2eeCall {
1419    /// A `StatusVoiceE2eeCall` with its required fields: every count 0, every flag `false`
1420    /// and every optional field unset.
1421    pub fn new(call_id: CallId, leaves_by_state: StatusVoiceE2eeLeaves) -> Self {
1422        StatusVoiceE2eeCall {
1423            call_id,
1424            generation: 0,
1425            epoch: 0,
1426            active_epoch: None,
1427            leaves_by_state,
1428            pending: 0,
1429            queue_len: 0,
1430            awaiting_creator: false,
1431            resetting: false,
1432            rebuilding: false,
1433            backoff: false,
1434        }
1435    }
1436}
1437
1438/// Leaf counts by state in a [`StatusVoiceE2eeCall`].
1439#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1440#[non_exhaustive]
1441pub struct StatusVoiceE2eeLeaves {
1442    /// Welcomed, not yet acked.
1443    pub joining: u32,
1444    /// Acked.
1445    pub active: u32,
1446    /// Left behind (behind the active epoch).
1447    pub lagging: u32,
1448    /// Being removed.
1449    pub leaving: u32,
1450}