sew-proto 0.11.6

Sew wire contracts: ids, addresses, errors, HTTP and gateway bodies, permissions, policies, audit.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
//! The JSON half of the call key wire:
//! the key join, the KeyPackage upload, the per-call key routes (`/calls/{call_id}/keys/…`), the
//! `call_keys_delivered` dispatch body ([`CallKeysMessage`]), the DS-signed [`LeafBindingTable`],
//! the relayed recorder [`Release`] and the READY section ([`ReadyCallKeys`]).
//!
//! Requests refuse unknown fields; responses, records and dispatch bodies ignore them.
//! Units: epochs `u64`, slots `u8`, leaves `u32`, ids [`Id`], `*_ms` `u64`. MLS objects are
//! [`B64`] (base64url, no padding). Sizes, quotas and every MLS check are the server's:
//! validators here bound strings and list lengths only.

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;

/// The only MLS ciphersuite of v1: `MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519`.
pub const CIPHERSUITE_V1: u16 = 0x0001;
/// The only `kdf` value.
pub const KDF_HKDF: &str = "hkdf";
/// A `key_package_ref` is a 32-byte RFC 9420 `KeyPackageRef`.
pub const KEY_PACKAGE_REF_BYTES: usize = 32;
/// A `group_id` is 16 random bytes.
pub const GROUP_ID_BYTES: usize = 16;
/// Longest caps string (`sdk`, `sdk_version`, `browser`, `lib`).
pub const CAPS_STRING_MAX: usize = 64;
/// Most entries in `caps.ciphersuites`.
pub const CAPS_CIPHERSUITES_MAX: usize = 16;
/// Longest `gateway_session` (the READY `session_id` wire form).
pub const GATEWAY_SESSION_MAX: usize = 128;
/// KeyPackages per KeyPackage upload.
pub const UPLOAD_KEY_PACKAGES_MAX: usize = 2;
/// The report `details` cap, as serialized JSON.
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
}

// ---------------------------------------------------------------- caps and joins

/// What the joining client can do. The server refuses an
/// incapable client with `422 e2ee_unsupported_client`, so the values themselves are
/// not checked here, only their sizes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct E2eeCaps {
    /// The SDK can move its sender to a new key slot.
    pub sender_key_index: bool,
    /// `"hkdf"`.
    pub kdf: String,
    /// 64; anything else is refused at join.
    pub key_ring_size: u32,
    /// The SDK family (`js`, `rust`, …).
    pub sdk: String,
    /// The SDK version as its `ClientInfo` reports it.
    pub sdk_version: String,
    /// `chrome`, `firefox`, `safari` or `other` (web only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub browser: Option<String>,
    /// `sew-e2ee/<version>`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lib: Option<String>,
    /// MLS ciphersuites the client supports; must contain 1 when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ciphersuites: Option<Vec<u16>>,
}

impl E2eeCaps {
    /// An `E2eeCaps` with its required fields: every count 0, every flag `false` and every
    /// optional field unset.
    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(())
    }
}

/// The `e2ee` object of a voice or call join (`VoiceJoinRequest.e2ee`, and DM call
/// joins).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct E2eeJoin {
    /// The single-use ref the KeyPackage upload returned (32 bytes).
    pub key_package_ref: B64,
    /// The caller's gateway session: READY's `session_id`.
    pub gateway_session: String,
    /// What the client can do.
    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"))
    }
}

/// K2 body: the key join after a move, with the Sew-minted `join_id` from
/// `voice_server_updated`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyJoinRequest {
    /// The join id Sew minted for the move.
    pub join_id: JoinIdHex,
    /// The caller's gateway session.
    pub gateway_session: String,
    /// A ref uploaded for the target channel's scope.
    pub key_package_ref: B64,
    /// What the client can do.
    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"))
    }
}

