vtc-service 0.12.0

Service for Verifiable Trust Communities
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
//! The community's administration surfaces that had only bearer REST, on the
//! signed-document spine: how the community presents itself to applicants,
//! its credential-schema registry, the vetting reads, the relationship graph's
//! suspend and restore, a join request's vetting facts and the credential
//! query an administrator sends a holder, and the rooms this host stores.
//!
//! | task | authority (the signer's ACL row, read now) |
//! |---|---|
//! | `vtc/community/{branding,requested-attributes,join-discovery}/show/0.1` | any entry |
//! | `vtc/community/{branding,requested-attributes,join-discovery}/update/0.1` | `Admin` |
//! | `vtc/schemas/{register,list,show,delete}/0.1` | `Admin` |
//! | `vtc/schemas/accepts/{register,list,show}/0.2`, `…/delete/0.1` | `Admin` |
//! | `vtc/vetting/vetters/grants/list/0.1` | `Admin` |
//! | `vtc/vetting/auto-grant/{show,update}/0.1` | `Admin` |
//! | `vtc/vetting/revocations/list/0.1` | `Admin` |
//! | `vtc/relationships/{suspend,restore}/0.1` | the edge's issuer, or `Admin` |
//! | `vtc/join-requests/vetting/show/0.1` | `Admin` |
//! | `vtc/join-requests/query/0.1` | `Admin` |
//! | `vtc/rooms/list/0.1` | `Admin` |
//!
//! Each is the question its bearer route asked: `AuthClaims` (any session —
//! which the VTC minted for an administrator only) for the presentation reads,
//! `AdminAuth` for everything else, and for suspend and restore the edge's
//! issuer or an administrator. On a document the edge's issuer is the signer
//! itself, so its proof stands in for the route's `pop` authorization: an edge
//! issued under a pairwise relationship DID is suspended by a document that DID
//! signs.
//!
//! None of them has a bearer route. The branding, requested-attributes,
//! vetter-grant, automatic-grant and withdrawal-notice routes were the last to
//! go, once `vtc-client` and the admin console signed the documents instead.
//!
//! The listings page in memory: every one of these collections is an
//! administrator's view of one community, bounded by what the community holds,
//! so the cursor is the offset of the next item.

use serde::Serialize;
use serde_json::{Value, json};
use trust_tasks_rs::specs::vtc::community::{
    branding::{show::v0_1 as branding_show, update::v0_1 as branding_update},
    join_discovery::{show::v0_1 as join_discovery_show, update::v0_1 as join_discovery_update},
    requested_attributes::{show::v0_1 as requested_show, update::v0_1 as requested_update},
    theme::{show::v0_1 as theme_show, update::v0_1 as theme_update},
};
use trust_tasks_rs::specs::vtc::join_requests::{
    query::v0_1 as join_query, vetting::show::v0_1 as join_vetting_show,
};
use trust_tasks_rs::specs::vtc::relationships::{
    restore::v0_1 as rel_restore, suspend::v0_1 as rel_suspend,
};
use trust_tasks_rs::specs::vtc::rooms::list::v0_1 as rooms_list;
use trust_tasks_rs::specs::vtc::schemas::{
    accepts::{
        delete::v0_1 as accepts_delete, list::v0_2 as accepts_list,
        register::v0_2 as accepts_register, show::v0_2 as accepts_show,
    },
    delete::v0_1 as schemas_delete,
    list::v0_1 as schemas_list,
    register::v0_1 as schemas_register,
    show::v0_1 as schemas_show,
};
use trust_tasks_rs::specs::vtc::vetting::{
    auto_grant::{show::v0_1 as auto_grant_show, update::v0_1 as auto_grant_update},
    revocations::list::v0_1 as revocations_list,
    vetters::grants::list::v0_1 as grants_list,
};
use trust_tasks_rs::{Payload, RejectReason, TrustTask};
use uuid::Uuid;

use super::admin_tasks::member_signer;
use super::helpers::{
    TrustTaskOutcome, app_error_to_reject, extended_code, parse_payload, reject_with,
    reject_with_code, success_response, task_error_to_reject,
};
use super::{JoinAuthCtx, admin_signer, parse_spec_payload};
use crate::error::AppError;
use crate::server::AppState;

pub(crate) const BRANDING_SHOW_TYPE: &str = <branding_show::Payload as Payload>::TYPE_URI;
pub(crate) const BRANDING_UPDATE_TYPE: &str = <branding_update::Payload as Payload>::TYPE_URI;
pub(crate) const THEME_SHOW_TYPE: &str = <theme_show::Payload as Payload>::TYPE_URI;
pub(crate) const THEME_UPDATE_TYPE: &str = <theme_update::Payload as Payload>::TYPE_URI;
pub(crate) const REQUESTED_SHOW_TYPE: &str = <requested_show::Payload as Payload>::TYPE_URI;
pub(crate) const REQUESTED_UPDATE_TYPE: &str = <requested_update::Payload as Payload>::TYPE_URI;
pub(crate) const JOIN_DISCOVERY_SHOW_TYPE: &str =
    <join_discovery_show::Payload as Payload>::TYPE_URI;
pub(crate) const JOIN_DISCOVERY_UPDATE_TYPE: &str =
    <join_discovery_update::Payload as Payload>::TYPE_URI;
