use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use super::CallScope;
use super::b64::B64;
use super::names::{CallId, JoinIdHex, LkIdentity};
use super::tls::{self, BindingKey, LeafBindingEntry, LeafBindingTableTbs};
use crate::error::{Validate, ValidationError, check_known};
use crate::id::Id;
pub const CIPHERSUITE_V1: u16 = 0x0001;
pub const KDF_HKDF: &str = "hkdf";
pub const KEY_PACKAGE_REF_BYTES: usize = 32;
pub const GROUP_ID_BYTES: usize = 16;
pub const CAPS_STRING_MAX: usize = 64;
pub const CAPS_CIPHERSUITES_MAX: usize = 16;
pub const GATEWAY_SESSION_MAX: usize = 128;
pub const UPLOAD_KEY_PACKAGES_MAX: usize = 2;
pub const REPORT_DETAILS_MAX_BYTES: usize = 256;
fn check_len(field: &str, s: &str, min: usize, max: usize) -> Result<(), ValidationError> {
if s.len() < min || s.len() > max {
return Err(ValidationError::invalid(
field,
format!("{field} must be {min}–{max} bytes, got {}", s.len()),
));
}
Ok(())
}
fn check_bytes(field: &str, b: &B64, len: usize) -> Result<(), ValidationError> {
if b.len() != len {
return Err(ValidationError::invalid(
field,
format!("{field} must be {len} bytes, got {}", b.len()),
));
}
Ok(())
}
fn check_nonempty(field: &str, b: &B64) -> Result<(), ValidationError> {
if b.is_empty() {
return Err(ValidationError::invalid(
field,
format!("{field} must not be empty"),
));
}
Ok(())
}
fn is_false(b: &bool) -> bool {
!*b
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct E2eeCaps {
pub sender_key_index: bool,
pub kdf: String,
pub key_ring_size: u32,
pub sdk: String,
pub sdk_version: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub browser: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lib: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ciphersuites: Option<Vec<u16>>,
}
impl E2eeCaps {
pub fn new(
kdf: impl Into<String>,
sdk: impl Into<String>,
sdk_version: impl Into<String>,
) -> Self {
E2eeCaps {
sender_key_index: false,
kdf: kdf.into(),
key_ring_size: 0,
sdk: sdk.into(),
sdk_version: sdk_version.into(),
browser: None,
lib: None,
ciphersuites: None,
}
}
}
impl Validate for E2eeCaps {
fn validate(&self) -> Result<(), ValidationError> {
check_len("kdf", &self.kdf, 1, CAPS_STRING_MAX)?;
check_len("sdk", &self.sdk, 1, CAPS_STRING_MAX)?;
check_len("sdk_version", &self.sdk_version, 1, CAPS_STRING_MAX)?;
if let Some(b) = &self.browser {
check_len("browser", b, 1, CAPS_STRING_MAX)?;
}
if let Some(l) = &self.lib {
check_len("lib", l, 1, CAPS_STRING_MAX)?;
}
if let Some(c) = &self.ciphersuites
&& (c.is_empty() || c.len() > CAPS_CIPHERSUITES_MAX)
{
return Err(ValidationError::invalid(
"ciphersuites",
format!("ciphersuites must hold 1–{CAPS_CIPHERSUITES_MAX} values"),
));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct E2eeJoin {
pub key_package_ref: B64,
pub gateway_session: String,
pub caps: E2eeCaps,
}
impl Validate for E2eeJoin {
fn validate(&self) -> Result<(), ValidationError> {
check_bytes(
"key_package_ref",
&self.key_package_ref,
KEY_PACKAGE_REF_BYTES,
)?;
check_len(
"gateway_session",
&self.gateway_session,
1,
GATEWAY_SESSION_MAX,
)?;
self.caps.validate().map_err(|e| e.nested("caps"))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyJoinRequest {
pub join_id: JoinIdHex,
pub gateway_session: String,
pub key_package_ref: B64,
pub caps: E2eeCaps,
}
impl Validate for KeyJoinRequest {
fn validate(&self) -> Result<(), ValidationError> {
check_bytes(
"key_package_ref",
&self.key_package_ref,
KEY_PACKAGE_REF_BYTES,
)?;
check_len(
"gateway_session",
&self.gateway_session,
1,
GATEWAY_SESSION_MAX,
)?;
self.caps.validate().map_err(|e| e.nested("caps"))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct CallKeysParams {
pub ciphersuite: u16,
pub ciphersuites: Vec<u16>,
pub key_ring_size: u32,
pub kdf: String,
pub exporter_label: String,
pub release_info_label: String,
pub retire_after_ms: u64,
pub client_activate_fallback_ms: u64,
pub key_package_max_lifetime_s: u64,
pub unknown_call_buffer_ms: u64,
pub securing_indicator_after_ms: u64,
}
impl CallKeysParams {
pub fn new(
kdf: impl Into<String>,
exporter_label: impl Into<String>,
release_info_label: impl Into<String>,
) -> Self {
CallKeysParams {
ciphersuite: 0,
ciphersuites: Vec::new(),
key_ring_size: 0,
kdf: kdf.into(),
exporter_label: exporter_label.into(),
release_info_label: release_info_label.into(),
retire_after_ms: 0,
client_activate_fallback_ms: 0,
key_package_max_lifetime_s: 0,
unknown_call_buffer_ms: 0,
securing_indicator_after_ms: 0,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct CallKeysInit {
pub call_id: CallId,
pub join_id: JoinIdHex,
pub lk_identity: LkIdentity,
pub scope: CallScope,
pub group_id: B64,
pub epoch: u64,
pub create: bool,
pub activate_on_create: bool,
pub slot_base: u8,
pub external_sender: B64,
pub params: CallKeysParams,
}
impl CallKeysInit {
pub fn new(
call_id: CallId,
join_id: JoinIdHex,
lk_identity: LkIdentity,
scope: CallScope,
group_id: B64,
external_sender: B64,
params: CallKeysParams,
) -> Self {
CallKeysInit {
call_id,
join_id,
lk_identity,
scope,
group_id,
epoch: 0,
create: false,
activate_on_create: false,
slot_base: 0,
external_sender,
params,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyPackageUploadRequest {
pub key_packages: Vec<B64>,
}
impl Validate for KeyPackageUploadRequest {
fn validate(&self) -> Result<(), ValidationError> {
if self.key_packages.is_empty() || self.key_packages.len() > UPLOAD_KEY_PACKAGES_MAX {
return Err(ValidationError::invalid(
"key_packages",
format!("key_packages must hold 1–{UPLOAD_KEY_PACKAGES_MAX} packages"),
));
}
for (i, kp) in self.key_packages.iter().enumerate() {
check_nonempty(&format!("key_packages[{i}]"), kp)?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct KeyPackageRefItem {
pub key_package_ref: B64,
pub expires_at_ms: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct KeyPackageUploadResponse {
pub items: Vec<KeyPackageRefItem>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct LeafBindingEntryJson {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub leaf: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_package_ref: Option<B64>,
pub join_id: JoinIdHex,
pub lk_identity: LkIdentity,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct LeafBindingTable {
pub call_id: CallId,
pub group_id: B64,
pub epoch: u64,
pub entries: Vec<LeafBindingEntryJson>,
pub sig: B64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BindingError {
EntryKey(usize),
Identity(usize),
CallId,
Table(tls::TableError),
}
impl std::fmt::Display for BindingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BindingError::EntryKey(i) => {
write!(f, "entry {i} needs exactly one of leaf and key_package_ref")
}
BindingError::Identity(i) => write!(f, "entry {i}: lk_identity does not match join_id"),
BindingError::CallId => f.write_str("call_id is not a room name"),
BindingError::Table(e) => write!(f, "{e}"),
}
}
}
impl std::error::Error for BindingError {}
impl LeafBindingTable {
pub fn tbs(&self) -> Result<LeafBindingTableTbs, BindingError> {
let mut entries = Vec::with_capacity(self.entries.len());
for (i, e) in self.entries.iter().enumerate() {
let key = match (e.leaf, &e.key_package_ref) {
(Some(l), None) => BindingKey::Leaf(l),
(None, Some(r)) => BindingKey::KeyPackageRef(r.as_bytes().to_vec()),
_ => return Err(BindingError::EntryKey(i)),
};
if e.join_id.lk_identity() != e.lk_identity {
return Err(BindingError::Identity(i));
}
entries.push(LeafBindingEntry {
key,
join_id: e.join_id.bytes(),
});
}
let tbs = LeafBindingTableTbs {
call_id: self.call_id.as_str().as_bytes().to_vec(),
group_id: self.group_id.as_bytes().to_vec(),
epoch: self.epoch,
entries,
};
tbs.check().map_err(BindingError::Table)?;
Ok(tbs)
}
pub fn from_tbs(
tbs: &LeafBindingTableTbs,
sig: Vec<u8>,
) -> Result<LeafBindingTable, BindingError> {
tbs.check().map_err(BindingError::Table)?;
let call_id = std::str::from_utf8(&tbs.call_id)
.ok()
.and_then(|s| CallId::parse(s).ok())
.ok_or(BindingError::CallId)?;
let entries = tbs
.entries
.iter()
.map(|e| {
let join_id = JoinIdHex::from_bytes(e.join_id);
let (leaf, key_package_ref) = match &e.key {
BindingKey::Leaf(l) => (Some(*l), None),
BindingKey::KeyPackageRef(r) => (None, Some(B64::new(r.clone()))),
};
LeafBindingEntryJson {
leaf,
key_package_ref,
lk_identity: join_id.lk_identity(),
join_id,
}
})
.collect();
Ok(LeafBindingTable {
call_id,
group_id: B64::new(tbs.group_id.clone()),
epoch: tbs.epoch,
entries,
sig: B64::new(sig),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct BindingsUpdate {
pub group_id: B64,
pub epoch: u64,
pub slot_base: u8,
pub table: LeafBindingTable,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CallPublicKey {
pub kid: String,
pub public_key: B64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CallPublicKeys {
pub ca: CallPublicKey,
pub ds: CallPublicKey,
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum KeyStateStatus {
InSync = "in_sync",
SendTree = "send_tree",
Rebuilding = "rebuilding",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyStateRequest {
pub join_id: JoinIdHex,
pub gateway_session: String,
pub group_id: B64,
pub leaf: u32,
pub epoch: u64,
pub active_epoch: u64,
pub slot_base: u8,
pub tree_hash: B64,
pub bindings_hash: B64,
pub group_info: B64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ratchet_tree: Option<B64>,
}
impl Validate for KeyStateRequest {
fn validate(&self) -> Result<(), ValidationError> {
check_len(
"gateway_session",
&self.gateway_session,
1,
GATEWAY_SESSION_MAX,
)?;
check_bytes("group_id", &self.group_id, GROUP_ID_BYTES)?;
check_nonempty("tree_hash", &self.tree_hash)?;
check_bytes("bindings_hash", &self.bindings_hash, 32)?;
check_nonempty("group_info", &self.group_info)?;
if let Some(t) = &self.ratchet_tree {
check_nonempty("ratchet_tree", t)?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct KeyStateResponse {
pub status: KeyStateStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retry_after_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bindings: Option<LeafBindingTable>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyCommitRequest {
pub join_id: JoinIdHex,
pub group_id: B64,
pub epoch: u64,
pub commit: B64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub welcome: Option<B64>,
pub group_info: B64,
}
impl Validate for KeyCommitRequest {
fn validate(&self) -> Result<(), ValidationError> {
check_bytes("group_id", &self.group_id, GROUP_ID_BYTES)?;
check_nonempty("commit", &self.commit)?;
if let Some(w) = &self.welcome {
check_nonempty("welcome", w)?;
}
check_nonempty("group_info", &self.group_info)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct KeyCommitAccepted {
pub accepted: bool,
pub epoch: u64,
pub slot: u8,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyReadyRequest {
pub join_id: JoinIdHex,
pub group_id: B64,
pub epoch: u64,
}
impl Validate for KeyReadyRequest {
fn validate(&self) -> Result<(), ValidationError> {
check_bytes("group_id", &self.group_id, GROUP_ID_BYTES)
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum InvalidReason {
CommitFailed = "commit_failed",
BadCommit = "bad_commit",
BadProposal = "bad_proposal",
BadWelcome = "bad_welcome",
MissedEpoch = "missed_epoch",
RecoveryTimeout = "recovery_timeout",
Behind = "behind",
StateLost = "state_lost",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyInvalidRequest {
pub join_id: JoinIdHex,
pub group_id: B64,
pub epoch: u64,
pub reason: InvalidReason,
pub key_package: B64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gateway_session: Option<String>,
}
impl Validate for KeyInvalidRequest {
fn validate(&self) -> Result<(), ValidationError> {
check_bytes("group_id", &self.group_id, GROUP_ID_BYTES)?;
check_known("reason", self.reason)?;
if let Some(s) = &self.gateway_session {
check_len("gateway_session", s, 1, GATEWAY_SESSION_MAX)?;
}
check_nonempty("key_package", &self.key_package)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyResetPackageRequest {
pub join_id: JoinIdHex,
pub new_group_id: B64,
pub key_package: B64,
}
impl Validate for KeyResetPackageRequest {
fn validate(&self) -> Result<(), ValidationError> {
check_bytes("new_group_id", &self.new_group_id, GROUP_ID_BYTES)?;
check_nonempty("key_package", &self.key_package)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyReleaseRequest {
pub join_id: JoinIdHex,
pub group_id: B64,
pub epoch: u64,
pub slot: u8,
pub recording_id: Id,
pub leaf: u32,
pub sender_identity: String,
pub enc: B64,
pub ct: B64,
}
impl Validate for KeyReleaseRequest {
fn validate(&self) -> Result<(), ValidationError> {
check_bytes("group_id", &self.group_id, GROUP_ID_BYTES)?;
check_len("sender_identity", &self.sender_identity, 1, CAPS_STRING_MAX)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Release {
pub call_id: CallId,
pub recording_id: Id,
pub group_id: B64,
pub epoch: u64,
pub leaf: u32,
pub slot: u8,
pub sender_identity: LkIdentity,
pub enc: B64,
pub ct: B64,
}
impl Release {
pub fn info(&self) -> tls::ReleaseInfo {
tls::ReleaseInfo {
call_id: self.call_id.as_str().as_bytes().to_vec(),
recording_id: self.recording_id.get(),
group_id: self.group_id.as_bytes().to_vec(),
epoch: self.epoch,
leaf_index: self.leaf,
slot: self.slot,
sender_identity: self.sender_identity.as_str().as_bytes().to_vec(),
}
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum RekeyReason {
ConsentWithdrawn = "consent_withdrawn",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyRekeyRequest {
pub join_id: JoinIdHex,
pub reason: RekeyReason,
}
impl Validate for KeyRekeyRequest {
fn validate(&self) -> Result<(), ValidationError> {
check_known("reason", self.reason)
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum ReportKind {
LeafWithoutVoiceState = "leaf_without_voice_state",
DuplicateMember = "duplicate_member",
EngineParticipantWithoutLeaf = "engine_participant_without_leaf",
ExternalSenderMismatch = "external_sender_mismatch",
CaChanged = "ca_changed",
LeafBindingInvalid = "leaf_binding_invalid",
ScopeInvalid = "scope_invalid",
SenderIndexStuck = "sender_index_stuck",
PeerUndecryptable = "peer_undecryptable",
EngineUnencryptedTrack = "engine_unencrypted_track",
EngineSifTrailer = "engine_sif_trailer",
EngineEncryptionDowngrade = "engine_encryption_downgrade",
}
}
impl ReportKind {
pub const fn is_roster(self) -> bool {
matches!(
self,
ReportKind::LeafWithoutVoiceState
| ReportKind::DuplicateMember
| ReportKind::EngineParticipantWithoutLeaf
| ReportKind::ExternalSenderMismatch
| ReportKind::CaChanged
| ReportKind::LeafBindingInvalid
| ReportKind::ScopeInvalid
)
}
pub const fn is_slot_signal(self) -> bool {
matches!(
self,
ReportKind::SenderIndexStuck | ReportKind::PeerUndecryptable
)
}
pub const fn is_engine(self) -> bool {
matches!(
self,
ReportKind::EngineUnencryptedTrack
| ReportKind::EngineSifTrailer
| ReportKind::EngineEncryptionDowngrade
)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReportDetails {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expected_slot: Option<u8>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub observed_slot: Option<u8>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub since_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failures: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attempts: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub missing_index: Option<u8>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sdk: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sdk_version: Option<String>,
}
impl Validate for ReportDetails {
fn validate(&self) -> Result<(), ValidationError> {
for (field, v) in [
("reason", &self.reason),
("sdk", &self.sdk),
("sdk_version", &self.sdk_version),
] {
if let Some(s) = v {
check_len(field, s, 1, CAPS_STRING_MAX)?;
}
}
let n = serde_json::to_vec(self)
.map(|v| v.len())
.unwrap_or(usize::MAX);
if n > REPORT_DETAILS_MAX_BYTES {
return Err(ValidationError::too_large(
"details",
format!("details must be at most {REPORT_DETAILS_MAX_BYTES} bytes of JSON"),
));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyReportRequest {
pub join_id: JoinIdHex,
pub group_id: B64,
pub epoch: u64,
pub kind: ReportKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub leaf: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub details: Option<ReportDetails>,
}
impl Validate for KeyReportRequest {
fn validate(&self) -> Result<(), ValidationError> {
check_bytes("group_id", &self.group_id, GROUP_ID_BYTES)?;
check_known("kind", self.kind)?;
if let Some(d) = &self.details {
d.validate().map_err(|e| e.nested("details"))?;
}
Ok(())
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum TransitionReason {
Join = "join",
Leave = "leave",
Swap = "swap",
Readd = "readd",
Rekey = "rekey",
Consent = "consent",
RecorderStop = "recorder_stop",
Revoke = "revoke",
Periodic = "periodic",
Refresh = "refresh",
RebuildOrphan = "rebuild_orphan",
StuckSender = "stuck_sender",
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum ResetReason {
CommitterTimeout = "committer_timeout",
RemoveDeadline = "remove_deadline",
RebuildConflict = "rebuild_conflict",
InvalidCommits = "invalid_commits",
Invariant = "invariant",
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum KeyResyncReason {
Behind = "behind",
GroupMismatch = "group_mismatch",
Lagging = "lagging",
StaleSlot = "stale_slot",
}
}
coded_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum RemoveReason {
Left = "left" => 1,
Disconnected = "disconnected" => 2,
Replaced = "replaced" => 3,
Moved = "moved" => 4,
RemovedByModerator = "removed_by_moderator" => 5,
PermsLost = "perms_lost" => 6,
ChannelArchived = "channel_archived" => 7,
RemovedFromSpace = "removed_from_space" => 8,
TimedOut = "timed_out" => 9,
AccountRemoved = "account_removed" => 10,
SessionRevoked = "session_revoked" => 11,
DeviceRevoked = "device_revoked" => 12,
Orphaned = "orphaned" => 13,
AloneTimeout = "alone_timeout" => 14,
ConnectTimeout = "connect_timeout" => 15,
MediaRestarted = "media_restarted" => 16,
VoiceDisabled = "voice_disabled" => 17,
E2eeSenderIndexStuck = "e2ee_sender_index_stuck" => 18,
Unresponsive = "unresponsive" => 19,
RebuildOrphan = "rebuild_orphan" => 20,
CreateFailed = "create_failed" => 21,
CallEnded = "call_ended" => 22,
}
}
impl RemoveReason {
pub const fn is_forced(self) -> bool {
!matches!(
self,
RemoveReason::Left
| RemoveReason::Disconnected
| RemoveReason::Replaced
| RemoveReason::Moved
| RemoveReason::ConnectTimeout
| RemoveReason::CallEnded
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CallKeysMessage {
Init(CallKeysInit),
Proposals {
call_id: CallId,
group_id: B64,
epoch: u64,
proposals: Vec<B64>,
committer: u32,
reason: TransitionReason,
bindings: LeafBindingTable,
},
CommitRequest {
call_id: CallId,
group_id: B64,
epoch: u64,
committer: u32,
attempt: u32,
},
Commit {
call_id: CallId,
group_id: B64,
epoch_from: u64,
commit: B64,
slot: u8,
bindings: LeafBindingTable,
},
Welcome {
call_id: CallId,
group_id: B64,
join_id: JoinIdHex,
epoch: u64,
welcome: B64,
ratchet_tree: B64,
slot_base: u8,
slot: u8,
bindings: LeafBindingTable,
},
Activate {
call_id: CallId,
group_id: B64,
epoch: u64,
slot: u8,
},
Reset {
call_id: CallId,
new_group_id: B64,
reason: ResetReason,
slot_base: u8,
collect_ms: u64,
},
Recorder {
call_id: CallId,
recording_id: Id,
#[serde(default, skip_serializing_if = "Option::is_none")]
recorder_cert: Option<B64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
hpke_pub: Option<B64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
lk_identity: Option<LkIdentity>,
#[serde(default, skip_serializing_if = "is_false")]
removed: bool,
},
Revoked {
serials: Vec<Id>,
},
Removed {
call_id: CallId,
group_id: B64,
join_id: JoinIdHex,
reason: RemoveReason,
},
Resync {
call_id: CallId,
join_id: JoinIdHex,
reason: KeyResyncReason,
#[serde(default, skip_serializing_if = "Option::is_none")]
expected_slot: Option<u8>,
},
#[serde(other)]
#[schemars(skip)]
Unknown,
}
impl CallKeysMessage {
pub const fn kind(&self) -> &'static str {
match self {
CallKeysMessage::Init(_) => "init",
CallKeysMessage::Proposals { .. } => "proposals",
CallKeysMessage::CommitRequest { .. } => "commit_request",
CallKeysMessage::Commit { .. } => "commit",
CallKeysMessage::Welcome { .. } => "welcome",
CallKeysMessage::Activate { .. } => "activate",
CallKeysMessage::Reset { .. } => "reset",
CallKeysMessage::Recorder { .. } => "recorder",
CallKeysMessage::Revoked { .. } => "revoked",
CallKeysMessage::Removed { .. } => "removed",
CallKeysMessage::Resync { .. } => "resync",
CallKeysMessage::Unknown => "unknown",
}
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum VerificationCode {
Shown = "shown",
Hidden = "hidden",
Required = "required",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct ReadyCallKeys {
pub external_sender: B64,
pub ds_public_key: B64,
pub ca: CallPublicKey,
pub crl: Vec<Id>,
#[serde(default, skip_serializing_if = "is_false")]
pub crl_partial: bool,
pub verification_code: VerificationCode,
pub params: CallKeysParams,
}
impl ReadyCallKeys {
pub fn new(
external_sender: B64,
ds_public_key: B64,
ca: CallPublicKey,
verification_code: VerificationCode,
params: CallKeysParams,
) -> Self {
ReadyCallKeys {
external_sender,
ds_public_key,
ca,
crl: Vec::new(),
crl_partial: false,
verification_code,
params,
}
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum ConsentState {
Granted = "granted",
Denied = "denied",
Pending = "pending",
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct StatusVoiceE2ee {
pub calls: u32,
pub leaves: u32,
pub lagging: u32,
pub rebuilding: u32,
pub resets_1h: u32,
pub removal_overdue_1h: u32,
pub roster_reports_1h: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ca_kid: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ds_kid: Option<String>,
pub devices: u64,
pub crl_size: u64,
#[serde(default)]
pub per_call: Vec<StatusVoiceE2eeCall>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct StatusVoiceE2eeCall {
pub call_id: CallId,
pub generation: u32,
pub epoch: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub active_epoch: Option<u64>,
pub leaves_by_state: StatusVoiceE2eeLeaves,
pub pending: u32,
pub queue_len: u32,
pub awaiting_creator: bool,
pub resetting: bool,
pub rebuilding: bool,
pub backoff: bool,
}
impl StatusVoiceE2eeCall {
pub fn new(call_id: CallId, leaves_by_state: StatusVoiceE2eeLeaves) -> Self {
StatusVoiceE2eeCall {
call_id,
generation: 0,
epoch: 0,
active_epoch: None,
leaves_by_state,
pending: 0,
queue_len: 0,
awaiting_creator: false,
resetting: false,
rebuilding: false,
backoff: false,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct StatusVoiceE2eeLeaves {
pub joining: u32,
pub active: u32,
pub lagging: u32,
pub leaving: u32,
}