vta-cli-common 0.5.0

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
use ratatui::{
    layout::Constraint,
    style::{Color, Modifier, Style},
    widgets::{Block, Cell, Row, Table},
};
use vta_sdk::client::{AddWebvhServerRequest, CreateDidWebvhRequest, UpdateWebvhServerRequest};
use vta_sdk::prelude::*;

use crate::render::{is_full_display, print_full_entry, print_full_list_title, print_widget};

pub async fn cmd_webvh_server_add(
    client: &VtaClient,
    id: String,
    did: String,
    label: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let req = AddWebvhServerRequest { id, did, label };
    let record = client.add_webvh_server(req).await?;
    println!("WebVH server added:");
    println!("  ID:  {}", record.id);
    println!("  DID: {}", record.did);
    if let Some(label) = &record.label {
        println!("  Label: {label}");
    }
    Ok(())
}

pub async fn cmd_webvh_server_list(client: &VtaClient) -> Result<(), Box<dyn std::error::Error>> {
    let resp = client.list_webvh_servers().await?;

    if resp.servers.is_empty() {
        println!("No WebVH servers configured.");
        return Ok(());
    }

    if is_full_display() {
        print_full_list_title("WebVH Servers", resp.servers.len());
        for s in &resp.servers {
            let label = s.label.as_deref().unwrap_or("");
            let created = s
                .created_at
                .with_timezone(&chrono::Local)
                .format("%Y-%m-%d %H:%M:%S %:z")
                .to_string();
            print_full_entry(&[
                ("ID", &s.id),
                ("DID", &s.did),
                ("Label", label),
                ("Created", &created),
            ]);
        }
        return Ok(());
    }

    let header_style = Style::default()
        .fg(Color::White)
        .add_modifier(Modifier::BOLD);
    let header = Row::new(vec!["ID", "DID", "Label", "Created"])
        .style(header_style)
        .bottom_margin(1);

    let rows: Vec<Row> = resp
        .servers
        .iter()
        .map(|s| {
            let label = s.label.clone().unwrap_or_else(|| "\u{2014}".into());
            let created = s
                .created_at
                .with_timezone(&chrono::Local)
                .format("%Y-%m-%d %H:%M")
                .to_string();

            Row::new(vec![
                Cell::from(s.id.clone()),
                Cell::from(s.did.clone()).style(Style::default().fg(Color::DarkGray)),
                Cell::from(label),
                Cell::from(created).style(Style::default().fg(Color::DarkGray)),
            ])
        })
        .collect();

    let title = format!(" WebVH Servers ({}) ", resp.servers.len());

    let table = Table::new(
        rows,
        [
            Constraint::Length(16), // ID
            Constraint::Min(40),    // DID
            Constraint::Min(16),    // Label
            Constraint::Length(18), // Created
        ],
    )
    .header(header)
    .column_spacing(2)
    .block(
        Block::bordered()
            .title(title)
            .border_style(Style::default().fg(Color::DarkGray)),
    );

    let height = resp.servers.len() as u16 + 4;
    print_widget(table, height);

    Ok(())
}

pub async fn cmd_webvh_server_update(
    client: &VtaClient,
    id: &str,
    label: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let req = UpdateWebvhServerRequest { label };
    let record = client.update_webvh_server(id, req).await?;
    println!("WebVH server updated:");
    println!("  ID:  {}", record.id);
    println!("  DID: {}", record.did);
    if let Some(label) = &record.label {
        println!("  Label: {label}");
    }
    Ok(())
}

pub async fn cmd_webvh_server_remove(
    client: &VtaClient,
    id: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    client.remove_webvh_server(id).await?;
    println!("WebVH server removed: {id}");
    Ok(())
}

// ── DID commands ────────────────────────────────────────────────────

