cnm-cli 0.17.3

CLI Tool for Verified Trust Agents operating in Verified 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
//! `cnm vetting …` — the community-admin side of peer identity vetting.
//!
//! Every command drives the VTC's vetting admin REST surface through
//! [`vtc_client::VtcClient`]: the vetter grants (`/v1/vetting/vetters`), the
//! automatic-grant configuration (`/v1/vetting/auto-grant`), the community's
//! branding (`/v1/community/branding`) and the statement withdrawal notices
//! (`/v1/vetting/revocations`). A grant is withdrawn like any endorsement,
//! with `DELETE /v1/credentials/endorsements/{endorsementId}`.
//!
//! `bootstrap-pgp` seeds the first vetters from an existing OpenPGP web of
//! trust; its graph and link logic is the pure [`wot`] and [`plan`] pair.
//!
//! The routes are REST-only and need a community-admin token, so every command
//! authenticates to the VTC itself, with the VTC's DID as the audience (see
//! [`crate::vtc`]), and fails with the fix when the VTC refuses. There are no
//! retries here: a failed call is reported, not repeated.

mod bootstrap;
pub mod plan;
#[cfg(test)]
mod test_web;
pub mod wot;

use chrono::{DateTime, Utc};
use clap::{Subcommand, ValueEnum};
use ratatui::layout::Constraint;
use ratatui::style::{Color, Modifier, Style};
use ratatui::widgets::{Block, Cell, Row, Table};
use serde_json::{Value, json};
use vta_cli_common::display::did_cell;
use vta_cli_common::duration::{humanize_duration, parse_duration_secs};
use vta_cli_common::render::{
    BOLD, DIM, GREEN, RESET, YELLOW, bin_name, is_full_display, is_json_output, print_full_entry,
    print_full_list_title, print_json, print_widget,
};
use vtc_client::join_requests::manifest::v0_2::{
    CommunityBranding, CommunityBrandingAccentColor, CommunityBrandingDisplayName,
};
use vtc_client::vetting::vetters::grant::v0_1 as grant_wire;
use vtc_client::vetting::{
    AutoGrantConfig, AutoGrantStatus, CheckShape, GrantOrigin, MAX_AUTO_GRANT_SWEEP_MINUTES,
    MAX_VETTER_GRANT_VALIDITY_SECONDS, MIN_AUTO_GRANT_SWEEP_MINUTES,
    MIN_VETTER_GRANT_VALIDITY_SECONDS, VetterGrantRow,
};
use vtc_client::{VtcClient, VtcError};

pub use bootstrap::BootstrapPgpArgs;

use crate::vtc::{self as vtc_target, VtcTarget};

type CliResult<T = ()> = Result<T, Box<dyn std::error::Error>>;

/// `cnm vetting …`
#[derive(Subcommand)]
pub enum VettingCommands {
    /// Vetter grants: list them, name a member a vetter, withdraw a grant, or
    /// deliver a grant credential again.
    Vetters {
        #[command(subcommand)]
        command: VetterCommands,
    },

    /// Automatic vetter grants: the sweep that names vetters by the
    /// `vetterEligibility` policy.
    #[command(name = "auto-grant")]
    AutoGrant {
        #[command(subcommand)]
        command: AutoGrantCommands,
    },

    /// How the community presents itself to an applicant's client
    /// (`join-requests/manifest/0.2` branding).
    Branding {
        #[command(subcommand)]
        command: BrandingCommands,
    },

    /// What the community asks an applicant to tell it about themselves
    /// (`join-requests/manifest/0.2` `requestedAttributes`). Answers are the
    /// applicant's own statement, never verified; ask for a credential in a
    /// criterion when you need one that is.
    Ask {
        #[command(subcommand)]
        command: AskCommands,
    },

    /// Vetting statement withdrawal notices, and the admissions each touches.
    Revocations,

    /// Seed vetters from an OpenPGP web of trust.
    ///
    /// Members link their OpenPGP key to their member DID with a clearsigned
    /// statement (`openvtc-link: <memberDid>`). Every active member whose
    /// linked key is within --max-depth certification hops of a root key, and
    /// who holds no live grant, is named a vetter. Run with --dry-run first.
    #[command(name = "bootstrap-pgp")]
    BootstrapPgp(BootstrapPgpArgs),
}

/// `cnm vetting vetters …`
#[derive(Subcommand)]
pub enum VetterCommands {
    /// Every vetter grant, newest first.
    List,
    /// Name a current member a vetter.
    Grant {
        /// The member's DID.
        member_did: String,
        /// How long the grant is valid: `N[s|m|h|d|w]`, one day to two years
        /// (e.g. `180d`). The community's default of one year when absent.
        #[arg(long)]
        validity: Option<String>,
    },
    /// Withdraw a vetter grant. The vetter's statements stop counting and
    /// their profile is deleted.
    Revoke {
        /// The grant's endorsement id, from `cnm vetting vetters list`.
        endorsement_id: String,
    },
    /// Deliver a vetter's live grant credential again, when their wallet lost
    /// it. Nothing new is issued.
    Resend {
        /// The vetter's member DID.
        member_did: String,
    },
}

