vta-service 0.3.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
// CLI-only modules (not part of the library)
mod acl_cli;
mod did_key;
#[cfg(feature = "setup")]
mod did_webvh;
mod import_did;
mod keys_cli;
#[cfg(feature = "setup")]
mod setup;
#[cfg(feature = "webvh")]
mod webvh_cli;

// Re-export library modules for use by CLI commands
use vta_service::*;

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64;
use clap::{Parser, Subcommand};
use config::AppConfig;
use ed25519_dalek::SigningKey;
use ed25519_dalek_bip32::{DerivationPath, ExtendedSigningKey};
use keys::seed_store::create_seed_store;
use keys::seeds::load_seed_bytes;
use multibase::Base;
use std::path::PathBuf;
use std::sync::Arc;

// There must be a valid mix of transports for the VTA Service
// The following checks if a valid set of features is enabled at compile time and produces a
// helpful error message if not.
#[cfg(not(any(feature = "rest", feature = "didcomm")))]
compile_error!("At least one of 'rest' or 'didcomm' must be enabled.");

#[derive(Parser)]
#[command(name = "vta", about = "Verifiable Trust Agent", version)]
struct Cli {
    /// Path to the configuration file
    #[arg(short, long, global = true)]
    config: Option<PathBuf>,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Run the interactive setup wizard
    Setup,
    /// Bootstrap the first admin and seal the VTA against offline CLI modifications.
    ///
    /// This is a ONE-TIME operation. After sealing, all CLI commands that modify
    /// state (ACL, keys, import, export) are disabled. Management is only possible
    /// via the authenticated REST API or DIDComm.
    BootstrapAdmin {
        /// DID to grant super admin access (must be a DID you control)
        #[arg(long)]
        did: String,
        /// Human-readable label for the admin ACL entry
        #[arg(long)]
        label: Option<String>,
    },
    /// Unseal the VTA — re-enables offline CLI commands (emergency recovery).
    ///
    /// Requires proof of super admin key ownership via challenge-response:
    /// the VTA generates a random challenge, you sign it with your admin
    /// private key using `pnm auth sign-challenge`, and paste the signature.
    Unseal,
    /// Export admin DID and credential (blocked when sealed)
    ExportAdmin,
    /// Show VTA status and statistics
    Status,
    /// Create a did:key in a context (offline, no server required)
    CreateDidKey {
        /// Target context ID
        #[arg(long)]
        context: String,
        /// Also create an ACL entry with Admin role for the new DID
        #[arg(long)]
        admin: bool,
        /// Human-readable label for the key record and ACL entry
        #[arg(long)]
        label: Option<String>,
    },
    /// Create a did:webvh DID for a context (interactive wizard, no server required)
    CreateDidWebvh {
        /// Target context ID
        #[arg(long)]
        context: String,
        /// Human-readable label prefix for key records (default: context id)
        #[arg(long)]
        label: Option<String>,
    },
    /// Import an external DID and create an ACL entry (offline, no server required)
    ImportDid {
        /// The DID to import
        #[arg(long)]
        did: String,
        /// Role to assign (admin, initiator, application, reader)
        #[arg(long)]
        role: Option<String>,
        /// Human-readable label for the ACL entry
        #[arg(long)]
        label: Option<String>,
        /// Restrict to specific context(s); omit for unrestricted access
        #[arg(long)]
        context: Vec<String>,
    },
    /// Manage Access Control List entries (offline, no server required)
    Acl {
        #[command(subcommand)]
        command: AclCommands,
    },
    /// Manage keys (offline, no server required)
    Keys {
        #[command(subcommand)]
        command: KeyCliCommands,
    },
    /// Manage WebVH servers and DIDs (offline, no server required)
    #[cfg(feature = "webvh")]
    Webvh {
        #[command(subcommand)]
        command: WebvhCommands,
    },
}

#[derive(Subcommand)]
enum KeyCliCommands {
    /// List keys
    List {
        /// Filter by context ID
        #[arg(long)]
        context: Option<String>,
        /// Filter by status (active or revoked)
        #[arg(long)]
        status: Option<String>,
    },
    /// Export secret key material for one or more keys
    Secrets {
        /// Key IDs to export (omit to export all active keys in --context)
        key_ids: Vec<String>,
        /// Export all active keys in this context
        #[arg(long)]
        context: Option<String>,
    },
    /// List seed generations and their status
    Seeds,
    /// Rotate to a new master seed (retires the current seed)
    RotateSeed {
        /// BIP-39 mnemonic for the new seed (generates random if omitted)
        #[arg(long)]
        mnemonic: Option<String>,
    },
}

