vta-service 0.23.2

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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
use std::path::PathBuf;
use std::sync::Arc;

use dialoguer::{Confirm, Input, Select};
use didwebvh_rs::url::WebVHURL;
use serde_json::json;
use url::Url;

use affinidi_did_resolver_cache_sdk::{DIDCacheClient, config::DIDCacheConfigBuilder};

use vta_sdk::did_secrets::{DidSecretsBundle, SecretEntry};
use vta_sdk::protocols::did_management::create::WebvhPathMode;

use crate::acl::{AclEntry, Role, store_acl_entry};
use crate::config::AppConfig;
use crate::keys::seed_store::create_seed_store;
use crate::operations;
use crate::operations::did_webvh::CreateDidWebvhParams;
use crate::setup;
use crate::store::Store;
use crate::webvh_cli::cli_super_admin;

pub struct CreateDidWebvhArgs {
    pub config_path: Option<PathBuf>,
    pub context: String,
    pub label: Option<String>,
    /// Hosting URL. When `Some`, the command runs fully non-interactive.
    pub url: Option<String>,
    /// Emit the `DidSecretsBundle` JSON to stdout and skip interactive prompts.
    pub export_secrets: bool,
    /// Create an ACL admin entry for the new DID in the target context.
    pub admin: bool,
    /// Write the DID log (did.jsonl) to this file.
    pub did_log_file: Option<PathBuf>,
}

