did-hosting-control 0.9.0

DID Hosting Control Plane — Unified management UI and service registry
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
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
//! Interactive setup wizard for generating a control plane config.toml.
//!
//! Three entry points: `run_setup` (online, talks to the VTA), and the
//! pair `run_setup_offline_prepare` / `run_setup_offline_complete` for
//! the air-gapped case where the VTA is reachable only by ferrying
//! a sealed bootstrap bundle.

use crate::acl::{AclEntry, Role};
use crate::auth::session::now_epoch;
use crate::config::{
    AppConfig, AuthConfig, FeaturesConfig, HostingConfig, LogConfig, LogFormat, RegistryConfig,
    SecretsConfig, ServerConfig, StoreConfig, TransportSelection, VtaConfig,
};
use crate::error::AppError;
use crate::secret_store::{ServerSecrets, create_secret_store};
use crate::store::Store;
use dialoguer::{Confirm, Input, Select};
use did_hosting_common::server::operator_messages::WebvhControlMessages;
use did_hosting_common::server::setup_prompts;
use did_hosting_common::server::store::KS_ACL;
use did_hosting_common::server::vta_setup;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use vta_sdk::provision_client::{EphemeralSetupKey, OperatorMessages};

/// Phase 1 of the headless setup flow: mint an ephemeral did:key,
/// persist it (chmod 0600 on Unix) under `out_path`, and print the
/// `pnm contexts create` command the operator must run before phase 2.
pub async fn run_setup_phase1(out_path: &Path, context_id: &str) -> Result<(), AppError> {
    use std::io::stderr;
    let messages = WebvhControlMessages;
    let finalise = format!(
        "did-hosting-control setup --setup-key-file {}",
        out_path.display()
    );
    let mut writer = stderr();
    vta_sdk::provision_client::driver::run_phase1_init(
        &mut writer,
        out_path,
        context_id,
        &messages,
        Some(&finalise),
    )
    .await
    .map_err(|e| AppError::Config(format!("phase 1 failed: {e}")))?;
    Ok(())
}