pub(crate) const SCHEMAS_REGISTER_TYPE: &str = <schemas_register::Payload as Payload>::TYPE_URI;
pub(crate) const SCHEMAS_LIST_TYPE: &str = <schemas_list::Payload as Payload>::TYPE_URI;
pub(crate) const SCHEMAS_SHOW_TYPE: &str = <schemas_show::Payload as Payload>::TYPE_URI;
pub(crate) const SCHEMAS_DELETE_TYPE: &str = <schemas_delete::Payload as Payload>::TYPE_URI;
pub(crate) const ACCEPTS_REGISTER_TYPE: &str = <accepts_register::Payload as Payload>::TYPE_URI;
pub(crate) const ACCEPTS_LIST_TYPE: &str = <accepts_list::Payload as Payload>::TYPE_URI;
pub(crate) const ACCEPTS_SHOW_TYPE: &str = <accepts_show::Payload as Payload>::TYPE_URI;
pub(crate) const ACCEPTS_DELETE_TYPE: &str = <accepts_delete::Payload as Payload>::TYPE_URI;
pub(crate) const VETTER_GRANTS_LIST_TYPE: &str = <grants_list::Payload as Payload>::TYPE_URI;
pub(crate) const AUTO_GRANT_SHOW_TYPE: &str = <auto_grant_show::Payload as Payload>::TYPE_URI;
pub(crate) const AUTO_GRANT_UPDATE_TYPE: &str = <auto_grant_update::Payload as Payload>::TYPE_URI;
pub(crate) const REVOCATIONS_LIST_TYPE: &str = <revocations_list::Payload as Payload>::TYPE_URI;
pub(crate) const RELATIONSHIPS_SUSPEND_TYPE: &str = <rel_suspend::Payload as Payload>::TYPE_URI;
pub(crate) const RELATIONSHIPS_RESTORE_TYPE: &str = <rel_restore::Payload as Payload>::TYPE_URI;
pub(crate) const JOIN_VETTING_SHOW_TYPE: &str = <join_vetting_show::Payload as Payload>::TYPE_URI;
pub(crate) const JOIN_QUERY_TYPE: &str = <join_query::Payload as Payload>::TYPE_URI;
pub(crate) const ROOMS_LIST_TYPE: &str = <rooms_list::Payload as Payload>::TYPE_URI;

// ─── the codes these tasks declare, as the error-code census witnesses them ─

pub(crate) const THEME_UPDATE_ERR_OUTSIDE_PROFILE: &str =
    theme_update::error_codes::OUTSIDE_PROFILE.code;
pub(crate) const REQUESTED_ERR_DUPLICATE_TYPE: &str =
    requested_update::error_codes::DUPLICATE_TYPE.code;
pub(crate) const SCHEMAS_REGISTER_ERR_INVALID_CREDENTIAL_SCHEMA: &str =
    schemas_register::error_codes::INVALID_CREDENTIAL_SCHEMA.code;
pub(crate) const SCHEMAS_SHOW_ERR_NOT_FOUND: &str = schemas_show::error_codes::NOT_FOUND.code;
pub(crate) const SCHEMAS_DELETE_ERR_NOT_FOUND: &str = schemas_delete::error_codes::NOT_FOUND.code;
pub(crate) const SCHEMAS_DELETE_ERR_IN_USE: &str = schemas_delete::error_codes::IN_USE.code;
pub(crate) const ACCEPTS_REGISTER_ERR_INVALID_QUERY: &str =
    accepts_register::error_codes::INVALID_QUERY.code;
pub(crate) const ACCEPTS_REGISTER_ERR_UNREGISTERED_TYPE: &str =
    accepts_register::error_codes::UNREGISTERED_TYPE.code;
pub(crate) const ACCEPTS_REGISTER_ERR_UNREGISTERED_STATEMENT_TYPE: &str =
    accepts_register::error_codes::UNREGISTERED_STATEMENT_TYPE.code;
pub(crate) const ACCEPTS_REGISTER_ERR_INVALID_VETTING: &str =
    accepts_register::error_codes::INVALID_VETTING.code;
pub(crate) const ACCEPTS_REGISTER_ERR_NOT_PUBLISHABLE: &str =
    accepts_register::error_codes::NOT_PUBLISHABLE.code;
pub(crate) const ACCEPTS_REGISTER_ERR_UNSUPPORTED_REQUIREMENT: &str =
    accepts_register::error_codes::UNSUPPORTED_REQUIREMENT.code;
pub(crate) const ACCEPTS_SHOW_ERR_NOT_FOUND: &str = accepts_show::error_codes::NOT_FOUND.code;
pub(crate) const ACCEPTS_DELETE_ERR_NOT_FOUND: &str = accepts_delete::error_codes::NOT_FOUND.code;
pub(crate) const SUSPEND_ERR_NOT_FOUND: &str = rel_suspend::error_codes::NOT_FOUND.code;
pub(crate) const SUSPEND_ERR_ALREADY_SUSPENDED: &str =
    rel_suspend::error_codes::ALREADY_SUSPENDED.code;
pub(crate) const SUSPEND_ERR_TERMINAL: &str = rel_suspend::error_codes::TERMINAL.code;
pub(crate) const RESTORE_ERR_NOT_FOUND: &str = rel_restore::error_codes::NOT_FOUND.code;
pub(crate) const RESTORE_ERR_NOT_SUSPENDED: &str = rel_restore::error_codes::NOT_SUSPENDED.code;
pub(crate) const RESTORE_ERR_TERMINAL: &str = rel_restore::error_codes::TERMINAL.code;
pub(crate) const JOIN_VETTING_ERR_NOT_FOUND: &str = join_vetting_show::error_codes::NOT_FOUND.code;
pub(crate) const JOIN_QUERY_ERR_CRITERION_NOT_FOUND: &str =
    join_query::error_codes::CRITERION_NOT_FOUND.code;

/// Exactly what [`dispatch`] routes.
pub(crate) const URIS: &[&str] = &[
    BRANDING_SHOW_TYPE,
    BRANDING_UPDATE_TYPE,
    THEME_SHOW_TYPE,
    THEME_UPDATE_TYPE,
    REQUESTED_SHOW_TYPE,
    REQUESTED_UPDATE_TYPE,
    JOIN_DISCOVERY_SHOW_TYPE,
    JOIN_DISCOVERY_UPDATE_TYPE,
    SCHEMAS_REGISTER_TYPE,
    SCHEMAS_LIST_TYPE,
    SCHEMAS_SHOW_TYPE,
    SCHEMAS_DELETE_TYPE,
    ACCEPTS_REGISTER_TYPE,
    ACCEPTS_LIST_TYPE,
    ACCEPTS_SHOW_TYPE,
    ACCEPTS_DELETE_TYPE,
    VETTER_GRANTS_LIST_TYPE,
    AUTO_GRANT_SHOW_TYPE,
    AUTO_GRANT_UPDATE_TYPE,
    REVOCATIONS_LIST_TYPE,
    RELATIONSHIPS_SUSPEND_TYPE,
    RELATIONSHIPS_RESTORE_TYPE,
    JOIN_VETTING_SHOW_TYPE,
    JOIN_QUERY_TYPE,
    ROOMS_LIST_TYPE,
];