pub async fn run_create_did_webvh(
    args: CreateDidWebvhArgs,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(args.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 webvh_ks = store.keyspace(crate::keyspaces::WEBVH)?;
    let audit_ks = store.keyspace(crate::keyspaces::AUDIT)?;
    let audit: vta_audit::SharedAuditSink =
        std::sync::Arc::new(vta_audit::KeyspaceAuditSink::new(audit_ks.clone()));
    let did_templates_ks = store.keyspace(crate::keyspaces::DID_TEMPLATES)?;

    // Resolve context
    let ctx = match crate::contexts::get_context(&contexts_ks, &args.context).await? {
        Some(ctx) => ctx,
        None => {
            eprintln!("Context '{}' does not exist.", args.context);
            let name: String = Input::new()
                .with_prompt("Create it with name")
                .default(args.context.clone())
                .interact_text()?;
            let ctx = crate::contexts::create_context(&contexts_ks, &args.context, &name).await?;
            eprintln!("Created context: {} ({})", ctx.id, ctx.base_path);
            ctx
        }
    };

    let label = args.label.as_deref().unwrap_or(&args.context);

    // `--url` selects fully non-interactive mode: no hosting-URL prompt, no
    // save-log prompt, no export-secrets confirm, and no DID-document
    // edit/portability/pre-rotation prompts. Without it, behave interactively
    // exactly as before.
    let interactive = args.url.is_none();

    // Resolve the hosting URL: from `--url` (non-interactive) or by prompting.
    let webvh_url = match &args.url {
        Some(raw) => {
            let parsed = Url::parse(raw).map_err(|e| format!("invalid --url `{raw}`: {e}"))?;
            WebVHURL::parse_url(&parsed)
                .map_err(|e| format!("invalid did:webvh hosting URL `{raw}`: {e}"))?
        }
        None => setup::prompt_webvh_url(label)?,
    };
    let url_str = webvh_url
        .get_http_url(None)
        .map_err(|e| format!("{e}"))?
        .to_string();

    // Build base DID document using shared helper (without services)
    let seed_store = create_seed_store(&config)?;
    let seed = crate::keys::seeds::load_seed_bytes(
        &keys_ks,
        &*seed_store,
        Some(
            crate::keys::seeds::get_active_seed_id(&keys_ks)
                .await
                .map_err(|e| format!("{e}"))?,
        ),
    )
    .await
    .map_err(|e| format!("{e}"))?;

    // In non-interactive mode, the operation derives keys and builds the
    // document itself. In interactive mode we must render a document *first*,
    // for the operator to inspect and edit — so the keys have to be derived
    // out here, and then handed to the operation via `pre_derived` so it uses
    // the same pair rather than allocating a second one. Deriving on both
    // sides is what made the DID advertise keys the store could not sign
    // with; `derive_entity_keys` allocates a fresh path index per call.
    let (did_document, pre_derived) = if interactive {
        let (doc, derived) =
            build_interactive_did_document(&seed, &ctx.base_path, label, &config, &keys_ks).await?;
        (Some(doc), Some(derived))
    } else {
        (None, None)
    };

    // Portability (interactive prompt; non-interactive uses the prompt default).
    let portable = if interactive {
        Confirm::new()
            .with_prompt("Make this DID portable (can move to a different domain later)?")
            .default(true)
            .interact()?
    } else {
        true
    };

    // Pre-rotation count (interactive prompt; non-interactive uses the default).
    let pre_rotation_count: u32 = if interactive {
        Input::new()
            .with_prompt("Number of pre-rotation keys (0 = none, recommended: 1-3)")
            .default(1u32)
            .interact_text()?
    } else {
        1
    };

    // Build params and call the operations layer
    let auth = cli_super_admin();
    let did_resolver = DIDCacheClient::new(DIDCacheConfigBuilder::default().build()).await?;
    let no_bridge: Arc<crate::didcomm_bridge::DIDCommBridge> =
        Arc::new(crate::didcomm_bridge::DIDCommBridge::placeholder());

    let params = CreateDidWebvhParams {
        context_id: args.context.clone(),
        server_id: None,
        url: Some(url_str.clone()),
        // Serverless (`server_id: None`) ignores `path_mode`.
        path_mode: WebvhPathMode::default(),
        domain: None,
        label: Some(label.to_string()),
        portable,
        // Interactive builds the service into the document it passes (and
        // the operator may have edited it), so the operation must not add a
        // second one. Non-interactive passes no document, so the operation
        // is the only thing that can advertise the mediator — without this,
        // `--url` mints a DID with no `service` entry at all, which no peer
        // can route to. `build_did_document` no-ops when `[messaging]` is
        // absent, but say so here too: the flag reads as a claim about what
        // this VTA can serve.
        add_mediator_service: !interactive && config.messaging.is_some(),
        add_tsp_service: false,
        additional_services: None,
        pre_rotation_count,
        did_document,
        did_log: None,
        set_primary: true,
        pre_derived,
        signing_key_id: None,
        ka_key_id: None,
        template: None,
        template_context: None,
        template_vars: std::collections::HashMap::new(),
        // `vta create-did-webvh` is the runtime integration-DID CLI — not
        // used to mint the VTA's own identity (that's setup wizard /
        // setup --from / TEE autogen).
        is_vta_identity: false,
    };

    // Offline CLI: no shared AppState, so create a local per-server
    // auth-lock registry. This path is serverless (`server_id: None`),
    // so it won't authenticate to a hosting server, but the deps bundle
    // requires the field.
    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,
    };
    let result = operations::did_webvh::create_did_webvh(&deps, &auth, params, "cli").await?;

    let final_did = &result.did;
    eprintln!("\x1b[1;32mCreated DID:\x1b[0m {final_did}");

    // Optionally grant the new DID admin in the target context. Mirrors
    // `create-did-key --admin` (`vta-service/src/did_key.rs`): same
    // `AclEntry::new(..).with_label(..).with_contexts(..)` +
    // `store_acl_entry` call, scoped to the target context.
    if args.admin {
        let acl_ks = store.keyspace(crate::keyspaces::ACL)?;
        let entry = AclEntry::new(final_did.clone(), Role::Admin, "cli:create-did-webvh")
            .with_label(args.label.clone())
            .with_contexts(vec![args.context.clone()]);
        store_acl_entry(&acl_ks, &entry).await?;
        eprintln!(
            "ACL entry created: {final_did} (admin, context: {})",
            args.context
        );
    }

    // Persist all writes (DID + optional ACL entry)
    store.persist().await?;

    // Save did.jsonl. Interactive: prompt for the filename (defaulting to
    // `--did-log-file` if given). Non-interactive (`--url`): write to
    // `--did-log-file` silently, or skip if not specified.
    if let Some(ref log_entry) = result.log_entry {
        if interactive {
            let default_file = args
                .did_log_file
                .as_ref()
                .map(|p| p.display().to_string())
                .unwrap_or_else(|| format!("{label}-did.jsonl"));
            let did_file: String = Input::new()
                .with_prompt("Save DID log to file")
                .default(default_file)
                .interact_text()?;

            std::fs::write(&did_file, log_entry)
                .map_err(|e| format!("failed to write did.jsonl to {did_file}: {e}"))?;
            eprintln!("  DID log saved to: {did_file}");
            eprintln!("  Context '{}' updated with DID: {final_did}", args.context);
            eprintln!();
            eprintln!("  \x1b[2mTo self-host this DID, upload {did_file} to:");
            eprintln!("  {url_str}\x1b[0m");
        } else {
            // Non-interactive (`--url`): stdout is reserved for the secrets
            // bundle, so there's no prompt — `--did-log-file` is the only way
            // to capture the log. Without it we just note where it belongs.
            if let Some(ref path) = args.did_log_file {
                std::fs::write(path, log_entry)
                    .map_err(|e| format!("failed to write did.jsonl to {}: {e}", path.display()))?;
                eprintln!("  DID log written to: {}", path.display());
            }
            eprintln!("  Context '{}' updated with DID: {final_did}", args.context);
            if args.did_log_file.is_none() {
                eprintln!(
                    "  \x1b[2mDID log (did.jsonl) ready; pass --did-log-file <path> to save it. Self-host at: {url_str}\x1b[0m"
                );
            } else {
                eprintln!("  \x1b[2mSelf-host the DID log at: {url_str}\x1b[0m");
            }
        }
    }

    // Optionally export secrets bundle. `--export-secrets` forces it
    // unconditionally (no confirm); interactively, prompt. Non-interactive
    // without the flag emits nothing on stdout.
    let want_export = if args.export_secrets {
        true
    } else if interactive {
        Confirm::new()
            .with_prompt("Export DID secrets bundle?")
            .default(false)
            .interact()?
    } else {
        false
    };
    if want_export {
        // Fetch key secrets via the operations layer
        let signing_secret = crate::operations::keys::get_key_secret(
            &keys_ks,
            &imported_ks,
            &Arc::from(seed_store),
            &(std::sync::Arc::new(vta_audit::KeyspaceAuditSink::new(
                store.keyspace(crate::keyspaces::AUDIT)?,
            )) as vta_audit::SharedAuditSink),
            &auth,
            &result.signing_key_id,
            "cli",
        )
        .await
        .map_err(|e| format!("failed to fetch signing key secret: {e}"))?;

        let mut secrets = vec![SecretEntry {
            key_id: result.signing_key_id.clone(),
            key_type: vta_sdk::keys::KeyType::Ed25519,
            private_key_multibase: signing_secret.private_key_multibase,
        }];

        if !result.ka_key_id.is_empty() {
            let ka_secret = crate::operations::keys::get_key_secret(
                &keys_ks,
                &imported_ks,
                &Arc::from(create_seed_store(&config)?),
                &(std::sync::Arc::new(vta_audit::KeyspaceAuditSink::new(
                    store.keyspace(crate::keyspaces::AUDIT)?,
                )) as vta_audit::SharedAuditSink),
                &auth,
                &result.ka_key_id,
                "cli",
            )
            .await
            .map_err(|e| format!("failed to fetch KA key secret: {e}"))?;

            secrets.push(SecretEntry {
                key_id: result.ka_key_id.clone(),
                key_type: vta_sdk::keys::KeyType::X25519,
                private_key_multibase: ka_secret.private_key_multibase,
            });
        }

        let bundle = DidSecretsBundle {
            did: final_did.clone(),
            secrets,
        };
        // Local operator export to stdout: JSON, not base64. The base64
        // wrapper offered no integrity or confidentiality — the OS
        // filesystem (for redirected output) or terminal scrollback is the
        // only protection here. Pretty-printed JSON is easier to audit
        // and indexes cleanly into secure storage.
        let json = serde_json::to_string_pretty(&bundle)?;
        eprintln!();
        eprintln!("\x1b[1;33m╔══════════════════════════════════════════════════════════╗");
        eprintln!("║  WARNING: The secrets bundle contains private keys.      ║");
        eprintln!("║  Redirect to a file with restrictive permissions.        ║");
        eprintln!("╚══════════════════════════════════════════════════════════╝\x1b[0m");
        eprintln!();
        println!("{json}");
        eprintln!();
    }

    Ok(())
}