pub async fn run_setup(preloaded_setup_key_file: Option<PathBuf>) -> Result<(), AppError> {
    eprintln!();
    eprintln!("  DID Hosting Control Plane — Setup Wizard");
    eprintln!("  -----------------------------------");
    eprintln!();

    if preloaded_setup_key_file.is_none() {
        match prompt_vta_mode()? {
            VtaMode::Online => {}
            VtaMode::OfflineStart => {
                let (request, state) = prompt_offline_prepare_paths()?;
                return run_setup_offline_prepare(request, state).await;
            }
            VtaMode::OfflineComplete => {
                let (bundle, digest, state) = prompt_offline_complete_inputs()?;
                return run_setup_offline_complete(bundle, digest, state).await;
            }
            VtaMode::SelfManaged => {
                return Err(AppError::Config(SELF_MANAGED_DAEMON_ONLY.into()));
            }
        }
    }

    // 1. Output path
    eprintln!("  The configuration file stores all settings for the control plane.");
    eprintln!("  You can edit it later or re-run setup to regenerate it.");
    eprintln!();
    let output_path: String = Input::new()
        .with_prompt("Config file output path")
        .default("config.toml".into())
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let output_path = PathBuf::from(output_path);

    // 2. VTA online provision: mint ephemeral did:key, print PNM
    //    `contexts create` command, drive run_provision with the
    //    `did-hosting-control` template. Headless phase 2 supplies a
    //    pre-loaded setup key.
    let messages: Arc<dyn OperatorMessages> = Arc::new(WebvhControlMessages);
    let preloaded_setup_key = match preloaded_setup_key_file.as_deref() {
        Some(path) => Some(
            EphemeralSetupKey::load_from(path)
                .map_err(|e| AppError::Config(format!("load setup key: {e}")))?,
        ),
        None => None,
    };

    // DID hosting URL must be collected BEFORE the VTA round-trip because
    // upstream `ProvisionAsk::did_host_http_didcomm` embeds it as the
    // `WebVHHosting` service endpoint in the resulting DID document.
    eprintln!();
    eprintln!("  The DID hosting URL is where your did-hosting-server serves DID documents.");
    eprintln!("  The control plane's DID will be published at <url>/<path>/did.jsonl.");
    eprintln!();
    let did_hosting_url =
        setup_prompts::prompt_long_value("DID hosting URL (e.g. https://did.example.com)", false)
            .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let did_hosting_url = did_hosting_url.trim_end_matches('/').to_string();

    // DID path must be collected BEFORE the VTA round-trip: the VTA derives
    // the minted DID's path segment from the hosting URL it receives, so the
    // path is folded into that URL (by `build_webvh_provision_ask`) before
    // the DID is minted. Collected after, it could not affect the
    // already-minted DID and the DID would fall back to the `.well-known` root.
    let did_path: String = Input::new()
        .with_prompt("DID path on the server")
        .default("services/control".into())
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;

    // Transport selection must be collected BEFORE the VTA round-trip: it
    // selects the DID template (TSP-only advertises only `TSPTransport`), so
    // it has to be known when the DID is minted. Control always has a
    // mediator, so the prompt is unconditional.
    let transport = setup_prompts::prompt_transport_selection()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let (didcomm, tsp) = transport.as_flags();

    let (mediator_did, outcome) = run_online_provision(
        messages,
        preloaded_setup_key,
        &did_hosting_url,
        &did_path,
        transport,
    )
    .await
    .map_err(|e| AppError::Config(format!("VTA provision-integration failed: {e}")))?;

    // 5. Persist DID log entry (if the template emitted one) so the
    //    operator can publish it on the webvh hosting server.
    if let Some(ref log_entry) = outcome.did_log_entry {
        let log_file = PathBuf::from("control-did.jsonl");
        let default_log_path = log_file.display().to_string();
        let log_path: String = Input::new()
            .with_prompt("DID log entry output file")
            .default(default_log_path)
            .interact_text()
            .map_err(|e| AppError::Config(format!("input error: {e}")))?;

        vta_setup::write_log_entry_file(log_entry, &PathBuf::from(&log_path))?;
        eprintln!("  DID log entry written to {log_path}");

        eprintln!();
        eprintln!("  DID Log Entry:");
        eprintln!("  ---");
        for line in log_entry.lines() {
            eprintln!("  {line}");
        }
        eprintln!("  ---");
    }

    // 7. Public URL (for WebAuthn/passkey)
    eprintln!();
    eprintln!("  The public URL is used for WebAuthn/passkey authentication.");
    eprintln!("  It must match the URL users will access in their browser.");
    eprintln!();
    let public_url: String = Input::new()
        .with_prompt("Public URL")
        .default("http://localhost:8532".into())
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let public_url = if public_url.is_empty() {
        None
    } else {
        Some(public_url)
    };

    // 8. Host & Port
    eprintln!();
    let host = setup_prompts::prompt_listen_host("0.0.0.0")
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let port = setup_prompts::prompt_listen_port(8532)
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;

    // 9. Log level & format
    eprintln!();
    let log_levels = ["info", "debug", "warn", "error", "trace"];
    let log_level_idx = Select::new()
        .with_prompt("Log level")
        .items(log_levels)
        .default(0)
        .interact()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let log_level = log_levels[log_level_idx].to_string();

    let log_format = setup_prompts::prompt_log_format()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;

    // 10. Data directory
    eprintln!();
    let data_dir: String = Input::new()
        .with_prompt("Data directory")
        .default("data/did-hosting-control".into())
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;

    // 11. Secrets backend
    eprintln!();
    let secrets_config = did_hosting_common::server::secret_store::wizard::prompt_secrets_backend(
        "did-hosting-control-secrets",
        "webvh",
    )
    .await
    .map_err(|e| AppError::Config(e.to_string()))?;

    // 12. JWT signing key (always generated)
    let jwt_signing_key = vta_setup::generate_ed25519_multibase();
    eprintln!("  Generated JWT signing key.");

    // 13. Store secrets
    let server_secrets = ServerSecrets {
        signing_key: outcome.integration_signing_key_mb.clone(),
        key_agreement_key: outcome.integration_ka_key_mb.clone(),
        jwt_signing_key,
        vta_credential: Some(outcome.vta_credential_b64.clone()),
        retired: Vec::new(),
    };

    // Transport selection was collected before the VTA round-trip (it
    // selects the DID template); `didcomm` / `tsp` here are that choice's
    // flags, gating which listener protocols run.
    // 15. Build and write config
    let config = AppConfig {
        features: FeaturesConfig {
            didcomm,
            tsp,
            rest_api: true,
            ..Default::default()
        },
        server_did: Some(outcome.integration_did.clone()),
        mediator_did,
        public_url,
        did_hosting_url: Some(did_hosting_url),
        server: ServerConfig {
            host,
            port,
            trusted_proxies: Vec::new(),
            trusted_proxy_cidrs: Vec::new(),
        },
        log: LogConfig {
            level: log_level,
            format: log_format,
        },
        store: StoreConfig {
            data_dir: PathBuf::from(&data_dir),
            ..StoreConfig::default()
        },
        fjall: Default::default(),
        auth: AuthConfig::default(),
        secrets: secrets_config,
        vta: VtaConfig {
            url: outcome.vta_url.clone(),
            did: Some(outcome.vta_did.clone()),
            context_id: None,
        },
        registry: RegistryConfig::default(),
        trust_tasks: Default::default(),
        hosting: HostingConfig::default(),
        identity: Default::default(),
        config_path: output_path.clone(),
    };

    let toml_str = toml::to_string_pretty(&config)
        .map_err(|e| AppError::Config(format!("failed to serialize config: {e}")))?;
    std::fs::write(&output_path, &toml_str)?;
    eprintln!("  Configuration written to {}", output_path.display());

    let secret_store = create_secret_store(&config)?;
    secret_store.set(&server_secrets).await?;
    eprintln!("  Secrets stored.");

    // 15. Admin ACL bootstrap
    eprintln!();
    eprintln!("  The Access Control List (ACL) determines who can authenticate");
    eprintln!("  with this service. Without at least one admin entry, all");
    eprintln!("  authenticated API calls will be rejected.");
    eprintln!();
    eprintln!("  For the control plane, the did-hosting-server's DID must be added");
    eprintln!("  as an admin so it can register itself on startup. You can do");
    eprintln!("  this now if you know the server DID, or later with:");
    eprintln!("    did-hosting-control add-acl --did <server-did> --role admin");
    eprintln!();
    eprintln!("  You may also want an operator admin (your own DID or a");
    eprintln!("  generated did:key) for manual management.");
    eprintln!();
    let admin_options = &[
        "Enter an existing DID (e.g. server DID or operator DID)",
        "Generate a new did:key identity for the operator",
        "Skip (add later with did-hosting-control add-acl)",
    ];
    let admin_idx = Select::new()
        .with_prompt("Admin ACL entry")
        .items(admin_options)
        .default(0)
        .interact()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;

    if admin_idx <= 1 {
        let admin_did = if admin_idx == 0 {
            let did: String = Input::new()
                .with_prompt("Admin DID")
                .interact_text()
                .map_err(|e| AppError::Config(format!("input error: {e}")))?;
            did
        } else {
            let (did, sk) = vta_setup::generate_admin_did_key();
            eprintln!("  Generated admin did:key: {did}");
            eprintln!("  Private key (save this!): {sk}");
            did
        };

        let store = Store::open(&config.store).await?;
        let acl_ks = store.keyspace(KS_ACL)?;

        let entry = AclEntry {
            did: admin_did.clone(),
            role: Role::Admin,
            label: Some("Setup wizard admin".into()),
            created_at: now_epoch(),
            max_total_size: None,
            max_did_count: None,

            domains: did_hosting_common::server::domain::DomainScope::All,
        };

        crate::acl::store_acl_entry(&acl_ks, &entry).await?;
        store.persist().await?;

        eprintln!("  Admin ACL entry added for {admin_did}");
    }

    // 16. Summary
    eprintln!();
    eprintln!("  Setup complete!");
    eprintln!();
    eprintln!("  Control DID: {}", outcome.integration_did);
    eprintln!("  Admin DID:   {}", outcome.admin_did);
    eprintln!();
    eprintln!("  Next steps:");
    eprintln!("    1. Set up did-hosting-server (if not already done)");
    eprintln!("    2. Import this DID on the server:");
    eprintln!(
        "       did-hosting-server bootstrap-did --path {} --did-log control-did.jsonl",
        did_path
    );
    eprintln!("    3. Start the control plane:");
    eprintln!(
        "       did-hosting-control --config {}",
        output_path.display()
    );
    eprintln!();

    Ok(())
}