/// `cnm vetting auto-grant …`
#[derive(Subcommand)]
pub enum AutoGrantCommands {
    /// The configuration and the last sweep.
    Show,
    /// Change the configuration. Values not given keep their current setting.
    Set {
        /// Turn the sweep on (`true`) or off (`false`).
        #[arg(long)]
        enabled: Option<bool>,
        /// Minutes between sweeps, 5–1440.
        #[arg(long)]
        sweep_minutes: Option<u32>,
        /// Validity of a grant the sweep issues: `N[s|m|h|d|w]`, one day to
        /// two years.
        #[arg(long)]
        validity: Option<String>,
    },
}

/// `cnm vetting branding …`
#[derive(Subcommand)]
pub enum BrandingCommands {
    /// The community's branding.
    Show,
    /// Change the branding. Values not given keep their current setting.
    Set {
        /// The name an applicant's client shows, 1–128 characters.
        #[arg(long)]
        display_name: Option<String>,
        /// Accent colour, `#rrggbb`.
        #[arg(long)]
        accent_color: Option<String>,
        /// Logo, an `https` URL of at most 2048 characters.
        #[arg(long)]
        logo_url: Option<String>,
        /// Remove a value: `display-name`, `accent-color` or `logo-url`
        /// (comma-separated or repeated).
        #[arg(long, value_enum, value_delimiter = ',')]
        clear: Vec<BrandingField>,
    },
}

/// `cnm vetting ask …`
#[derive(Subcommand)]
pub enum AskCommands {
    /// What the community asks applicants for now.
    Show,
    /// Replace what the community asks for. Omit every flag, or pass
    /// `--nothing`, to ask for nothing.
    Set {
        /// A claim type every applicant must answer, e.g. `name.display`.
        /// Repeatable.
        #[arg(long = "require")]
        require: Vec<String>,
        /// A claim type an applicant may decline, e.g. `address.country`.
        /// Repeatable.
        #[arg(long = "optional")]
        optional: Vec<String>,
        /// Why you ask, shown to the applicant before they answer:
        /// `<type>=<words>`. Repeatable.
        #[arg(long = "purpose")]
        purpose: Vec<String>,
        /// Ask for nothing.
        #[arg(long, conflicts_with_all = ["require", "optional", "purpose"])]
        nothing: bool,
    },
}

/// Build the requested-attribute list from the `ask set` flags, in the order
/// given — required first. Refuses a purpose for a type that is not asked, and
/// a type asked both ways.
fn requested_from_flags(
    require: &[String],
    optional: &[String],
    purpose: &[String],
) -> Result<Vec<serde_json::Value>, String> {
    let mut purposes = std::collections::BTreeMap::new();
    for p in purpose {
        let (t, words) = p
            .split_once('=')
            .ok_or_else(|| format!("--purpose {p}: expected `<type>=<words>`"))?;
        purposes.insert(t.trim().to_string(), words.trim().to_string());
    }
    if let Some(both) = require.iter().find(|t| optional.contains(t)) {
        return Err(format!("{both} is both --require and --optional; pick one"));
    }
    if let Some(stray) = purposes
        .keys()
        .find(|t| !require.contains(t) && !optional.contains(t))
    {
        return Err(format!("--purpose names {stray}, which is not asked for"));
    }
    Ok(require
        .iter()
        .map(|t| (t, true))
        .chain(optional.iter().map(|t| (t, false)))
        .map(|(t, required)| {
            let mut o = serde_json::json!({ "type": t, "required": required });
            if let Some(w) = purposes.get(t) {
                o["purpose"] = serde_json::json!(w);
            }
            o
        })
        .collect())
}

async fn cmd_ask_show(vtc: &VtcClient) -> CliResult {
    let asked = vtc
        .requested_attributes()
        .await
        .map_err(|e| guidance(e, Op::AskShow))?;
    print_asked(&asked)
}

async fn cmd_ask_set(
    vtc: &VtcClient,
    require: Vec<String>,
    optional: Vec<String>,
    purpose: Vec<String>,
) -> CliResult {
    let list = requested_from_flags(&require, &optional, &purpose)?;
    let requested = serde_json::from_value::<
        Vec<vtc_client::join_requests::manifest::v0_2::ResponseRequestedAttributesItem>,
    >(serde_json::Value::Array(list))
    .map_err(|e| {
        format!(
            "{e}.
A type is a claim-type token such as `name.display` or `x:handle`; a purpose              is at most 256 characters."
        )
    })?;
    let stored = vtc
        .set_requested_attributes(&requested)
        .await
        .map_err(|e| guidance(e, Op::AskSet))?;
    if !is_json_output() {
        println!("{GREEN}✓{RESET} Applicants are now asked for this.");
    }
    print_asked(&stored)
}

fn print_asked(
    asked: &[vtc_client::join_requests::manifest::v0_2::ResponseRequestedAttributesItem],
) -> CliResult {
    if is_json_output() {
        println!("{}", serde_json::to_string_pretty(asked)?);
        return Ok(());
    }
    if asked.is_empty() {
        println!("Applicants are asked for nothing about themselves.");
        return Ok(());
    }
    for a in asked {
        let kind = if a.required { "required" } else { "optional" };
        match &a.purpose {
            Some(p) => println!("  {} ({kind}) — {}", a.type_.as_str(), p.as_str()),
            None => println!("  {} ({kind})", a.type_.as_str()),
        }
    }
    println!(
        "Answers are the applicant's own statement. Ask for a credential in a criterion when you \
         need one that is verified."
    );
    Ok(())
}

/// A branding member `--clear` can remove.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
pub enum BrandingField {
    DisplayName,
    AccentColor,
    LogoUrl,
}

