cnm-cli 0.52.0

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
//! `cnm access …` — the community's own access-control list, on its VTC.
//!
//! Not `cnm acl`, which administers the community's **VTA**. This is the VTC's
//! ACL: who may administer the community, and with what — the list the admin
//! console shows under *Access control*.
//!
//! Administration is role-based (`docs/05-design-notes/vtc-admin-roles.md`):
//! an entry holds an **administrative role** (`community-admin`, `moderator`,
//! `vetting-lead`, `repo-manager`, `credential-officer`, `auditor`, `approver`)
//! whose ceiling `--capability` may narrow, optionally to a resource
//! (`git.repo.manage@git-ns:github.com/acme`). `list`, `show`, `grant` and
//! `update` speak `acl/*/0.2`; `change-role` moves the **community** role
//! (`member`, `moderator`, `issuer`, `admin`) with `vtc/members/role/set/0.1`,
//! and `revoke` removes an entry.
//!
//! Every verb is a canonical `acl/*` Trust Task, signed with this profile's own
//! key. They reach the VTC over TSP when it advertises it, else DIDComm, else
//! a signed document over HTTPS (`--transport` pins one), through the connect
//! helper `cnm git` and `cnm backup` share
//! ([`vtc_target::connect_for_tasks`]). The VTC authorizes each from the
//! signer's own ACL entry at the moment it runs.

use chrono::{DateTime, Utc};
use clap::Subcommand;
use serde_json::Value;
use vta_cli_common::render::{DIM, GREEN, RESET, YELLOW, bin_name, is_json_output, print_json};
use vta_sdk::session::TransportChoice;
use vtc_client::acl::{AclGrant, AclListFilter, AclUpdate};
use vtc_client::{HolderKey, VtcError};

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

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