/// Choice of VTA reachability for the unified `setup` wizard.
enum VtaMode {
    Online,
    OfflineStart,
    OfflineComplete,
    /// Selected only to produce a clear "daemon-only" error — did-hosting-control
    /// has no self-managed implementation in v1.
    SelfManaged,
}

use did_hosting_common::server::vta_setup::SELF_MANAGED_DAEMON_ONLY;

fn prompt_vta_mode() -> Result<VtaMode, AppError> {
    let items = [
        "Online — VTA reachable from this host",
        "Offline — start a new sealed-bundle bootstrap (phase 1)",
        "Offline — complete a pending sealed-bundle bootstrap (phase 2)",
        "Self-managed (no VTA — daemon-only mode, will exit with error here)",
    ];
    let idx = Select::new()
        .with_prompt("How will the control plane reach its VTA?")
        .items(items)
        .default(0)
        .interact()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    Ok(match idx {
        0 => VtaMode::Online,
        1 => VtaMode::OfflineStart,
        2 => VtaMode::OfflineComplete,
        _ => VtaMode::SelfManaged,
    })
}

fn prompt_offline_prepare_paths() -> Result<(PathBuf, PathBuf), AppError> {
    let request: String = Input::new()
        .with_prompt("Bootstrap request file path")
        .default("bootstrap-request.json".into())
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let state: String = Input::new()
        .with_prompt("Pending state file path")
        .default("setup-offline-state.toml".into())
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    Ok((PathBuf::from(request), PathBuf::from(state)))
}

