vta-service 0.10.0

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
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
use std::path::PathBuf;
use std::sync::Arc;

use affinidi_did_resolver_cache_sdk::{DIDCacheClient, config::DIDCacheConfigBuilder};
use vta_sdk::protocols::did_management::create::WebvhPathMode;

use crate::auth::AuthClaims;
use crate::config::AppConfig;
use crate::didcomm_bridge::DIDCommBridge;
use crate::keys::seed_store::create_seed_store;
use crate::operations;
use crate::store::Store;

/// Format a UTC `DateTime` as a readable local-timezone string with ISO offset.
///
/// The service stores timestamps in UTC internally (wire format, storage);
/// operator-facing CLI output converts to the local timezone for readability.
fn format_local_datetime(dt: chrono::DateTime<chrono::Utc>) -> String {
    dt.with_timezone(&chrono::Local)
        .format("%Y-%m-%d %H:%M:%S %:z")
        .to_string()
}

/// Create a synthetic super-admin AuthClaims for CLI operations.
///
/// Thin wrapper over the workspace-level
/// [`AuthClaims::unsafe_local_cli_super_admin`] factory so the
/// trust-boundary documentation lives in one place. Callers should
/// prefer the factory directly in new code.
pub(crate) fn cli_super_admin() -> AuthClaims {
    AuthClaims::unsafe_local_cli_super_admin("webvh")
}

pub async fn run_add_server(
    config_path: Option<PathBuf>,
    id: String,
    did: String,
    label: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let store = Store::open(&config.store)?;
    let webvh_ks = store.keyspace(crate::keyspaces::WEBVH)?;
    let did_resolver = DIDCacheClient::new(DIDCacheConfigBuilder::default().build()).await?;

    let auth = cli_super_admin();
    let result = operations::did_webvh::add_webvh_server(
        &webvh_ks,
        &auth,
        &id,
        &did,
        label,
        &did_resolver,
        "cli",
    )
    .await?;
    store.persist().await?;

    eprintln!("WebVH server added:");
    eprintln!("  ID:  {}", result.id);
    eprintln!("  DID: {}", result.did);
    if let Some(label) = &result.label {
        eprintln!("  Label: {label}");
    }
    Ok(())
}

pub async fn run_list_servers(
    config_path: Option<PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let store = Store::open(&config.store)?;
    let webvh_ks = store.keyspace(crate::keyspaces::WEBVH)?;

    let auth = cli_super_admin();
    let result = operations::did_webvh::list_webvh_servers(&webvh_ks, &auth, "cli").await?;

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

    eprintln!("{} WebVH server(s):\n", result.servers.len());
    for server in &result.servers {
        eprintln!("  ID:      {}", server.id);
        eprintln!("  DID:     {}", server.did);
        if let Some(label) = &server.label {
            eprintln!("  Label:   {label}");
        }
        eprintln!("  Created: {}", format_local_datetime(server.created_at));
        eprintln!();
    }
    Ok(())
}

pub async fn run_update_server(
    config_path: Option<PathBuf>,
    id: String,
    label: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let store = Store::open(&config.store)?;
    let webvh_ks = store.keyspace(crate::keyspaces::WEBVH)?;

    let auth = cli_super_admin();
    let result =
        operations::did_webvh::update_webvh_server(&webvh_ks, &auth, &id, label, "cli").await?;
    store.persist().await?;

    eprintln!("WebVH server updated:");
    eprintln!("  ID:  {}", result.id);
    eprintln!("  DID: {}", result.did);
    if let Some(label) = &result.label {
        eprintln!("  Label: {label}");
    }
    Ok(())
}