/// Run a `cnm vetting` command.
pub async fn run(command: VettingCommands, keyring_key: &str, target: &VtcTarget) -> CliResult {
    if let VettingCommands::BootstrapPgp(args) = command {
        // The keyring, roots and links are read and checked before any call to
        // the community, so a mistake in them costs no round trip.
        return bootstrap::run(args, keyring_key, target).await;
    }
    let vtc = connect(keyring_key, target).await?;
    match command {
        VettingCommands::Vetters { command } => match command {
            VetterCommands::List => cmd_vetters_list(&vtc).await,
            VetterCommands::Grant {
                member_did,
                validity,
            } => cmd_vetters_grant(&vtc, &member_did, validity.as_deref()).await,
            VetterCommands::Revoke { endorsement_id } => {
                cmd_vetters_revoke(&vtc, &endorsement_id).await
            }
            VetterCommands::Resend { member_did } => cmd_vetters_resend(&vtc, &member_did).await,
        },
        VettingCommands::AutoGrant { command } => match command {
            AutoGrantCommands::Show => cmd_auto_grant_show(&vtc).await,
            AutoGrantCommands::Set {
                enabled,
                sweep_minutes,
                validity,
            } => cmd_auto_grant_set(&vtc, enabled, sweep_minutes, validity.as_deref()).await,
        },
        VettingCommands::Ask { command } => match command {
            AskCommands::Show => cmd_ask_show(&vtc).await,
            AskCommands::Set {
                require,
                optional,
                purpose,
                nothing: _,
            } => cmd_ask_set(&vtc, require, optional, purpose).await,
        },
        VettingCommands::Branding { command } => match command {
            BrandingCommands::Show => cmd_branding_show(&vtc).await,
            BrandingCommands::Set {
                display_name,
                accent_color,
                logo_url,
                clear,
            } => {
                let change = BrandingChange {
                    display_name,
                    accent_color,
                    logo_url,
                    clear,
                };
                cmd_branding_set(&vtc, change).await
            }
        },
        VettingCommands::Revocations => cmd_revocations(&vtc).await,
        VettingCommands::BootstrapPgp(_) => unreachable!("handled above"),
    }
}

/// A community-admin [`VtcClient`], authenticated to the VTC with the VTC's
/// DID as the audience.
async fn connect(keyring_key: &str, target: &VtcTarget) -> CliResult<VtcClient> {
    Ok(vtc_target::connect(keyring_key, target).await?.client)
}

// ---------------------------------------------------------------------------
// vetters
// ---------------------------------------------------------------------------

async fn cmd_vetters_list(vtc: &VtcClient) -> CliResult {
    let list = vtc
        .list_vetter_grants()
        .await
        .map_err(|e| guidance(e, Op::VettersList))?;
    if is_json_output() {
        print_json(&list.vetters)?;
        return Ok(());
    }
    if list.vetters.is_empty() {
        println!("No vetter grants.");
        println!(
            "  {DIM}Name a member a vetter with `{} vetting vetters grant <memberDid>`.{RESET}",
            bin_name()
        );
        return Ok(());
    }
    let now = Utc::now();
    if is_full_display() {
        print_full_list_title("Vetter grants", list.vetters.len());
        for row in &list.vetters {
            print_full_entry(&[
                ("Member", &row.member_did),
                ("Status", grant_status(row, now)),
                ("Origin", origin_label(row.origin)),
                ("Valid from", &date(row.valid_from)),
                ("Valid until", &row.valid_until.map_or("—".into(), date)),
                ("Endorsement", &row.endorsement_id),
                ("Credential", &row.credential_id),
                ("Profile", &profile_label(row)),
            ]);
        }
        return Ok(());
    }

    let header = Row::new(vec![
        "Member",
        "Status",
        "Origin",
        "Valid Until",
        "Endorsement ID",
        "Profile",
    ])
    .style(header_style())
    .bottom_margin(1);
    let rows: Vec<Row> = list
        .vetters
        .iter()
        .map(|row| {
            let status = grant_status(row, now);
            let status_style = match status {
                "live" => Style::default().fg(Color::Green),
                "revoked" => Style::default().fg(Color::Red),
                _ => Style::default().fg(Color::Yellow),
            };
            Row::new(vec![
                did_cell(&row.member_did),
                Cell::from(status).style(status_style),
                Cell::from(origin_label(row.origin)),
                Cell::from(row.valid_until.map_or("—".into(), date)),
                Cell::from(row.endorsement_id.clone()),
                Cell::from(profile_label(row)),
            ])
        })
        .collect();
    let table = Table::new(
        rows,
        [
            Constraint::Min(30),
            Constraint::Length(12),
            Constraint::Length(7),
            Constraint::Length(11),
            Constraint::Length(36),
            Constraint::Min(20),
        ],
    )
    .header(header)
    .column_spacing(2)
    .block(bordered(format!(
        " Vetter grants ({}) ",
        list.vetters.len()
    )));
    print_widget(table, height(list.vetters.len()));
    println!(
        "  {DIM}Withdraw a grant with `{bin} vetting vetters revoke <endorsementId>`; \
         `{bin} --full-display vetting vetters list` shows every DID in full.{RESET}",
        bin = bin_name()
    );
    Ok(())
}