fn prompt_offline_complete_inputs() -> Result<(PathBuf, String, PathBuf), AppError> {
    let bundle: String = Input::new()
        .with_prompt("ASCII-armored sealed bundle path")
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let digest: String = Input::new()
        .with_prompt("Expected SHA-256 digest (lowercase hex)")
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let state: String = Input::new()
        .with_prompt("Pending state file path (from phase 1)")
        .default("setup-offline-state.toml".into())
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    Ok((PathBuf::from(bundle), digest, PathBuf::from(state)))
}

/// Run the online VTA provision-integration round-trip:
/// prompt for VTA DID + context, resolve the VTA's mediator (since the
/// `did-hosting-control` template requires `MEDIATOR_DID`), let the operator
/// confirm or override it, mint an ephemeral did:key, print the
/// operator's `pnm contexts create` command, wait for confirmation,
/// then drive `vta_sdk::provision_client::run_provision`.
///
/// Returns the chosen mediator DID alongside the provision outcome —
/// the caller persists it as `config.mediator_did` so the runtime
/// DIDComm path uses the same mediator the DID document embeds.
async fn run_online_provision(
    messages: Arc<dyn OperatorMessages>,
    preloaded_setup_key: Option<EphemeralSetupKey>,
    origin: &str,
    did_path: &str,
    transport: TransportSelection,
) -> Result<(Option<String>, vta_setup::OnlineProvisionOutcome), Box<dyn std::error::Error>> {
    eprintln!();
    eprintln!("  Authenticating to the VTA.");
    eprintln!();
    let vta_did =
        setup_prompts::prompt_long_value("VTA DID (e.g. did:webvh:vta.example.com)", false)?;
    let context_id: String = Input::new()
        .with_prompt("Context ID")
        .default("webvh".to_string())
        .interact_text()?;

    // The did-hosting-control template needs a MEDIATOR_DID up-front (it
    // embeds a DIDComm service endpoint pointing at the mediator).
    eprintln!();
    eprintln!("  A DIDComm mediator routes encrypted messages to the control plane.");
    eprintln!("  The mediator DID is embedded in the control plane's DID document");
    eprintln!("  and reused at runtime for outbound DIDComm.");
    eprintln!();
    let vta_mediator = vta_setup::resolve_vta_mediator(&vta_did).await;
    let mut mediator_options: Vec<String> = Vec::new();
    if let Some(ref did) = vta_mediator {
        mediator_options.push(format!("Use VTA's mediator ({did})"));
    }
    mediator_options.push("Enter a custom mediator DID".into());
    let mediator_idx = Select::new()
        .with_prompt("DIDComm mediator")
        .items(&mediator_options)
        .default(0)
        .interact()?;
    let mediator_did: String = if mediator_options[mediator_idx].starts_with("Use VTA") {
        vta_mediator
            .clone()
            .expect("Use VTA option only present when discovered")
    } else {
        setup_prompts::prompt_long_value("Mediator DID", false)?
    };

    let setup_key = match preloaded_setup_key {
        Some(key) => {
            eprintln!();
            eprintln!("  Using pre-loaded setup DID: {}", key.did);
            key
        }
        None => {
            let key = EphemeralSetupKey::generate()?;
            eprintln!();
            eprintln!("  Ephemeral setup DID: {}", key.did);
            eprintln!();
            eprintln!("  Run this on a workstation with PNM authenticated to the VTA");
            eprintln!("  to create the context and grant the setup DID admin access:");
            eprintln!();
            eprintln!(
                "    {}",
                messages.pnm_admin_command_hint(&context_id, &key.did)
            );
            eprintln!();
            eprintln!("  --admin-expires defaults to 1h. The entry is promoted to");
            eprintln!("  permanent on first auth — this wizard does that for you.");
            eprintln!();

            let proceed = Confirm::new()
                .with_prompt("Has the context been created?")
                .default(true)
                .interact()?;
            if !proceed {
                return Err("setup cancelled before VTA round-trip".into());
            }
            key
        }
    };

    let shape = vta_setup::WebvhDidShape::Hosted {
        origin,
        did_path,
        mediator_did: Some(&mediator_did),
        transport,
        remote: None,
    };
    let ask = vta_setup::build_webvh_provision_ask(
        &context_id,
        &shape,
        Some(&format!("did-hosting-control setup — {context_id}")),
    );

    eprintln!();
    eprintln!("  Provisioning control plane DID via VTA...");
    eprintln!();

    let outcome = vta_setup::online_provision_setup(vta_setup::OnlineProvisionInputs {
        vta_did,
        context_id,
        ask,
        messages,
        setup_key,
    })
    .await?;

    Ok((Some(mediator_did), outcome))
}