pub async fn run_remove_server(
    config_path: Option<PathBuf>,
    id: String,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let store = Store::open(&config.store)?;
    let webvh_ks = store.keyspace(crate::keyspaces::WEBVH)?;

    let auth = cli_super_admin();
    operations::did_webvh::remove_webvh_server(&webvh_ks, &auth, &id, "cli").await?;
    store.persist().await?;

    eprintln!("WebVH server removed: {id}");
    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub async fn run_create_did(
    config_path: Option<PathBuf>,
    context_id: String,
    server_id: String,
    path: Option<String>,
    label: Option<String>,
    portable: bool,
    mediator_service: bool,
    services_json: Option<String>,
    pre_rotation: Option<u32>,
    print_mnemonic: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path.clone())?;
    let store = Store::open(&config.store)?;
    let keys_ks = store.keyspace(crate::keyspaces::KEYS)?;
    let imported_ks = store.keyspace(crate::keyspaces::IMPORTED_SECRETS)?;
    let contexts_ks = store.keyspace(crate::keyspaces::CONTEXTS)?;
    let webvh_ks = store.keyspace(crate::keyspaces::WEBVH)?;
    let did_templates_ks = store.keyspace(crate::keyspaces::DID_TEMPLATES)?;
    let seed_store: Arc<dyn crate::keys::seed_store::SeedStore> =
        Arc::from(create_seed_store(&config)?);

    let additional_services: Option<Vec<serde_json::Value>> = match services_json {
        Some(json) => Some(serde_json::from_str(&json)?),
        None => None,
    };

    let auth = cli_super_admin();
    let params = operations::did_webvh::CreateDidWebvhParams {
        context_id: context_id.clone(),
        server_id: Some(server_id),
        url: None,
        // `--path <p>` → explicit; `--path .well-known` → root; absent
        // → server auto-assigns.
        path_mode: WebvhPathMode::from(path),
        // CLI-driven flow: no per-DID domain selection here. Wired
        // via `--domain` in pnm-cli's surface.
        domain: None,
        label,
        portable,
        add_mediator_service: mediator_service,
        additional_services,
        pre_rotation_count: pre_rotation.unwrap_or(0),
        did_document: None,
        did_log: None,
        set_primary: true,
        signing_key_id: None,
        ka_key_id: None,
        template: None,
        template_context: None,
        template_vars: std::collections::HashMap::new(),
        // `pnm did-webvh create` is a runtime integration-DID CLI; it
        // never mints the VTA's own identity (setup wizard does that).
        is_vta_identity: false,
    };

    let did_resolver = DIDCacheClient::new(DIDCacheConfigBuilder::default().build()).await?;
    let no_bridge: Arc<DIDCommBridge> = Arc::new(DIDCommBridge::placeholder());
    let deps = operations::did_webvh::CreateDidWebvhDeps {
        keys_ks: &keys_ks,
        imported_ks: &imported_ks,
        contexts_ks: &contexts_ks,
        webvh_ks: &webvh_ks,
        did_templates_ks: &did_templates_ks,
        seed_store: &*seed_store,
        config: &config,
        did_resolver: &did_resolver,
        didcomm_bridge: &no_bridge,
    };
    let result = operations::did_webvh::create_did_webvh(&deps, &auth, params, "cli").await?;
    store.persist().await?;

    eprintln!("\x1b[1;32mCreated DID:\x1b[0m {}", result.did);
    eprintln!("  Context:    {}", result.context_id);
    if let Some(ref server_id) = result.server_id {
        eprintln!("  Server:     {}", server_id);
    }
    eprintln!("  SCID:       {}", result.scid);
    if let Some(ref mnemonic) = result.mnemonic {
        if print_mnemonic {
            eprintln!("  Mnemonic:   {mnemonic}");
        } else {
            eprintln!(
                "  Mnemonic:   <redacted — re-run with `--print-mnemonic` if you really need it on stderr>"
            );
        }
    }
    eprintln!("  Portable:   {}", result.portable);
    eprintln!("  Signing:    {}", result.signing_key_id);
    eprintln!("  KA:         {}", result.ka_key_id);
    if result.pre_rotation_key_count > 0 {
        eprintln!("  Pre-rot:    {} keys", result.pre_rotation_key_count);
    }
    Ok(())
}