pub(super) async fn dispatch(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
    type_uri: &str,
) -> Option<TrustTaskOutcome> {
    Some(match type_uri {
        BRANDING_SHOW_TYPE => handle_branding_show(state, ctx, doc).await,
        BRANDING_UPDATE_TYPE => handle_branding_update(state, ctx, doc).await,
        THEME_SHOW_TYPE => handle_theme_show(state, doc).await,
        THEME_UPDATE_TYPE => handle_theme_update(state, ctx, doc).await,
        REQUESTED_SHOW_TYPE => handle_requested_show(state, ctx, doc).await,
        REQUESTED_UPDATE_TYPE => handle_requested_update(state, ctx, doc).await,
        JOIN_DISCOVERY_SHOW_TYPE => handle_join_discovery_show(state, ctx, doc).await,
        JOIN_DISCOVERY_UPDATE_TYPE => handle_join_discovery_update(state, ctx, doc).await,
        SCHEMAS_REGISTER_TYPE => handle_schemas_register(state, ctx, doc).await,
        SCHEMAS_LIST_TYPE => handle_schemas_list(state, ctx, doc).await,
        SCHEMAS_SHOW_TYPE => handle_schemas_show(state, ctx, doc).await,
        SCHEMAS_DELETE_TYPE => handle_schemas_delete(state, ctx, doc).await,
        ACCEPTS_REGISTER_TYPE => handle_accepts_register(state, ctx, doc).await,
        ACCEPTS_LIST_TYPE => handle_accepts_list(state, ctx, doc).await,
        ACCEPTS_SHOW_TYPE => handle_accepts_show(state, ctx, doc).await,
        ACCEPTS_DELETE_TYPE => handle_accepts_delete(state, ctx, doc).await,
        VETTER_GRANTS_LIST_TYPE => handle_vetter_grants_list(state, ctx, doc).await,
        AUTO_GRANT_SHOW_TYPE => handle_auto_grant_show(state, ctx, doc).await,
        AUTO_GRANT_UPDATE_TYPE => handle_auto_grant_update(state, ctx, doc).await,
        REVOCATIONS_LIST_TYPE => handle_revocations_list(state, ctx, doc).await,
        RELATIONSHIPS_SUSPEND_TYPE => {
            handle_edge_lifecycle(state, ctx, doc, EdgeVerb::Suspend).await
        }
        RELATIONSHIPS_RESTORE_TYPE => {
            handle_edge_lifecycle(state, ctx, doc, EdgeVerb::Restore).await
        }
        JOIN_VETTING_SHOW_TYPE => handle_join_vetting_show(state, ctx, doc).await,
        JOIN_QUERY_TYPE => handle_join_query(state, ctx, doc).await,
        ROOMS_LIST_TYPE => handle_rooms_list(state, ctx, doc).await,
        _ => return None,
    })
}

// ─── authority, payloads and pages ───────────────────────────────────────

/// The signer as an administrator of any role, with its payload held to the
/// published schema — the gate on this family's reads. A write asks the
/// capability it needs instead ([`as_capable`]).
async fn as_admin<P>(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: &TrustTask<Value>,
) -> Result<String, TrustTaskOutcome>
where
    P: trust_tasks_rs::validate::ValidatedPayload + serde::de::DeserializeOwned,
{
    let actor = admin_signer(state, ctx, doc).await?;
    parse_spec_payload::<P>(doc)?;
    Ok(actor.did)
}

/// The signer holding `cap` (`vtc-admin-roles.md` §4 "Gates"), with its
/// payload held to the published schema.
async fn as_capable<P>(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: &TrustTask<Value>,
    cap: crate::acl::Capability,
) -> Result<String, TrustTaskOutcome>
where
    P: trust_tasks_rs::validate::ValidatedPayload + serde::de::DeserializeOwned,
{
    let actor = super::capable_signer(state, ctx, doc, cap, None).await?;
    parse_spec_payload::<P>(doc)?;
    Ok(actor.did)
}

/// [`as_capable`], keeping the signer's claims for a consent gate.
async fn as_capable_claims<P>(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: &TrustTask<Value>,
    cap: crate::acl::Capability,
) -> Result<vti_common::auth::extractor::AuthClaims, TrustTaskOutcome>
where
    P: trust_tasks_rs::validate::ValidatedPayload + serde::de::DeserializeOwned,
{
    let actor = super::capable_signer(state, ctx, doc, cap, None).await?;
    parse_spec_payload::<P>(doc)?;
    Ok(actor)
}

/// What a criterion states — every requirement the register payload carries —
/// without what the store adds (registrant, time, position, hidden-vetting
/// parameters). Two criteria that state the same are no change, so
/// re-registering one as it stands asks nobody for anything.
fn stated_requirements(c: &crate::schemas::AcceptsCriterion) -> Value {
    json!({
        "admission": c.admission.as_str(),
        "query": c.query,
        "credentialIssuers": c.credential_issuers,
        "invitationRequired": c.invitation_required,
        "description": c.description,
        "vetting": c.vetting,
    })
}

/// The gate on registering, replacing or deleting a join criterion —
/// **VTI-APV-023**: the requester's bound gesture and the consent of the other
/// holders of `vtc.surface.admin`, or, in single-administrator mode
/// (VTI-APV-022), the gesture alone at `Critical`
/// ([`super::acl_tasks::settle_consent_gate`]). The parked action runs this
/// handler again on its N-th approval, against the criteria as they are then
/// (VTI-APV-017); the consent is pinned to the criterion as stored, so a write
/// to it in the meantime voids the action.
async fn settle_criteria_gate(
    state: &AppState,
    actor: &vti_common::auth::extractor::AuthClaims,
    doc: &TrustTask<Value>,
    id: &str,
    summary: &str,
) -> Result<(), TrustTaskOutcome> {
    settle_criterion_consent(
        state,
        actor,
        doc,
        crate::acl::admin_consent::Act::ChangeJoinCriteria,
        id,
        summary,
    )
    .await
}

/// [`settle_criteria_gate`] for any act that changes a join criterion —
/// [`Act::ChangeHiddenVetting`](crate::acl::admin_consent::Act::ChangeHiddenVetting)
/// too, which `vtc/vetting/hidden/{publish,withdraw}` settle before they write.
pub(crate) async fn settle_criterion_consent(
    state: &AppState,
    actor: &vti_common::auth::extractor::AuthClaims,
    doc: &TrustTask<Value>,
    act: crate::acl::admin_consent::Act,
    id: &str,
    summary: &str,
) -> Result<(), TrustTaskOutcome> {
    super::acl_tasks::settle_consent_gate(state, actor, doc, act, id, summary, summary).await
}