/// The client timings and constants the server relays (READY `call_keys.params` and every
/// [`CallKeysInit`]). The single source for client timings.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct CallKeysParams {
    /// The ciphersuite every group uses (1).
    pub ciphersuite: u16,
    /// The ciphersuites the server accepts (`[1]` in v1).
    pub ciphersuites: Vec<u16>,
    /// Always 64.
    pub key_ring_size: u32,
    /// `"hkdf"`.
    pub kdf: String,
    /// The MLS exporter label of frame keys ([`tls::EXPORTER_LABEL`]).
    pub exporter_label: String,
    /// The recorder release `info` label ([`tls::RELEASE_INFO_LABEL`]).
    pub release_info_label: String,
    /// Receivers retire an old slot this long after `activate`.
    pub retire_after_ms: u64,
    /// A sender that acked but hears no `activate` switches after this long.
    pub client_activate_fallback_ms: u64,
    /// Longest KeyPackage lifetime the server accepts.
    pub key_package_max_lifetime_s: u64,
    /// Dispatches for a `call_id` the client does not know yet are buffered this long.
    pub unknown_call_buffer_ms: u64,
    /// "Securing…" shows only after this long.
    pub securing_indicator_after_ms: u64,
}

impl CallKeysParams {
    /// A `CallKeysParams` with its required fields: every count 0 and every list empty.
    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,
        }
    }
}

/// What a key join answers (the voice join's `VoiceJoinResponse.e2ee`, the key join, and
/// the `init` dispatch).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct CallKeysInit {
    /// The call: its `r_…` room.
    pub call_id: CallId,
    /// The caller's Sew-minted join id; every per-call key route's body carries it.
    pub join_id: JoinIdHex,
    /// The caller's engine identity (`p_` + base32 of `join_id`; the token's `sub`).
    pub lk_identity: LkIdentity,
    /// The call's scope, `call:<channel_id>`; members refuse leaves with another.
    pub scope: CallScope,
    /// The current group (16 bytes).
    pub group_id: B64,
    /// The group's epoch.
    pub epoch: u64,
    /// The caller creates the group now.
    pub create: bool,
    /// The creator activates epoch 0 at once (first joiner of a fresh call only).
    pub activate_on_create: bool,
    /// `slot(e) = (slot_base + e) mod 64`.
    pub slot_base: u8,
    /// TLS `ExternalSender` of the install's DS key.
    pub external_sender: B64,
    /// Client timings.
    pub params: CallKeysParams,
}

impl CallKeysInit {
    /// A `CallKeysInit` with its required fields: every count 0 and every flag `false`.
    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,
        }
    }
}

// ---------------------------------------------------------------- KeyPackage upload

/// KeyPackage upload body: 1–2 KeyPackages uploaded before any join.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyPackageUploadRequest {
    /// TLS `MLSMessage(KeyPackage)` each.
    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(())
    }
}

/// One uploaded KeyPackage's single-use ref.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct KeyPackageRefItem {
    /// RFC 9420 `KeyPackageRef` (`KeyPackage::hash_ref`, 32 bytes).
    pub key_package_ref: B64,
    /// When the ref expires (unix ms).
    pub expires_at_ms: u64,
}

/// KeyPackage upload answer: one item per package, in request order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct KeyPackageUploadResponse {
    /// The refs.
    pub items: Vec<KeyPackageRefItem>,
}

// ---------------------------------------------------------------- binding tables

/// One `LeafBinding` entry in JSON: exactly one of `leaf` (key type 1) or `key_package_ref`
/// (key type 2), the join id and its engine identity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct LeafBindingEntryJson {
    /// The leaf index (commit, welcome, state report reply, recorder tables).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub leaf: Option<u32>,
    /// The Add's `key_package_ref` (proposals).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key_package_ref: Option<B64>,
    /// The join id.
    pub join_id: JoinIdHex,
    /// `p_` + base32 of `join_id` (not signed; clients recompute and compare).
    pub lk_identity: LkIdentity,
}

/// The DS-signed leaf ↔ join id table. `sig` = Ed25519(`sew-call-ds`,
/// `"sew call leaf binding v1"` ‖ TLS([`LeafBindingTableTbs`])).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct LeafBindingTable {
    /// The call.
    pub call_id: CallId,
    /// The group (16 bytes).
    pub group_id: B64,
    /// The proposal epoch (key type 2) or the new epoch (key type 1).
    pub epoch: u64,
    /// Ascending by leaf or by ref; one key type per table.
    pub entries: Vec<LeafBindingEntryJson>,
    /// 64-byte Ed25519 signature.
    pub sig: B64,
}