#[cfg(feature = "webvh")]
#[derive(Subcommand)]
enum WebvhCommands {
    /// Add a WebVH server
    AddServer {
        /// Server identifier
        #[arg(long)]
        id: String,
        /// Server DID (must resolve to a DID document with a WebVHHostingService endpoint)
        #[arg(long)]
        did: String,
        /// Human-readable label
        #[arg(long)]
        label: Option<String>,
    },
    /// List configured WebVH servers
    ListServers,
    /// Update a WebVH server
    UpdateServer {
        /// Server identifier to update
        id: String,
        /// New label (empty string to clear)
        #[arg(long)]
        label: Option<String>,
    },
    /// Remove a WebVH server
    RemoveServer {
        /// Server identifier to remove
        id: String,
    },
    /// Create a did:webvh DID and publish to a WebVH server
    CreateDid {
        /// Target context ID
        #[arg(long)]
        context: String,
        /// WebVH server ID
        #[arg(long)]
        server: String,
        /// Optional path on the server (server allocates if omitted)
        #[arg(long)]
        path: Option<String>,
        /// Human-readable label for the DID and key records
        #[arg(long)]
        label: Option<String>,
        /// Make the DID portable (default: true)
        #[arg(long, default_value_t = true)]
        portable: bool,
        /// Add mediator DIDComm service endpoint
        #[arg(long)]
        mediator_service: bool,
        /// Additional services as JSON array
        #[arg(long)]
        services: Option<String>,
        /// Number of pre-rotation keys to generate
        #[arg(long)]
        pre_rotation: Option<u32>,
    },
    /// List WebVH DIDs
    ListDids {
        /// Filter by context ID
        #[arg(long)]
        context: Option<String>,
        /// Filter by server ID
        #[arg(long)]
        server: Option<String>,
    },
    /// Delete a WebVH DID
    DeleteDid {
        /// The DID to delete
        did: String,
    },
}

#[derive(Subcommand)]
enum AclCommands {
    /// List all ACL entries
    List {
        /// Filter by context
        #[arg(long)]
        context: Option<String>,
        /// Filter by role (admin, initiator, application, reader)
        #[arg(long)]
        role: Option<String>,
    },
    /// Show details of a single ACL entry
    Get {
        /// The DID to look up
        did: String,
    },
    /// Update an existing ACL entry
    Update {
        /// The DID to update
        did: String,
        /// New role (admin, initiator, application, reader)
        #[arg(long)]
        role: Option<String>,
        /// New label (empty string to clear)
        #[arg(long)]
        label: Option<String>,
        /// New context list (comma-separated; omit flag to keep unchanged)
        #[arg(long, value_delimiter = ',')]
        contexts: Option<Vec<String>>,
    },
    /// Delete an ACL entry
    Delete {
        /// The DID to delete
        did: String,
        /// Skip confirmation prompt
        #[arg(short, long)]
        yes: bool,
    },
}