pub async fn cmd_webvh_did_create(
    client: &VtaClient,
    req: CreateDidWebvhRequest,
) -> Result<(), Box<dyn std::error::Error>> {
    let result = client.create_did_webvh(req).await?;
    println!("WebVH DID created:");
    println!("  DID:              {}", result.did);
    println!("  Context:          {}", result.context_id);
    if let Some(ref server_id) = result.server_id {
        println!("  Server:           {}", server_id);
    }
    if let Some(ref mnemonic) = result.mnemonic {
        println!("  Mnemonic:         {}", mnemonic);
    }
    println!("  SCID:             {}", result.scid);
    println!("  Portable:         {}", result.portable);
    println!("  Signing key:      {}", result.signing_key_id);
    println!("  KA key:           {}", result.ka_key_id);
    println!("  Pre-rotation keys: {}", result.pre_rotation_key_count);

    if let Some(ref did_document) = result.did_document {
        println!();
        println!("DID Document:");
        println!(
            "{}",
            serde_json::to_string_pretty(did_document)
                .unwrap_or_else(|_| format!("{did_document}"))
        );
    }
    if let Some(ref log_entry) = result.log_entry {
        println!();
        println!("Log Entry (did.jsonl):");
        println!("{}", log_entry);
        println!();
        println!("To self-host this DID, place the log entry in a file named `did.jsonl`");
        println!("at the URL path corresponding to your DID URL.");
    }

    Ok(())
}

/// Helper that reads optional file inputs before building a `CreateDidWebvhRequest`.
#[allow(clippy::too_many_arguments)]
pub async fn cmd_webvh_did_create_with_files(
    client: &VtaClient,
    context_id: String,
    server_id: Option<String>,
    url: Option<String>,
    path: Option<String>,
    label: Option<String>,
    portable: bool,
    add_mediator_service: bool,
    services: Option<String>,
    pre_rotation_count: u32,
    did_document_path: Option<String>,
    did_log_path: Option<String>,
    no_primary: bool,
    signing_key_id: Option<String>,
    ka_key_id: Option<String>,
    template: Option<String>,
    template_context: Option<String>,
    template_vars: Vec<(String, String)>,
) -> Result<(), Box<dyn std::error::Error>> {
    let did_document = match did_document_path {
        Some(p) => {
            let content =
                std::fs::read_to_string(&p).map_err(|e| format!("failed to read {p}: {e}"))?;
            Some(
                serde_json::from_str::<serde_json::Value>(&content)
                    .map_err(|e| format!("invalid JSON in {p}: {e}"))?,
            )
        }
        None => None,
    };
    if template.is_some() && (did_document.is_some() || did_log_path.is_some()) {
        return Err("--template is mutually exclusive with --did-document and --did-log".into());
    }
    let did_log = match did_log_path {
        Some(p) => {
            Some(std::fs::read_to_string(&p).map_err(|e| format!("failed to read {p}: {e}"))?)
        }
        None => None,
    };
    let additional_services = services
        .map(|s| serde_json::from_str::<Vec<serde_json::Value>>(&s))
        .transpose()
        .map_err(|e| format!("invalid --services JSON: {e}"))?;

    let template_vars: std::collections::HashMap<String, serde_json::Value> = template_vars
        .into_iter()
        .map(|(k, v)| (k, serde_json::Value::String(v)))
        .collect();

    let req = CreateDidWebvhRequest {
        context_id,
        server_id,
        url,
        path,
        label,
        portable,
        add_mediator_service,
        additional_services,
        pre_rotation_count,
        did_document,
        did_log,
        set_primary: !no_primary,
        signing_key_id,
        ka_key_id,
        template,
        template_context,
        template_vars,
    };
    cmd_webvh_did_create(client, req).await
}