/// Why a JSON binding table does not match its signed form.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BindingError {
    /// An entry has both or neither of `leaf` and `key_package_ref` (its index is named).
    EntryKey(usize),
    /// An entry's `lk_identity` is not `p_` + base32 of its `join_id` (its index is named).
    Identity(usize),
    /// The TBS `call_id` is not an `r_…` room.
    CallId,
    /// The content rules ([`LeafBindingTableTbs::check`]).
    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 {
    /// The signed structure: entries in their key form, checked against the content rules
    /// (one key type, strictly ascending, unique join ids) and each `lk_identity`.
    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)
    }

    /// The JSON form of a signed structure (identities derived from the join ids).
    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),
        })
    }
}

/// A full key-type-1 table of one committed epoch for the recorder
/// (`RecorderSink::bindings`, the recorder's `/bindings`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct BindingsUpdate {
    /// The group.
    pub group_id: B64,
    /// The epoch the table is for.
    pub epoch: u64,
    /// The group's slot base.
    pub slot_base: u8,
    /// The signed table.
    pub table: LeafBindingTable,
}

/// A public key and its id (`kid` = hex of the first 8 bytes of SHA-256 of the raw key).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CallPublicKey {
    /// 16 lowercase hex characters.
    pub kid: String,
    /// The raw 32-byte Ed25519 public key.
    pub public_key: B64,
}

/// The install CA and DS public keys (`CallKeyService::public_keys`, for the recorder PUT).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CallPublicKeys {
    /// `sew-call-ca`.
    pub ca: CallPublicKey,
    /// `sew-call-ds`.
    pub ds: CallPublicKey,
}

// ---------------------------------------------------------------- per-call key routes

unit_enum! {
    /// The state report's answer.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum KeyStateStatus {
        /// The leaf is bound and current.
        InSync = "in_sync",
        /// Repeat the call with `ratchet_tree`.
        SendTree = "send_tree",
        /// A rebuild is collecting reports; retry after `retry_after_ms`.
        Rebuilding = "rebuilding",
    }
}

/// State report body: the create report, a re-bind after a re-identify, or a rebuild report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyStateRequest {
    /// The caller's join id.
    pub join_id: JoinIdHex,
    /// The caller's current gateway session.
    pub gateway_session: String,
    /// The group the client holds.
    pub group_id: B64,
    /// The reporter's own leaf index.
    pub leaf: u32,
    /// The client's epoch.
    pub epoch: u64,
    /// The client's active epoch.
    pub active_epoch: u64,
    /// The client's slot base.
    pub slot_base: u8,
    /// The client's tree hash.
    pub tree_hash: B64,
    /// SHA-256 of the TLS binding table the client holds.
    pub bindings_hash: B64,
    /// TLS `MLSMessage(GroupInfo)`.
    pub group_info: B64,
    /// TLS `RatchetTree`, only when the DS asked (`send_tree`).
    #[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(())
    }
}

/// State report answer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct KeyStateResponse {
    /// `in_sync`, `send_tree` or `rebuilding`.
    pub status: KeyStateStatus,
    /// With `rebuilding`: the rest of the rebuild window.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retry_after_ms: Option<u64>,
    /// The full signed table when the client's `bindings_hash` differs from the DS's.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bindings: Option<LeafBindingTable>,
}

/// Commit body: the designated committer's commit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyCommitRequest {
    /// The committer's join id.
    pub join_id: JoinIdHex,
    /// The group.
    pub group_id: B64,
    /// The epoch the commit is for (the proposals' epoch).
    pub epoch: u64,
    /// TLS `MLSMessage(PublicMessage commit)`.
    pub commit: B64,
    /// TLS `MLSMessage(Welcome)`; present iff the commit adds leaves.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub welcome: Option<B64>,
    /// TLS `MLSMessage(GroupInfo)` for `epoch + 1`.
    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)
    }
}

/// Commit `200` answer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct KeyCommitAccepted {
    /// Always `true`.
    pub accepted: bool,
    /// The new epoch.
    pub epoch: u64,
    /// Its slot.
    pub slot: u8,
}

/// Ready report body: every remote sender's key for `epoch` is installed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyReadyRequest {
    /// The caller's join id.
    pub join_id: JoinIdHex,
    /// The group.
    pub group_id: B64,
    /// The installed epoch.
    pub epoch: u64,
}