// ---------------------------------------------------------------------------
// Offline setup wizard (air-gapped VTA)
//
// prepare = interactive prompts for everything the online wizard asks, minus
//     the VTA credential. Emits a `bootstrap-request.json` + ephemeral seed
//     and serialises the operator's choices to a TOML state file so the
//     follow-up `complete` invocation can finish setup without re-prompting.
//
// complete = loads the state, opens the sealed response bundle, persists the
//     DID + keys + config.toml exactly like the online wizard, and bootstraps
//     the admin ACL the operator picked earlier.
//
// The state file is plaintext (no secrets — the ephemeral seed lives in
// its own chmod-0600 file). Safe to hand between operators.
// ---------------------------------------------------------------------------

/// How the operator wants to bootstrap the admin ACL. Captured at
/// `prepare` time so `complete` can insert the entry without prompting.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "kind", content = "did", rename_all = "snake_case")]
enum AdminChoice {
    Did(String),
    Skip,
}

fn default_transport() -> String {
    TransportSelection::Both.as_str().to_string()
}

/// Everything the offline-prepare step captured, serialised as TOML.
#[derive(Debug, Clone, Deserialize, Serialize)]
struct PendingSetupState {
    config_output: PathBuf,
    did_hosting_url: String,
    did_path: String,
    mediator_did: Option<String>,
    /// Transport selection (`didcomm` / `tsp` / `both`) captured at prepare
    /// time. Only meaningful with a mediator; defaults to `both`.
    #[serde(default = "default_transport")]
    transport: String,
    did_log_output: PathBuf,
    public_url: Option<String>,
    host: String,
    port: u16,
    log_level: String,
    log_format: LogFormat,
    data_dir: String,
    secrets: SecretsConfig,
    admin: AdminChoice,
}