pub async fn run_list_dids(
    config_path: Option<PathBuf>,
    context_id: Option<String>,
    server_id: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let store = Store::open(&config.store)?;
    let webvh_ks = store.keyspace(crate::keyspaces::WEBVH)?;

    let auth = cli_super_admin();
    let result = operations::did_webvh::list_dids_webvh(
        &webvh_ks,
        &auth,
        context_id.as_deref(),
        server_id.as_deref(),
        "cli",
    )
    .await?;

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

    eprintln!("{} WebVH DID(s):\n", result.dids.len());
    for d in &result.dids {
        eprintln!("  DID:      {}", d.did);
        eprintln!("  Context:  {}", d.context_id);
        eprintln!("  Server:   {}", d.server_id);
        eprintln!("  SCID:     {}", d.scid);
        eprintln!("  Portable: {}", d.portable);
        eprintln!("  Created:  {}", format_local_datetime(d.created_at));
        eprintln!();
    }
    Ok(())
}

pub async fn run_delete_did(
    config_path: Option<PathBuf>,
    did: String,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let store = Store::open(&config.store)?;
    let keys_ks = store.keyspace(crate::keyspaces::KEYS)?;
    let imported_ks = store.keyspace(crate::keyspaces::IMPORTED_SECRETS)?;
    let contexts_ks = store.keyspace(crate::keyspaces::CONTEXTS)?;
    let audit_ks = store.keyspace(crate::keyspaces::AUDIT)?;
    let webvh_ks = store.keyspace(crate::keyspaces::WEBVH)?;
    let seed_store: Arc<dyn crate::keys::seed_store::SeedStore> =
        Arc::from(create_seed_store(&config)?);

    let auth = cli_super_admin();
    let did_resolver = DIDCacheClient::new(DIDCacheConfigBuilder::default().build()).await?;
    let no_bridge: Arc<DIDCommBridge> = Arc::new(DIDCommBridge::placeholder());
    let auth_locks = crate::operations::did_webvh::WebvhAuthLocks::new();
    let deps = operations::did_webvh::WebvhDeps {
        keys_ks: &keys_ks,
        imported_ks: &imported_ks,
        contexts_ks: &contexts_ks,
        webvh_ks: &webvh_ks,
        audit_ks: &audit_ks,
        seed_store: &*seed_store,
        did_resolver: &did_resolver,
        didcomm_bridge: &no_bridge,
        auth_locks: &auth_locks,
    };
    operations::did_webvh::delete_did_webvh(&deps, &auth, &did, config.vta_did.as_deref(), "cli")
        .await?;
    store.persist().await?;

    eprintln!("WebVH DID deleted: {did}");
    Ok(())
}

/// `vta webvh did-log` — print the raw `did.jsonl` log for a DID the
/// VTA knows (provisioning-time snapshot).
pub async fn run_did_log(
    config_path: Option<PathBuf>,
    did: String,
    out: Option<PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let store = Store::open(&config.store)?;
    let webvh_ks = store.keyspace(crate::keyspaces::WEBVH)?;

    let log = crate::webvh_store::get_did_log(&webvh_ks, &did)
        .await?
        .ok_or_else(|| format!("webvh DID log not found: {did}"))?;

    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 so it can be piped to a webvh server or
            // saved to `.well-known/did.jsonl` directly.
            print!("{log}");
        }
    }
    Ok(())
}