impl Validate for KeyReadyRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        check_bytes("group_id", &self.group_id, GROUP_ID_BYTES)
    }
}

unit_enum! {
    /// Why a client asks to be re-added.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum InvalidReason {
        /// A commit failed to process.
        CommitFailed = "commit_failed",
        /// A commit failed the member-side checks.
        BadCommit = "bad_commit",
        /// A proposal failed the member-side checks.
        BadProposal = "bad_proposal",
        /// A Welcome failed to process or check.
        BadWelcome = "bad_welcome",
        /// An epoch was missed.
        MissedEpoch = "missed_epoch",
        /// The recovery watchdog ran out.
        RecoveryTimeout = "recovery_timeout",
        /// The state report answered `e2ee_epoch_behind`, or a `resync{behind}`.
        Behind = "behind",
        /// The client lost its MLS state.
        StateLost = "state_lost",
    }
}

/// Invalid report body: re-add the caller's leaf with a fresh inline KeyPackage (one Replace
/// commit).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyInvalidRequest {
    /// The caller's join id (kept by the new leaf).
    pub join_id: JoinIdHex,
    /// The group the client holds.
    pub group_id: B64,
    /// The client's epoch.
    pub epoch: u64,
    /// Why.
    pub reason: InvalidReason,
    /// TLS `MLSMessage(KeyPackage)`: same member, device and scope as the leaf.
    pub key_package: B64,
    /// The caller's current gateway session, when it re-identified while holding no group
    /// (its Welcome went to the dead socket, or its join waited across a restart): the DS
    /// re-binds the join to it (additive, KB).
    #[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)
    }
}

/// `key_package` body: a fresh inline KeyPackage for a resetting call's new group.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyResetPackageRequest {
    /// The caller's join id.
    pub join_id: JoinIdHex,
    /// The group being collected (from `reset`).
    pub new_group_id: B64,
    /// TLS `MLSMessage(KeyPackage)`.
    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)
    }
}

/// Release body: the caller's own sender key for one epoch, sealed to the recorder.
/// `enc` and `ct` sizes and `sender_identity` are the DS's routing checks (`422`), not shape
/// checks.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyReleaseRequest {
    /// The caller's join id.
    pub join_id: JoinIdHex,
    /// The group.
    pub group_id: B64,
    /// The released epoch.
    pub epoch: u64,
    /// `slot(epoch)`.
    pub slot: u8,
    /// The live recording.
    pub recording_id: Id,
    /// The caller's leaf index in `epoch`.
    pub leaf: u32,
    /// The caller's engine identity.
    pub sender_identity: String,
    /// HPKE `enc` (32 bytes).
    pub enc: B64,
    /// HPKE ciphertext (48 bytes).
    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)
    }
}

/// A release as the DS relays it to the recorder (`RecorderSink::release`; the recorder opens it
/// with the client library's `ReleaseOpener`, which rebuilds the `info` with `leaf`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Release {
    /// The call.
    pub call_id: CallId,
    /// The recording.
    pub recording_id: Id,
    /// The group.
    pub group_id: B64,
    /// The epoch.
    pub epoch: u64,
    /// The sender's leaf index in `epoch`.
    pub leaf: u32,
    /// `slot(epoch)`.
    pub slot: u8,
    /// The sender's engine identity.
    pub sender_identity: LkIdentity,
    /// HPKE `enc` (32 bytes).
    pub enc: B64,
    /// HPKE ciphertext (48 bytes).
    pub ct: B64,
}

impl Release {
    /// The structure the HPKE `info` binds.
    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! {
    /// Why a client asks for an immediate rekey.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum RekeyReason {
        /// The member withdrew recording consent.
        ConsentWithdrawn = "consent_withdrawn",
    }
}

/// Rekey body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyRekeyRequest {
    /// The caller's join id.
    pub join_id: JoinIdHex,
    /// Why.
    pub reason: RekeyReason,
}

impl Validate for KeyRekeyRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        check_known("reason", self.reason)
    }
}