/// The `vtc/vetting/vetters/grant/0.1` payload naming `member_did`.
pub(crate) fn grant_payload(
    member_did: &str,
    validity_seconds: Option<u64>,
) -> CliResult<grant_wire::Payload> {
    let validity_seconds = validity_seconds
        .map(i64::try_from)
        .transpose()
        .map_err(|_| "the grant validity is too large")?;
    grant_wire::Payload::try_from(
        grant_wire::Payload::builder()
            .member_did(member_did)
            .validity_seconds(validity_seconds),
    )
    .map_err(|e| format!("{member_did} cannot be named in a vetter grant: {e}").into())
}

async fn cmd_vetters_grant(vtc: &VtcClient, member_did: &str, validity: Option<&str>) -> CliResult {
    let validity_seconds = validity
        .map(|v| parse_grant_validity("--validity", v))
        .transpose()?;
    let result = vtc
        .grant_vetter(&grant_payload(member_did, validity_seconds)?)
        .await
        .map_err(|e| guidance(e, Op::Grant { member_did }))?;
    let grant = &result.grant;
    if is_json_output() {
        let mut value = serde_json::to_value(grant)?;
        value["created"] = json!(result.created);
        print_json(&value)?;
        return Ok(());
    }
    if result.created {
        println!("{GREEN}✓{RESET} Named {member_did} a vetter.");
    } else {
        println!(
            "{YELLOW}!{RESET} {member_did} already holds a live vetter grant — nothing new was \
             issued."
        );
        if validity_seconds.is_some() {
            println!(
                "  {DIM}--validity applies to a new grant only. To change it, revoke this grant \
                 and grant again.{RESET}"
            );
        }
    }
    println!("  Endorsement:  {}", grant.endorsement_id.as_str());
    println!("  Credential:   {}", grant.credential_id.as_str());
    println!(
        "  Valid:        {} → {}",
        date(grant.valid_from),
        date(grant.valid_until)
    );
    println!(
        "  {DIM}Withdraw it with `{} vetting vetters revoke {}`.{RESET}",
        bin_name(),
        grant.endorsement_id.as_str()
    );
    Ok(())
}

async fn cmd_vetters_revoke(vtc: &VtcClient, endorsement_id: &str) -> CliResult {
    let revoked = vtc
        .revoke_endorsement(endorsement_id)
        .await
        .map_err(|e| guidance(e, Op::Revoke { endorsement_id }))?;
    if is_json_output() {
        print_json(&revoked)?;
        return Ok(());
    }
    println!(
        "{GREEN}✓{RESET} Revoked endorsement {} (credential {}) at {}.",
        revoked.endorsement_id, revoked.revocation.credential_id, revoked.revocation.revoked_at
    );
    println!(
        "  {DIM}A vetter whose grant is revoked no longer counts toward any join, and their \
         profile is removed from listings.{RESET}"
    );
    Ok(())
}

async fn cmd_vetters_resend(vtc: &VtcClient, member_did: &str) -> CliResult {
    let sent = vtc
        .resend_vetter_grant(member_did)
        .await
        .map_err(|e| guidance(e, Op::Resend { member_did }))?;
    if is_json_output() {
        print_json(&sent)?;
        return Ok(());
    }
    // R1.1: a send the transport accepted is not a delivery, so do not say
    // "delivered".
    println!(
        "{GREEN}✓{RESET} Handed credential {} to the community's messaging transport for \
         {member_did}.",
        sent.credential_id.as_str()
    );
    println!("  Valid until:  {}", date(sent.valid_until));
    println!(
        "  {DIM}Delivery is not confirmed by the member's wallet; ask the vetter to check it.{RESET}"
    );
    Ok(())
}

// ---------------------------------------------------------------------------
// auto-grant
// ---------------------------------------------------------------------------

async fn cmd_auto_grant_show(vtc: &VtcClient) -> CliResult {
    let status = vtc
        .auto_grant()
        .await
        .map_err(|e| guidance(e, Op::AutoGrantShow))?;
    print_auto_grant(&status)
}

async fn cmd_auto_grant_set(
    vtc: &VtcClient,
    enabled: Option<bool>,
    sweep_minutes: Option<u32>,
    validity: Option<&str>,
) -> CliResult {
    if enabled.is_none() && sweep_minutes.is_none() && validity.is_none() {
        return Err(format!(
            "nothing to change. Pass at least one of --enabled <true|false>, --sweep-minutes \
             <{MIN_AUTO_GRANT_SWEEP_MINUTES}–{MAX_AUTO_GRANT_SWEEP_MINUTES}> or --validity \
             <duration>.\nSee the current configuration with `{} vetting auto-grant show`.",
            bin_name()
        )
        .into());
    }
    let validity_seconds = validity
        .map(|v| parse_grant_validity("--validity", v))
        .transpose()?;
    if let Some(m) = sweep_minutes
        && !(MIN_AUTO_GRANT_SWEEP_MINUTES..=MAX_AUTO_GRANT_SWEEP_MINUTES).contains(&m)
    {
        return Err(format!(
            "--sweep-minutes {m} is out of range: the sweep runs every \
             {MIN_AUTO_GRANT_SWEEP_MINUTES} to {MAX_AUTO_GRANT_SWEEP_MINUTES} minutes (a day). \
             Try `--sweep-minutes 60`."
        )
        .into());
    }
    // PUT replaces the whole configuration and an absent member takes its
    // default, so start from what is stored: `--sweep-minutes 30` alone must
    // not quietly switch the sweep off.
    let current = vtc
        .auto_grant()
        .await
        .map_err(|e| guidance(e, Op::AutoGrantShow))?;
    let config = merged_auto_grant(&current, enabled, sweep_minutes, validity_seconds);
    config
        .check_shape()
        .map_err(|e| format!("the automatic-grant configuration is out of bounds: {e}"))?;
    let stored = vtc
        .configure_auto_grant(&config)
        .await
        .map_err(|e| guidance(e, Op::AutoGrantSet))?;
    if !is_json_output() {
        println!("{GREEN}✓{RESET} Automatic vetter grants updated.");
    }
    print_auto_grant(&stored)
}