/// Interactive DID document builder: derives the entity keys, prompts for
/// service endpoints, displays the document, and offers editor access.
///
/// Returns the document **and the keys it was built from**. The caller must
/// hand those keys to the operation (`CreateDidWebvhParams::pre_derived`) —
/// letting it derive its own pair would store keys this document does not
/// name, which is precisely the mismatch the non-interactive path had.
async fn build_interactive_did_document(
    seed: &[u8],
    base_path: &str,
    label: &str,
    config: &AppConfig,
    keys_ks: &vti_common::store::KeyspaceHandle,
) -> Result<(serde_json::Value, crate::keys::DerivedEntityKeys), Box<dyn std::error::Error>> {
    let derived = crate::keys::derive_entity_keys(
        seed,
        base_path,
        &format!("{label} signing key"),
        &format!("{label} key-agreement key"),
        keys_ks,
    )
    .await?;
    let mut doc = operations::did_webvh::build_did_document(&derived, config, false, &None);

    if let Some(ref msg) = config.messaging {
        let service_options = &[
            "DIDComm endpoint (references mediator DID for routing)",
            "No service endpoints",
        ];
        let want_didcomm = Select::new()
            .with_prompt("Service endpoints")
            .items(service_options)
            .default(0)
            .interact()?
            == 0;

        if want_didcomm {
            doc["service"] = json!([
                {
                    "id": "{DID}#vta-didcomm",
                    "type": "DIDCommMessaging",
                    "serviceEndpoint": [{
                        "accept": ["didcomm/v2"],
                        "uri": msg.mediator_did
                    }]
                }
            ]);
        }
    }

    eprintln!();
    eprintln!(
        "\x1b[2mDID Document:\n{}\x1b[0m",
        serde_json::to_string_pretty(&doc)?
    );
    eprintln!();

    if Confirm::new()
        .with_prompt("Edit DID document in your editor?")
        .default(false)
        .interact()?
    {
        doc = edit_did_document(doc)?;
    }

    Ok((doc, derived))
}