unit_enum! {
    /// What a report is about.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum ReportKind {
        /// A leaf whose member has no voice state in the channel.
        LeafWithoutVoiceState = "leaf_without_voice_state",
        /// Two leaves of one member outside a swap.
        DuplicateMember = "duplicate_member",
        /// An engine participant with no leaf past 5 s.
        EngineParticipantWithoutLeaf = "engine_participant_without_leaf",
        /// The group's external sender differs from READY's.
        ExternalSenderMismatch = "external_sender_mismatch",
        /// The CA key differs from the pinned one.
        CaChanged = "ca_changed",
        /// A binding table failed the client's checks.
        LeafBindingInvalid = "leaf_binding_invalid",
        /// A leaf's credential scope is empty or differs from the call's.
        ScopeInvalid = "scope_invalid",
        /// The reporter's own sender stays on a stale slot after one re-apply.
        SenderIndexStuck = "sender_index_stuck",
        /// Another leaf's frames do not decrypt (quorum only).
        PeerUndecryptable = "peer_undecryptable",
        /// A bridge saw an unencrypted track from the engine.
        EngineUnencryptedTrack = "engine_unencrypted_track",
        /// A bridge saw a non-empty `sif_trailer` from the engine.
        EngineSifTrailer = "engine_sif_trailer",
        /// A bridge saw an encryption downgrade from the engine.
        EngineEncryptionDowngrade = "engine_encryption_downgrade",
    }
}

impl ReportKind {
    /// The roster kinds (audited `call.e2ee_roster_report`, alarm `e2ee_roster_mismatch`).
    pub const fn is_roster(self) -> bool {
        matches!(
            self,
            ReportKind::LeafWithoutVoiceState
                | ReportKind::DuplicateMember
                | ReportKind::EngineParticipantWithoutLeaf
                | ReportKind::ExternalSenderMismatch
                | ReportKind::CaChanged
                | ReportKind::LeafBindingInvalid
                | ReportKind::ScopeInvalid
        )
    }

    /// The slot signals (`sender_index_stuck`, `peer_undecryptable`; their own count).
    pub const fn is_slot_signal(self) -> bool {
        matches!(
            self,
            ReportKind::SenderIndexStuck | ReportKind::PeerUndecryptable
        )
    }

    /// The bridge detections of a misbehaving engine.
    pub const fn is_engine(self) -> bool {
        matches!(
            self,
            ReportKind::EngineUnencryptedTrack
                | ReportKind::EngineSifTrailer
                | ReportKind::EngineEncryptionDowngrade
        )
    }
}

/// Report `details` (≤ 256 bytes of JSON). Every field is optional; strings ≤ 64 bytes.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReportDetails {
    /// The slot the sender should be on.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expected_slot: Option<u8>,
    /// The slot the reporter saw.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observed_slot: Option<u8>,
    /// For how long the condition held.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub since_ms: Option<u64>,
    /// Failed decrypts counted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub failures: Option<u32>,
    /// Re-apply attempts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attempts: Option<u32>,
    /// The key index a receiver missed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub missing_index: Option<u8>,
    /// A short reason (`missing_key`, `invalid_key`, …).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// The reporter's SDK family.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sdk: Option<String>,
    /// The reporter's SDK version.
    #[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(())
    }
}

/// Report body: a ghost-member, slot or engine report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeyReportRequest {
    /// The reporter's join id.
    pub join_id: JoinIdHex,
    /// The group the reporter holds.
    pub group_id: B64,
    /// The reporter's epoch.
    pub epoch: u64,
    /// What is reported.
    pub kind: ReportKind,
    /// The leaf it is about (the reporter's own for `sender_index_stuck`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub leaf: Option<u32>,
    /// Optional details.
    #[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(())
    }
}

// ---------------------------------------------------------------- the dispatch

unit_enum! {
    /// Why a transition started (`proposals.reason`).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum TransitionReason {
        /// Leaves joined.
        Join = "join",
        /// Leaves left or were removed.
        Leave = "leave",
        /// A device swap (Remove + Add of one member).
        Swap = "swap",
        /// A re-add after a missed epoch or a failed commit.
        Readd = "readd",
        /// A requested rekey.
        Rekey = "rekey",
        /// Recording consent was withdrawn.
        Consent = "consent",
        /// The recording stopped.
        RecorderStop = "recorder_stop",
        /// A device was revoked.
        Revoke = "revoke",
        /// The periodic rekey.
        Periodic = "periodic",
        /// A leaf-lifetime refresh.
        Refresh = "refresh",
        /// Leaves a rebuild could not match.
        RebuildOrphan = "rebuild_orphan",
        /// A sender stuck on a stale slot was removed.
        StuckSender = "stuck_sender",
    }
}