/// Offline equivalent of `pnm webvh edit-did` — edit a WebVH
/// DID document and publish a new LogEntry. Operates directly on
/// the local fjall keystore. The VTA daemon must be stopped
/// (fjall holds an exclusive lock when the daemon is running).
///
/// Same flag surface as the online command:
/// - No flags → interactive mode (opens `$EDITOR`, asks about
///   webvh parameters, confirms).
/// - `--document <file>` / `--options-file <file>` plus per-field
///   flags → non-interactive mode.
#[allow(clippy::too_many_arguments)]
pub async fn run_edit_did(
    config_path: Option<PathBuf>,
    did: String,
    document: Option<PathBuf>,
    options_file: Option<PathBuf>,
    pre_rotation: Option<u32>,
    ttl: Option<u32>,
    watchers: Vec<String>,
    no_watchers: bool,
    label: Option<String>,
    no_confirm: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    use vta_cli_common::commands::webvh_edit::{
        EditFlags, assert_did_id_unchanged, build_options_from_flags, confirm_publish,
        diff_summary, document_id, extract_current_document, launch_editor, prompt_webvh_params,
    };
    use vta_sdk::protocols::did_management::update::UpdateDidWebvhBody;

    let config = AppConfig::load(config_path)?;
    let store = Store::open(&config.store)?;
    let webvh_ks = store.keyspace(crate::keyspaces::WEBVH)?;
    let keys_ks = store.keyspace(crate::keyspaces::KEYS)?;
    let imported_ks = store.keyspace(crate::keyspaces::IMPORTED_SECRETS)?;
    let contexts_ks = store.keyspace(crate::keyspaces::CONTEXTS)?;
    let audit_ks = store.keyspace(crate::keyspaces::AUDIT)?;
    let did_resolver = DIDCacheClient::new(DIDCacheConfigBuilder::default().build()).await?;
    let didcomm_bridge: Arc<DIDCommBridge> = Arc::new(DIDCommBridge::placeholder());
    let seed_store: Arc<dyn crate::keys::seed_store::SeedStore> =
        Arc::from(create_seed_store(&config)?);

    // Look up the DID record for scid (update_did_webvh keys off it).
    let record = crate::webvh_store::get_did(&webvh_ks, &did)
        .await?
        .ok_or_else(|| format!("DID `{did}` not found on this VTA"))?;
    let scid = record.scid.clone();

    let any_flag_set = document.is_some()
        || options_file.is_some()
        || pre_rotation.is_some()
        || ttl.is_some()
        || !watchers.is_empty()
        || no_watchers
        || label.is_some();

    let body: UpdateDidWebvhBody = if any_flag_set {
        let flags = EditFlags {
            document_file: document,
            options_file,
            pre_rotation,
            ttl,
            watchers,
            no_watchers,
            label,
        };
        let body = build_options_from_flags(&flags)?;
        if let Some(edited) = &body.document {
            let log = crate::webvh_store::get_did_log(&webvh_ks, &did)
                .await?
                .ok_or_else(|| format!("DID `{did}` has no log on disk"))?;
            let prior = extract_current_document(&log)?;
            assert_did_id_unchanged(&prior, edited)?;
        }
        body
    } else {
        let log = crate::webvh_store::get_did_log(&webvh_ks, &did)
            .await?
            .ok_or_else(|| format!("DID `{did}` has no log on disk"))?;
        let prior = extract_current_document(&log)?;
        let prior_id = document_id(&prior)?.to_string();
        let pre_rotation_status =
            vta_cli_common::commands::webvh_edit::extract_pre_rotation_status(&log);
        eprintln!("Editing DID document for {prior_id}.");
        eprintln!("Opening $EDITOR — save and exit to continue, or quit without saving to abort.");

        let edited = match launch_editor(&prior)? {
            Some(doc) => {
                let summary = diff_summary(&prior, &doc);
                eprintln!();
                eprintln!("Document diff:");
                for line in summary.lines() {
                    eprintln!("  {line}");
                }
                eprintln!();
                Some(doc)
            }
            None => {
                eprintln!("Editor cancelled. No changes will be published.");
                return Ok(());
            }
        };
        prompt_webvh_params(edited, Some(&pre_rotation_status))?
    };

    confirm_publish(&body, no_confirm)?;

    // Convert the wire body into the op-layer options shape. The
    // SDK type carries `witnesses` as opaque JSON to stay
    // didwebvh-rs-free; we deserialise into the typed enum at
    // intake (matching the REST handler's behaviour).
    let witnesses = match body.witnesses {
        Some(value) => Some(
            serde_json::from_value(value)
                .map_err(|e| format!("invalid witnesses JSON in options-file: {e}"))?,
        ),
        None => None,
    };
    let opts = crate::operations::did_webvh::UpdateDidWebvhOptions {
        document: body.document,
        pre_rotation_count: body.pre_rotation_count,
        witnesses,
        watchers: body.watchers,
        ttl: body.ttl,
        label: body.label,
        expected_version_id: body.expected_version_id,
    };

    let auth = cli_super_admin();
    let vta_did = config.vta_did.clone();
    let auth_locks = crate::operations::did_webvh::WebvhAuthLocks::new();
    let deps = crate::operations::did_webvh::WebvhDeps {
        keys_ks: &keys_ks,
        imported_ks: &imported_ks,
        contexts_ks: &contexts_ks,
        webvh_ks: &webvh_ks,
        audit_ks: &audit_ks,
        seed_store: &*seed_store,
        did_resolver: &did_resolver,
        didcomm_bridge: &didcomm_bridge,
        auth_locks: &auth_locks,
    };
    let result = crate::operations::did_webvh::update_did_webvh(
        &deps,
        &auth,
        &scid,
        opts,
        vta_did.as_deref(),
        "vta-cli-offline",
    )
    .await?;
    store.persist().await?;

    eprintln!("WebVH DID updated.");
    eprintln!("  DID:             {}", result.did);
    eprintln!("  New version ID:  {}", result.new_version_id);
    eprintln!("  New SCID:        {}", result.new_scid);
    eprintln!("  Update keys:     {}", result.update_keys_count);
    eprintln!("  Pre-rotation:    {}", result.pre_rotation_key_count);
    Ok(())
}