/// Any signer the community holds an entry for, with its payload held to the
/// published schema.
async fn as_member<P>(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: &TrustTask<Value>,
) -> Result<String, TrustTaskOutcome>
where
    P: trust_tasks_rs::validate::ValidatedPayload + serde::de::DeserializeOwned,
{
    let actor = member_signer(state, ctx, doc).await?;
    parse_spec_payload::<P>(doc)?;
    Ok(actor.did)
}

/// The default and largest page, as the listing specifications state them.
const DEFAULT_PAGE: usize = 50;
const MAX_PAGE: usize = 100;

/// One page of `items` from the payload's `cursor` and `limit`, as
/// `{ items, nextCursor? }`. The cursor is the decimal offset of the next item,
/// prefixed so that a cursor from another listing's scheme is refused rather
/// than read as an offset.
fn page<T: Serialize>(doc: &TrustTask<Value>, items: Vec<T>) -> TrustTaskOutcome {
    page_with(doc, items, None)
}

/// [`page`], with an `ext` member on the response.
fn page_with<T: Serialize>(
    doc: &TrustTask<Value>,
    items: Vec<T>,
    ext: Option<Value>,
) -> TrustTaskOutcome {
    let start = match doc.payload.get("cursor").and_then(Value::as_str) {
        None => 0,
        Some(c) => match c.strip_prefix("o").and_then(|n| n.parse::<usize>().ok()) {
            Some(n) if n <= items.len() => n,
            _ => {
                return reject_with(
                    doc,
                    RejectReason::MalformedRequest {
                        reason: "cursor is not one this listing issued".into(),
                    },
                );
            }
        },
    };
    let limit = doc
        .payload
        .get("limit")
        .and_then(Value::as_u64)
        .map_or(DEFAULT_PAGE, |l| (l as usize).clamp(1, MAX_PAGE));
    let end = start.saturating_add(limit).min(items.len());
    let next = (end < items.len()).then(|| format!("o{end}"));
    let slice: Vec<&T> = items[start..end].iter().collect();
    let mut body = json!({ "items": slice });
    if let Some(next) = next {
        body["nextCursor"] = Value::String(next);
    }
    if let Some(ext) = ext {
        body["ext"] = ext;
    }
    success_response(doc, body)
}

/// The payload member `field`, parsed as the route parsed its body.
fn member_of<T: serde::de::DeserializeOwned>(
    doc: &TrustTask<Value>,
    field: &str,
) -> Result<T, TrustTaskOutcome> {
    serde_json::from_value(doc.payload.get(field).cloned().unwrap_or(Value::Null)).map_err(|e| {
        reject_with(
            doc,
            RejectReason::MalformedRequest {
                reason: format!("payload.{field}: {e}"),
            },
        )
    })
}

/// The payload's own members without `ext`, for a route type that refuses
/// unknown members.
fn without_ext(doc: &TrustTask<Value>) -> Value {
    let mut v = doc.payload.clone();
    if let Some(map) = v.as_object_mut() {
        map.remove("ext");
    }
    v
}

fn declared(doc: &TrustTask<Value>, code: &str, message: impl Into<String>) -> TrustTaskOutcome {
    reject_with_code(doc, extended_code(code), message, None)
}

/// A declared code carrying `err`'s kind as `details.reason` (`not_found`,
/// `conflict`), the marker `vtc-client` reads a typed error back from.
fn declared_as(doc: &TrustTask<Value>, code: &'static str, err: AppError) -> TrustTaskOutcome {
    task_error_to_reject(doc, &crate::error::TaskError::declared(code, err))
}

// ─── how the community presents itself ───────────────────────────────────