unit_enum! {
    /// Why a call's group is reset (`reset.reason`).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum ResetReason {
        /// Every committer candidate was silent.
        CommitterTimeout = "committer_timeout",
        /// A removal was not activated by `remove_deadline_ms`.
        RemoveDeadline = "remove_deadline",
        /// A rebuild found two equally covered groups.
        RebuildConflict = "rebuild_conflict",
        /// Too many invalid commits in one generation.
        InvalidCommits = "invalid_commits",
        /// A state report broke a group invariant.
        Invariant = "invariant",
    }
}

unit_enum! {
    /// Why a leaf is told to resync (`resync.reason`). `stale_slot` re-asserts the
    /// sender slot; every other reason is answered with an invalid report.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum KeyResyncReason {
        /// The leaf is behind the DS's epoch.
        Behind = "behind",
        /// The leaf holds another group.
        GroupMismatch = "group_mismatch",
        /// The leaf stopped acking.
        Lagging = "lagging",
        /// The engine sees the leaf sending on the wrong slot.
        StaleSlot = "stale_slot",
    }
}

coded_enum! {
    /// Why a leaf left the key group (`removed.reason`; every voice leave reason plus
    /// the key service's and DM calls' own). Codes are stable for metrics and logs.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum RemoveReason {
        /// The member left.
        Left = "left" => 1,
        /// The media connection ended for good.
        Disconnected = "disconnected" => 2,
        /// Another device of the member took over (swap).
        Replaced = "replaced" => 3,
        /// The member moved or switched channel.
        Moved = "moved" => 4,
        /// A moderator disconnected the member.
        RemovedByModerator = "removed_by_moderator" => 5,
        /// The member lost CONNECT or VIEW.
        PermsLost = "perms_lost" => 6,
        /// The channel was archived.
        ChannelArchived = "channel_archived" => 7,
        /// The member left or was removed from the space.
        RemovedFromSpace = "removed_from_space" => 8,
        /// The member was timed out.
        TimedOut = "timed_out" => 9,
        /// The account was deprovisioned.
        AccountRemoved = "account_removed" => 10,
        /// The login session was revoked.
        SessionRevoked = "session_revoked" => 11,
        /// The device was revoked.
        DeviceRevoked = "device_revoked" => 12,
        /// The media outlived every socket.
        Orphaned = "orphaned" => 13,
        /// Alone in the call too long.
        AloneTimeout = "alone_timeout" => 14,
        /// Media never connected.
        ConnectTimeout = "connect_timeout" => 15,
        /// The engine restarted and the media did not come back.
        MediaRestarted = "media_restarted" => 16,
        /// Voice was turned off.
        VoiceDisabled = "voice_disabled" => 17,
        /// The sender stayed on a stale key slot.
        E2eeSenderIndexStuck = "e2ee_sender_index_stuck" => 18,
        /// The device stopped answering key requests (removed as unresponsive).
        Unresponsive = "unresponsive" => 19,
        /// A rebuild found no live entry for the leaf.
        RebuildOrphan = "rebuild_orphan" => 20,
        /// The creator's group was refused.
        CreateFailed = "create_failed" => 21,
        /// The DM call ended for everyone.
        CallEnded = "call_ended" => 22,
    }
}

impl RemoveReason {
    /// A forced removal: audited `call.e2ee_member_removed`. Ordinary departures
    /// are not.
    pub const fn is_forced(self) -> bool {
        !matches!(
            self,
            RemoveReason::Left
                | RemoveReason::Disconnected
                | RemoveReason::Replaced
                | RemoveReason::Moved
                | RemoveReason::ConnectTimeout
                | RemoveReason::CallEnded
        )
    }
}