fn merged_auto_grant(
    current: &AutoGrantStatus,
    enabled: Option<bool>,
    sweep_minutes: Option<u32>,
    validity_seconds: Option<u64>,
) -> AutoGrantConfig {
    AutoGrantConfig {
        enabled: enabled.unwrap_or(current.enabled),
        sweep_minutes: Some(sweep_minutes.unwrap_or(current.sweep_minutes)),
        validity_seconds: Some(validity_seconds.unwrap_or(current.validity_seconds)),
    }
}

fn print_auto_grant(status: &AutoGrantStatus) -> CliResult {
    if is_json_output() {
        print_json(status)?;
        return Ok(());
    }
    let enabled = if status.enabled {
        format!("{GREEN}on{RESET}")
    } else {
        format!("{YELLOW}off{RESET}")
    };
    println!("  Enabled:        {enabled}");
    println!("  Sweep every:    {} minutes", status.sweep_minutes);
    println!(
        "  Grant validity: {}",
        humanize_duration(status.validity_seconds)
    );
    match &status.last_sweep {
        Some(sweep) => println!(
            "  Last sweep:     {} — {} granted, {} revoked, {} errors",
            sweep.ran_at.to_rfc3339(),
            sweep.granted,
            sweep.revoked,
            sweep.errors
        ),
        None => println!("  Last sweep:     {DIM}none yet{RESET}"),
    }
    if !status.enabled {
        println!(
            "  {DIM}Turn it on with `{} vetting auto-grant set --enabled true`. Which members it \
             names is the `vetterEligibility` policy's decision.{RESET}",
            bin_name()
        );
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// branding
// ---------------------------------------------------------------------------

async fn cmd_branding_show(vtc: &VtcClient) -> CliResult {
    let branding = vtc
        .branding()
        .await
        .map_err(|e| guidance(e, Op::BrandingShow))?;
    print_branding(&branding)
}

/// The `branding set` flags.
#[derive(Debug, Default)]
struct BrandingChange {
    display_name: Option<String>,
    accent_color: Option<String>,
    logo_url: Option<String>,
    clear: Vec<BrandingField>,
}

async fn cmd_branding_set(vtc: &VtcClient, change: BrandingChange) -> CliResult {
    if change.display_name.is_none()
        && change.accent_color.is_none()
        && change.logo_url.is_none()
        && change.clear.is_empty()
    {
        return Err(format!(
            "nothing to change. Pass --display-name, --accent-color, --logo-url or --clear \
             <field>.\nSee the current branding with `{} vetting branding show`.",
            bin_name()
        )
        .into());
    }
    let current = vtc
        .branding()
        .await
        .map_err(|e| guidance(e, Op::BrandingShow))?;
    let branding = merged_branding(current, change)?;
    branding.check_shape().map_err(|e| {
        format!(
            "the branding is out of bounds: {e}.\nA display name is 1–128 characters, an accent \
             colour `#rrggbb`, and a logo an https URL of at most 2048 characters."
        )
    })?;
    let stored = vtc
        .set_branding(&branding)
        .await
        .map_err(|e| guidance(e, Op::BrandingSet))?;
    if !is_json_output() {
        println!("{GREEN}✓{RESET} Branding updated.");
    }
    print_branding(&stored)
}

/// Apply `change` over `current`. PUT replaces the whole branding, so a value
/// the operator did not mention is carried over rather than cleared.
fn merged_branding(
    mut current: CommunityBranding,
    change: BrandingChange,
) -> CliResult<CommunityBranding> {
    for field in &change.clear {
        let set = match field {
            BrandingField::DisplayName => change.display_name.is_some(),
            BrandingField::AccentColor => change.accent_color.is_some(),
            BrandingField::LogoUrl => change.logo_url.is_some(),
        };
        if set {
            return Err(format!(
                "--clear {} and a new value for it were both given; pass one or the other",
                field
                    .to_possible_value()
                    .map(|v| v.get_name().to_string())
                    .unwrap_or_default()
            )
            .into());
        }
        match field {
            BrandingField::DisplayName => current.display_name = None,
            BrandingField::AccentColor => current.accent_color = None,
            BrandingField::LogoUrl => current.logo_url = None,
        }
    }
    if let Some(name) = change.display_name {
        current.display_name = Some(
            CommunityBrandingDisplayName::try_from(name)
                .map_err(|e| format!("--display-name: {e}"))?,
        );
    }
    if let Some(color) = change.accent_color {
        current.accent_color = Some(
            CommunityBrandingAccentColor::try_from(color)
                .map_err(|e| format!("--accent-color must be #rrggbb: {e}"))?,
        );
    }
    if change.logo_url.is_some() {
        current.logo_url = change.logo_url;
    }
    Ok(current)
}

fn print_branding(branding: &CommunityBranding) -> CliResult {
    if is_json_output() {
        print_json(branding)?;
        return Ok(());
    }
    let unset = format!("{DIM}(not set){RESET}");
    let show = |v: Option<&str>| v.map_or_else(|| unset.clone(), str::to_owned);
    println!(
        "  Display name:  {}",
        show(branding.display_name.as_ref().map(|v| v.as_str()))
    );
    println!(
        "  Accent colour: {}",
        show(branding.accent_color.as_ref().map(|v| v.as_str()))
    );
    println!("  Logo URL:      {}", show(branding.logo_url.as_deref()));
    if branding.display_name.is_none()
        && branding.accent_color.is_none()
        && branding.logo_url.is_none()
    {
        println!(
            "  {DIM}No branding is published on the join manifest. Set it with `{} vetting \
             branding set --display-name …`.{RESET}",
            bin_name()
        );
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// revocations
// ---------------------------------------------------------------------------

async fn cmd_revocations(vtc: &VtcClient) -> CliResult {
    let notices = vtc
        .vetting_revocations()
        .await
        .map_err(|e| guidance(e, Op::Revocations))?;
    if is_json_output() {
        print_json(&notices)?;
        return Ok(());
    }
    if notices.is_empty() {
        println!("No vetting statement has been withdrawn.");
        return Ok(());
    }
    if is_full_display() {
        print_full_list_title("Statement withdrawals", notices.len());
        for n in &notices {
            print_full_entry(&[
                ("Recorded", &n.recorded_at.to_rfc3339()),
                ("Vetter", &n.issuer),
                ("Statement", &n.statement_id),
                ("Digest", &n.statement_digest_multibase),
                ("Reason", n.reason.as_deref().unwrap_or("—")),
                ("Review", &n.review_state),
                ("Members", &join_or_dash(&n.affected_members)),
                ("Join requests", &join_or_dash(&n.affected_join_requests)),
            ]);
        }
        return Ok(());
    }
    let header = Row::new(vec![
        "Recorded",
        "Vetter",
        "Statement",
        "Reason",
        "Review",
        "Affected Members",
    ])
    .style(header_style())
    .bottom_margin(1);
    let rows: Vec<Row> = notices
        .iter()
        .map(|n| {
            let review = if n.review_state == "needsReview" {
                Cell::from("needs review").style(Style::default().fg(Color::Yellow))
            } else {
                Cell::from("no admission")
            };
            Row::new(vec![
                Cell::from(date(n.recorded_at)),
                did_cell(&n.issuer),
                Cell::from(n.statement_id.clone()),
                Cell::from(n.reason.clone().unwrap_or_else(|| "—".into())),
                review,
                Cell::from(n.affected_members.len().to_string()),
            ])
        })
        .collect();
    let table = Table::new(
        rows,
        [
            Constraint::Length(11),
            Constraint::Min(30),
            Constraint::Min(30),
            Constraint::Length(15),
            Constraint::Length(13),
            Constraint::Length(16),
        ],
    )
    .header(header)
    .column_spacing(2)
    .block(bordered(format!(
        " Statement withdrawals ({}) ",
        notices.len()
    )));
    print_widget(table, height(notices.len()));
    let pending = notices
        .iter()
        .filter(|n| n.review_state == "needsReview")
        .count();
    if pending > 0 {
        println!(
            "  {BOLD}{pending}{RESET} {DIM}withdrawal(s) touch a current membership. \
             `{} --full-display vetting revocations` names the members and join requests; the \
             vetting facts a request was decided on are at `GET /v1/join-requests/<id>/vetting`.{RESET}",
            bin_name()
        );
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Errors that say what to do
// ---------------------------------------------------------------------------

/// Which call failed, so a status can be read as the operator's situation.
#[derive(Debug, Clone, Copy)]
enum Op<'a> {
    VettersList,
    Grant { member_did: &'a str },
    Revoke { endorsement_id: &'a str },
    Resend { member_did: &'a str },
    AutoGrantShow,
    AutoGrantSet,
    BrandingShow,
    BrandingSet,
    AskShow,
    AskSet,
    Revocations,
    Members,
}

impl Op<'_> {
    /// The route, for a 404 that means the VTC does not serve it at all.
    fn route(&self) -> &'static str {
        match self {
            Self::VettersList | Self::Grant { .. } => "/v1/vetting/vetters",
            Self::Revoke { .. } => "/v1/credentials/endorsements/{id}",
            Self::Resend { .. } => "/v1/vetting/vetters/{memberDid}/resend",
            Self::AutoGrantShow | Self::AutoGrantSet => "/v1/vetting/auto-grant",
            Self::BrandingShow | Self::BrandingSet => "/v1/community/branding",
            Self::AskShow | Self::AskSet => "/v1/community/requested-attributes",
            Self::Revocations => "/v1/vetting/revocations",
            Self::Members => "/v1/members",
        }
    }
}

/// Turn a client error into an operator error that names the fix.
fn guidance(err: VtcError, op: Op<'_>) -> Box<dyn std::error::Error> {
    let bin = bin_name();
    let message = match err {
        VtcError::Http { status: 401, .. } => "the VTC refused this command's token (401). It \
             was minted moments ago, so the VTC has likely revoked the session or changed its \
             signing key; re-run the command."
            .to_string(),
        VtcError::Http { status: 403, .. } => format!(
            "this identity is not a community admin (403); vetting administration is admin-only.\n\
             `{bin} auth status` shows the DID it authenticates as (Client DID). Give it an admin \
             entry in the VTC's ACL. On the VTC host, with the daemon stopped:\n  \
             vtc --config <config.toml> acl add --did <client-did> --role admin"
        ),
        VtcError::Http { status, body } => {
            let detail = human_message(&body);
            match (op, status) {
                (Op::Grant { member_did }, 400) => format!(
                    "the community refused to name {member_did} a vetter: {detail}\n\
                     Only a current member can be a vetter. Check the DID is the member's DID \
                     (not their PGP key or email), and if they have applied, approve their join \
                     request first; then re-run `{bin} vetting vetters grant {member_did}`."
                ),
                (Op::Revoke { endorsement_id }, 404) => format!(
                    "there is no endorsement {endorsement_id}.\nList the vetter grants with \
                     `{bin} vetting vetters list` and pass the Endorsement ID column (not the \
                     member DID or credential id)."
                ),
                (Op::Revoke { endorsement_id }, 400) => format!(
                    "`{endorsement_id}` is not an endorsement id: {detail}\nEndorsement ids are \
                     UUIDs; copy one from `{bin} vetting vetters list`."
                ),
                (Op::Resend { member_did }, 404) => format!(
                    "{member_did} holds no live vetter grant whose credential the community \
                     kept, so there is nothing to resend.\nGrant one with `{bin} vetting vetters \
                     grant {member_did}`. A grant recorded before credentials were kept cannot \
                     be resent: revoke it (`{bin} vetting vetters revoke <endorsementId>`) and \
                     grant again."
                ),
                (Op::Resend { member_did }, 503) => format!(
                    "the community could not hand the credential to its messaging transport \
                     ({detail}).\nThe grant still stands. Check the VTC's mediator is configured \
                     and reachable (`{bin} health`), then re-run `{bin} vetting vetters resend \
                     {member_did}`."
                ),
                (Op::AutoGrantSet, 400) => format!(
                    "the community refused the automatic-grant configuration: {detail}\n\
                     --sweep-minutes is {MIN_AUTO_GRANT_SWEEP_MINUTES}–{MAX_AUTO_GRANT_SWEEP_MINUTES} \
                     and --validity one day to two years."
                ),
                (Op::AutoGrantSet, 503) => format!(
                    "the community refused to change automatic grants because its audit log is \
                     not configured ({detail}). Configure the VTC's audit writer and retry."
                ),
                (Op::AskSet, 400) => format!(
                    "the community refused the list: {detail}\nEach type once, at most 32, and a \
                     purpose of at most 256 characters."
                ),
                (Op::BrandingSet, 400) => format!(
                    "the community refused the branding: {detail}\nA display name is 1–128 \
                     characters, an accent colour `#rrggbb`, and a logo an https URL of at most \
                     2048 characters."
                ),
                (_, 404) => format!(
                    "the VTC does not serve {} (404) — it predates the vetter registry.\nUpgrade \
                     the VTC to a release with peer identity vetting.",
                    op.route()
                ),
                (_, _) => format!("the VTC answered HTTP {status}: {detail}"),
            }
        }
        VtcError::Transport(e) => format!(
            "could not reach the VTC: {e}.\nCheck the community is up and its URL resolves with \
             `{bin} health`."
        ),
        VtcError::NotAuthenticated => {
            format!("no token for the VTC; re-run the command (`{bin}` authenticates on each run).")
        }
        other => other.to_string(),
    };
    message.into()
}

/// The `message` or `error` of a JSON error body, else the body itself.
fn human_message(body: &str) -> String {
    serde_json::from_str::<Value>(body)
        .ok()
        .and_then(|v| {
            ["message", "error", "detail"]
                .iter()
                .find_map(|k| v.get(*k).and_then(Value::as_str).map(str::to_string))
        })
        .unwrap_or_else(|| {
            if body.is_empty() {
                "no detail".into()
            } else {
                body.to_string()
            }
        })
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

/// Parse a grant validity flag and check it against the grant bounds.
fn parse_grant_validity(flag: &str, value: &str) -> CliResult<u64> {
    let secs = parse_duration_secs(value)
        .map_err(|e| format!("{flag} {value}: {e}. Use N[s|m|h|d|w], e.g. `{flag} 365d`"))?;
    if !(MIN_VETTER_GRANT_VALIDITY_SECONDS..=MAX_VETTER_GRANT_VALIDITY_SECONDS).contains(&secs) {
        return Err(format!(
            "{flag} {value} is {}; a vetter grant is valid for one day to two years. Try `{flag} \
             365d`.",
            humanize_duration(secs)
        )
        .into());
    }
    Ok(secs)
}

fn grant_status(row: &VetterGrantRow, now: DateTime<Utc>) -> &'static str {
    if row.revoked {
        "revoked"
    } else if row.live {
        "live"
    } else if row.valid_until.is_some_and(|u| u <= now) {
        "expired"
    } else {
        "not member"
    }
}

fn origin_label(origin: GrantOrigin) -> &'static str {
    match origin {
        GrantOrigin::Auto => "auto",
        GrantOrigin::Manual => "manual",
    }
}

fn profile_label(row: &VetterGrantRow) -> String {
    let Some(p) = &row.profile else {
        return "—".into();
    };
    let mut parts = vec![if p.listed { "listed" } else { "unlisted" }.to_string()];
    if let Some(name) = &p.display_name {
        parts.push(name.clone());
    }
    if let Some(country) = &p.country {
        parts.push(country.clone());
    }
    if p.event_count > 0 {
        parts.push(format!("{} events", p.event_count));
    }
    parts.join(" · ")
}

fn date(at: DateTime<Utc>) -> String {
    at.format("%Y-%m-%d").to_string()
}

fn join_or_dash(items: &[String]) -> String {
    if items.is_empty() {
        "—".into()
    } else {
        items.join(", ")
    }
}

fn header_style() -> Style {
    Style::default()
        .fg(Color::White)
        .add_modifier(Modifier::BOLD)
}

fn bordered(title: String) -> Block<'static> {
    Block::bordered()
        .title(title)
        .border_style(Style::default().fg(Color::DarkGray))
}

fn height(rows: usize) -> u16 {
    u16::try_from(rows).unwrap_or(u16::MAX - 4) + 4
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn grant_validity_is_bounded_with_a_suggestion() {
        assert_eq!(
            parse_grant_validity("--validity", "365d").unwrap(),
            31_536_000
        );
        let err = parse_grant_validity("--validity", "3h")
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("one day to two years") && err.contains("365d"),
            "{err}"
        );
        let err = parse_grant_validity("--validity", "3y")
            .unwrap_err()
            .to_string();
        assert!(err.contains("N[s|m|h|d|w]"), "{err}");
    }

    #[test]
    fn auto_grant_set_keeps_what_it_was_not_told_to_change() {
        let current = AutoGrantStatus {
            enabled: true,
            sweep_minutes: 60,
            validity_seconds: 31_536_000,
            last_sweep: None,
        };
        let config = merged_auto_grant(&current, None, Some(30), None);
        assert!(
            config.enabled,
            "--sweep-minutes alone must not turn the sweep off"
        );
        assert_eq!(config.sweep_minutes, Some(30));
        assert_eq!(config.validity_seconds, Some(31_536_000));
        let off = merged_auto_grant(&current, Some(false), None, None);
        assert!(!off.enabled);
        assert_eq!(off.sweep_minutes, Some(60));
    }

    #[test]
    fn branding_set_merges_clears_and_refuses_a_contradiction() {
        let current: CommunityBranding = serde_json::from_value(json!({
            "displayName": "Linux Kernel",
            "accentColor": "#1a2b3c",
            "logoUrl": "https://kernel.example/logo.svg",
        }))
        .unwrap();
        let merged = merged_branding(
            current.clone(),
            BrandingChange {
                accent_color: Some("#000000".into()),
                clear: vec![BrandingField::LogoUrl],
                ..BrandingChange::default()
            },
        )
        .unwrap();
        assert_eq!(
            merged.display_name.as_ref().map(|v| v.as_str()),
            Some("Linux Kernel")
        );
        assert_eq!(
            merged.accent_color.as_ref().map(|v| v.as_str()),
            Some("#000000")
        );
        assert!(merged.logo_url.is_none());

        let err = merged_branding(
            current.clone(),
            BrandingChange {
                accent_color: Some("red".into()),
                ..BrandingChange::default()
            },
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("--accent-color"), "{err}");

        let err = merged_branding(
            current,
            BrandingChange {
                logo_url: Some("https://x.example/l.svg".into()),
                clear: vec![BrandingField::LogoUrl],
                ..BrandingChange::default()
            },
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("--clear logo-url"), "{err}");
    }

    #[test]
    fn errors_name_the_command_that_fixes_them() {
        let revoke = guidance(
            VtcError::Http {
                status: 404,
                body: r#"{"error":"not found"}"#.into(),
            },
            Op::Revoke {
                endorsement_id: "did:key:zWrong",
            },
        )
        .to_string();
        assert!(revoke.contains("vetting vetters list"), "{revoke}");

        let resend = guidance(
            VtcError::Http {
                status: 404,
                body: String::new(),
            },
            Op::Resend {
                member_did: "did:key:zCarol",
            },
        )
        .to_string();
        assert!(
            resend.contains("vetting vetters grant did:key:zCarol"),
            "{resend}"
        );

        let grant = guidance(
            VtcError::Http {
                status: 400,
                body: r#"{"message":"did:key:zX is not a current member"}"#.into(),
            },
            Op::Grant {
                member_did: "did:key:zX",
            },
        )
        .to_string();
        assert!(
            grant.contains("is not a current member") && grant.contains("approve their join"),
            "{grant}"
        );

        let old_vtc = guidance(
            VtcError::Http {
                status: 404,
                body: String::new(),
            },
            Op::AutoGrantShow,
        )
        .to_string();
        assert!(old_vtc.contains("/v1/vetting/auto-grant") && old_vtc.contains("Upgrade"));
    }

    #[test]
    fn ask_set_builds_required_then_optional_with_purposes() {
        let list = requested_from_flags(
            &["name.display".into()],
            &["address.country".into()],
            &["name.display=So members know what to call you".into()],
        )
        .unwrap();
        assert_eq!(
            serde_json::Value::Array(list),
            serde_json::json!([
                { "type": "name.display", "required": true,
                  "purpose": "So members know what to call you" },
                { "type": "address.country", "required": false },
            ])
        );
        assert!(requested_from_flags(&["a.b".into()], &["a.b".into()], &[]).is_err());
        assert!(requested_from_flags(&[], &[], &["a.b=why".into()]).is_err());
    }
}