1use 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
21pub const CIPHERSUITE_V1: u16 = 0x0001;
23pub const KDF_HKDF: &str = "hkdf";
25pub const KEY_PACKAGE_REF_BYTES: usize = 32;
27pub const GROUP_ID_BYTES: usize = 16;
29pub const CAPS_STRING_MAX: usize = 64;
31pub const CAPS_CIPHERSUITES_MAX: usize = 16;
33pub const GATEWAY_SESSION_MAX: usize = 128;
35pub const UPLOAD_KEY_PACKAGES_MAX: usize = 2;
37pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
80#[serde(deny_unknown_fields)]
81#[non_exhaustive]
82pub struct E2eeCaps {
83 pub sender_key_index: bool,
85 pub kdf: String,
87 pub key_ring_size: u32,
89 pub sdk: String,
91 pub sdk_version: String,
93 #[serde(default, skip_serializing_if = "Option::is_none")]
95 pub browser: Option<String>,
96 #[serde(default, skip_serializing_if = "Option::is_none")]
98 pub lib: Option<String>,
99 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub ciphersuites: Option<Vec<u16>>,
102}
103
104impl E2eeCaps {
105 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
151#[serde(deny_unknown_fields)]
152pub struct E2eeJoin {
153 pub key_package_ref: B64,
155 pub gateway_session: String,
157 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
181#[serde(deny_unknown_fields)]
182pub struct KeyJoinRequest {
183 pub join_id: JoinIdHex,
185 pub gateway_session: String,
187 pub key_package_ref: B64,
189 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
213#[non_exhaustive]
214pub struct CallKeysParams {
215 pub ciphersuite: u16,
217 pub ciphersuites: Vec<u16>,
219 pub key_ring_size: u32,
221 pub kdf: String,
223 pub exporter_label: String,
225 pub release_info_label: String,
227 pub retire_after_ms: u64,
229 pub client_activate_fallback_ms: u64,
231 pub key_package_max_lifetime_s: u64,
233 pub unknown_call_buffer_ms: u64,
235 pub securing_indicator_after_ms: u64,
237}
238
239impl CallKeysParams {
240 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
265#[non_exhaustive]
266pub struct CallKeysInit {
267 pub call_id: CallId,
269 pub join_id: JoinIdHex,
271 pub lk_identity: LkIdentity,
273 pub scope: CallScope,
275 pub group_id: B64,
277 pub epoch: u64,
279 pub create: bool,
281 pub activate_on_create: bool,
283 pub slot_base: u8,
285 pub external_sender: B64,
287 pub params: CallKeysParams,
289}
290
291impl CallKeysInit {
292 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
322#[serde(deny_unknown_fields)]
323pub struct KeyPackageUploadRequest {
324 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
345pub struct KeyPackageRefItem {
346 pub key_package_ref: B64,
348 pub expires_at_ms: u64,
350}
351
352#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
354pub struct KeyPackageUploadResponse {
355 pub items: Vec<KeyPackageRefItem>,
357}
358
359#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
364pub struct LeafBindingEntryJson {
365 #[serde(default, skip_serializing_if = "Option::is_none")]
367 pub leaf: Option<u32>,
368 #[serde(default, skip_serializing_if = "Option::is_none")]
370 pub key_package_ref: Option<B64>,
371 pub join_id: JoinIdHex,
373 pub lk_identity: LkIdentity,
375}
376
377#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
380pub struct LeafBindingTable {
381 pub call_id: CallId,
383 pub group_id: B64,
385 pub epoch: u64,
387 pub entries: Vec<LeafBindingEntryJson>,
389 pub sig: B64,
391}
392
393#[derive(Debug, Clone, PartialEq, Eq)]
395pub enum BindingError {
396 EntryKey(usize),
398 Identity(usize),
400 CallId,
402 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
490pub struct BindingsUpdate {
491 pub group_id: B64,
493 pub epoch: u64,
495 pub slot_base: u8,
497 pub table: LeafBindingTable,
499}
500
501#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
503pub struct CallPublicKey {
504 pub kid: String,
506 pub public_key: B64,
508}
509
510#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
512pub struct CallPublicKeys {
513 pub ca: CallPublicKey,
515 pub ds: CallPublicKey,
517}
518
519unit_enum! {
522 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
524 pub enum KeyStateStatus {
525 InSync = "in_sync",
527 SendTree = "send_tree",
529 Rebuilding = "rebuilding",
531 }
532}
533
534#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
536#[serde(deny_unknown_fields)]
537pub struct KeyStateRequest {
538 pub join_id: JoinIdHex,
540 pub gateway_session: String,
542 pub group_id: B64,
544 pub leaf: u32,
546 pub epoch: u64,
548 pub active_epoch: u64,
550 pub slot_base: u8,
552 pub tree_hash: B64,
554 pub bindings_hash: B64,
556 pub group_info: B64,
558 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
584pub struct KeyStateResponse {
585 pub status: KeyStateStatus,
587 #[serde(default, skip_serializing_if = "Option::is_none")]
589 pub retry_after_ms: Option<u64>,
590 #[serde(default, skip_serializing_if = "Option::is_none")]
592 pub bindings: Option<LeafBindingTable>,
593}
594
595#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
597#[serde(deny_unknown_fields)]
598pub struct KeyCommitRequest {
599 pub join_id: JoinIdHex,
601 pub group_id: B64,
603 pub epoch: u64,
605 pub commit: B64,
607 #[serde(default, skip_serializing_if = "Option::is_none")]
609 pub welcome: Option<B64>,
610 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
627pub struct KeyCommitAccepted {
628 pub accepted: bool,
630 pub epoch: u64,
632 pub slot: u8,
634}
635
636#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
638#[serde(deny_unknown_fields)]
639pub struct KeyReadyRequest {
640 pub join_id: JoinIdHex,
642 pub group_id: B64,
644 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 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
657 pub enum InvalidReason {
658 CommitFailed = "commit_failed",
660 BadCommit = "bad_commit",
662 BadProposal = "bad_proposal",
664 BadWelcome = "bad_welcome",
666 MissedEpoch = "missed_epoch",
668 RecoveryTimeout = "recovery_timeout",
670 Behind = "behind",
672 StateLost = "state_lost",
674 }
675}
676
677#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
680#[serde(deny_unknown_fields)]
681pub struct KeyInvalidRequest {
682 pub join_id: JoinIdHex,
684 pub group_id: B64,
686 pub epoch: u64,
688 pub reason: InvalidReason,
690 pub key_package: B64,
692 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
712#[serde(deny_unknown_fields)]
713pub struct KeyResetPackageRequest {
714 pub join_id: JoinIdHex,
716 pub new_group_id: B64,
718 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
733#[serde(deny_unknown_fields)]
734pub struct KeyReleaseRequest {
735 pub join_id: JoinIdHex,
737 pub group_id: B64,
739 pub epoch: u64,
741 pub slot: u8,
743 pub recording_id: Id,
745 pub leaf: u32,
747 pub sender_identity: String,
749 pub enc: B64,
751 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
765pub struct Release {
766 pub call_id: CallId,
768 pub recording_id: Id,
770 pub group_id: B64,
772 pub epoch: u64,
774 pub leaf: u32,
776 pub slot: u8,
778 pub sender_identity: LkIdentity,
780 pub enc: B64,
782 pub ct: B64,
784}
785
786impl Release {
787 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 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
804 pub enum RekeyReason {
805 ConsentWithdrawn = "consent_withdrawn",
807 }
808}
809
810#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
812#[serde(deny_unknown_fields)]
813pub struct KeyRekeyRequest {
814 pub join_id: JoinIdHex,
816 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 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
829 pub enum ReportKind {
830 LeafWithoutVoiceState = "leaf_without_voice_state",
832 DuplicateMember = "duplicate_member",
834 EngineParticipantWithoutLeaf = "engine_participant_without_leaf",
836 ExternalSenderMismatch = "external_sender_mismatch",
838 CaChanged = "ca_changed",
840 LeafBindingInvalid = "leaf_binding_invalid",
842 ScopeInvalid = "scope_invalid",
844 SenderIndexStuck = "sender_index_stuck",
846 PeerUndecryptable = "peer_undecryptable",
848 EngineUnencryptedTrack = "engine_unencrypted_track",
850 EngineSifTrailer = "engine_sif_trailer",
852 EngineEncryptionDowngrade = "engine_encryption_downgrade",
854 }
855}
856
857impl ReportKind {
858 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 pub const fn is_slot_signal(self) -> bool {
874 matches!(
875 self,
876 ReportKind::SenderIndexStuck | ReportKind::PeerUndecryptable
877 )
878 }
879
880 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
893#[serde(deny_unknown_fields)]
894pub struct ReportDetails {
895 #[serde(default, skip_serializing_if = "Option::is_none")]
897 pub expected_slot: Option<u8>,
898 #[serde(default, skip_serializing_if = "Option::is_none")]
900 pub observed_slot: Option<u8>,
901 #[serde(default, skip_serializing_if = "Option::is_none")]
903 pub since_ms: Option<u64>,
904 #[serde(default, skip_serializing_if = "Option::is_none")]
906 pub failures: Option<u32>,
907 #[serde(default, skip_serializing_if = "Option::is_none")]
909 pub attempts: Option<u32>,
910 #[serde(default, skip_serializing_if = "Option::is_none")]
912 pub missing_index: Option<u8>,
913 #[serde(default, skip_serializing_if = "Option::is_none")]
915 pub reason: Option<String>,
916 #[serde(default, skip_serializing_if = "Option::is_none")]
918 pub sdk: Option<String>,
919 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
950#[serde(deny_unknown_fields)]
951pub struct KeyReportRequest {
952 pub join_id: JoinIdHex,
954 pub group_id: B64,
956 pub epoch: u64,
958 pub kind: ReportKind,
960 #[serde(default, skip_serializing_if = "Option::is_none")]
962 pub leaf: Option<u32>,
963 #[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
979unit_enum! {
982 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
984 pub enum TransitionReason {
985 Join = "join",
987 Leave = "leave",
989 Swap = "swap",
991 Readd = "readd",
993 Rekey = "rekey",
995 Consent = "consent",
997 RecorderStop = "recorder_stop",
999 Revoke = "revoke",
1001 Periodic = "periodic",
1003 Refresh = "refresh",
1005 RebuildOrphan = "rebuild_orphan",
1007 StuckSender = "stuck_sender",
1009 }
1010}
1011
1012unit_enum! {
1013 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1015 pub enum ResetReason {
1016 CommitterTimeout = "committer_timeout",
1018 RemoveDeadline = "remove_deadline",
1020 RebuildConflict = "rebuild_conflict",
1022 InvalidCommits = "invalid_commits",
1024 Invariant = "invariant",
1026 }
1027}
1028
1029unit_enum! {
1030 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1033 pub enum KeyResyncReason {
1034 Behind = "behind",
1036 GroupMismatch = "group_mismatch",
1038 Lagging = "lagging",
1040 StaleSlot = "stale_slot",
1042 }
1043}
1044
1045coded_enum! {
1046 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1049 pub enum RemoveReason {
1050 Left = "left" => 1,
1052 Disconnected = "disconnected" => 2,
1054 Replaced = "replaced" => 3,
1056 Moved = "moved" => 4,
1058 RemovedByModerator = "removed_by_moderator" => 5,
1060 PermsLost = "perms_lost" => 6,
1062 ChannelArchived = "channel_archived" => 7,
1064 RemovedFromSpace = "removed_from_space" => 8,
1066 TimedOut = "timed_out" => 9,
1068 AccountRemoved = "account_removed" => 10,
1070 SessionRevoked = "session_revoked" => 11,
1072 DeviceRevoked = "device_revoked" => 12,
1074 Orphaned = "orphaned" => 13,
1076 AloneTimeout = "alone_timeout" => 14,
1078 ConnectTimeout = "connect_timeout" => 15,
1080 MediaRestarted = "media_restarted" => 16,
1082 VoiceDisabled = "voice_disabled" => 17,
1084 E2eeSenderIndexStuck = "e2ee_sender_index_stuck" => 18,
1086 Unresponsive = "unresponsive" => 19,
1088 RebuildOrphan = "rebuild_orphan" => 20,
1090 CreateFailed = "create_failed" => 21,
1092 CallEnded = "call_ended" => 22,
1094 }
1095}
1096
1097impl RemoveReason {
1098 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1116#[serde(tag = "kind", rename_all = "snake_case")]
1117pub enum CallKeysMessage {
1118 Init(CallKeysInit),
1120 Proposals {
1122 call_id: CallId,
1124 group_id: B64,
1126 epoch: u64,
1128 proposals: Vec<B64>,
1130 committer: u32,
1132 reason: TransitionReason,
1134 bindings: LeafBindingTable,
1136 },
1137 CommitRequest {
1139 call_id: CallId,
1141 group_id: B64,
1143 epoch: u64,
1145 committer: u32,
1147 attempt: u32,
1149 },
1150 Commit {
1152 call_id: CallId,
1154 group_id: B64,
1156 epoch_from: u64,
1158 commit: B64,
1160 slot: u8,
1162 bindings: LeafBindingTable,
1164 },
1165 Welcome {
1167 call_id: CallId,
1169 group_id: B64,
1171 join_id: JoinIdHex,
1173 epoch: u64,
1175 welcome: B64,
1177 ratchet_tree: B64,
1179 slot_base: u8,
1181 slot: u8,
1183 bindings: LeafBindingTable,
1185 },
1186 Activate {
1188 call_id: CallId,
1190 group_id: B64,
1192 epoch: u64,
1194 slot: u8,
1196 },
1197 Reset {
1199 call_id: CallId,
1201 new_group_id: B64,
1203 reason: ResetReason,
1205 slot_base: u8,
1207 collect_ms: u64,
1209 },
1210 Recorder {
1212 call_id: CallId,
1214 recording_id: Id,
1216 #[serde(default, skip_serializing_if = "Option::is_none")]
1218 recorder_cert: Option<B64>,
1219 #[serde(default, skip_serializing_if = "Option::is_none")]
1221 hpke_pub: Option<B64>,
1222 #[serde(default, skip_serializing_if = "Option::is_none")]
1224 lk_identity: Option<LkIdentity>,
1225 #[serde(default, skip_serializing_if = "is_false")]
1227 removed: bool,
1228 },
1229 Revoked {
1231 serials: Vec<Id>,
1233 },
1234 Removed {
1236 call_id: CallId,
1238 group_id: B64,
1240 join_id: JoinIdHex,
1242 reason: RemoveReason,
1244 },
1245 Resync {
1247 call_id: CallId,
1249 join_id: JoinIdHex,
1251 reason: KeyResyncReason,
1253 #[serde(default, skip_serializing_if = "Option::is_none")]
1255 expected_slot: Option<u8>,
1256 },
1257 #[serde(other)]
1259 #[schemars(skip)]
1260 Unknown,
1261}
1262
1263impl CallKeysMessage {
1264 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
1283unit_enum! {
1286 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1289 pub enum VerificationCode {
1290 Shown = "shown",
1292 Hidden = "hidden",
1294 Required = "required",
1296 }
1297}
1298
1299#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1302#[non_exhaustive]
1303pub struct ReadyCallKeys {
1304 pub external_sender: B64,
1306 pub ds_public_key: B64,
1308 pub ca: CallPublicKey,
1310 pub crl: Vec<Id>,
1312 #[serde(default, skip_serializing_if = "is_false")]
1314 pub crl_partial: bool,
1315 pub verification_code: VerificationCode,
1317 pub params: CallKeysParams,
1319}
1320
1321impl ReadyCallKeys {
1322 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 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1345 pub enum ConsentState {
1346 Granted = "granted",
1348 Denied = "denied",
1350 Pending = "pending",
1352 }
1353}
1354
1355#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1357#[non_exhaustive]
1358pub struct StatusVoiceE2ee {
1359 pub calls: u32,
1361 pub leaves: u32,
1363 pub lagging: u32,
1365 pub rebuilding: u32,
1367 pub resets_1h: u32,
1369 pub removal_overdue_1h: u32,
1371 pub roster_reports_1h: u32,
1373 #[serde(default, skip_serializing_if = "Option::is_none")]
1375 pub ca_kid: Option<String>,
1376 #[serde(default, skip_serializing_if = "Option::is_none")]
1378 pub ds_kid: Option<String>,
1379 pub devices: u64,
1381 pub crl_size: u64,
1383 #[serde(default)]
1386 pub per_call: Vec<StatusVoiceE2eeCall>,
1387}
1388
1389#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1391#[non_exhaustive]
1392pub struct StatusVoiceE2eeCall {
1393 pub call_id: CallId,
1395 pub generation: u32,
1397 pub epoch: u64,
1399 #[serde(default, skip_serializing_if = "Option::is_none")]
1401 pub active_epoch: Option<u64>,
1402 pub leaves_by_state: StatusVoiceE2eeLeaves,
1404 pub pending: u32,
1406 pub queue_len: u32,
1408 pub awaiting_creator: bool,
1410 pub resetting: bool,
1412 pub rebuilding: bool,
1414 pub backoff: bool,
1416}
1417
1418impl StatusVoiceE2eeCall {
1419 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1440#[non_exhaustive]
1441pub struct StatusVoiceE2eeLeaves {
1442 pub joining: u32,
1444 pub active: u32,
1446 pub lagging: u32,
1448 pub leaving: u32,
1450}