/// The `call_keys_delivered` dispatch body, tagged by `kind`. Clients ignore kinds
/// they do not know ([`CallKeysMessage::Unknown`]).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CallKeysMessage {
    /// A creator failover or a reset creator: the [`CallKeysInit`] fields.
    Init(CallKeysInit),
    /// A transition starts.
    Proposals {
        /// The call.
        call_id: CallId,
        /// The group.
        group_id: B64,
        /// The epoch the proposals are for.
        epoch: u64,
        /// DS-signed external `MLSMessage`s (Add and Remove only); empty for a rekey.
        proposals: Vec<B64>,
        /// The designated committer's leaf.
        committer: u32,
        /// Why.
        reason: TransitionReason,
        /// One entry per Add, keyed by its `key_package_ref`.
        bindings: LeafBindingTable,
    },
    /// Failover to the next committer candidate.
    CommitRequest {
        /// The call.
        call_id: CallId,
        /// The group.
        group_id: B64,
        /// The epoch.
        epoch: u64,
        /// The candidate's leaf.
        committer: u32,
        /// 2 or 3.
        attempt: u32,
    },
    /// The accepted commit.
    Commit {
        /// The call.
        call_id: CallId,
        /// The group.
        group_id: B64,
        /// The epoch the commit leaves.
        epoch_from: u64,
        /// TLS `MLSMessage(PublicMessage commit)`.
        commit: B64,
        /// The slot of `epoch_from + 1`.
        slot: u8,
        /// The leaves this commit added, keyed by leaf, for `epoch_from + 1`.
        bindings: LeafBindingTable,
    },
    /// A joiner's Welcome.
    Welcome {
        /// The call.
        call_id: CallId,
        /// The group.
        group_id: B64,
        /// The joiner's join id.
        join_id: JoinIdHex,
        /// The epoch the Welcome joins.
        epoch: u64,
        /// TLS `MLSMessage(Welcome)`.
        welcome: B64,
        /// TLS `RatchetTree` of `epoch`.
        ratchet_tree: B64,
        /// The group's slot base.
        slot_base: u8,
        /// `slot(epoch)`.
        slot: u8,
        /// The full table of `epoch`.
        bindings: LeafBindingTable,
    },
    /// Every sender switches to `slot`.
    Activate {
        /// The call.
        call_id: CallId,
        /// The group.
        group_id: B64,
        /// The epoch.
        epoch: u64,
        /// Its slot.
        slot: u8,
    },
    /// The group is replaced; send a fresh KeyPackage.
    Reset {
        /// The call.
        call_id: CallId,
        /// The group being collected.
        new_group_id: B64,
        /// Why.
        reason: ResetReason,
        /// The new group's slot base.
        slot_base: u8,
        /// The collection window.
        collect_ms: u64,
    },
    /// The recorder: a certified key recipient, or `removed: true` (no key fields).
    Recorder {
        /// The call.
        call_id: CallId,
        /// The recording.
        recording_id: Id,
        /// TLS `RecorderCert`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        recorder_cert: Option<B64>,
        /// The recorder's X25519 public key (32 bytes).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        hpke_pub: Option<B64>,
        /// The recorder's engine identity (`p_…`, from the voice service's `admit_recorder`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        lk_identity: Option<LkIdentity>,
        /// The recording stopped.
        #[serde(default, skip_serializing_if = "is_false")]
        removed: bool,
    },
    /// Device certificates were revoked.
    Revoked {
        /// The revoked serials.
        serials: Vec<Id>,
    },
    /// The leaf was removed; its last key message.
    Removed {
        /// The call.
        call_id: CallId,
        /// The group.
        group_id: B64,
        /// The removed join.
        join_id: JoinIdHex,
        /// Why.
        reason: RemoveReason,
    },
    /// The dispatch form of the state report's `409` answers, and `stale_slot`.
    Resync {
        /// The call.
        call_id: CallId,
        /// The leaf's join id.
        join_id: JoinIdHex,
        /// Why.
        reason: KeyResyncReason,
        /// With `stale_slot`: the slot the sender must use.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        expected_slot: Option<u8>,
    },
    /// A kind this build does not know.
    #[serde(other)]
    #[schemars(skip)]
    Unknown,
}

impl CallKeysMessage {
    /// The `kind` string (`"unknown"` for [`CallKeysMessage::Unknown`]); metrics label it.
    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",
        }
    }
}