async fn handle_branding_show(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = as_member::<branding_show::Payload>(state, ctx, &doc).await {
        return reject;
    }
    match crate::community::branding::load_branding(&state.community_ks).await {
        Ok(b) => success_response(&doc, json!({ "branding": b })),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_branding_update(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor = match as_capable::<branding_update::Payload>(
        state,
        ctx,
        &doc,
        crate::acl::Capability::SurfaceAdmin,
    )
    .await
    {
        Ok(a) => a,
        Err(reject) => return reject,
    };
    let body = doc.payload.get("branding").cloned().unwrap_or(Value::Null);
    match crate::routes::community::branding::update_branding(state, &actor, &body).await {
        Ok(b) => success_response(&doc, json!({ "branding": b })),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

/// `vtc/community/theme/show/0.1`. Answered to anyone, identified or not
/// (show item 1): the sign-in pages draw the theme before the visitor holds an
/// identity, and the stylesheet is what every loaded page shows anyway.
async fn handle_theme_show(state: &AppState, doc: TrustTask<Value>) -> TrustTaskOutcome {
    if let Err(reject) = parse_spec_payload::<theme_show::Payload>(&doc) {
        return reject;
    }
    match crate::community::theme::shown_stylesheet(&state.community_ks).await {
        Ok(Some(t)) => success_response(
            &doc,
            json!({ "stylesheet": t.stylesheet, "updatedAt": t.updated_at }),
        ),
        Ok(None) => success_response(&doc, json!({ "stylesheet": "" })),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

/// `vtc/community/theme/update/0.1` — administrator standing, as for branding.
async fn handle_theme_update(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    use crate::routes::community::theme::{ThemeUpdateError, update_theme};

    let actor = match as_capable::<theme_update::Payload>(
        state,
        ctx,
        &doc,
        crate::acl::Capability::SurfaceAdmin,
    )
    .await
    {
        Ok(a) => a,
        Err(reject) => return reject,
    };
    let stylesheet = doc
        .payload
        .get("stylesheet")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string();
    let dry_run = doc
        .payload
        .get("dryRun")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    match update_theme(state, &actor, &stylesheet, dry_run).await {
        Ok(u) => {
            let mut body = json!({ "stylesheet": u.stylesheet, "stored": u.stored });
            if let Some(at) = u.updated_at {
                body["updatedAt"] = json!(at);
            }
            success_response(&doc, body)
        }
        Err(ThemeUpdateError::OutsideProfile(v)) => reject_with_code(
            &doc,
            extended_code(THEME_UPDATE_ERR_OUTSIDE_PROFILE),
            v.message.clone(),
            Some(json!({ "line": v.line, "column": v.column, "rule": v.rule })),
        ),
        // Item 2's byte bound arrives here as a validation error, so it is
        // `malformedRequest`, not `outsideProfile`.
        Err(ThemeUpdateError::App(e)) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_requested_show(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = as_member::<requested_show::Payload>(state, ctx, &doc).await {
        return reject;
    }
    match crate::community::requested_attributes::load_requested(&state.community_ks).await {
        Ok(r) => success_response(&doc, json!({ "requestedAttributes": r })),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_requested_update(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor = match as_capable::<requested_update::Payload>(
        state,
        ctx,
        &doc,
        crate::acl::Capability::SurfaceAdmin,
    )
    .await
    {
        Ok(a) => a,
        Err(reject) => return reject,
    };
    let body = doc
        .payload
        .get("requestedAttributes")
        .cloned()
        .unwrap_or(Value::Null);
    // A type asked for twice is the one refusal the specification names.
    if let Some(list) = body.as_array() {
        let mut seen = std::collections::BTreeSet::new();
        for t in list.iter().filter_map(|a| a["type"].as_str()) {
            if !seen.insert(t) {
                return declared(
                    &doc,
                    REQUESTED_ERR_DUPLICATE_TYPE,
                    format!("`{t}` is requested twice"),
                );
            }
        }
    }
    match crate::routes::community::requested_attributes::update_requested_attributes(
        state, &actor, body,
    )
    .await
    {
        Ok(r) => success_response(&doc, json!({ "requestedAttributes": r })),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_join_discovery_show(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = as_member::<join_discovery_show::Payload>(state, ctx, &doc).await {
        return reject;
    }
    match crate::routes::community::join_discovery::show_join_discovery(state).await {
        Ok(d) => success_response(&doc, json!({ "joinDiscovery": d })),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_join_discovery_update(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor = match as_capable::<join_discovery_update::Payload>(
        state,
        ctx,
        &doc,
        crate::acl::Capability::SurfaceAdmin,
    )
    .await
    {
        Ok(a) => a,
        Err(reject) => return reject,
    };
    let mut setting = doc
        .payload
        .get("joinDiscovery")
        .cloned()
        .unwrap_or(Value::Null);
    if let Some(map) = setting.as_object_mut() {
        map.remove("ext");
    }
    let setting: crate::community::join_discovery::JoinDiscovery =
        match serde_json::from_value(setting) {
            Ok(s) => s,
            Err(e) => {
                return reject_with(
                    &doc,
                    RejectReason::MalformedRequest {
                        reason: format!("payload.joinDiscovery: {e}"),
                    },
                );
            }
        };
    match crate::routes::community::join_discovery::update_join_discovery(state, &actor, &setting)
        .await
    {
        Ok(d) => success_response(&doc, json!({ "joinDiscovery": d })),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

// ─── the credential-schema registry ──────────────────────────────────────

async fn handle_schemas_register(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor = match as_capable::<schemas_register::Payload>(
        state,
        ctx,
        &doc,
        crate::acl::Capability::SurfaceAdmin,
    )
    .await
    {
        Ok(a) => a,
        Err(reject) => return reject,
    };
    let body: crate::routes::schemas::RegisterSchemaBody = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    if let Some(schema) = &body.credential_schema
        && let Err(e) = jsonschema::validator_for(schema)
    {
        return declared(
            &doc,
            SCHEMAS_REGISTER_ERR_INVALID_CREDENTIAL_SCHEMA,
            format!("credentialSchema does not compile: {e}"),
        );
    }
    match crate::routes::schemas::register_inner(state, &actor, body).await {
        Ok(entry) => success_response(&doc, json!({ "schema": entry })),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

/// A registry entry as a listing shows it: whether it carries a credential
/// schema, not the schema itself.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SchemaSummary {
    pub(crate) type_uri: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) dtg_type: Option<String>,
    pub(crate) kind: crate::schemas::SchemaKind,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) description: Option<String>,
    pub(crate) has_credential_schema: bool,
    pub(crate) created_at: chrono::DateTime<chrono::Utc>,
    pub(crate) created_by_did: String,
}

async fn handle_schemas_list(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = as_admin::<schemas_list::Payload>(state, ctx, &doc).await {
        return reject;
    }
    let kind: Option<crate::schemas::SchemaKind> = match member_of(&doc, "kind") {
        Ok(k) => k,
        Err(reject) => return reject,
    };
    let mut entries = match crate::schemas::list_schemas(&state.schemas_ks).await {
        Ok(e) => e,
        Err(e) => return app_error_to_reject(&doc, &e),
    };
    entries.sort_by(|a, b| a.type_uri.cmp(&b.type_uri));
    let items: Vec<SchemaSummary> = entries
        .into_iter()
        .filter(|e| kind.is_none_or(|k| e.kind == k))
        .map(|e| SchemaSummary {
            has_credential_schema: e.credential_schema.is_some(),
            type_uri: e.type_uri,
            dtg_type: e.dtg_type,
            kind: e.kind,
            description: e.description,
            created_at: e.created_at,
            created_by_did: e.created_by_did,
        })
        .collect();
    page(&doc, items)
}

async fn handle_schemas_show(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = as_admin::<schemas_show::Payload>(state, ctx, &doc).await {
        return reject;
    }
    let type_uri: String = match member_of(&doc, "typeUri") {
        Ok(t) => t,
        Err(reject) => return reject,
    };
    match crate::schemas::get_schema(&state.schemas_ks, type_uri.trim()).await {
        Ok(Some(entry)) => success_response(&doc, json!({ "schema": entry })),
        Ok(None) => declared_as(
            &doc,
            SCHEMAS_SHOW_ERR_NOT_FOUND,
            AppError::NotFound(format!("schema `{type_uri}` not found")),
        ),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_schemas_delete(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor = match as_capable::<schemas_delete::Payload>(
        state,
        ctx,
        &doc,
        crate::acl::Capability::SurfaceAdmin,
    )
    .await
    {
        Ok(a) => a,
        Err(reject) => return reject,
    };
    let type_uri: String = match member_of(&doc, "typeUri") {
        Ok(t) => t,
        Err(reject) => return reject,
    };
    // A criterion whose query names the type would be left unevaluable.
    let type_uri = type_uri.trim().to_string();
    let criteria = match crate::schemas::list_accepts(&state.schemas_ks).await {
        Ok(c) => c,
        Err(e) => return app_error_to_reject(&doc, &e),
    };
    let users: Vec<String> = criteria
        .into_iter()
        .filter(|c| {
            c.dcql()
                .ok()
                .flatten()
                .is_some_and(|q| crate::schemas::accepts::referenced_types(&q).contains(&type_uri))
        })
        .map(|c| c.id)
        .collect();
    if !users.is_empty() {
        return reject_with_code(
            &doc,
            extended_code(SCHEMAS_DELETE_ERR_IN_USE),
            format!(
                "`{type_uri}` is referenced by the Accepts criteria {}; delete or re-register \
                 them first",
                users.join(", ")
            ),
            Some(json!({ "criterionIds": users.iter().take(16).collect::<Vec<_>>() })),
        );
    }
    match crate::routes::schemas::delete_inner(state, &actor, &type_uri).await {
        Ok(id) => success_response(&doc, json!({ "typeUri": id })),
        Err(e @ AppError::NotFound(_)) => declared_as(&doc, SCHEMAS_DELETE_ERR_NOT_FOUND, e),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_accepts_register(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let claims = match as_capable_claims::<accepts_register::Payload>(
        state,
        ctx,
        &doc,
        crate::acl::Capability::SurfaceAdmin,
    )
    .await
    {
        Ok(a) => a,
        Err(reject) => return reject,
    };
    let actor = claims.did.clone();
    let body: accepts_register::Payload = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    let criterion = match accepts_criterion_from(body) {
        Ok(c) => c,
        Err(e) => return app_error_to_reject(&doc, &e),
    };
    // The refusals the specification orders: the query parses, the types it
    // names are registered, the statement type is registered, the vetting
    // requirements are satisfiable, every requirement is one this community
    // can evaluate, and the manifest can publish the result.
    if let Some(query) = &criterion.query
        && let Err(AppError::Validation(m)) =
            crate::schemas::accepts::validate_accepts_query(&state.schemas_ks, query).await
    {
        let code = if m.starts_with("invalid DCQL query") {
            ACCEPTS_REGISTER_ERR_INVALID_QUERY
        } else {
            ACCEPTS_REGISTER_ERR_UNREGISTERED_TYPE
        };
        return declared(&doc, code, m);
    }
    if let Some(vetting) = &criterion.vetting {
        match crate::endorsement_types::storage::type_exists(
            &state.endorsement_types_ks,
            &vetting.statement_type,
        )
        .await
        {
            Ok(true) => {}
            Ok(false) => {
                return declared(
                    &doc,
                    ACCEPTS_REGISTER_ERR_UNREGISTERED_STATEMENT_TYPE,
                    format!(
                        "vetting.statementType `{}` is not a registered endorsement type — \
                         register it with vtc/endorsement-types/register first",
                        vetting.statement_type
                    ),
                );
            }
            Err(e) => return app_error_to_reject(&doc, &e),
        }
        use vta_sdk::protocols::vetting::CheckShape as _;
        if let Err(e) = vetting.check_shape() {
            return declared(
                &doc,
                ACCEPTS_REGISTER_ERR_INVALID_VETTING,
                format!("vetting: {e}"),
            );
        }
    }
    if let Some(reason) = unsupported_requirement(state, &criterion) {
        return declared(&doc, ACCEPTS_REGISTER_ERR_UNSUPPORTED_REQUIREMENT, reason);
    }
    // VTI-APV-023: a criterion that differs from the one stored under its id —
    // a new one, or any requirement changed — takes the requester's bound
    // gesture and the other `vtc.surface.admin` holders' consent. Last, so a
    // criterion the checks above refuse asks nobody for anything.
    let stored = match crate::schemas::get_accepts(&state.schemas_ks, &criterion.id).await {
        Ok(c) => c,
        Err(e) => return app_error_to_reject(&doc, &e),
    };
    if !criterion.id.is_empty()
        && stored.as_ref().map(stated_requirements) != Some(stated_requirements(&criterion))
    {
        let verb = if stored.is_some() { "Replace" } else { "Add" };
        let summary = format!(
            "{verb} the join criterion {} (admission {}), which decides who may become a \
             member of this community",
            criterion.id,
            criterion.admission.as_str()
        );
        if let Err(refusal) =
            settle_criteria_gate(state, &claims, &doc, &criterion.id, &summary).await
        {
            return refusal;
        }
    }
    match crate::routes::schemas::register_accepts_inner(state, &actor, criterion).await {
        Ok(criterion) => success_response(&doc, json!({ "criterion": criterion.to_wire() })),
        // Every check above passed, so what is left is the manifest refusing it.
        Err(AppError::Validation(m)) => declared(&doc, ACCEPTS_REGISTER_ERR_NOT_PUBLISHABLE, m),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

/// The criterion a `vtc/schemas/accepts/register/0.2` payload states, as the
/// store holds it: every requirement it states, and none it does not. The
/// registrant and time are the handler's to set.
fn accepts_criterion_from(
    body: accepts_register::Payload,
) -> Result<crate::schemas::AcceptsCriterion, AppError> {
    use crate::schemas::{Admission, CredentialIssuers};
    let admission = match body.admission {
        accepts_register::Admission::Automatic => Admission::Automatic,
        accepts_register::Admission::Review => Admission::Review,
        // A mode this build does not know is one it cannot honour; refusing is
        // the only reading that does not change what the criterion says.
        #[allow(unreachable_patterns)]
        other => {
            return Err(AppError::Validation(format!(
                "admission `{other}` is not one this community can decide by"
            )));
        }
    };
    let credential_issuers = match body.credential_issuers {
        None => None,
        Some(accepts_register::CredentialIssuers::Any) => Some(CredentialIssuers::Any),
        Some(accepts_register::CredentialIssuers::Community) => Some(CredentialIssuers::Community),
        Some(accepts_register::CredentialIssuers::Recognised) => {
            Some(CredentialIssuers::Recognised)
        }
        #[allow(unreachable_patterns)]
        Some(other) => {
            return Err(AppError::Validation(format!(
                "credentialIssuers `{other}` is not one this community can evaluate"
            )));
        }
    };
    let vetting = body
        .vetting
        .map(|v| serde_json::to_value(v).and_then(serde_json::from_value))
        .transpose()
        .map_err(|e| AppError::Validation(format!("vetting: {e}")))?;
    let mut criterion = crate::schemas::AcceptsCriterion::new(
        String::from(body.id).trim(),
        admission,
        String::new(),
    );
    criterion.query = body.query.map(|q| Value::Object(q.0));
    criterion.credential_issuers = credential_issuers;
    criterion.invitation_required = body.invitation_required.unwrap_or(false);
    criterion.description = body.description.map(String::from);
    criterion.vetting = vetting;
    Ok(criterion)
}

/// A requirement the criterion states that this community cannot decide a
/// submission against, if it states one. Only `recognised` issuers can be: a
/// community with no trust registry recognises no other community, and a
/// criterion it publishes must be one it can evaluate.
fn unsupported_requirement(
    state: &AppState,
    criterion: &crate::schemas::AcceptsCriterion,
) -> Option<String> {
    (criterion.credential_issuers == Some(crate::schemas::CredentialIssuers::Recognised)
        && state.registry_client.is_none())
    .then(|| {
        "credentialIssuers `recognised` needs a trust registry to recognise other communities \
         by, and this community has none configured — use `community`, or configure the \
         registry first"
            .to_string()
    })
}

async fn handle_accepts_list(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = as_admin::<accepts_list::Payload>(state, ctx, &doc).await {
        return reject;
    }
    match crate::schemas::list_accepts(&state.schemas_ks).await {
        Ok(mut criteria) => {
            criteria.sort_by(|a, b| a.id.cmp(&b.id));
            page(&doc, criteria.iter().map(|c| c.to_wire()).collect())
        }
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_accepts_show(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = as_admin::<accepts_show::Payload>(state, ctx, &doc).await {
        return reject;
    }
    let id: String = match member_of(&doc, "id") {
        Ok(i) => i,
        Err(reject) => return reject,
    };
    match crate::schemas::get_accepts(&state.schemas_ks, id.trim()).await {
        Ok(Some(c)) => success_response(&doc, json!({ "criterion": c.to_wire() })),
        Ok(None) => declared_as(
            &doc,
            ACCEPTS_SHOW_ERR_NOT_FOUND,
            AppError::NotFound(format!("accepts criterion `{id}` not found")),
        ),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_accepts_delete(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let claims = match as_capable_claims::<accepts_delete::Payload>(
        state,
        ctx,
        &doc,
        crate::acl::Capability::SurfaceAdmin,
    )
    .await
    {
        Ok(a) => a,
        Err(reject) => return reject,
    };
    let actor = claims.did.clone();
    let id: String = match member_of(&doc, "id") {
        Ok(i) => i,
        Err(reject) => return reject,
    };
    // VTI-APV-023: removing a criterion changes who may become a member as
    // surely as adding one does. One that does not exist is refused as such,
    // without asking anyone to approve it.
    match crate::schemas::get_accepts(&state.schemas_ks, id.trim()).await {
        Ok(Some(_)) => {
            let summary = format!(
                "Remove the join criterion {}, which decides who may become a member of this \
                 community",
                id.trim()
            );
            if let Err(refusal) =
                settle_criteria_gate(state, &claims, &doc, id.trim(), &summary).await
            {
                return refusal;
            }
        }
        Ok(None) => {
            return declared_as(
                &doc,
                ACCEPTS_DELETE_ERR_NOT_FOUND,
                AppError::NotFound(format!("accepts criterion `{}` not found", id.trim())),
            );
        }
        Err(e) => return app_error_to_reject(&doc, &e),
    }
    match crate::routes::schemas::delete_accepts_inner(state, &actor, id.trim()).await {
        Ok(id) => success_response(&doc, json!({ "id": id })),
        Err(e @ AppError::NotFound(_)) => declared_as(&doc, ACCEPTS_DELETE_ERR_NOT_FOUND, e),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

// ─── the vetting reads ───────────────────────────────────────────────────

async fn handle_vetter_grants_list(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = as_admin::<grants_list::Payload>(state, ctx, &doc).await {
        return reject;
    }
    match crate::vetting::vetters::grant_rows(state).await {
        Ok(rows) => page(&doc, rows),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_auto_grant_show(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = as_admin::<auto_grant_show::Payload>(state, ctx, &doc).await {
        return reject;
    }
    match crate::vetting::auto_grant::status(state).await {
        Ok(s) => success_response(&doc, json!({ "autoGrant": s })),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_auto_grant_update(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor = match as_capable::<auto_grant_update::Payload>(
        state,
        ctx,
        &doc,
        crate::acl::Capability::VettingManage,
    )
    .await
    {
        Ok(a) => a,
        Err(reject) => return reject,
    };
    let config: vta_sdk::protocols::vetting::AutoGrantConfig =
        match serde_json::from_value(without_ext(&doc)) {
            Ok(c) => c,
            Err(e) => {
                return reject_with(
                    &doc,
                    RejectReason::MalformedRequest {
                        reason: format!("payload: {e}"),
                    },
                );
            }
        };
    match crate::vetting::auto_grant::configure(state, &actor, &config).await {
        Ok(s) => success_response(&doc, json!({ "autoGrant": s })),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_revocations_list(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = as_admin::<revocations_list::Payload>(state, ctx, &doc).await {
        return reject;
    }
    let wanted: Option<crate::routes::vetting::RevocationReviewState> =
        match member_of(&doc, "reviewState") {
            Ok(w) => w,
            Err(reject) => return reject,
        };
    match crate::routes::vetting::revocation_rows(state).await {
        Ok(rows) => page(
            &doc,
            rows.into_iter()
                .filter(|r| wanted.is_none_or(|w| r.review_state == w))
                .collect(),
        ),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

// ─── the relationship graph's suspend and restore ────────────────────────

#[derive(Clone, Copy)]
enum EdgeVerb {
    Suspend,
    Restore,
}

/// `vtc/relationships/{suspend,restore}/0.1`.
///
/// The edge is loaded first. Its issuer — the signer itself, whatever DID the
/// edge was issued under — acts as issuer; an administrator acts as
/// moderator; anyone else is told `notFound`, as for an edge that does not
/// exist.
async fn handle_edge_lifecycle(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
    verb: EdgeVerb,
) -> TrustTaskOutcome {
    use crate::routes::relationships::EdgeLifecycleVerb;
    let (not_found, already, terminal, route_verb) = match verb {
        EdgeVerb::Suspend => (
            SUSPEND_ERR_NOT_FOUND,
            SUSPEND_ERR_ALREADY_SUSPENDED,
            SUSPEND_ERR_TERMINAL,
            EdgeLifecycleVerb::Suspend,
        ),
        EdgeVerb::Restore => (
            RESTORE_ERR_NOT_FOUND,
            RESTORE_ERR_NOT_SUSPENDED,
            RESTORE_ERR_TERMINAL,
            EdgeLifecycleVerb::Restore,
        ),
    };
    let Some(signer) = ctx.verified_signer.clone() else {
        return reject_with(&doc, RejectReason::ProofRequired);
    };
    let valid = match verb {
        EdgeVerb::Suspend => parse_spec_payload::<rel_suspend::Payload>(&doc).map(|_| ()),
        EdgeVerb::Restore => parse_spec_payload::<rel_restore::Payload>(&doc).map(|_| ()),
    };
    if let Err(reject) = valid {
        return reject;
    }
    let id: String = match member_of(&doc, "id") {
        Ok(i) => i,
        Err(reject) => return reject,
    };
    let reason: Option<String> = match member_of(&doc, "reason") {
        Ok(r) => r,
        Err(reject) => return reject,
    };
    let missing = |doc: &TrustTask<Value>| {
        declared_as(
            doc,
            not_found,
            AppError::NotFound(format!("VRC {id} not found")),
        )
    };
    let Ok(uuid) = id.parse::<Uuid>() else {
        return missing(&doc);
    };
    let rel = match crate::relationships::get_relationship(&state.relationships_ks, uuid).await {
        Ok(Some(rel)) => rel,
        Ok(None) => return missing(&doc),
        Err(e) => return app_error_to_reject(&doc, &e),
    };
    let (actor, capacity) = if signer == rel.issuer_did {
        (signer, "issuer")
    } else {
        // Suspending or restoring another member's relationship is managing
        // members (vtc-admin-roles.md §4).
        match super::capable_signer(
            state,
            ctx,
            &doc,
            crate::acl::Capability::MembersManage,
            None,
        )
        .await
        {
            Ok(admin) => (admin.did, "admin"),
            Err(_) => return missing(&doc),
        }
    };
    match crate::routes::relationships::record_lifecycle_as(
        state, &actor, capacity, &rel, route_verb, reason,
    )
    .await
    {
        Ok(response) => success_response(&doc, response),
        Err(AppError::Conflict(m)) if m.contains("terminal") => {
            declared_as(&doc, terminal, AppError::Conflict(m))
        }
        Err(e @ AppError::Conflict(_)) => declared_as(&doc, already, e),
        Err(AppError::NotFound(_)) => missing(&doc),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

// ─── the join queue's vetting facts and credential query ─────────────────

async fn handle_join_vetting_show(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = as_admin::<join_vetting_show::Payload>(state, ctx, &doc).await {
        return reject;
    }
    let id: String = match member_of(&doc, "id") {
        Ok(i) => i,
        Err(reject) => return reject,
    };
    let not_found = |doc: &TrustTask<Value>| {
        declared_as(
            doc,
            JOIN_VETTING_ERR_NOT_FOUND,
            AppError::NotFound(format!("join request not found: {id}")),
        )
    };
    let Ok(uuid) = id.parse::<Uuid>() else {
        return not_found(&doc);
    };
    match crate::routes::join_requests::read::vetting_of(state, uuid).await {
        Ok(response) => success_response(&doc, response),
        Err(AppError::NotFound(_)) => not_found(&doc),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_join_query(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = as_admin::<join_query::Payload>(state, ctx, &doc).await {
        return reject;
    }
    let body: crate::routes::join_requests::present::SendQueryRequest =
        match serde_json::from_value(without_ext(&doc)) {
            Ok(b) => b,
            Err(e) => {
                return reject_with(
                    &doc,
                    RejectReason::MalformedRequest {
                        reason: format!("payload: {e}"),
                    },
                );
            }
        };
    match crate::routes::join_requests::present::send_query_inner(state, body).await {
        Ok(response) => success_response(&doc, response),
        Err(e @ AppError::NotFound(_)) => declared_as(&doc, JOIN_QUERY_ERR_CRITERION_NOT_FOUND, e),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

// ─── the rooms this host stores ──────────────────────────────────────────

async fn handle_rooms_list(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    // `vtc.rooms.admin`, as every task about hosting rooms is
    // (`data-rooms-files.md` §6.2): a community can hand room hosting to someone
    // who is not a full administrator.
    if let Err(reject) =
        as_capable::<rooms_list::Payload>(state, ctx, &doc, crate::acl::Capability::RoomsAdmin)
            .await
    {
        return reject;
    }
    let lifecycle: Option<String> = match member_of(&doc, "lifecycle") {
        Ok(l) => l,
        Err(reject) => return reject,
    };
    match crate::routes::rooms::hosted_rooms(state).await {
        Ok(mut rooms) => {
            rooms.sort_by(|a, b| a.room_id.cmp(&b.room_id));
            // Whether this community takes room files, so the console can say how to
            // turn them on (a `[rooms.files]` section) rather than show uploads that
            // would be refused — and, when it does, the defaults its configuration
            // sets: what every room is held to unless the rooms policy or an override
            // says otherwise (`data-rooms-files.md` §8.1, Settings ▸ Rooms). Read-only:
            // they are changed in the configuration file.
            let host = state.room_files.host_limits();
            let room_files = if host.files_enabled {
                let mut on = json!({
                    "enabled": true,
                    "defaults": {
                        "room": host.room.capped(host.max_file_bytes),
                        "member": host.member.capped(host.max_file_bytes),
                    },
                    "maxFileBytes": host.max_file_bytes,
                    "orphanGraceHours": host.orphan_grace_secs / 3600,
                });
                if let Some(capacity) = host.storage_capacity_bytes {
                    on["storageCapacityBytes"] = json!(capacity);
                }
                on
            } else {
                json!({ "enabled": false })
            };
            let ext = json!({ "org.openvtc": { "roomFiles": room_files } });
            page_with(
                &doc,
                rooms
                    .into_iter()
                    .filter(|r| lifecycle.as_deref().is_none_or(|l| r.lifecycle == l))
                    .collect(),
                Some(ext),
            )
        }
        Err(e) => app_error_to_reject(&doc, &e),
    }
}