fn edit_did_document(
    doc: serde_json::Value,
) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
    use std::io::Write;
    use std::process::Command;

    let json = serde_json::to_string_pretty(&doc)?;

    // Write to a named temp file with .json extension for editor syntax highlighting
    let mut tmp = tempfile::Builder::new().suffix(".json").tempfile()?;
    tmp.write_all(json.as_bytes())?;
    tmp.flush()?;
    let path = tmp.path().to_path_buf();

    // Resolve editor: $VISUAL > $EDITOR > fallback
    let editor = std::env::var("VISUAL")
        .or_else(|_| std::env::var("EDITOR"))
        .unwrap_or_else(|_| "vi".to_string());

    // Open editor and wait
    let status = Command::new(&editor)
        .arg(&path)
        .status()
        .map_err(|e| format!("failed to launch editor '{editor}': {e}"))?;

    if !status.success() {
        return Err(format!("editor exited with {status}").into());
    }

    // Read back and parse
    let edited = std::fs::read_to_string(&path)?;
    let new_doc: serde_json::Value =
        serde_json::from_str(&edited).map_err(|e| format!("invalid JSON from editor: {e}"))?;

    // Basic validation: must be an object with "id" field
    if !new_doc.is_object() || !new_doc.get("id").is_some_and(|v| v.is_string()) {
        return Err("DID document must be a JSON object with an \"id\" field".into());
    }

    // Show the updated document
    eprintln!(
        "\x1b[2mUpdated DID Document:\n{}\x1b[0m",
        serde_json::to_string_pretty(&new_doc)?
    );

    Ok(new_doc)
}

#[cfg(all(test, feature = "config-seed"))]
mod tests {
    use super::*;
    use crate::acl::get_acl_entry;
    use crate::keys::seeds::{SeedRecord, save_seed_record, set_active_seed_id};
    use vti_common::acl::Role;