/// Offline equivalent of `pnm webvh register-did` — promote a
/// serverless WebVH DID to a server-managed one. Operates directly
/// on the local fjall keystore. The VTA daemon must be stopped
/// (fjall holds an exclusive lock when the daemon is running).
pub async fn run_register_did(
    config_path: Option<PathBuf>,
    did: String,
    server: String,
    force: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let store = Store::open(&config.store)?;
    let webvh_ks = store.keyspace(crate::keyspaces::WEBVH)?;
    let keys_ks = store.keyspace(crate::keyspaces::KEYS)?;
    let imported_ks = store.keyspace(crate::keyspaces::IMPORTED_SECRETS)?;
    let contexts_ks = store.keyspace(crate::keyspaces::CONTEXTS)?;
    let audit_ks = store.keyspace(crate::keyspaces::AUDIT)?;
    let did_resolver = DIDCacheClient::new(DIDCacheConfigBuilder::default().build()).await?;
    let didcomm_bridge: Arc<DIDCommBridge> = Arc::new(DIDCommBridge::placeholder());
    let seed_store: Arc<dyn crate::keys::seed_store::SeedStore> =
        Arc::from(create_seed_store(&config)?);
    let auth_locks = crate::operations::did_webvh::WebvhAuthLocks::new();

    let auth = cli_super_admin();
    let deps = operations::did_webvh::WebvhDeps {
        keys_ks: &keys_ks,
        imported_ks: &imported_ks,
        contexts_ks: &contexts_ks,
        webvh_ks: &webvh_ks,
        audit_ks: &audit_ks,
        seed_store: &*seed_store,
        did_resolver: &did_resolver,
        didcomm_bridge: &didcomm_bridge,
        auth_locks: &auth_locks,
    };
    let result = operations::did_webvh::register_did_with_server(
        &deps,
        &auth,
        operations::did_webvh::RegisterDidWithServerParams {
            did,
            server_id: server,
            force,
            domain: None,
        },
        config.vta_did.as_deref(),
        "vta-cli-offline",
    )
    .await?;
    store.persist().await?;

    eprintln!("DID registered with WebVH server.");
    eprintln!("  DID:         {}", result.did);
    eprintln!("  Server:      {}", result.server_id);
    eprintln!("  Log entries: {}", result.log_entry_count);
    eprintln!();
    eprintln!(
        "Future `pnm services …` mutations will auto-publish to `{}`.",
        result.server_id
    );
    Ok(())
}