pub async fn cmd_webvh_did_list(
    client: &VtaClient,
    context_id: Option<&str>,
    server_id: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    let resp = client.list_dids_webvh(context_id, server_id).await?;

    if resp.dids.is_empty() {
        println!("No WebVH DIDs found.");
        return Ok(());
    }

    if is_full_display() {
        print_full_list_title("WebVH DIDs", resp.dids.len());
        for d in &resp.dids {
            let created = d
                .created_at
                .with_timezone(&chrono::Local)
                .format("%Y-%m-%d %H:%M:%S %:z")
                .to_string();
            let portable = if d.portable { "yes" } else { "no" };
            print_full_entry(&[
                ("DID", &d.did),
                ("Context", &d.context_id),
                ("Server", &d.server_id),
                ("SCID", &d.scid),
                ("Portable", portable),
                ("Created", &created),
            ]);
        }
        return Ok(());
    }

    let header_style = Style::default()
        .fg(Color::White)
        .add_modifier(Modifier::BOLD);
    let header = Row::new(vec!["DID", "Context", "Server", "Portable", "Created"])
        .style(header_style)
        .bottom_margin(1);

    let rows: Vec<Row> = resp
        .dids
        .iter()
        .map(|d| {
            let portable = if d.portable { "yes" } else { "no" };
            let created = d
                .created_at
                .with_timezone(&chrono::Local)
                .format("%Y-%m-%d %H:%M")
                .to_string();

            Row::new(vec![
                Cell::from(d.did.clone()),
                Cell::from(d.context_id.clone()),
                Cell::from(d.server_id.clone()),
                Cell::from(portable.to_string()),
                Cell::from(created).style(Style::default().fg(Color::DarkGray)),
            ])
        })
        .collect();

    let title = format!(" WebVH DIDs ({}) ", resp.dids.len());

    let table = Table::new(
        rows,
        [
            Constraint::Min(40),    // DID
            Constraint::Length(16), // Context
            Constraint::Length(16), // Server
            Constraint::Length(10), // Portable
            Constraint::Length(18), // Created
        ],
    )
    .header(header)
    .column_spacing(2)
    .block(
        Block::bordered()
            .title(title)
            .border_style(Style::default().fg(Color::DarkGray)),
    );

    let height = resp.dids.len() as u16 + 4;
    print_widget(table, height);

    Ok(())
}

pub async fn cmd_webvh_did_get(
    client: &VtaClient,
    did: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let record = client.get_did_webvh(did).await?;
    println!("WebVH DID:");
    println!("  DID:             {}", record.did);
    println!("  Context:         {}", record.context_id);
    println!("  Server:          {}", record.server_id);
    println!("  Mnemonic:        {}", record.mnemonic);
    println!("  SCID:            {}", record.scid);
    println!("  Portable:        {}", record.portable);
    println!("  Log entries:     {}", record.log_entry_count);
    println!(
        "  Created:         {}",
        crate::duration::format_local_datetime(record.created_at)
    );
    println!(
        "  Updated:         {}",
        crate::duration::format_local_datetime(record.updated_at)
    );
    Ok(())
}

pub async fn cmd_webvh_did_delete(
    client: &VtaClient,
    did: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    client.delete_did_webvh(did).await?;
    println!("WebVH DID deleted: {did}");
    Ok(())
}

/// `pnm webvh did-log <did> [--out <path>]` — fetch the raw `did.jsonl`
/// log from the VTA's public `GET /did/{did}/log` endpoint.
///
/// Unauthenticated — matches webvh's world-readable log model. Reads
/// the VTA base URL off the caller's current session (no token needed
/// for this endpoint specifically).
pub async fn cmd_webvh_did_log(
    vta_base_url: &str,
    did: &str,
    out: Option<std::path::PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
    // Cheap URL-path-segment escaping for DIDs. DIDs use `:` (reserved
    // but safe in a path segment) and possibly `#` / `?` — we only need
    // to handle `#` and `?` (both would terminate the path) and `%`
    // (escape char). Keep `:` as-is.
    let escaped_did = did
        .replace('%', "%25")
        .replace('#', "%23")
        .replace('?', "%3F");
    let url = format!("{vta_base_url}/did/{escaped_did}/log");
    let http = reqwest::Client::new();
    let resp = http.get(&url).send().await?;
    let status = resp.status();
    if !status.is_success() {
        let body = resp.text().await.unwrap_or_default();
        return Err(format!("GET {url} failed ({status}): {body}").into());
    }
    let log = resp.text().await?;

    match out {
        Some(path) => {
            std::fs::write(&path, log.as_bytes())
                .map_err(|e| format!("write {}: {e}", path.display()))?;
            eprintln!(
                "DID log written to {} ({} bytes)",
                path.display(),
                log.len()
            );
        }
        None => {
            // Raw to stdout — pipe to a file, to `curl --data-binary`,
            // or to `.well-known/did.jsonl` directly.
            print!("{log}");
        }
    }
    Ok(())
}