    /// `vta create-did-webvh --url <URL> --admin --export-secrets` must run
    /// fully non-interactive and, in one shot:
    ///   * mint a did:webvh with #key-0 (Ed25519 signing) + #key-1 (X25519
    ///     key-agreement),
    ///   * create an ACL **admin** entry for that DID, scoped to the context,
    ///   * (export-secrets emits the bundle to stdout — verified by the
    ///     vta-sdk `secrets_from_bundle` tests; here we assert the store-side
    ///     effects that prove the non-interactive + ACL wiring).
    ///
    /// Gated on `config-seed` so the seed store is the in-config backend (no
    /// OS keyring), making the test hermetic. Run with:
    /// `cargo test -p vta-service --bin vta --features config-seed`.
    #[tokio::test]
    async fn create_did_webvh_url_admin_export_is_noninteractive_and_grants_admin() {
        let dir = tempfile::TempDir::new().expect("tempdir");
        let data_dir = dir.path().join("data");
        std::fs::create_dir_all(&data_dir).unwrap();
        let config_path = dir.path().join("config.toml");

        // Minimal config: local store + a config-seed backend carrying a
        // fixed hex seed (dev/test only; selected ahead of keyring in the
        // factory). No messaging, so the DID gets no DIDComm service.
        let seed_hex = hex::encode([7u8; 64]);
        std::fs::write(
            &config_path,
            format!(
                "[store]\ndata_dir = \"{}\"\n\n[secrets]\nseed = \"{seed_hex}\"\n",
                data_dir.display()
            ),
        )
        .unwrap();

        // Bootstrap the seed generation record (the bytes live in the
        // config-seed backend); record generation 0 as active.
        let config = AppConfig::load(Some(config_path.clone())).expect("load config");
        let store = Store::open(&config.store).expect("open store");
        let keys_ks = store.keyspace(crate::keyspaces::KEYS).unwrap();
        let contexts_ks = store.keyspace(crate::keyspaces::CONTEXTS).unwrap();

        save_seed_record(
            &keys_ks,
            &SeedRecord {
                id: 0,
                seed_hex: None,
                seed_enc: None,
                created_at: chrono::Utc::now(),
                retired_at: None,
            },
        )
        .await
        .unwrap();
        set_active_seed_id(&keys_ks, 0).await.unwrap();

        // Create the target context up-front (so no "create context?" prompt).
        crate::contexts::create_context(&contexts_ks, "agents", "Agents")
            .await
            .unwrap();
        store.persist().await.unwrap();
        // Release the fjall lock fully before the command opens its own Store.
        drop(keys_ks);
        drop(contexts_ks);
        drop(store);

        // Run fully non-interactive: --url set, --admin, --export-secrets.
        let args = CreateDidWebvhArgs {
            config_path: Some(config_path.clone()),
            context: "agents".to_string(),
            label: Some("agent-1".to_string()),
            url: Some("https://example.com/agents/agent-1".to_string()),
            export_secrets: true,
            admin: true,
            did_log_file: None,
        };
        run_create_did_webvh(args).await.expect("create-did-webvh");

        // Reopen the store and assert the side effects.
        let store = Store::open(&config.store).expect("reopen store");
        let webvh_ks = store.keyspace(crate::keyspaces::WEBVH).unwrap();
        let acl_ks = store.keyspace(crate::keyspaces::ACL).unwrap();

        // Exactly one did:webvh was created, with #key-0 + #key-1 records.
        let dids = crate::webvh_store::list_dids(&webvh_ks).await.unwrap();
        assert_eq!(dids.len(), 1, "one did:webvh minted");
        let did = &dids[0].did;
        assert!(did.starts_with("did:webvh:"), "got {did}");

        let keys_ks2 = store.keyspace(crate::keyspaces::KEYS).unwrap();
        let key0: Option<crate::keys::KeyRecord> = keys_ks2
            .get(crate::keys::store_key(&format!("{did}#key-0")))
            .await
            .unwrap();
        let key1: Option<crate::keys::KeyRecord> = keys_ks2
            .get(crate::keys::store_key(&format!("{did}#key-1")))
            .await
            .unwrap();
        assert!(key0.is_some(), "#key-0 (signing) record present");
        assert!(key1.is_some(), "#key-1 (key-agreement) record present");
        assert_eq!(key1.unwrap().key_type, crate::keys::KeyType::X25519);

        // The ACL admin entry exists for the new DID, scoped to the context.
        let entry = get_acl_entry(&acl_ks, did)
            .await
            .unwrap()
            .expect("ACL entry created for the did:webvh");
        assert_eq!(entry.role, Role::Admin);
        assert_eq!(entry.allowed_contexts, vec!["agents".to_string()]);
    }

    /// `--did-log-file` writes the `did.jsonl` the command would otherwise
    /// only mention. The target is an **absolute path outside the working
    /// directory** on purpose — that is the whole point of the flag (publish
    /// into a checkout of an external host, e.g. GitLab Pages), and the
    /// operator is the one supplying it.
    ///
    /// Same `config-seed` gate + hermetic tempdir config as the test above.
    #[tokio::test]
    async fn did_log_file_writes_the_log_to_the_given_path() {
        let dir = tempfile::TempDir::new().expect("tempdir");
        let data_dir = dir.path().join("data");
        std::fs::create_dir_all(&data_dir).unwrap();
        let config_path = dir.path().join("config.toml");

        let seed_hex = hex::encode([9u8; 64]);
        std::fs::write(
            &config_path,
            format!(
                "[store]\ndata_dir = \"{}\"\n\n[secrets]\nseed = \"{seed_hex}\"\n",
                data_dir.display()
            ),
        )
        .unwrap();

        let config = AppConfig::load(Some(config_path.clone())).expect("load config");
        let store = Store::open(&config.store).expect("open store");
        let keys_ks = store.keyspace(crate::keyspaces::KEYS).unwrap();
        let contexts_ks = store.keyspace(crate::keyspaces::CONTEXTS).unwrap();

        save_seed_record(
            &keys_ks,
            &SeedRecord {
                id: 0,
                seed_hex: None,
                seed_enc: None,
                created_at: chrono::Utc::now(),
                retired_at: None,
            },
        )
        .await
        .unwrap();
        set_active_seed_id(&keys_ks, 0).await.unwrap();
        crate::contexts::create_context(&contexts_ks, "agents", "Agents")
            .await
            .unwrap();
        store.persist().await.unwrap();
        drop(keys_ks);
        drop(contexts_ks);
        drop(store);

        // Absolute, outside cwd, into a directory the operator nominated.
        let publish_dir = dir.path().join("pages");
        std::fs::create_dir_all(&publish_dir).unwrap();
        let log_path = publish_dir.join("did.jsonl");

        let args = CreateDidWebvhArgs {
            config_path: Some(config_path.clone()),
            context: "agents".to_string(),
            label: Some("agent-1".to_string()),
            url: Some("https://example.com/agents/agent-1".to_string()),
            export_secrets: false,
            admin: false,
            did_log_file: Some(log_path.clone()),
        };
        run_create_did_webvh(args).await.expect("create-did-webvh");

        let written = std::fs::read_to_string(&log_path).expect("did.jsonl written");
        assert!(!written.trim().is_empty(), "did.jsonl is not empty");

        // It is the real log: the first line parses as JSON and carries the
        // minted DID's version id.
        let first = written.lines().next().expect("at least one log entry");
        let entry: serde_json::Value = serde_json::from_str(first).expect("log entry is JSON");
        assert!(
            entry.get("versionId").is_some(),
            "log entry carries versionId, got: {entry}"
        );
    }