#[tokio::main]
async fn main() {
    let cli = Cli::parse();

    print_banner();

    match cli.command {
        Some(Commands::Setup) => {
            #[cfg(feature = "setup")]
            {
                if let Err(e) = setup::run_setup_wizard(cli.config).await {
                    eprintln!("Setup failed: {e}");
                    std::process::exit(1);
                }
            }
            #[cfg(not(feature = "setup"))]
            {
                eprintln!("Setup wizard not available (compiled without 'setup' feature)");
                std::process::exit(1);
            }
        }
        Some(Commands::BootstrapAdmin { did, label }) => {
            if let Err(e) = run_bootstrap_admin(cli.config, did, label).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::Unseal) => {
            let config = match AppConfig::load(cli.config) {
                Ok(c) => c,
                Err(e) => {
                    eprintln!("Error: {e}");
                    std::process::exit(1);
                }
            };
            let store = store::Store::open(&config.store).expect("failed to open store");
            if let Err(e) = seal::run_unseal_challenge(&store).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::ExportAdmin) => {
            // SEALED CHECK: export-admin leaks private keys
            check_seal(&cli.config).await;
            if let Err(e) = export_admin(cli.config).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::Status) => {
            if let Ok(config) = AppConfig::load(cli.config.clone()) {
                init_tracing(&config);
            }
            if let Err(e) = status::run_status(cli.config).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::CreateDidKey {
            context,
            admin,
            label,
        }) => {
            // SEALED CHECK: creates keys and optionally admin ACL entries
            check_seal(&cli.config).await;
            let args = did_key::CreateDidKeyArgs {
                config_path: cli.config,
                context,
                admin,
                label,
            };
            if let Err(e) = did_key::run_create_did_key(args).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::CreateDidWebvh { context, label }) => {
            // SEALED CHECK: creates keys and DIDs
            check_seal(&cli.config).await;
            #[cfg(feature = "setup")]
            {
                let args = did_webvh::CreateDidWebvhArgs {
                    config_path: cli.config,
                    context,
                    label,
                };
                if let Err(e) = did_webvh::run_create_did_webvh(args).await {
                    eprintln!("Error: {e}");
                    std::process::exit(1);
                }
            }
            #[cfg(not(feature = "setup"))]
            {
                let _ = (context, label);
                eprintln!("create-did-webvh is not available (compiled without 'setup' feature)");
                std::process::exit(1);
            }
        }
        Some(Commands::ImportDid {
            did,
            role,
            label,
            context,
        }) => {
            // SEALED CHECK: imports DIDs with arbitrary roles
            check_seal(&cli.config).await;
            let args = import_did::ImportDidArgs {
                config_path: cli.config,
                did,
                role,
                label,
                context,
            };
            if let Err(e) = import_did::run_import_did(args).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::Keys { command }) => {
            // SEALED CHECK: secrets export and seed rotation
            match &command {
                KeyCliCommands::List { .. } | KeyCliCommands::Seeds => {}
                KeyCliCommands::Secrets { .. } | KeyCliCommands::RotateSeed { .. } => {
                    check_seal(&cli.config).await;
                }
            }
            let result = match command {
                KeyCliCommands::List { context, status } => {
                    keys_cli::run_keys_list(cli.config, context, status).await
                }
                KeyCliCommands::Secrets { key_ids, context } => {
                    keys_cli::run_keys_secrets(cli.config, key_ids, context).await
                }
                KeyCliCommands::Seeds => keys_cli::run_keys_seeds_list(cli.config).await,
                KeyCliCommands::RotateSeed { mnemonic } => {
                    keys_cli::run_rotate_seed(cli.config, mnemonic).await
                }
            };
            if let Err(e) = result {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::Acl { command }) => {
            // SEALED CHECK: update and delete modify ACL
            match &command {
                AclCommands::List { .. } | AclCommands::Get { .. } => {}
                AclCommands::Update { .. } | AclCommands::Delete { .. } => {
                    check_seal(&cli.config).await;
                }
            }
            let result = match command {
                AclCommands::List { context, role } => {
                    acl_cli::run_acl_list(cli.config, context, role).await
                }
                AclCommands::Get { did } => acl_cli::run_acl_get(cli.config, did).await,
                AclCommands::Update {
                    did,
                    role,
                    label,
                    contexts,
                } => acl_cli::run_acl_update(cli.config, did, role, label, contexts).await,
                AclCommands::Delete { did, yes } => {
                    acl_cli::run_acl_delete(cli.config, did, yes).await
                }
            };
            if let Err(e) = result {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        #[cfg(feature = "webvh")]
        Some(Commands::Webvh { command }) => {
            // SEALED CHECK: webvh commands modify servers and DIDs
            match &command {
                WebvhCommands::ListServers | WebvhCommands::ListDids { .. } => {}
                _ => check_seal(&cli.config).await,
            }
            let result = match command {
                WebvhCommands::AddServer { id, did, label } => {
                    webvh_cli::run_add_server(cli.config, id, did, label).await
                }
                WebvhCommands::ListServers => webvh_cli::run_list_servers(cli.config).await,
                WebvhCommands::UpdateServer { id, label } => {
                    webvh_cli::run_update_server(cli.config, id, label).await
                }
                WebvhCommands::RemoveServer { id } => {
                    webvh_cli::run_remove_server(cli.config, id).await
                }
                WebvhCommands::CreateDid {
                    context,
                    server,
                    path,
                    label,
                    portable,
                    mediator_service,
                    services,
                    pre_rotation,
                } => {
                    webvh_cli::run_create_did(
                        cli.config,
                        context,
                        server,
                        path,
                        label,
                        portable,
                        mediator_service,
                        services,
                        pre_rotation,
                    )
                    .await
                }
                WebvhCommands::ListDids { context, server } => {
                    webvh_cli::run_list_dids(cli.config, context, server).await
                }
                WebvhCommands::DeleteDid { did } => {
                    webvh_cli::run_delete_did(cli.config, did).await
                }
            };
            if let Err(e) = result {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        None => {
            let config = match AppConfig::load(cli.config) {
                Ok(config) => config,
                Err(e) => {
                    eprintln!("Error: {e}");
                    eprintln!();
                    eprintln!("To set up a new VTA instance, run:");
                    eprintln!("  vta setup");
                    eprintln!();
                    eprintln!("Or specify a config file:");
                    eprintln!("  vta --config <path>");
                    std::process::exit(1);
                }
            };

            init_tracing(&config);

            let store = store::Store::open(&config.store).expect("failed to open store");
            let seed_store: Arc<dyn keys::seed_store::SeedStore> =
                Arc::from(create_seed_store(&config).expect("failed to create seed store"));

            if let Err(e) = server::run(
                config, store, seed_store, None, // no storage encryption (non-TEE mode)
                None, // no TEE context (use vta-enclave for TEE mode)
            )
            .await
            {
                tracing::error!("server error: {e}");
                std::process::exit(1);
            }
        }
    }
}

fn print_banner() {
    let cyan = "\x1b[36m";
    let magenta = "\x1b[35m";
    let yellow = "\x1b[33m";
    let dim = "\x1b[2m";
    let reset = "\x1b[0m";

    eprintln!(
        r#"
{cyan} ██╗   ██╗{magenta}████████╗{yellow} █████╗{reset}
{cyan} ██║   ██║{magenta}╚══██╔══╝{yellow}██╔══██╗{reset}
{cyan} ██║   ██║{magenta}   ██║   {yellow}███████║{reset}
{cyan} ╚██╗ ██╔╝{magenta}   ██║   {yellow}██╔══██║{reset}
{cyan}  ╚████╔╝ {magenta}   ██║   {yellow}██║  ██║{reset}
{cyan}   ╚═══╝  {magenta}   ╚═╝   {yellow}╚═╝  ╚═╝{reset}
{dim}  Verifiable Trust Agent v{version}{reset}
"#,
        version = env!("CARGO_PKG_VERSION"),
    );
}

/// Check if the VTA is sealed; exit with an error if so.
/// Called before any CLI command that modifies state.
async fn check_seal(config_path: &Option<PathBuf>) {
    let config = match AppConfig::load(config_path.clone()) {
        Ok(c) => c,
        Err(_) => return, // Config not loadable — let the actual command handle it
    };
    let store = match store::Store::open(&config.store) {
        Ok(s) => s,
        Err(_) => return, // Store not openable — let the actual command handle it
    };
    if let Err(e) = seal::require_unsealed(&store).await {
        eprintln!("Error: {e}");
        std::process::exit(1);
    }
}

/// Bootstrap the first super admin and seal the VTA.
async fn run_bootstrap_admin(
    config_path: Option<PathBuf>,
    did: String,
    label: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let store = store::Store::open(&config.store)?;
    let acl_ks = store.keyspace("acl")?;

    // Check if already sealed
    if let Some(existing) = seal::get_seal(&acl_ks).await? {
        eprintln!(
            "VTA is already sealed (by {} on {}).",
            existing.sealed_by,
            existing.sealed_at.format("%Y-%m-%d %H:%M:%S UTC")
        );
        eprintln!("Cannot bootstrap again. Manage admins via the REST API or DIDComm.");
        std::process::exit(1);
    }

    // Check no existing super admins
    let entries = acl::list_acl_entries(&acl_ks).await?;
    let existing_super_admins: Vec<_> = entries
        .iter()
        .filter(|e| e.role == acl::Role::Admin && e.allowed_contexts.is_empty())
        .collect();

    if !existing_super_admins.is_empty() {
        eprintln!(
            "WARNING: {} existing super admin(s) found:",
            existing_super_admins.len()
        );
        for admin in &existing_super_admins {
            eprintln!(
                "  - {} ({})",
                admin.did,
                admin.label.as_deref().unwrap_or("no label")
            );
        }
        eprintln!();
        eprintln!("Proceeding will add another super admin and seal the VTA.");
        eprintln!("Press Ctrl+C to cancel, or Enter to continue...");
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf)?;
    }

    // Create the super admin ACL entry
    let entry = acl::AclEntry {
        did: did.clone(),
        role: acl::Role::Admin,
        label,
        allowed_contexts: vec![], // Empty = super admin
        created_at: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs(),
        created_by: "cli:bootstrap-admin".into(),
    };
    acl::store_acl_entry(&acl_ks, &entry).await?;

    // Seal the VTA
    let seal_record = seal::seal(&acl_ks, &did).await?;

    store.persist().await?;

    eprintln!();
    eprintln!("=== VTA Bootstrapped and Sealed ===");
    eprintln!();
    eprintln!("  Admin DID: {}", did);
    eprintln!(
        "  Sealed at: {}",
        seal_record.sealed_at.format("%Y-%m-%d %H:%M:%S UTC")
    );
    eprintln!();
    eprintln!("  The VTA is now sealed. Offline CLI commands that modify state are disabled.");
    eprintln!("  All management must go through the authenticated REST API or DIDComm.");
    eprintln!();
    eprintln!("  To start the VTA server:");
    eprintln!("    vta --config config.toml");
    eprintln!();

    Ok(())
}

// init_tracing is now in vta_service::init_tracing (lib.rs)

async fn export_admin(config_path: Option<PathBuf>) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let store = store::Store::open(&config.store)?;
    let acl_ks = store.keyspace("acl")?;
    let keys_ks = store.keyspace("keys")?;
    let seed_store = create_seed_store(&config)?;

    let vta_did = config.vta_did.as_deref().unwrap_or("(not set)");

    // Find admin ACL entries
    let entries = acl::list_acl_entries(&acl_ks).await?;
    let admins: Vec<_> = entries
        .iter()
        .filter(|e| e.role == acl::Role::Admin)
        .collect();

    if admins.is_empty() {
        eprintln!("No admin entries found in ACL.");
        return Ok(());
    }

    eprintln!("VTA DID: {vta_did}");
    if let Some(msg) = &config.messaging {
        eprintln!("Mediator DID: {}", msg.mediator_did);
    }
    eprintln!();

    for admin in &admins {
        eprintln!("Admin DID: {}", admin.did);
        if let Some(label) = &admin.label {
            eprintln!("  Label: {label}");
        }

        // For did:key admins, reconstruct the credential
        if admin.did.starts_with("did:key:") {
            match reconstruct_credential(&*seed_store, &admin.did, vta_did, &keys_ks).await {
                Ok(credential) => {
                    eprintln!();
                    eprintln!("  Credential:");
                    eprintln!("  {credential}");
                }
                Err(e) => {
                    eprintln!("  Could not reconstruct credential: {e}");
                }
            }
        }
        eprintln!();
    }

    Ok(())
}

/// Re-derive the admin private key from BIP-32 seed and build the credential bundle.
async fn reconstruct_credential(
    seed_store: &dyn keys::seed_store::SeedStore,
    admin_did: &str,
    vta_did: &str,
    keys_ks: &store::KeyspaceHandle,
) -> Result<String, Box<dyn std::error::Error>> {
    // The did:key fragment is {did}#{multibase_pubkey}
    let multibase_pubkey = admin_did.strip_prefix("did:key:").unwrap();
    let key_id = format!("{admin_did}#{multibase_pubkey}");

    // Look up the key record to get the derivation path
    let record: keys::KeyRecord = keys_ks
        .get(keys::store_key(&key_id))
        .await?
        .ok_or("admin key record not found in store")?;

    // Load seed for this key's generation
    let seed = load_seed_bytes(keys_ks, seed_store, record.seed_id).await?;

    // Re-derive the private key
    let root = ExtendedSigningKey::from_seed(&seed)
        .map_err(|e| format!("failed to create BIP-32 root key: {e}"))?;
    let derivation_path: DerivationPath = record
        .derivation_path
        .parse()
        .map_err(|e| format!("invalid derivation path: {e}"))?;
    let derived = root
        .derive(&derivation_path)
        .map_err(|e| format!("key derivation failed: {e}"))?;

    let signing_key = SigningKey::from_bytes(derived.signing_key.as_bytes());
    let private_key_multibase = multibase::encode(Base::Base58Btc, signing_key.as_bytes());

    let bundle = serde_json::json!({
        "did": admin_did,
        "privateKeyMultibase": private_key_multibase,
        "vtaDid": vta_did,
    });
    let bundle_json = serde_json::to_string(&bundle)?;
    Ok(BASE64.encode(bundle_json.as_bytes()))
}