/// Interactive offline-prepare: prompt for everything except VTA
/// credentials, write a bootstrap request file, persist the ephemeral
/// seed in the configured secrets backend, and serialise the choices
/// to a state TOML.
pub async fn run_setup_offline_prepare(
    request_out: PathBuf,
    state_out: PathBuf,
) -> Result<(), AppError> {
    eprintln!();
    eprintln!("  DID Hosting Control Plane — Offline Setup (step 1/2)");
    eprintln!("  -----------------------------------------------");
    eprintln!();
    eprintln!("  This step captures all local settings and writes a sealed-bundle");
    eprintln!("  bootstrap request. No VTA connection is made. After the operator");
    eprintln!("  ferries the request to the VTA admin and receives a sealed reply,");
    eprintln!("  run `did-hosting-control setup-offline-complete` to finish.");
    eprintln!();

    let output_path: String = Input::new()
        .with_prompt("Config file output path")
        .default("config.toml".into())
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let config_output = PathBuf::from(output_path);

    let did_hosting_url =
        setup_prompts::prompt_long_value("DID hosting URL (e.g. https://did.example.com)", false)
            .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let did_hosting_url = did_hosting_url.trim_end_matches('/').to_string();

    let did_path: String = Input::new()
        .with_prompt("DID path on the server")
        .default("services/control".into())
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;

    eprintln!();
    eprintln!("  VTA context the integration will live in. Embedded in the");
    eprintln!("  bootstrap request as `contextHint` so the VTA admin can run");
    eprintln!("  `vta bootstrap provision-integration` without `--context`.");
    eprintln!();
    let context_id: String = Input::new()
        .with_prompt("VTA context ID")
        .default("webvh".to_string())
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;

    eprintln!();
    eprintln!("  A DIDComm mediator routes encrypted messages to this service.");
    eprintln!("  In the offline flow we can't auto-discover the VTA's mediator,");
    eprintln!("  so enter the mediator DID manually or skip.");
    eprintln!();
    let mediator_raw = setup_prompts::prompt_long_value("Mediator DID (leave empty to skip)", true)
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let mediator_did = if mediator_raw.trim().is_empty() {
        None
    } else {
        Some(mediator_raw.trim().to_string())
    };

    // Transport selection only applies with a mediator (shared socket).
    let transport = if mediator_did.is_some() {
        setup_prompts::prompt_transport_selection()
            .map_err(|e| AppError::Config(format!("input error: {e}")))?
    } else {
        TransportSelection::Both
    };

    let did_log_output: String = Input::new()
        .with_prompt("DID log output file (written in step 2)")
        .default("control-did.jsonl".into())
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let did_log_output = PathBuf::from(did_log_output);

    let public_url: String = Input::new()
        .with_prompt("Public URL")
        .default("http://localhost:8532".into())
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let public_url = if public_url.is_empty() {
        None
    } else {
        Some(public_url)
    };

    let host = setup_prompts::prompt_listen_host("0.0.0.0")
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let port = setup_prompts::prompt_listen_port(8532)
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;

    let log_levels = ["info", "debug", "warn", "error", "trace"];
    let log_level_idx = Select::new()
        .with_prompt("Log level")
        .items(log_levels)
        .default(0)
        .interact()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;
    let log_level = log_levels[log_level_idx].to_string();

    let log_format = setup_prompts::prompt_log_format()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;

    let data_dir: String = Input::new()
        .with_prompt("Data directory")
        .default("data/did-hosting-control".into())
        .interact_text()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;

    let secrets = did_hosting_common::server::secret_store::wizard::prompt_secrets_backend(
        "did-hosting-control-secrets",
        "webvh",
    )
    .await
    .map_err(|e| AppError::Config(e.to_string()))?;

    // Admin ACL choice — resolve to a concrete DID now (so the
    // operator can save a generated private key immediately). The
    // `complete` step won't re-prompt.
    eprintln!();
    eprintln!("  Admin ACL entry — the control plane rejects authenticated calls");
    eprintln!("  until at least one admin DID is enrolled.");
    eprintln!();
    let admin_options = &[
        "Enter an existing DID (e.g. server DID or operator DID)",
        "Generate a new did:key identity for the operator",
        "Skip (add later with did-hosting-control add-acl)",
    ];
    let admin_idx = Select::new()
        .with_prompt("Admin ACL entry")
        .items(admin_options)
        .default(0)
        .interact()
        .map_err(|e| AppError::Config(format!("input error: {e}")))?;

    let admin = match admin_idx {
        0 => {
            let did: String = Input::new()
                .with_prompt("Admin DID")
                .interact_text()
                .map_err(|e| AppError::Config(format!("input error: {e}")))?;
            AdminChoice::Did(did)
        }
        1 => {
            let (did, sk) = vta_setup::generate_admin_did_key();
            eprintln!("  Generated admin did:key: {did}");
            eprintln!("  Private key (save this now — will not be re-shown): {sk}");
            AdminChoice::Did(did)
        }
        _ => AdminChoice::Skip,
    };

    // Package the bootstrap request via the shared builder — same ask shape
    // the online flow sends, so the path-fold and template selection live in
    // one place. The seed is returned in memory and persisted via the
    // configured secret store (no on-disk seed file).
    let shape = vta_setup::WebvhDidShape::Hosted {
        origin: &did_hosting_url,
        did_path: &did_path,
        mediator_did: mediator_did.as_deref(),
        transport,
        remote: None,
    };
    let ask = vta_setup::build_webvh_provision_ask(
        &context_id,
        &shape,
        Some(&format!("did-hosting-control setup — {context_id}")),
    );
    let info = vta_setup::write_offline_bootstrap_request(&request_out, &ask)
        .await
        .map_err(|e| AppError::Config(format!("failed to write bootstrap request: {e}")))?;
    let secret_store =
        did_hosting_common::server::secret_store::create_secret_store(&secrets, &config_output)?;
    secret_store.set_bootstrap_seed(&info.seed).await?;

    // Persist state for `setup-offline-complete` to pick up.
    let state = PendingSetupState {
        config_output: config_output.clone(),
        did_hosting_url,
        did_path,
        mediator_did,
        transport: transport.as_str().to_string(),
        did_log_output,
        public_url,
        host,
        port,
        log_level,
        log_format,
        data_dir,
        secrets,
        admin,
    };
    let state_toml = toml::to_string_pretty(&state)
        .map_err(|e| AppError::Config(format!("failed to serialize state: {e}")))?;
    if let Some(parent) = state_out.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(&state_out, &state_toml)?;

    eprintln!();
    eprintln!("  Offline setup step 1/2 complete.");
    eprintln!();
    eprintln!("  Request file:   {}", info.request_path.display());
    eprintln!("  State file:     {}", state_out.display());
    eprintln!("  Bootstrap seed: stored in the configured secrets backend");
    eprintln!();
    eprintln!("  Consumer DID:   {}", info.client_did);
    eprintln!("  Nonce:          {}", info.nonce);
    eprintln!();
    eprintln!("  Next steps:");
    eprintln!(
        "    1. Ferry {} to your VTA admin.",
        info.request_path.display()
    );
    eprintln!("    2. Ask them to create the VTA context with this DID as admin");
    eprintln!("       (skip if the context already exists), via either:");
    eprintln!(
        "         pnm contexts create --context {} \\\n           --admin {}",
        context_id, info.client_did
    );
    eprintln!("       or, on the VTA host directly:");
    eprintln!(
        "         vta contexts create --id {} \\\n           --admin-did {} --admin-expires 1h",
        context_id, info.client_did
    );
    eprintln!("    3. Ask them to seal the response:");
    eprintln!(
        "         vta bootstrap provision-integration --request <request-file> \\\n           --out <bundle-file>"
    );
    eprintln!("    4. They send back an ASCII-armored sealed bundle + SHA-256 digest.");
    eprintln!("    5. Run:");
    eprintln!(
        "         did-hosting-control setup-offline-complete \\\n           --bundle <bundle> --expect-digest <hex> --state {}",
        state_out.display()
    );
    eprintln!();

    Ok(())
}