    /// Write a config + open a seeded store with one context, ready for a
    /// `create-did-webvh`. `mediator_did` adds a `[messaging]` section — the
    /// switch that decides whether the minted DID advertises DIDComm.
    async fn setup_seeded_store(
        dir: &tempfile::TempDir,
        mediator_did: Option<&str>,
    ) -> (AppConfig, std::path::PathBuf) {
        let data_dir = dir.path().join("data");
        std::fs::create_dir_all(&data_dir).unwrap();
        let config_path = dir.path().join("config.toml");

        let seed_hex = hex::encode([42u8; 64]);
        let messaging = mediator_did
            .map(|did| format!("\n[messaging]\nmediator_did = \"{did}\"\n"))
            .unwrap_or_default();
        std::fs::write(
            &config_path,
            format!(
                "[store]\ndata_dir = \"{}\"\n\n[secrets]\nseed = \"{seed_hex}\"\n{messaging}",
                data_dir.display()
            ),
        )
        .unwrap();

        let config = AppConfig::load(Some(config_path.clone())).expect("load config");
        let store = Store::open(&config.store).expect("open store");
        let keys_ks = store.keyspace(crate::keyspaces::KEYS).unwrap();
        let contexts_ks = store.keyspace(crate::keyspaces::CONTEXTS).unwrap();

        save_seed_record(
            &keys_ks,
            &SeedRecord {
                id: 0,
                seed_hex: None,
                seed_enc: None,
                created_at: chrono::Utc::now(),
                retired_at: None,
            },
        )
        .await
        .unwrap();
        set_active_seed_id(&keys_ks, 0).await.unwrap();
        crate::contexts::create_context(&contexts_ks, "test-ctx", "Test")
            .await
            .unwrap();
        store.persist().await.unwrap();
        drop(keys_ks);
        drop(contexts_ks);
        drop(store);

        (config, config_path)
    }

    /// Stand up a config + seeded store + context, run a non-interactive
    /// `create-did-webvh`, and return the loaded config alongside the first
    /// `did.jsonl` log entry.
    ///
    /// `mediator_did` adds a `[messaging]` section — the switch that decides
    /// whether the minted DID advertises a DIDComm service.
    async fn run_non_interactive_create(
        dir: &tempfile::TempDir,
        mediator_did: Option<&str>,
    ) -> (AppConfig, serde_json::Value) {
        let (config, config_path) = setup_seeded_store(dir, mediator_did).await;
        // Create DID non-interactively with --did-log-file
        let log_path = dir.path().join("did.jsonl");
        let args = CreateDidWebvhArgs {
            config_path: Some(config_path.clone()),
            context: "test-ctx".to_string(),
            label: Some("test".to_string()),
            url: Some("https://example.com/test".to_string()),
            export_secrets: false,
            admin: false,
            did_log_file: Some(log_path.clone()),
        };
        run_create_did_webvh(args).await.expect("create-did-webvh");

        let content = std::fs::read_to_string(&log_path).expect("did.jsonl");
        let entry: serde_json::Value =
            serde_json::from_str(content.lines().next().unwrap()).unwrap();
        (config, entry)
    }

