vta-service 0.36.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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
use std::path::PathBuf;
use std::sync::Arc;

use vta_sdk::protocols::did_management::create::WebvhPathMode;

use crate::auth::AuthClaims;
use crate::cli_store::CliStore;
use crate::config::AppConfig;
use crate::didcomm_bridge::DIDCommBridge;
use crate::keys::seed_store::create_seed_store;
use crate::operations;

/// 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 cs = CliStore::open(&config).await?;
    let webvh_ks = cs.keyspace(crate::keyspaces::WEBVH)?;
    let did_resolver = vta_sdk::resolver::shared_did_resolver_from_env().await?;

    let auth = cli_super_admin();
    let result = operations::did_webvh::register_webvh_server(
        &webvh_ks,
        &auth,
        &id,
        Some(&did),
        label,
        Some(&did_resolver),
        "cli",
    )
    .await?;
    cs.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 cs = CliStore::open(&config).await?;
    let webvh_ks = cs.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 cs = CliStore::open(&config).await?;
    let webvh_ks = cs.keyspace(crate::keyspaces::WEBVH)?;

    let auth = cli_super_admin();
    // `did: None` — label-only, so an unknown id is NotFound rather
    // than a silent registration, and no resolver is needed.
    let result = operations::did_webvh::register_webvh_server(
        &webvh_ks, &auth, &id, None, label, None, "cli",
    )
    .await?;
    cs.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 cs = CliStore::open(&config).await?;
    let webvh_ks = cs.keyspace(crate::keyspaces::WEBVH)?;

    // Read before the row goes: DIDs still naming this server, and the
    // server's own DID for the re-add command in the notice below. Deleting
    // the registry row does not refuse in that case — it is what the
    // operation does over the wire too — but it is not a complete delete of
    // what the operator may think they are deleting, so say what remains.
    let dependents: Vec<String> = crate::webvh_store::list_dids(&webvh_ks)
        .await?
        .into_iter()
        .filter(|d| d.server_id == id)
        .map(|d| d.did)
        .collect();
    let server_did = crate::webvh_store::get_server(&webvh_ks, &id)
        .await?
        .map(|s| s.did);

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

    eprintln!("WebVH server deleted: {id}");
    if !dependents.is_empty() {
        eprintln!(
            "Warning: only the registry entry was deleted. {} DID(s) are still registered \
             against server '{id}', and their logs are still hosted on it:",
            dependents.len()
        );
        for did in &dependents {
            eprintln!("    {did}");
        }
        eprintln!(
            "  While the id is unregistered, `vta did-mgmt dids delete` removes only the local \
             record and leaves the hosted log behind. To delete those DIDs completely, re-add \
             the server and delete them first:\n    \
             vta did-mgmt servers add --id {id} --did {}\n    \
             vta did-mgmt dids delete <did>",
            server_did.as_deref().unwrap_or("<server-did>")
        );
    }
    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 cs = CliStore::open(&config).await?;
    let keys_ks = cs.keyspace(crate::keyspaces::KEYS)?;
    let imported_ks = cs.keyspace(crate::keyspaces::IMPORTED_SECRETS)?;
    let contexts_ks = cs.keyspace(crate::keyspaces::CONTEXTS)?;
    let webvh_ks = cs.keyspace(crate::keyspaces::WEBVH)?;
    let audit_ks = cs.keyspace(crate::keyspaces::AUDIT)?;
    let audit: vta_audit::SharedAuditSink = vta_audit::shared_keyspace_sink(audit_ks.clone());
    let did_templates_ks = cs.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,
        add_tsp_service: false,
        additional_services,
        pre_rotation_count: pre_rotation.unwrap_or(0),
        did_document: None,
        did_log: None,
        set_primary: true,
        // Online CLI: no local preview to keep in step with.
        pre_derived: None,
        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 = vta_sdk::resolver::shared_did_resolver_from_env().await?;
    let no_bridge: Arc<DIDCommBridge> = Arc::new(DIDCommBridge::placeholder());
    // Offline CLI: no shared AppState, so create a local per-server
    // auth-lock registry for any daemon-REST authentication a publish
    // may need.
    let auth_locks = operations::did_webvh::WebvhAuthLocks::new();
    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,
        audit: &audit,
        seed_store: &*seed_store,
        config: &config,
        did_resolver: &did_resolver,
        didcomm_bridge: &no_bridge,
        auth_locks: &auth_locks,
        // Offline: no mediator socket to lend, so the seam cannot choose
        // TSP. Same reason as the `auth_locks` note above.
        #[cfg(feature = "tsp")]
        tsp: None,
    };
    let result = operations::did_webvh::create_did_webvh(&deps, &auth, params, "cli").await?;
    cs.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 cs = CliStore::open(&config).await?;
    let webvh_ks = cs.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(())
}

