vta-cli-common 0.15.2

Shared CLI command handlers and rendering helpers for VTA CLIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! `persona …` operator commands — a person's own identity.
//!
//! # Two vocabularies, and which one goes where
//!
//! Commands and flags keep the spec's words, because that is what they address:
//! `persona profile put --profile-id` names `persona/profile/put/1.0`, and a
//! command that did not would be a second name for a task, drifting from the
//! URI it sends and from every script already written against it.
//!
//! What an operator *reads* uses the words a person would
//! (`design-docs/persona-vocabulary.md`): an attribute stays an **attribute**, a
//! profile is a **face** — the set of attributes you show together — and a
//! persona **wears** a face in a context. So `persona profile list` prints `Faces:` above JSON
//! whose members are `profileId`. That pairing is deliberate: it is where an
//! operator learns the mapping, once, in the one place both halves are on
//! screen together.
//!
//! Thin wrappers over the `VtaClient::persona_*` methods, with one exception
//! worth knowing about before reading further: [`cmd_disclosure_preview`]
//! renders its response rather than dumping it, because that response is the
//! only thing standing between an automated request and the holder's name
//! leaving the machine. Everything else prints the payload.
//!
//! ## Scope, and the error an operator will actually hit
//!
//! Ten of these are holder-scoped — the attribute pool, profiles, correlation,
//! and cross-context disclosure history — and the VTA requires *unrestricted*
//! authority for them. An operator whose credential is scoped to one trust
//! context gets `e.p.msg.forbidden`, and that is the boundary working: the pool
//! sits above every context and is not any one context's to read. The
//! context-scoped commands all take `--context`.
//!
//! `persona renderers` is on neither side. It lists the output formats this
//! VTA ships and what each discards, which names nothing about the holder —
//! and a context-scoped operator about to request a disclosure needs it, since
//! `persona disclosure preview` takes a renderer by name.

use serde_json::Value;
use vta_sdk::client::VtaClient;
use vta_sdk::protocols::persona::{
    ContactDocument, LocalProfileEntry, ProfileEntry, Provenance, ValueType,
};

use crate::render::{BOLD, CYAN, DIM, RED, RESET, YELLOW, is_json_output, print_json};

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