    /// The DID document's `publicKeyMultibase` must match the key the VTA
    /// serves via `get_key_secret`. This is the bug that caused the
    /// "double-allocate path counter" mismatch: derivation happened twice
    /// (once for preview, once in the operation), consuming different indices.
    /// After the fix, non-interactive mode derives once — the document and
    /// the store agree.
    #[tokio::test]
    async fn non_interactive_did_doc_key_matches_stored_key() {
        let dir = tempfile::TempDir::new().expect("tempdir");
        let (config, entry) = run_non_interactive_create(&dir, None).await;

        // Extract the public key from the DID document
        let state = entry.get("state").expect("state field");
        let vms = state
            .get("verificationMethod")
            .and_then(|v| v.as_array())
            .expect("verificationMethod array");
        // Find the Ed25519 key (multicodec prefix 0xed01)
        let doc_pubkey: [u8; 32] = vms
            .iter()
            .filter_map(|vm| vm.get("publicKeyMultibase")?.as_str())
            .filter_map(|mb| multibase::decode(mb).ok())
            .filter_map(|(_, bytes)| {
                if bytes.starts_with(&[0xed, 0x01]) && bytes.len() == 34 {
                    <[u8; 32]>::try_from(&bytes[2..]).ok()
                } else {
                    None
                }
            })
            .next()
            .expect("DID doc must have an Ed25519 key");

        // Fetch the same key from the store (same path the VTA REST would use)
        let store = Store::open(&config.store).expect("reopen store");
        let keys_ks = store.keyspace(crate::keyspaces::KEYS).unwrap();
        let imported_ks = store.keyspace(crate::keyspaces::IMPORTED_SECRETS).unwrap();
        let audit_ks = store.keyspace(crate::keyspaces::AUDIT).unwrap();
        let audit: vta_audit::SharedAuditSink =
            std::sync::Arc::new(vta_audit::KeyspaceAuditSink::new(audit_ks.clone()));
        let seed_store = Arc::from(create_seed_store(&config).unwrap());
        let auth = cli_super_admin();

        let did = entry
            .get("state")
            .and_then(|s| s.get("id"))
            .and_then(|v| v.as_str())
            .expect("DID id");
        let key_id = format!("{did}#key-0");

        let secret = crate::operations::keys::get_key_secret(
            &keys_ks,
            &imported_ks,
            &seed_store,
            &audit,
            &auth,
            &key_id,
            "test",
        )
        .await
        .expect("fetch key secret");

        // Derive the public key from the secret
        let secret_bytes =
            multibase::decode(&secret.private_key_multibase).expect("decode secret multibase");
        let signing_key =
            ed25519_dalek::SigningKey::from_bytes(secret_bytes.1[2..].try_into().unwrap());
        let store_pubkey = signing_key.verifying_key().to_bytes();

        // The key in the DID document MUST match the key the store serves.
        assert_eq!(
            doc_pubkey, store_pubkey,
            "DID doc key must match stored key — if this fails, the path \
             counter was double-allocated (preview + operation derived separately)"
        );
    }

    /// A DID minted with `--url` must still advertise the mediator when
    /// `[messaging]` is configured.
    ///
    /// The pre-fix CLI built the service into a preview document it handed to
    /// the operation. Dropping that document to fix the key mismatch also
    /// dropped the only thing advertising DIDComm, and nothing caught it: the
    /// service array had no coverage. A DID that advertises no transport has
    /// an empty protocol intersection with every peer, so nothing can route
    /// to it — the failure surfaces far from here, as an unreachable DID.
    #[tokio::test]
    async fn non_interactive_did_doc_advertises_the_mediator() {
        const MEDIATOR_DID: &str = "did:key:z6MkiSEhwSnqRMjfsZnfoqCkVsao8SYaBwQ2HREh6F91R5wL";

        let dir = tempfile::TempDir::new().expect("tempdir");
        let (_config, entry) = run_non_interactive_create(&dir, Some(MEDIATOR_DID)).await;

        let services = entry
            .get("state")
            .and_then(|s| s.get("service"))
            .and_then(|v| v.as_array())
            .expect("DID doc must carry a service array when [messaging] is set");

        let didcomm = services
            .iter()
            .find(|s| s.get("type").and_then(|t| t.as_str()) == Some("DIDCommMessaging"))
            .expect("a DIDCommMessaging service must be advertised");

        // Matched on `type`, not on the `#id` fragment — the fragment is an
        // arbitrary label, and this assertion should not pin one.
        let endpoint = serde_json::to_string(didcomm).expect("serialize service");
        assert!(
            endpoint.contains(MEDIATOR_DID),
            "the DIDComm service must route via the configured mediator DID, got {didcomm}"
        );
    }