/// Finalise offline setup: open the sealed response, persist the DID
/// + keys + config + admin ACL using the state saved by `prepare`.
pub async fn run_setup_offline_complete(
    bundle_path: PathBuf,
    expect_digest: String,
    state_path: PathBuf,
) -> Result<(), AppError> {
    eprintln!();
    eprintln!("  DID Hosting Control Plane — Offline Setup (step 2/2)");
    eprintln!("  -----------------------------------------------");
    eprintln!();

    // Load the state the prepare step wrote.
    let state_toml = std::fs::read_to_string(&state_path).map_err(|e| {
        AppError::Config(format!(
            "failed to read state {}: {e}",
            state_path.display()
        ))
    })?;
    let state: PendingSetupState = toml::from_str(&state_toml)
        .map_err(|e| AppError::Config(format!("failed to parse state: {e}")))?;

    // Open the sealed bundle.
    let armor = std::fs::read_to_string(&bundle_path).map_err(|e| {
        AppError::Config(format!(
            "failed to read bundle {}: {e}",
            bundle_path.display()
        ))
    })?;
    let pre_secret_store = did_hosting_common::server::secret_store::create_secret_store(
        &state.secrets,
        &state.config_output,
    )?;
    let seed = pre_secret_store
        .get_bootstrap_seed()
        .await?
        .ok_or_else(|| {
            AppError::Config(
                "bootstrap seed missing from secret store — phase 1 may not have run".into(),
            )
        })?;
    let result = vta_setup::open_offline_bootstrap_response(&armor, &expect_digest, &seed)
        .map_err(|e| AppError::Config(format!("failed to open sealed response: {e}")))?;

    eprintln!("  Sealed response opened.");
    eprintln!("  DID:          {}", result.did);
    eprintln!("  VTA DID:      {}", result.vta_did);
    if let Some(ref url) = result.vta_url {
        eprintln!("  VTA URL:      {url}");
    }
    eprintln!();

    // Write DID log entry file if the template emitted one.
    if let Some(ref log) = result.log_entry {
        vta_setup::write_log_entry_file(log, &state.did_log_output)?;
        eprintln!(
            "  DID log entry written to {}",
            state.did_log_output.display()
        );
    } else {
        eprintln!(
            "  Warning: sealed response carried no WebvhLog — nothing written to {}",
            state.did_log_output.display()
        );
    }

    // Generate JWT signing key.
    let jwt_signing_key = vta_setup::generate_ed25519_multibase();
    eprintln!("  Generated JWT signing key.");

    let server_secrets = ServerSecrets {
        signing_key: result.signing_key_multibase,
        key_agreement_key: result.key_agreement_multibase,
        jwt_signing_key,
        vta_credential: None, // offline flow has no reusable VTA credential
        retired: Vec::new(),
    };

    // Build and write config.toml.
    let (didcomm, tsp) = TransportSelection::parse(&state.transport)?.as_flags();
    let config = AppConfig {
        features: FeaturesConfig {
            didcomm,
            tsp,
            rest_api: true,
            ..Default::default()
        },
        server_did: Some(result.did.clone()),
        mediator_did: state.mediator_did.clone(),
        public_url: state.public_url.clone(),
        did_hosting_url: Some(state.did_hosting_url.clone()),
        server: ServerConfig {
            host: state.host.clone(),
            port: state.port,
            trusted_proxies: Vec::new(),
            trusted_proxy_cidrs: Vec::new(),
        },
        log: LogConfig {
            level: state.log_level.clone(),
            format: state.log_format.clone(),
        },
        store: StoreConfig {
            data_dir: PathBuf::from(&state.data_dir),
            ..StoreConfig::default()
        },
        fjall: Default::default(),
        auth: AuthConfig::default(),
        secrets: state.secrets.clone(),
        vta: VtaConfig {
            url: result.vta_url.clone(),
            did: Some(result.vta_did.clone()),
            context_id: None, // offline flow doesn't surface the VTA context id
        },
        registry: RegistryConfig::default(),
        trust_tasks: Default::default(),
        hosting: HostingConfig::default(),
        identity: Default::default(),
        config_path: state.config_output.clone(),
    };

    let toml_str = toml::to_string_pretty(&config)
        .map_err(|e| AppError::Config(format!("failed to serialize config: {e}")))?;
    std::fs::write(&state.config_output, &toml_str)?;
    eprintln!(
        "  Configuration written to {}",
        state.config_output.display()
    );

    let secret_store = create_secret_store(&config)?;
    secret_store.set(&server_secrets).await?;
    eprintln!("  Secrets stored.");

    // Bootstrap admin ACL per the choice captured in state.
    if let AdminChoice::Did(ref admin_did) = state.admin {
        let store = Store::open(&config.store).await?;
        let acl_ks = store.keyspace(KS_ACL)?;
        let entry = AclEntry {
            did: admin_did.clone(),
            role: Role::Admin,
            label: Some("Setup wizard admin (offline)".into()),
            created_at: now_epoch(),
            max_total_size: None,
            max_did_count: None,

            domains: did_hosting_common::server::domain::DomainScope::All,
        };
        crate::acl::store_acl_entry(&acl_ks, &entry).await?;
        store.persist().await?;
        eprintln!("  Admin ACL entry added for {admin_did}");
    }

    // Drop the now-spent bootstrap seed from the secret store. We
    // re-instantiate post-finalize because plaintext mode rewrites the
    // config.toml when persisting `ServerSecrets`.
    let post_secret_store = did_hosting_common::server::secret_store::create_secret_store(
        &config.secrets,
        &state.config_output,
    )?;
    if let Err(e) = post_secret_store.clear_bootstrap_seed().await {
        eprintln!("  Warning: failed to clear bootstrap seed: {e}");
    }

    // Best-effort cleanup — the operator may also want to keep the
    // state file around for audit, so failure here is only a warning.
    cleanup_offline_artifacts(&state_path);

    eprintln!();
    eprintln!("  Setup complete!");
    eprintln!();
    eprintln!("  Control DID: {}", result.did);
    eprintln!();
    eprintln!("  Next steps:");
    eprintln!("    1. Set up did-hosting-server (if not already done)");
    eprintln!("    2. Import this DID on the server:");
    eprintln!(
        "       did-hosting-server bootstrap-did --path {} --did-log {}",
        state.did_path,
        state.did_log_output.display()
    );
    eprintln!("    3. Start the control plane:");
    eprintln!(
        "       did-hosting-control --config {}",
        state.config_output.display()
    );
    eprintln!();

    Ok(())
}

fn cleanup_offline_artifacts(state_path: &Path) {
    if let Err(e) = std::fs::remove_file(state_path) {
        eprintln!(
            "  Warning: failed to remove state file {}: {e}",
            state_path.display()
        );
    }
}