fn print_result(label: &str, value: &Value) -> CmdResult {
    if is_json_output() {
        print_json(value)?;
    } else {
        println!("{label}");
        println!("{}", serde_json::to_string_pretty(value)?);
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// The pool
// ---------------------------------------------------------------------------

/// `persona attribute put` — store one attribute about the holder.
#[allow(clippy::too_many_arguments)]
pub async fn cmd_attribute_put(
    client: &VtaClient,
    claim_type: String,
    value: Value,
    value_type: ValueType,
    provenance: Provenance,
    label: Option<String>,
    attribute_id: Option<String>,
    expected_version: Option<u64>,
) -> CmdResult {
    let result = client
        .persona_attribute_put(
            &claim_type,
            value,
            value_type,
            provenance,
            label.as_deref(),
            attribute_id.as_deref(),
            expected_version,
        )
        .await?;
    print_result("Attribute:", &result)
}

/// `persona attribute list` — enumerate the pool.
///
/// Metadata-only unless `--values` is given. The default is not timidity: a
/// listing that returns values is a read of the holder's identity, and the
/// command that does it should be the one the operator typed on purpose.
///
/// `--sensitive` is the second half of that, and only widens the first: a card
/// number or a passport number stays out of a `--values` listing until it is
/// asked for by name.
pub async fn cmd_attribute_list(
    client: &VtaClient,
    type_prefix: Option<String>,
    include_values: bool,
    include_sensitive: bool,
    include_stale: Option<bool>,
    limit: Option<std::num::NonZeroU64>,
    cursor: Option<String>,
) -> CmdResult {
    let result = client
        .persona_attribute_list(
            type_prefix.as_deref(),
            include_values,
            include_sensitive,
            include_stale,
            limit,
            cursor.as_deref(),
        )
        .await?;
    if !is_json_output() {
        // Said only where it is true, and said once. The agent withholds a
        // sensitive value without saying so in the response — the row comes
        // back with no `value`, which reads exactly like an attribute that never had
        // one — so the person is told here or not at all.
        if !include_values {
            println!("{DIM}Names only — add --values to include the values themselves.{RESET}");
        } else if !include_sensitive {
            println!(
                "{DIM}Sensitive values — cards, passports, phone numbers — are held back. \
                 Add --sensitive to include them.{RESET}"
            );
        }
    }
    print_result("Your attributes:", &result)
}

/// `persona attribute delete` — remove one attribute.
pub async fn cmd_attribute_delete(
    client: &VtaClient,
    attribute_id: String,
    cascade: bool,
    expected_version: Option<u64>,
) -> CmdResult {
    let result = client
        .persona_attribute_delete(&attribute_id, cascade, expected_version)
        .await?;
    if !is_json_output() && cascade {
        println!(
            "{DIM}Cascaded: {attribute_id} was taken off every face that showed it. Nothing \
             already shared is affected — that has left.{RESET}"
        );
    }
    print_result("Result:", &result)
}

// ---------------------------------------------------------------------------
// Profiles
// ---------------------------------------------------------------------------

/// `persona profile put` — create or update a projection over the pool.
pub async fn cmd_profile_put(
    client: &VtaClient,
    name: String,
    entries: Vec<ProfileEntry>,
    credential_refs: Vec<String>,
    profile_id: Option<String>,
    expected_version: Option<u64>,
) -> CmdResult {
    let result = client
        .persona_profile_put(
            &name,
            entries,
            credential_refs,
            profile_id.as_deref(),
            expected_version,
        )
        .await?;
    print_result("Face:", &result)
}

/// `persona profile get` — read one profile.
pub async fn cmd_profile_get(client: &VtaClient, profile_id: String, resolve: bool) -> CmdResult {
    let result = client.persona_profile_get(&profile_id, resolve).await?;
    if !is_json_output() && !resolve {
        println!(
            "{DIM}Showing how the face is built — add --resolve to see the attributes it would \
             show.{RESET}"
        );
    }
    print_result("Face:", &result)
}

/// `persona profile list` — enumerate profiles.
pub async fn cmd_profile_list(
    client: &VtaClient,
    limit: Option<std::num::NonZeroU64>,
    cursor: Option<String>,
) -> CmdResult {
    let result = client
        .persona_profile_list(limit, cursor.as_deref())
        .await?;
    print_result("Faces:", &result)
}

/// `persona profile delete` — remove a profile.
pub async fn cmd_profile_delete(
    client: &VtaClient,
    profile_id: String,
    unbind: bool,
    expected_version: Option<u64>,
) -> CmdResult {
    let result = client
        .persona_profile_delete(&profile_id, unbind, expected_version)
        .await?;
    if !is_json_output() && unbind {
        println!(
            "{YELLOW}Taken off: every persona wearing {profile_id} now shows nothing until \
             it wears another. Nothing already shared is affected — that has left.{RESET}"
        );
    }
    print_result("Result:", &result)
}

// ---------------------------------------------------------------------------
// Bindings
// ---------------------------------------------------------------------------

/// `persona binding set` — decide what a context sees.
pub async fn cmd_binding_set(
    client: &VtaClient,
    context_id: String,
    persona_did: String,
    profile_id: Option<String>,
    public_entries: Vec<String>,
    expected_version: Option<u64>,
) -> CmdResult {
    let clearing = profile_id.is_none();
    let result = client
        .persona_binding_set(
            &context_id,
            &persona_did,
            profile_id.as_deref(),
            public_entries,
            expected_version,
        )
        .await?;
    if !is_json_output() {
        if clearing {
            println!("{DIM}Taken off — {persona_did} now shows nothing in {context_id}.{RESET}");
        } else {
            println!(
                "{DIM}A context only ever gets a copy: the face's values were written into \
                 {context_id}. Editing an attribute refreshes it; copies go down, and nothing reads \
                 up.{RESET}"
            );
        }
    }
    print_result("Binding:", &result)
}

/// `persona binding get` — what one persona presents in one context.
pub async fn cmd_binding_get(
    client: &VtaClient,
    context_id: String,
    persona_did: String,
) -> CmdResult {
    let result = client
        .persona_binding_get(&context_id, &persona_did)
        .await?;
    print_result("Binding:", &result)
}

/// `persona binding list` — every persona bound in one context.
pub async fn cmd_binding_list(
    client: &VtaClient,
    context_id: String,
    limit: Option<std::num::NonZeroU64>,
    cursor: Option<String>,
) -> CmdResult {
    let result = client
        .persona_binding_list(&context_id, limit, cursor.as_deref())
        .await?;
    print_result("Bindings:", &result)
}

// ---------------------------------------------------------------------------
// Contacts
// ---------------------------------------------------------------------------

/// `persona contact put` — record what someone disclosed.
pub async fn cmd_contact_put(
    client: &VtaClient,
    context_id: String,
    subject_did: String,
    known_by_persona: String,
    document: ContactDocument,
    credential_refs: Vec<String>,
    notes: Option<String>,
) -> CmdResult {
    let result = client
        .persona_contact_put(
            &context_id,
            &subject_did,
            &known_by_persona,
            document,
            credential_refs,
            notes.as_deref(),
        )
        .await?;
    print_result("Contact:", &result)
}

/// `persona contact get` — read one contact.
pub async fn cmd_contact_get(
    client: &VtaClient,
    context_id: String,
    contact_id: String,
    rev: Option<std::num::NonZeroU64>,
    include_history: bool,
) -> CmdResult {
    let result = client
        .persona_contact_get(&context_id, &contact_id, rev, include_history)
        .await?;
    print_result("Contact:", &result)
}

/// `persona contact list` — enumerate contacts.
pub async fn cmd_contact_list(
    client: &VtaClient,
    context_id: String,
    known_by_persona: Option<String>,
    changed_since: Option<String>,
    limit: Option<std::num::NonZeroU64>,
    cursor: Option<String>,
) -> CmdResult {
    let result = client
        .persona_contact_list(
            &context_id,
            known_by_persona.as_deref(),
            changed_since.as_deref(),
            limit,
            cursor.as_deref(),
        )
        .await?;
    print_result("Contacts:", &result)
}

/// `persona contact delete` — forget a contact.
pub async fn cmd_contact_delete(
    client: &VtaClient,
    context_id: String,
    contact_id: String,
) -> CmdResult {
    let result = client
        .persona_contact_delete(&context_id, &contact_id)
        .await?;
    print_result("Result:", &result)
}

// ---------------------------------------------------------------------------
// Disclosure
// ---------------------------------------------------------------------------

/// `persona disclosure preview` — what would this reveal, and to whom?
///
/// Signs nothing and sends nothing. This is the only place the holder sees
/// what is about to leave, so the response is rendered rather than dumped —
/// and rendered by *rank*, not as a flat list. A preview that shows fourteen
/// fields with fourteen equal weights is a notice-and-consent dialog, which is
/// the pattern that teaches people to click through.
pub async fn cmd_disclosure_preview(
    client: &VtaClient,
    context_id: String,
    persona_did: String,
    verifier_did: String,
    requested_claims: Vec<String>,
    purpose: Option<String>,
    renderer: Option<String>,
) -> CmdResult {
    let result = client
        .persona_disclosure_preview(
            &context_id,
            &persona_did,
            &verifier_did,
            requested_claims,
            purpose.as_deref(),
            renderer.as_deref(),
        )
        .await?;

    if is_json_output() {
        print_json(&result)?;
        return Ok(());
    }
    render_preview(&result, &context_id, &verifier_did, purpose.as_deref());
    Ok(())
}

/// Render a preview for a human, falling back to the raw payload if the
/// response is not the shape this function knows how to read.
///
/// The fallback is the point. A renderer that quietly showed an empty claim
/// table on an unfamiliar response would tell the holder "nothing will be
/// disclosed" about a disclosure that is about to happen — the one lie this
/// screen must not tell. Better an ugly payload than a confident wrong
/// summary.
fn render_preview(result: &Value, context_id: &str, verifier_did: &str, purpose: Option<&str>) {
    let (Some(preview_id), Some(claims)) = (
        result.get("previewId").and_then(Value::as_str),
        result.get("claims").and_then(Value::as_array),
    ) else {
        println!(
            "{YELLOW}Preview response was not in the expected shape; showing it as received.{RESET}"
        );
        println!(
            "{}",
            serde_json::to_string_pretty(result).unwrap_or_else(|_| format!("{result:?}"))
        );
        return;
    };

    println!();
    println!("{BOLD}Before anything leaves{RESET} — nothing has been sent.");
    println!();
    println!("  {DIM}To{RESET}         {verifier_did}");
    println!("  {DIM}Context{RESET}    {context_id}");
    if let Some(p) = purpose {
        println!("  {DIM}Purpose{RESET}    {p}");
    }
    if let Some(subject) = result.get("subject").and_then(Value::as_str) {
        println!("  {DIM}As{RESET}         {subject}");
    }

    // What the chosen renderer cannot carry. Declared, not discovered.
    if let Some(r) = result.get("renderer") {
        let id = r.get("id").and_then(Value::as_str).unwrap_or("?");
        let drops: Vec<&str> = r
            .get("drops")
            .and_then(Value::as_array)
            .map(|a| a.iter().filter_map(Value::as_str).collect())
            .unwrap_or_default();
        if drops.is_empty() {
            println!("  {DIM}Format{RESET}     {id} {DIM}(carries everything){RESET}");
        } else {
            println!(
                "  {DIM}Format{RESET}     {id} {YELLOW}— discards: {}{RESET}",
                drops.join(", ")
            );
        }
    }

    // Correlation. The inversion is easy to get backwards, so the reason the
    // VTA supplies is printed rather than re-derived here.
    if let Some(c) = result.get("correlation") {
        let severity = c.get("severity").and_then(Value::as_str).unwrap_or("none");
        let colour = match severity {
            "high" => RED,
            "low" => YELLOW,
            _ => DIM,
        };
        let reason = c.get("reason").and_then(Value::as_str).unwrap_or("");
        println!(
            "  {DIM}Linked{RESET}     {colour}{}{RESET} {reason}",
            severity.to_uppercase()
        );
    }

    let anomalous: Vec<&str> = result
        .get("anomalous")
        .and_then(Value::as_array)
        .map(|a| a.iter().filter_map(Value::as_str).collect())
        .unwrap_or_default();

    println!();
    if claims.is_empty() {
        println!("  {DIM}No attributes would leave.{RESET}");
    }
    for claim in claims {
        let ty = claim.get("type").and_then(Value::as_str).unwrap_or("?");
        let provenance = claim
            .get("provenance")
            .and_then(Value::as_str)
            .unwrap_or("");
        let rung = claim.get("rung").and_then(Value::as_str).unwrap_or("");
        let stale = claim.get("stale").and_then(Value::as_bool).unwrap_or(false);
        let fresh = claim
            .get("newToThisVerifier")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        let odd = anomalous.contains(&ty);

        // A predicate claim carries no value, and that absence is the whole
        // point of the rung — never render it as missing data.
        let shown = if let Some(p) = claim.get("predicate") {
            let op = p.get("op").and_then(Value::as_str).unwrap_or("?");
            let arg = p.get("arg").map(render_scalar).unwrap_or_default();
            format!("{DIM}proves {op} {arg} — the value itself is not sent{RESET}")
        } else if stale {
            format!("{YELLOW}stale — will NOT be sent{RESET}")
        } else {
            claim.get("value").map(render_scalar).unwrap_or_default()
        };

        let mark = if odd || fresh {
            format!("{RED}!{RESET}")
        } else {
            " ".into()
        };
        println!("  {mark} {CYAN}{ty}{RESET}");
        println!("      {shown}");
        let mut notes: Vec<String> = Vec::new();
        if !provenance.is_empty() {
            notes.push(provenance.to_string());
        }
        if !rung.is_empty() {
            notes.push(rung.to_string());
        }
        if fresh {
            notes.push("new to this verifier".into());
        }
        if odd {
            notes.push("unusual for the stated purpose".into());
        }
        if !notes.is_empty() {
            println!("      {DIM}{}{RESET}", notes.join(" · "));
        }
    }

    println!();
    if let Some(expiry) = result.get("expiresAt").and_then(Value::as_str) {
        println!("  {DIM}This preview expires at {expiry} and can be used once.{RESET}");
    }
    println!(
        "  Disclose with: {BOLD}persona disclosure present --context {context_id} \
         --preview-id {preview_id}{RESET}"
    );
    println!();
}

/// Render a JSON scalar the way a person reads it — a string without its
/// quotes, anything else as compact JSON.
fn render_scalar(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// `persona disclosure present` — hand over what the preview showed.
pub async fn cmd_disclosure_present(
    client: &VtaClient,
    context_id: String,
    preview_id: String,
    challenge: Option<String>,
    mint: Option<Value>,
) -> CmdResult {
    let result = client
        .persona_disclosure_present(&context_id, &preview_id, challenge.as_deref(), mint)
        .await?;

    // The document the VTA returns is unsigned; signing belongs to the key
    // custodian. Say so, rather than letting an operator hand a verifier
    // something that looks presentable and is not.
    if !is_json_output()
        && result
            .get("document")
            .and_then(|d| d.get("unsigned"))
            .and_then(Value::as_bool)
            .unwrap_or(false)
    {
        println!(
            "{YELLOW}This document is UNSIGNED. Sign it with the persona's key \
             (`keys derive-and-sign-document`) before sending it to a verifier.{RESET}"
        );
    }
    print_result("What left:", &result)
}

/// `persona disclosure history` — what was disclosed, to whom, when.
pub async fn cmd_disclosure_history(
    client: &VtaClient,
    context_id: Option<String>,
    verifier_did: Option<String>,
    attribute_type: Option<String>,
    since: Option<String>,
    limit: Option<std::num::NonZeroU64>,
    cursor: Option<String>,
) -> CmdResult {
    let result = client
        .persona_disclosure_history(
            context_id.as_deref(),
            verifier_did.as_deref(),
            attribute_type.as_deref(),
            since.as_deref(),
            limit,
            cursor.as_deref(),
        )
        .await?;
    print_result("What has left:", &result)
}

// ---------------------------------------------------------------------------
// Correlation and renderers
// ---------------------------------------------------------------------------

/// `persona correlate` — how linkable would this make the holder?
pub async fn cmd_correlate(
    client: &VtaClient,
    attribute_id: Option<String>,
    profile_id: Option<String>,
    candidate: Option<Value>,
) -> CmdResult {
    let result = client
        .persona_correlation_analyze(attribute_id.as_deref(), profile_id.as_deref(), candidate)
        .await?;
    print_result("Links:", &result)
}

/// `persona renderers` — the output formats, and what each one discards.
pub async fn cmd_renderers(client: &VtaClient) -> CmdResult {
    let result = client.persona_renderers_list().await?;
    print_result("Renderers:", &result)
}

// ---------------------------------------------------------------------------
// Context-local profiles and bindings
// ---------------------------------------------------------------------------

/// `persona local profile put` — a profile that lives inside one context.
pub async fn cmd_local_profile_put(
    client: &VtaClient,
    context_id: String,
    name: String,
    entries: Vec<LocalProfileEntry>,
    profile_id: Option<String>,
    expected_version: Option<u64>,
) -> CmdResult {
    let result = client
        .persona_local_profile_put(
            &context_id,
            &name,
            entries,
            profile_id.as_deref(),
            expected_version,
        )
        .await?;
    print_result("Local profile:", &result)
}

/// `persona local profile get` — read one context-local profile.
pub async fn cmd_local_profile_get(
    client: &VtaClient,
    context_id: String,
    profile_id: String,
) -> CmdResult {
    let result = client
        .persona_local_profile_get(&context_id, &profile_id)
        .await?;
    print_result("Local profile:", &result)
}

/// `persona local profile list` — enumerate a context's own profiles.
pub async fn cmd_local_profile_list(
    client: &VtaClient,
    context_id: String,
    limit: Option<std::num::NonZeroU64>,
    cursor: Option<String>,
) -> CmdResult {
    let result = client
        .persona_local_profile_list(&context_id, limit, cursor.as_deref())
        .await?;
    print_result("Local profiles:", &result)
}

/// `persona local profile delete` — remove a context-local profile.
pub async fn cmd_local_profile_delete(
    client: &VtaClient,
    context_id: String,
    profile_id: String,
    unbind: bool,
) -> CmdResult {
    let result = client
        .persona_local_profile_delete(&context_id, &profile_id, unbind)
        .await?;
    print_result("Result:", &result)
}

/// `persona local binding set` — bind a persona to a context-local profile.
pub async fn cmd_local_binding_set(
    client: &VtaClient,
    context_id: String,
    persona_did: String,
    profile_id: Option<String>,
    expected_version: Option<u64>,
) -> CmdResult {
    let result = client
        .persona_local_binding_set(
            &context_id,
            &persona_did,
            profile_id.as_deref(),
            expected_version,
        )
        .await?;
    print_result("Local binding:", &result)
}