    /// A caller that renders the DID document itself must get a DID whose
    /// stored keys are the ones its document names.
    ///
    /// This is the interactive path in miniature. That path cannot be driven
    /// from a test — it blocks on `dialoguer` prompts — so this exercises the
    /// mechanism underneath it: derive once out here (as
    /// `build_interactive_did_document` does), build a document from those
    /// keys, and hand both to the operation. Before `pre_derived`, the
    /// operation ignored the caller's derivation and allocated its own path
    /// indices, so the document advertised `n, n+1` while the store held
    /// `n+2, n+3` — a DID that cannot sign for the keys it publishes.
    #[tokio::test]
    async fn caller_rendered_document_names_the_keys_the_store_holds() {
        let dir = tempfile::TempDir::new().expect("tempdir");
        let (config, _config_path) = setup_seeded_store(&dir, None).await;

        let store = Store::open(&config.store).expect("open store");
        let keys_ks = store.keyspace(crate::keyspaces::KEYS).unwrap();
        let imported_ks = store.keyspace(crate::keyspaces::IMPORTED_SECRETS).unwrap();
        let contexts_ks = store.keyspace(crate::keyspaces::CONTEXTS).unwrap();
        let webvh_ks = store.keyspace(crate::keyspaces::WEBVH).unwrap();
        let audit_ks = store.keyspace(crate::keyspaces::AUDIT).unwrap();
        let audit: vta_audit::SharedAuditSink =
            std::sync::Arc::new(vta_audit::KeyspaceAuditSink::new(audit_ks.clone()));
        let did_templates_ks = store.keyspace(crate::keyspaces::DID_TEMPLATES).unwrap();
        let seed_store = create_seed_store(&config).unwrap();

        let ctx = crate::contexts::get_context(&contexts_ks, "test-ctx")
            .await
            .unwrap()
            .expect("context");
        let seed = crate::keys::seeds::load_seed_bytes(&keys_ks, &*seed_store, Some(0))
            .await
            .expect("load seed");

        // Derive once, exactly as the interactive preview does, and build the
        // document from that pair.
        let derived = crate::keys::derive_entity_keys(
            &seed,
            &ctx.base_path,
            "test signing key",
            "test key-agreement key",
            &keys_ks,
        )
        .await
        .expect("derive");
        let preview_signing_pub = derived.signing_pub.clone();
        let did_document =
            operations::did_webvh::build_did_document(&derived, &config, false, &None);

        let did_resolver = DIDCacheClient::new(DIDCacheConfigBuilder::default().build())
            .await
            .unwrap();
        let no_bridge: Arc<crate::didcomm_bridge::DIDCommBridge> =
            Arc::new(crate::didcomm_bridge::DIDCommBridge::placeholder());
        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,
        };

        let result = operations::did_webvh::create_did_webvh(
            &deps,
            &cli_super_admin(),
            CreateDidWebvhParams {
                context_id: "test-ctx".to_string(),
                server_id: None,
                url: Some("https://example.com/test".to_string()),
                path_mode: WebvhPathMode::default(),
                domain: None,
                label: Some("test".to_string()),
                portable: true,
                add_mediator_service: false,
                add_tsp_service: false,
                additional_services: None,
                pre_rotation_count: 1,
                did_document: Some(did_document),
                did_log: None,
                set_primary: true,
                pre_derived: Some(derived),
                signing_key_id: None,
                ka_key_id: None,
                template: None,
                template_context: None,
                template_vars: std::collections::HashMap::new(),
                is_vta_identity: false,
            },
            "test",
        )
        .await
        .expect("create_did_webvh");

        // What the store will serve for `#key-0`.
        let secret = crate::operations::keys::get_key_secret(
            &keys_ks,
            &imported_ks,
            &Arc::from(create_seed_store(&config).unwrap()),
            &audit,
            &cli_super_admin(),
            &format!("{}#key-0", result.did),
            "test",
        )
        .await
        .expect("fetch key secret");
        let secret_bytes =
            multibase::decode(&secret.private_key_multibase).expect("decode secret multibase");
        let signing_key =
            ed25519_dalek::SigningKey::from_bytes(secret_bytes.1[2..].try_into().unwrap());
        let store_pub_mb = multibase::encode(
            multibase::Base::Base58Btc,
            [
                &[0xed, 0x01][..],
                &signing_key.verifying_key().to_bytes()[..],
            ]
            .concat(),
        );

        assert_eq!(
            store_pub_mb, preview_signing_pub,
            "the store must hold the key the caller's document names — if this \
             fails, the operation re-derived and allocated a second path index"
        );
    }

    /// The same DID, minted with no `[messaging]` configured, must advertise
    /// no DIDComm service — the VTA cannot serve a transport it has no
    /// mediator for, and advertising one fails two layers down.
    #[tokio::test]
    async fn non_interactive_did_doc_omits_didcomm_without_messaging() {
        let dir = tempfile::TempDir::new().expect("tempdir");
        let (_config, entry) = run_non_interactive_create(&dir, None).await;

        let has_didcomm = entry
            .get("state")
            .and_then(|s| s.get("service"))
            .and_then(|v| v.as_array())
            .is_some_and(|services| {
                services
                    .iter()
                    .any(|s| s.get("type").and_then(|t| t.as_str()) == Some("DIDCommMessaging"))
            });
        assert!(
            !has_didcomm,
            "no [messaging] configured, so nothing should advertise DIDComm"
        );
    }
}