// ---------------------------------------------------------------- READY, consent, status

unit_enum! {
    /// Policy `calls.verification_code`: whether "Call info → Security code" is
    /// shown. `required` is reserved for a later mode and refused by the policy validator.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum VerificationCode {
        /// Shown on request, never modal (the default).
        Shown = "shown",
        /// Not shown.
        Hidden = "hidden",
        /// Reserved: "confirm before you speak" (refused in v1).
        Required = "required",
    }
}

/// READY `call_keys`: the trust anchors and client parameters. Absent when voice is
/// disabled.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct ReadyCallKeys {
    /// TLS `ExternalSender` of every group.
    pub external_sender: B64,
    /// The raw 32-byte DS Ed25519 key, for pinning.
    pub ds_public_key: B64,
    /// The install CA.
    pub ca: CallPublicKey,
    /// Serials of revoked, unexpired device certificates (at most 5,000).
    pub crl: Vec<Id>,
    /// More revoked serials exist: page them with `GET /api/v1/devices/crl`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub crl_partial: bool,
    /// Policy `calls.verification_code`.
    pub verification_code: VerificationCode,
    /// Client timings.
    pub params: CallKeysParams,
}

impl ReadyCallKeys {
    /// A `ReadyCallKeys` with its required fields: every flag `false` and every list empty.
    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! {
    /// A member's consent for one recording (the key service's `ConsentSource`).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum ConsentState {
        /// Granted: releases are forwarded.
        Granted = "granted",
        /// Declined.
        Denied = "denied",
        /// Not answered yet.
        Pending = "pending",
    }
}

/// `status.voice.e2ee`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct StatusVoiceE2ee {
    /// Live key groups.
    pub calls: u32,
    /// Leaves across them.
    pub leaves: u32,
    /// Lagging leaves.
    pub lagging: u32,
    /// Calls rebuilding after a restart.
    pub rebuilding: u32,
    /// Group resets in the last hour.
    pub resets_1h: u32,
    /// Removals past their hard bound in the last hour.
    pub removal_overdue_1h: u32,
    /// Roster-kind reports in the last hour.
    pub roster_reports_1h: u32,
    /// The CA key id; absent when the key failed to load.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ca_kid: Option<String>,
    /// The DS key id; absent when the key failed to load.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ds_kid: Option<String>,
    /// Unrevoked enrolled devices.
    pub devices: u64,
    /// Serials in the in-memory CRL.
    pub crl_size: u64,
    /// One entry per live key group, sorted by `call_id` (Sew 0.7.1). No member, device, join
    /// id or key material: what K2 needs to diagnose a stuck call without the mgmt socket.
    #[serde(default)]
    pub per_call: Vec<StatusVoiceE2eeCall>,
}

/// One call in `status.voice.e2ee.per_call` (Sew 0.7.1).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct StatusVoiceE2eeCall {
    /// The call (its room name, as the key routes carry it).
    pub call_id: CallId,
    /// Group resets so far (0 for the first group).
    pub generation: u32,
    /// The DS group's epoch.
    pub epoch: u64,
    /// The last activated epoch; absent before the first activation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active_epoch: Option<u64>,
    /// Leaves by state.
    pub leaves_by_state: StatusVoiceE2eeLeaves,
    /// Admitted joins without a leaf yet.
    pub pending: u32,
    /// Queued changes.
    pub queue_len: u32,
    /// The call waits for its first joiner to create the group.
    pub awaiting_creator: bool,
    /// A group reset is in flight.
    pub resetting: bool,
    /// The call is rebuilding after a `sew` restart.
    pub rebuilding: bool,
    /// The call is in reset back-off.
    pub backoff: bool,
}

impl StatusVoiceE2eeCall {
    /// A `StatusVoiceE2eeCall` with its required fields: every count 0, every flag `false`
    /// and every optional field unset.
    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,
        }
    }
}

/// Leaf counts by state in a [`StatusVoiceE2eeCall`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct StatusVoiceE2eeLeaves {
    /// Welcomed, not yet acked.
    pub joining: u32,
    /// Acked.
    pub active: u32,
    /// Left behind (behind the active epoch).
    pub lagging: u32,
    /// Being removed.
    pub leaving: u32,
}