/// Print what deleting a DID would destroy and revoke.
///
/// Credentials are listed by id rather than counted. An operator deciding
/// whether to proceed is deciding about *those* credentials, and "3 will be
/// revoked" cannot be checked against what they expected — which is the only
/// question a confirmation prompt is actually asking.
fn render_did_deletion_plan(
    did: &str,
    plan: &operations::did_webvh::DidDeletionPlan,
    local_only: bool,
) {
    println!("Deleting {did} would:");
    if plan.has_acl_entry {
        println!("  - remove its ACL entry (its authorization at this VTA)");
    }
    if plan.sessions_to_revoke > 0 {
        println!("  - end {} live session(s)", plan.sessions_to_revoke);
    }
    if plan.credentials_to_revoke.is_empty() {
        println!("  - revoke no credentials");
    } else {
        println!(
            "  - REVOKE {} credential(s) issued to it — copies held by others stop being \
             valid, and this cannot be undone:",
            plan.credentials_to_revoke.len()
        );
        for id in &plan.credentials_to_revoke {
            println!("      {id}");
        }
    }
    if local_only {
        println!("  - delete its keys and its local record");
        println!("  - LEAVE its published log on the hosting server, where it may still resolve");
    } else {
        println!("  - delete its keys, its local record and its published log");
    }
    if !plan.blockers.is_empty() {
        println!("\nIt will be refused until these are resolved:");
        for blocker in &plan.blockers {
            println!("  - {blocker}");
        }
    }
    println!();
}