#[derive(Subcommand)]
pub enum AccessCommands {
    /// Authorize another key — your AI assistant's `vtc-mcp` bridge, say — to
    /// act with your administrative standing, as a signing-key delegation of
    /// this profile's identity (`auth/signing-key/authorize/0.1`).
    ///
    /// Prints the signed authorization, which the key's holder sends inside
    /// its own `auth/signing-key/enroll/0.2` (`vtc_enrol_signing_key` in
    /// vtc-mcp). It creates no access-control entry and confers nothing of its
    /// own: the key acts with this identity's standing, read at every call,
    /// never approves anything or answers a step-up, expires within 30 days,
    /// and is revoked on its own. Single-use, and only the holder of that key
    /// can use it. Makes no network call.
    ///
    ///   cnm access authorize-key did:key:z6Mk… --label "vtc-mcp laptop"
    AuthorizeKey {
        /// The `did:key` of the key to authorize (the bridge prints its own:
        /// `vtc_enrol_signing_key` with no authorization, or `vtc_status`).
        signing_key_did: String,
        /// A label for the key, shown in the console's list of your keys.
        #[arg(long)]
        label: Option<String>,
        /// Ask for the delegation to lapse after this long: N[s|m|h|d|w]. The
        /// community caps it at 30 days, and uses its default when omitted.
        #[arg(long)]
        expires: Option<String>,
        /// Revoke this active key of yours in the same step (for an identity at
        /// the community's cap on active keys).
        #[arg(long)]
        replaces: Option<String>,
        /// How long the authorization itself may wait before the key's holder
        /// sends it: N[s|m|h|d|w], default 1h.
        #[arg(long, default_value = "1h")]
        valid_for: String,
        /// Write it to this file (0600) instead of stdout.
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
    /// List the entries you may see.
    List {
        /// Only entries with this administrative role (`member` for none).
        #[arg(long = "admin-role")]
        admin_role: Option<String>,
        /// Only entries holding this capability (e.g. vtc.roles.assign).
        #[arg(long)]
        capability: Option<String>,
        /// Only entries holding a capability at a qualifier related to this
        /// resource (e.g. git-ns:github.com/acme), read in `--direction`.
        #[arg(long)]
        resource: Option<String>,
        /// How `--resource` reads: actingIn (default), subtree, any.
        #[arg(long, requires = "resource")]
        direction: Option<String>,
        /// Only subjects starting with this prefix.
        #[arg(long)]
        subject_prefix: Option<String>,
    },
    /// Show one entry.
    Show {
        /// The subject DID.
        subject: String,
    },
    /// Write the entry a subject should hold (create, or restate at its
    /// current role).
    Grant {
        /// The subject DID.
        subject: String,
        /// The administrative role: community-admin, moderator, vetting-lead,
        /// repo-manager, credential-officer, auditor, approver — or member for
        /// none.
        #[arg(long = "admin-role")]
        admin_role: String,
        /// Narrow the role's ceiling to this capability, optionally at a
        /// resource (cap@resource). Repeatable. Omitted: the full ceiling.
        /// Granting an authority-conferring capability (vtc.roles.assign,
        /// vtc.config.admin, …) needs another holder's consent.
        #[arg(long = "capability")]
        capabilities: Vec<String>,
        /// Let the subject approve others' actions within its role.
        #[arg(long)]
        approve: bool,
        /// Grant approve authority only — no act authority (the
        /// least-privilege approver).
        #[arg(long)]
        approve_only: bool,
        /// The community role, when it should differ from the one the
        /// administrative role implies.
        #[arg(long)]
        community_role: Option<String>,
        /// A human-readable label.
        #[arg(long)]
        label: Option<String>,
        /// Expire the entry after this long: N[s|m|h|d|w].
        #[arg(long)]
        expires: Option<String>,
        /// Why, recorded with the change.
        #[arg(long)]
        reason: Option<String>,
    },
    /// Amend an existing entry's capabilities, approve authority, label or
    /// expiry. Never its role.
    Update {
        /// The subject DID.
        subject: String,
        /// Replace the capability set: cap or cap@resource, repeatable.
        #[arg(long = "capability", conflicts_with = "full_ceiling")]
        capabilities: Vec<String>,
        /// Return the entry to its role's full ceiling.
        #[arg(long)]
        full_ceiling: bool,
        /// Set whether the subject may approve: true or false.
        #[arg(long)]
        approve: Option<bool>,
        /// Set the label.
        #[arg(long, conflicts_with = "clear_label")]
        label: Option<String>,
        /// Remove the label.
        #[arg(long)]
        clear_label: bool,
        /// Expire the entry after this long from now: N[s|m|h|d|w].
        #[arg(long, conflicts_with = "permanent")]
        expires: Option<String>,
        /// Remove the expiry, making the entry permanent.
        #[arg(long)]
        permanent: bool,
        /// Why, recorded with the change.
        #[arg(long)]
        reason: Option<String>,
    },
    /// Move a subject's community role (member, moderator, issuer, admin) —
    /// with the administrative role it implies — with
    /// `vtc/members/role/set/0.1`; `--from` must be its current role.
    ChangeRole {
        /// The subject DID.
        subject: String,
        /// The role it holds now.
        #[arg(long = "from")]
        from_role: String,
        /// The role to move it to.
        #[arg(long = "to")]
        to_role: String,
        /// Why, recorded with the change.
        #[arg(long)]
        reason: Option<String>,
    },
    /// Remove a subject's entry.
    ///
    /// Removing another unrestricted administrator when nobody else can
    /// consent waits out a cooling-off (`acl.removal_cooling_off`, default
    /// 24 h), during which they are suspended: their entry authorizes nothing,
    /// and cancelling restores it. In single-administrator mode, `--now`
    /// removes them at once instead — or, with `--action`, lands that open
    /// cooling-off now — after you type their DID (or the action id) to
    /// confirm and make a passkey gesture bound to the immediate removal.
    Revoke {
        /// The subject DID.
        subject: String,
        /// Why, recorded with the change.
        #[arg(long)]
        reason: Option<String>,
        /// Single-administrator mode only: remove now, without the
        /// cooling-off.
        #[arg(long)]
        now: bool,
        /// With `--now`: the open cooling-off of this same removal to land
        /// now. Send the same `--reason` it was raised with.
        #[arg(long, requires = "now")]
        action: Option<String>,
        /// With `--now`: the confirmation, typed in advance — the subject's
        /// DID, or the `--action` id. Prompted for when omitted on a terminal.
        #[arg(long, requires = "now")]
        confirm: Option<String>,
    },
}

/// What the operator typed to confirm a removal now: `--confirm`, or a
/// prompt on a terminal. Checked here as well as by the VTC, so a slip costs
/// neither a gesture nor a round trip.
fn confirm_now(subject: &str, action: Option<&str>, given: Option<String>) -> CliResult<String> {
    use std::io::IsTerminal as _;
    let typed = match given {
        Some(c) => c,
        None if std::io::stderr().is_terminal() => {
            eprintln!(
                "This removes {subject} {}, without the cooling-off — single-administrator mode.",
                if action.is_some() {
                    "now, landing the open cooling-off"
                } else {
                    "now"
                }
            );
            dialoguer::Input::<String>::new()
                .with_prompt(match action {
                    Some(_) => "Type the subject's DID, or the action id, to confirm",
                    None => "Type the subject's DID to confirm",
                })
                .interact_text()?
        }
        None => {
            return Err(
                "removing now needs a typed confirmation: pass `--confirm <the subject's DID>`"
                    .into(),
            );
        }
    };
    let typed = typed.trim().to_string();
    if typed != subject && action.is_none_or(|a| typed != a) {
        return Err("the confirmation does not match — nothing was removed".into());
    }
    Ok(typed)
}

/// Run one `cnm access` command.
///
/// Every verb is an `acl/*` Trust Task, and they all go the one way, through
/// the connect helper `cnm git` and `cnm backup` share
/// ([`vtc_target::connect_for_tasks`]): over TSP when the VTC advertises it,
/// else DIDComm, else a signed document over HTTPS — `transport`
/// (`--transport`) pins one. The session is closed on every path out.
pub async fn run(
    command: AccessCommands,
    keyring_key: &str,
    target: &VtcTarget,
    transport: TransportChoice,
) -> CliResult {
    // Signing an authorization needs this profile's key and the community's
    // DID, and no connection.
    if let AccessCommands::AuthorizeKey {
        signing_key_did,
        label,
        expires,
        replaces,
        valid_for,
        out,
    } = command
    {
        let key = signing_key(keyring_key)?;
        let doc = authorize_key_document(
            &key,
            &target.did,
            &signing_key_did,
            label.as_deref(),
            expires.as_deref(),
            replaces.as_deref(),
            &valid_for,
            chrono::Utc::now(),
        )
        .await?;
        let text = serde_json::to_string_pretty(&doc)?;
        match out {
            Some(path) => {
                write_private(&path, &text)?;
                eprintln!(
                    "Authorization for {signing_key_did} to act as {} written to {}.\nHand it to \
                     the key's holder (vtc-mcp: vtc_enrol_signing_key with this file). It is \
                     single-use and only that key can use it.",
                    key.holder_did(),
                    path.display()
                );
            }
            None => println!("{text}"),
        }
        return Ok(());
    }
    let vtc = vtc_target::connect_for_tasks(keyring_key, target, transport).await?;
    let outcome = run_command(command, &vtc, keyring_key).await;
    vtc.client.shutdown().await;
    outcome
}

/// `auth/signing-key/authorize/0.1`'s Type URI.
const AUTHORIZE_TYPE: &str = "https://trusttasks.org/spec/auth/signing-key/authorize/0.1";

/// A duration flag: N followed by s, m, h, d or w.
fn parse_duration(s: &str) -> CliResult<chrono::TimeDelta> {
    let s = s.trim();
    let (n, unit) = s.split_at(s.len().saturating_sub(1));
    let n: i64 = n
        .parse()
        .map_err(|_| format!("`{s}` is not a duration: N followed by s, m, h, d or w"))?;
    Ok(match unit {
        "s" => chrono::TimeDelta::seconds(n),
        "m" => chrono::TimeDelta::minutes(n),
        "h" => chrono::TimeDelta::hours(n),
        "d" => chrono::TimeDelta::days(n),
        "w" => chrono::TimeDelta::weeks(n),
        _ => return Err(format!("`{s}` is not a duration: N followed by s, m, h, d or w").into()),
    })
}

/// The identity's signed terms of one signing-key enrolment: exactly the
/// payload the key's `enroll/0.2` will carry beside it. The document states
/// its own `expiresAt` so it is still accepted after the time it takes to
/// reach the key's holder (the community honours a stated expiry up to its
/// 30-day horizon, in place of its ten-minute maximum age).
#[allow(clippy::too_many_arguments)]
async fn authorize_key_document(
    key: &HolderKey,
    vtc_did: &str,
    signing_key_did: &str,
    label: Option<&str>,
    expires: Option<&str>,
    replaces: Option<&str>,
    valid_for: &str,
    now: chrono::DateTime<chrono::Utc>,
) -> CliResult<serde_json::Value> {
    if !signing_key_did.starts_with("did:key:") {
        return Err(format!(
            "`{signing_key_did}` is not a did:key; a signing key is named by its own did:key"
        )
        .into());
    }
    if signing_key_did == key.holder_did() {
        return Err("a key cannot be authorized to act as itself".into());
    }
    let mut terms = serde_json::json!({
        "identityDid": key.holder_did(),
        "signingKeyDid": signing_key_did,
        "scope": "console",
    });
    if let Some(label) = label {
        terms["deviceLabel"] = serde_json::json!(label);
    }
    if let Some(expires) = expires {
        let at = now + parse_duration(expires)?;
        terms["expiresAt"] =
            serde_json::json!(at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true));
    }
    if let Some(replaces) = replaces {
        terms["replaces"] = serde_json::json!(replaces);
    }
    let mut doc =
        vta_sdk::trust_task_sign::build_unsigned(AUTHORIZE_TYPE, terms, key.holder_did(), vtc_did)
            .map_err(|e| format!("could not build the authorization: {e}"))?;
    doc.issued_at = Some(now);
    doc.expires_at = Some(now + parse_duration(valid_for)?);
    vta_sdk::trust_task_sign::sign_in_place_with(&mut doc, key)
        .await
        .map_err(|e| format!("could not sign the authorization: {e}"))?;
    Ok(serde_json::to_value(&doc)?)
}