pub async fn run_delete_did(
    config_path: Option<PathBuf>,
    did: String,
    local_only: bool,
    yes: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let options = if local_only {
        operations::did_webvh::DeleteDidOptions::local_only()
    } else {
        operations::did_webvh::DeleteDidOptions::default()
    };
    let config = AppConfig::load(config_path)?;
    let cs = CliStore::open(&config).await?;
    let keys_ks = cs.keyspace(crate::keyspaces::KEYS)?;
    let imported_ks = cs.keyspace(crate::keyspaces::IMPORTED_SECRETS)?;
    let contexts_ks = cs.keyspace(crate::keyspaces::CONTEXTS)?;
    let audit_ks = cs.keyspace(crate::keyspaces::AUDIT)?;
    let audit: vta_audit::SharedAuditSink = vta_audit::shared_keyspace_sink(audit_ks.clone());
    let webvh_ks = cs.keyspace(crate::keyspaces::WEBVH)?;
    // The offline delete cascades exactly as the online one does. An operator
    // reaching for the break-glass CLI is the *last* person who should be left
    // with a half-deleted DID.
    let acl_ks = cs.keyspace(crate::keyspaces::ACL)?;
    let sessions_ks = cs.keyspace(crate::keyspaces::SESSIONS)?;
    let issued_credentials_ks = cs.keyspace(crate::keyspaces::ISSUED_CREDENTIALS)?;
    let seed_store: Arc<dyn crate::keys::seed_store::SeedStore> =
        Arc::from(create_seed_store(&config)?);

    let auth = cli_super_admin();
    let did_resolver = vta_sdk::resolver::shared_did_resolver_from_env().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 {
        delete_cascade: Some(crate::operations::did_webvh::DeleteCascadeDeps {
            acl_ks: &acl_ks,
            sessions_ks: &sessions_ks,
            issued_credentials_ks: &issued_credentials_ks,
        }),
        keys_ks: &keys_ks,
        imported_ks: &imported_ks,
        contexts_ks: &contexts_ks,
        webvh_ks: &webvh_ks,
        audit: &audit,
        seed_store: &*seed_store,
        did_resolver: &did_resolver,
        didcomm_bridge: &no_bridge,
        auth_locks: &auth_locks,
        // Offline: no mediator socket to lend, so the seam cannot choose
        // TSP. Same reason as the `auth_locks` note above.
        #[cfg(feature = "tsp")]
        tsp: None,
    };
    // Show what this would do before doing it.
    //
    // Deleting a DID is irreversible and now also *revokes* — credentials in
    // other people's wallets stop being good, and no undo puts them back. The
    // same plan the deletion acts on is rendered here, so the preview cannot
    // under-report what is about to happen.
    let plan = operations::did_webvh::plan_did_deletion_with(
        &deps,
        &auth,
        &did,
        config.vta_did.as_deref(),
        options,
    )
    .await?;
    render_did_deletion_plan(&did, &plan, local_only);
    // `--yes` skips the *prompt*, not the blockers — those are refused by
    // `delete_did_webvh` regardless, and deliberately have no escape hatch.
    if plan.touches_anything_else()
        && !yes
        && !vta_cli_common::commands::contexts::confirm_destructive("Proceed with deletion?")?
    {
        println!("Aborted.");
        return Ok(());
    }

    let result = operations::did_webvh::delete_did_webvh_with(
        &deps,
        &auth,
        &did,
        config.vta_did.as_deref(),
        "cli",
        options,
    )
    .await?;
    cs.persist().await?;

    eprintln!("WebVH DID deleted: {did}");
    // The spec's partial success: the record is gone but the host copy was not
    // confirmed deleted, so the DID may still resolve. Said, never swallowed.
    if let Some(reason) = &result.daemon_cleanup_error {
        eprintln!("warning: {reason}");
    }
    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 cs = CliStore::open(&config).await?;
    let webvh_ks = cs.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 cs = CliStore::open(&config).await?;
    let webvh_ks = cs.keyspace(crate::keyspaces::WEBVH)?;
    let keys_ks = cs.keyspace(crate::keyspaces::KEYS)?;
    let imported_ks = cs.keyspace(crate::keyspaces::IMPORTED_SECRETS)?;
    let contexts_ks = cs.keyspace(crate::keyspaces::CONTEXTS)?;
    let audit_ks = cs.keyspace(crate::keyspaces::AUDIT)?;
    let audit: vta_audit::SharedAuditSink = vta_audit::shared_keyspace_sink(audit_ks.clone());
    let did_resolver = vta_sdk::resolver::shared_did_resolver_from_env().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` needs the body, but building `opts` below moves out of
    // it — and the confirmation has to come after the plan, since the plan is
    // what the operator is confirming.
    let body_for_confirm = body.clone();

    // 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 {
        // `update` publishes a new log entry; it deletes nothing.
        delete_cascade: None,
        keys_ks: &keys_ks,
        imported_ks: &imported_ks,
        contexts_ks: &contexts_ks,
        webvh_ks: &webvh_ks,
        audit: &audit,
        seed_store: &*seed_store,
        did_resolver: &did_resolver,
        didcomm_bridge: &didcomm_bridge,
        auth_locks: &auth_locks,
        // Offline: no mediator socket to lend, so the seam cannot choose
        // TSP. Same reason as the `auth_locks` note above.
        #[cfg(feature = "tsp")]
        tsp: None,
    };
    // Dry-run the real update and show the operator what it will actually do.
    //
    // The document diff shown during editing cannot answer this. It is computed
    // from the document alone, so it can say "you changed `service`" but it has
    // no way to know that changing *anything* rotates this DID's update key —
    // that consequence lives in the update handler's semantics, not in the
    // document's shape. An operator confirming on the strength of the diff is
    // being asked to approve a key rotation they were never shown.
    //
    // So the confirmation is driven by a plan produced by the update code
    // itself, run up to (and not through) its first write.
    let plan =
        crate::operations::did_webvh::plan_did_webvh_update(&deps, &auth, &scid, opts.clone())
            .await?;

    eprintln!("\nPlanned changes to {}:", plan.did);
    eprintln!(
        "  Version: {}{}",
        plan.prior_version_id, plan.new_version_id
    );
    eprintln!();
    for effect in plan.to_effects() {
        eprintln!("{}", effect.summary);
    }
    if plan.to_effects().is_empty() {
        eprintln!("  (no effects — this update would change nothing)");
    }
    eprintln!();

    confirm_publish(&body_for_confirm, no_confirm)?;

    let result = crate::operations::did_webvh::update_did_webvh(
        &deps,
        &auth,
        &scid,
        opts,
        vta_did.as_deref(),
        "vta-cli-offline",
    )
    .await?;
    cs.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 cs = CliStore::open(&config).await?;
    let webvh_ks = cs.keyspace(crate::keyspaces::WEBVH)?;
    let keys_ks = cs.keyspace(crate::keyspaces::KEYS)?;
    let imported_ks = cs.keyspace(crate::keyspaces::IMPORTED_SECRETS)?;
    let contexts_ks = cs.keyspace(crate::keyspaces::CONTEXTS)?;
    let audit_ks = cs.keyspace(crate::keyspaces::AUDIT)?;
    let audit: vta_audit::SharedAuditSink = vta_audit::shared_keyspace_sink(audit_ks.clone());
    let did_resolver = vta_sdk::resolver::shared_did_resolver_from_env().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 {
        // This surface publishes; it deletes nothing.
        delete_cascade: None,
        keys_ks: &keys_ks,
        imported_ks: &imported_ks,
        contexts_ks: &contexts_ks,
        webvh_ks: &webvh_ks,
        audit: &audit,
        seed_store: &*seed_store,
        did_resolver: &did_resolver,
        didcomm_bridge: &didcomm_bridge,
        auth_locks: &auth_locks,
        // Offline: no mediator socket to lend, so the seam cannot choose
        // TSP. Same reason as the `auth_locks` note above.
        #[cfg(feature = "tsp")]
        tsp: None,
    };
    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?;
    cs.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(())
}