/// Write `text` to `path`, owner-only.
fn write_private(path: &std::path::Path, text: &str) -> CliResult {
    use std::io::Write;
    let mut options = std::fs::OpenOptions::new();
    options.create(true).truncate(true).write(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let mut file = options.open(path)?;
    file.write_all(text.as_bytes())?;
    Ok(())
}

/// This profile's key, as the signer of `acl/*` documents.
pub(crate) fn signing_key(keyring_key: &str) -> CliResult<HolderKey> {
    let session = auth::loaded_session(keyring_key).ok_or_else(|| {
        format!(
            "no stored identity for this community profile. Run `{} setup` first.",
            bin_name()
        )
    })?;
    HolderKey::from_did_key(&session.client_did, &session.private_key_multibase)
        .map_err(|e| format!("this profile's key cannot sign: {e}").into())
}

async fn run_command(command: AccessCommands, vtc: &Connected, keyring_key: &str) -> CliResult {
    let key = signing_key(keyring_key)?;
    let fail = |e: VtcError| access_error(vtc, e);
    match command {
        // Handled in `run`, before any connection.
        AccessCommands::AuthorizeKey { .. } => {}
        AccessCommands::List {
            admin_role,
            capability,
            resource,
            direction,
            subject_prefix,
        } => {
            let direction = match (&resource, direction) {
                (Some(_), None) => Some("actingIn".to_string()),
                (_, d) => d,
            };
            let filter = AclListFilter {
                role: admin_role,
                capability,
                resource,
                direction,
                subject_prefix,
                ..Default::default()
            };
            let entries = vtc.client.acl_list_all(&filter, &key).await.map_err(fail)?;
            let values: Vec<Value> = entries
                .iter()
                .map(serde_json::to_value)
                .collect::<Result<_, _>>()?;
            if is_json_output() {
                print_json(&values)?;
            } else if values.is_empty() {
                println!("{DIM}no entries{RESET}");
            } else {
                for v in &values {
                    print_entry(v);
                }
            }
        }
        AccessCommands::Show { subject } => {
            let shown = vtc.client.acl_show(&subject, &key).await.map_err(fail)?;
            let shown = serde_json::to_value(&shown)?;
            if shown["entry"].is_null() && !is_json_output() {
                println!("{DIM}{subject} holds no entry{RESET}");
            } else {
                report(&shown, "entry")?;
            }
        }
        AccessCommands::Grant {
            subject,
            admin_role,
            capabilities,
            approve,
            approve_only,
            community_role,
            label,
            expires,
            reason,
        } => {
            let grant = AclGrant {
                subject,
                admin_role,
                // No --capability: the role's full ceiling. Approve-only: none.
                capabilities: if approve_only {
                    Some(Vec::new())
                } else {
                    Some(capabilities).filter(|c| !c.is_empty())
                },
                approve: approve || approve_only,
                act: !approve_only,
                community_role,
                label,
                expires_at: expires.as_deref().map(expiry_from_now).transpose()?,
                reason,
            };
            let granted = vtc.client.acl_grant(&grant, &key).await.map_err(fail)?;
            report(&serde_json::to_value(&granted)?, "granted")?;
        }
        AccessCommands::Update {
            subject,
            capabilities,
            full_ceiling,
            approve,
            label,
            clear_label,
            expires,
            permanent,
            reason,
        } => {
            let update = AclUpdate {
                subject,
                label: if clear_label {
                    Some(None)
                } else {
                    label.map(Some)
                },
                capabilities: if full_ceiling {
                    Some(None)
                } else {
                    Some(capabilities).filter(|c| !c.is_empty()).map(Some)
                },
                approve,
                expires_at: if permanent {
                    Some(None)
                } else {
                    expires
                        .as_deref()
                        .map(expiry_from_now)
                        .transpose()?
                        .map(Some)
                },
                reason,
            };
            let updated = vtc.client.acl_update(&update, &key).await.map_err(fail)?;
            report(&serde_json::to_value(&updated)?, "updated")?;
        }
        AccessCommands::ChangeRole {
            subject,
            from_role,
            to_role,
            reason,
        } => {
            let changed = vtc
                .client
                .members_role_set(&subject, &from_role, &to_role, reason.as_deref(), &key)
                .await
                .map_err(fail)?;
            report(&serde_json::to_value(&changed)?, "role changed")?;
        }
        AccessCommands::Revoke {
            subject,
            reason,
            now,
            action,
            confirm,
        } => {
            let revoked = if now {
                let typed = confirm_now(&subject, action.as_deref(), confirm)?;
                vtc.client
                    .acl_revoke_now(&subject, &typed, action.as_deref(), reason.as_deref(), &key)
                    .await
            } else {
                vtc.client
                    .acl_revoke(&subject, reason.as_deref(), &key)
                    .await
            }
            .map_err(fail)?;
            let v = serde_json::to_value(&revoked)?;
            if is_json_output() {
                print_json(&v)?;
            } else {
                println!("{GREEN}revoked{RESET} {subject} — the entry is removed");
            }
        }
    }
    Ok(())
}

/// `now + duration` for an `--expires` value.
fn expiry_from_now(s: &str) -> CliResult<DateTime<Utc>> {
    let secs = vta_cli_common::duration::parse_duration_secs(s)?;
    let secs = i64::try_from(secs).map_err(|_| format!("--expires {s} is too far away"))?;
    Ok(Utc::now() + chrono::TimeDelta::seconds(secs))
}

/// Print a `{entry: …}` reply, or its JSON.
fn report(reply: &Value, verb: &str) -> CliResult {
    if is_json_output() {
        print_json(reply)?;
    } else {
        println!("{GREEN}{verb}{RESET}");
        print_entry(&reply["entry"]);
    }
    Ok(())
}

/// One line per entry: subject, administrative role, and what it may do —
/// "everything" only for a community administrator holding its full ceiling,
/// "nothing" for no administrative role or no act authority (the #746 class:
/// two different authorities never print alike).
fn print_entry(e: &Value) {
    let s = |k: &str| e.get(k).and_then(Value::as_str);
    let role = s("role").unwrap_or("?");
    let acts = e["act"]["scope"] == "all";
    let holds = match e["capabilities"]["scope"].as_str() {
        _ if role == "member" => "nothing".to_string(),
        _ if !acts => "acts nowhere (approves only)".to_string(),
        Some("ceiling") if role == "community-admin" => "everything".to_string(),
        Some("ceiling") => format!("the {role} ceiling"),
        Some("none") => "nothing".to_string(),
        Some("listed") => e["capabilities"]["grants"]
            .as_array()
            .map(|g| {
                g.iter()
                    .map(|g| match g["resource"].as_str() {
                        Some(r) => format!("{}@{r}", g["capability"].as_str().unwrap_or("?")),
                        None => g["capability"].as_str().unwrap_or("?").to_string(),
                    })
                    .collect::<Vec<_>>()
                    .join(", ")
            })
            .unwrap_or_default(),
        _ => "?".to_string(),
    };
    let community = e["ext"]["org.openvtc"]["communityRole"]
        .as_str()
        .map(|c| format!("  {DIM}community role {c}{RESET}"))
        .unwrap_or_default();
    let scopes = holds;
    // A cooling-off reduction is open: the entry authorizes nothing until it
    // lands or is cancelled (`vtc-action-list.md` §8.2).
    let suspended = e["ext"]["org.openvtc"]["suspended"]["landsAt"]
        .as_str()
        .map(|t| format!("  {YELLOW}suspended — removal lands {t}{RESET}"))
        .unwrap_or_default();
    println!(
        "  {}  {role}  {scopes}{community}{}{}{suspended}",
        s("subject").unwrap_or("?"),
        s("label").map(|l| format!("  \"{l}\"")).unwrap_or_default(),
        s("expiresAt")
            .map(|t| format!("  {DIM}expires {t}{RESET}"))
            .unwrap_or_default(),
    );
}

/// What to tell the operator when the VTC refuses.
///
/// A refusal that needs a passkey gesture or another administrator's consent
/// carries the ceremony in its `details`; the operator completes it in the
/// admin console, then re-runs the same command.
fn access_error(vtc: &Connected, err: VtcError) -> Box<dyn std::error::Error> {
    // Not a failure: parked for other administrators' approval, and it
    // completes itself when enough approve (VTI-APV-017).
    if let VtcError::Parked { action_id, message } = &err {
        if message.contains("cooling-off") {
            return format!(
                "{message}\n  Nothing more to send: it lands by itself. Follow it with `{bin} \
                 actions show {action_id}`, or withdraw it with `{bin} actions cancel \
                 {action_id}`. In single-administrator mode, `{bin} access revoke <subject> \
                 --now --action {action_id}` lands it now.",
                bin = bin_name()
            )
            .into();
        }
        return format!(
            "{message}\n  Nothing more to send: it runs when the approvals land. Follow it with \
             `{bin} actions show {action_id}`, or withdraw it with `{bin} actions cancel \
             {action_id}`.",
            bin = bin_name()
        )
        .into();
    }
    let text = err.to_string();
    if text.contains("stepUpRequest") || text.contains("passkey gesture") {
        return format!(
            "the VTC needs a passkey gesture from {} before it makes this change. Approve it in \
             the admin console, then run the same command again.\n({text})",
            vtc.client_did
        )
        .into();
    }
    format!("the VTC refused {}: {text}", vtc.client_did).into()
}

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

    fn profile_key(seed: u8) -> HolderKey {
        let signing = ed25519_dalek::SigningKey::from_bytes(&[seed; 32]);
        let did = format!(
            "did:key:{}",
            vta_sdk::did_key::ed25519_multibase_pubkey(&signing.verifying_key().to_bytes())
        );
        let private = multibase::encode(multibase::Base::Base58Btc, signing.to_bytes());
        HolderKey::from_did_key(&did, private).unwrap()
    }

    /// The authorization is the identity's signed terms, addressed to the
    /// community, alive long enough to reach the key's holder, and exactly
    /// the payload an `enroll/0.2` for that key carries.
    #[tokio::test]
    async fn an_authorization_is_the_identitys_signed_terms() {
        let identity = profile_key(1);
        let bridge = profile_key(2);
        let now = chrono::DateTime::parse_from_rfc3339("2026-11-07T00:00:00Z")
            .unwrap()
            .with_timezone(&chrono::Utc);
        let doc = authorize_key_document(
            &identity,
            "did:web:vtc.example.com",
            bridge.holder_did(),
            Some("vtc-mcp laptop"),
            Some("30d"),
            None,
            "1h",
            now,
        )
        .await
        .unwrap();
        assert_eq!(doc["type"], AUTHORIZE_TYPE);
        assert_eq!(doc["issuer"], identity.holder_did());
        assert_eq!(doc["recipient"], "did:web:vtc.example.com");
        assert_eq!(doc["expiresAt"], "2026-11-07T01:00:00Z");
        assert!(doc["proof"].is_object());
        let terms = &doc["payload"];
        assert_eq!(terms["identityDid"], identity.holder_did());
        assert_eq!(terms["signingKeyDid"], bridge.holder_did());
        assert_eq!(terms["scope"], "console");
        assert_eq!(terms["deviceLabel"], "vtc-mcp laptop");
        assert_eq!(terms["expiresAt"], "2026-12-07T00:00:00Z");
        assert!(terms.get("replaces").is_none());
        // The terms satisfy the specification's schema for the enrolment.
        vti_specs::schema_index::schema_for(AUTHORIZE_TYPE)
            .map(|s| trust_tasks_rs::validate::against_schema(s, terms).unwrap())
            .expect("authorize/0.1 is pinned");
    }

    #[tokio::test]
    async fn an_authorization_refuses_what_could_never_enrol() {
        let identity = profile_key(1);
        let now = chrono::Utc::now();
        for (did, why) in [
            ("did:webvh:abc:example.com:x", "not a did:key"),
            (identity.holder_did(), "act as itself"),
        ] {
            let err =
                authorize_key_document(&identity, "did:web:v", did, None, None, None, "1h", now)
                    .await
                    .unwrap_err()
                    .to_string();
            assert!(err.contains(why), "{err}");
        }
        assert!(parse_duration("30x").is_err());
        assert_eq!(parse_duration("2w").unwrap(), chrono::TimeDelta::weeks(2));
    }

    /// `--now` proceeds only on the subject's DID typed back — or, landing an
    /// open cooling-off, its action id (`vtc-action-list.md` §8.5).
    #[test]
    fn remove_now_needs_the_subject_or_the_action_typed_back() {
        let did = "did:key:zSubject";
        assert_eq!(
            confirm_now(did, None, Some(format!(" {did} "))).unwrap(),
            did
        );
        assert!(confirm_now(did, None, Some("did:key:zOther".into())).is_err());
        assert!(confirm_now(did, None, Some("act-1".into())).is_err());
        assert_eq!(
            confirm_now(did, Some("act-1"), Some("act-1".into())).unwrap(),
            "act-1"
        );
        assert_eq!(
            confirm_now(did, Some("act-1"), Some(did.into())).unwrap(),
            did
        );
    }
}