did-hosting-server 0.9.0

DID Hosting Server, handles management and serving of WebVH Content
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
use std::path::{Path, PathBuf};
use std::sync::Arc;

use dialoguer::{Confirm, Input, Select};
use serde::{Deserialize, Serialize};

use crate::config::{
    AppConfig, AuthConfig, FeaturesConfig, LimitsConfig, LogConfig, LogFormat, SecretsConfig,
    ServerConfig, StoreConfig, TransportSelection, VtaConfig,
};
use crate::secret_store::{ServerSecrets, create_secret_store};
use did_hosting_common::server::store::KS_DIDS;

use did_hosting_common::server::operator_messages::WebvhServerMessages;
use did_hosting_common::server::setup_prompts;
use did_hosting_common::server::setup_recipe::split_origin_and_did_path;
use did_hosting_common::server::vta_setup;
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<(), Box<dyn std::error::Error>> {
    use std::io::stderr;
    let messages = WebvhServerMessages;
    let finalise = format!(
        "did-hosting-server 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?;
    Ok(())
}

pub async fn run_wizard(
    config_path: Option<PathBuf>,
    preloaded_setup_key_file: Option<PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
    eprintln!();
    eprintln!("  DID Hosting Server — Setup Wizard");
    eprintln!("  ===========================");
    eprintln!();
    eprintln!("  This configures a read-only server edge node that serves DID");
    eprintln!("  documents and receives sync updates from the control plane.");
    eprintln!("  All DID management is handled by the control plane.");
    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(config_path, 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(SELF_MANAGED_DAEMON_ONLY.into());
            }
        }
    }

    // 1. Output path
    let default_path = config_path
        .as_ref()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "config.toml".to_string());

    let output_path: String = Input::new()
        .with_prompt("Configuration file path")
        .default(default_path)
        .interact_text()?;

    let output_path = PathBuf::from(&output_path);

    if output_path.exists() {
        let overwrite = Confirm::new()
            .with_prompt(format!(
                "{} already exists. Overwrite?",
                output_path.display()
            ))
            .default(false)
            .interact()?;
        if !overwrite {
            eprintln!("Setup cancelled.");
            return Ok(());
        }
    }

    // 2. Public URL — this becomes the server's DID identifier
    eprintln!();
    eprintln!("  This server needs its own DID identity (did:webvh). The URL you");
    eprintln!("  provide here determines the DID — for example, if you enter");
    eprintln!("  https://server1.example.com, the server's DID will be:");
    eprintln!("    did:webvh:<scid>:server1.example.com");
    eprintln!();
    eprintln!("  Each server instance in a distributed deployment should have a");
    eprintln!("  unique URL and therefore a unique DID.");
    eprintln!();
    let public_url =
        setup_prompts::prompt_long_value("Server URL (e.g. https://server1.example.com)", false)?;
    let public_url = public_url.trim_end_matches('/').to_string();

    // DID path derived from the URL's path component. With a bare host
    // (`https://example.com`) the DID is published at `.well-known`;
    // otherwise the URL path becomes the DID path.
    let did_path = {
        let after_scheme = public_url
            .find("://")
            .map(|i| &public_url[i + 3..])
            .unwrap_or(&public_url);
        let path = after_scheme
            .find('/')
            .map(|i| after_scheme[i..].trim_matches('/'))
            .unwrap_or("");
        if path.is_empty() {
            ".well-known".to_string()
        } else {
            path.to_string()
        }
    };

    // 3. VTA online provision — mint ephemeral did:key, print PNM
    //    `contexts create` command, then drive run_provision.
    //    Headless phase 2 supplies a pre-loaded setup key.
    let messages: Arc<dyn OperatorMessages> = Arc::new(WebvhServerMessages);
    let preloaded_setup_key = match preloaded_setup_key_file.as_deref() {
        Some(path) => Some(EphemeralSetupKey::load_from(path)?),
        None => None,
    };
    // The mediator + transport are chosen inside `run_online_provision`,
    // before the mint, so the selection is embedded in the minted DID's
    // service block (mediator-configured servers advertise their transports).
    let OnlineProvision {
        outcome,
        mediator_did,
        didcomm,
        tsp,
    } = run_online_provision(&public_url, messages, preloaded_setup_key).await?;
    let did_result_log_entry = outcome.did_log_entry.clone();

    if let Some(ref log_entry) = did_result_log_entry {
        eprintln!();
        eprintln!("  DID Log Entry:");
        eprintln!("  ---");
        for line in log_entry.lines() {
            eprintln!("  {line}");
        }
        eprintln!("  ---");
    }

    // 4. Control plane DID (for DIDComm sync)
    eprintln!();
    eprintln!("  The control plane manages all DIDs and replicates them to this");
    eprintln!("  server as signed Trust Tasks. Enter the control plane's DID: it is");
    eprintln!("  the only party this server takes directives from, and the server");
    eprintln!("  does not start without it. (For a single host with no separate");
    eprintln!("  control plane, run did-hosting-daemon instead.)");
    eprintln!();
    let control_did = Some(prompt_control_did()?);

    // 5. Host / Port
    let host = setup_prompts::prompt_listen_host("0.0.0.0")?;
    let port = setup_prompts::prompt_listen_port(8530)?;

    // 6. Log level / format
    let log_levels = ["info", "debug", "warn", "error", "trace"];
    let log_level_idx = Select::new()
        .with_prompt("Log level")
        .items(log_levels)
        .default(0)
        .interact()?;
    let log_level = log_levels[log_level_idx].to_string();

    let log_format = setup_prompts::prompt_log_format()?;

    // 7. Data directory
    let data_dir: String = Input::new()
        .with_prompt("Data directory")
        .default("data/did-hosting-server".to_string())
        .interact_text()?;

    // `ServerSecrets` carries a `jwt_signing_key` for every service alike, but
    // this edge has no JWT-based session auth to sign with it (deleted along
    // with the rest of its REST management surface); generated silently,
    // with no operator-facing announcement implying it matters.
    let jwt_signing_key = vta_setup::generate_ed25519_multibase();

    // 9. Secrets backend selection
    let secrets_config = did_hosting_common::server::secret_store::wizard::prompt_secrets_backend(
        "did-hosting-server-secrets",
        "webvh",
    )
    .await?;

    // 10. Build and write config
    let config = AppConfig {
        features: FeaturesConfig {
            didcomm,
            tsp,
            rest_api: false,
            ..Default::default()
        },
        server_did: Some(outcome.integration_did.clone()),
        mediator_did,
        public_url: Some(public_url.clone()),
        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(),
        hosting: crate::config::HostingConfig::default(),
        secrets: secrets_config,
        limits: LimitsConfig::default(),
        replication: Default::default(),
        control_did,
        vta: VtaConfig {
            url: outcome.vta_url.clone(),
            did: Some(outcome.vta_did.clone()),
            context_id: None,
        },
        stats: crate::config::StatsConfig::default(),
        identity: Default::default(),
        config_path: output_path.clone(),
    };

    let toml_str = toml::to_string_pretty(&config)?;
    std::fs::write(&output_path, &toml_str)?;
    eprintln!("  Configuration written to {}", output_path.display());

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

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

    // 14. Import DID log entry into store at the correct path
    if let Some(ref log_entry) = did_result_log_entry {
        eprintln!();
        eprintln!("  Importing server DID into store at path '{did_path}'...");

        let store = crate::store::Store::open(&config.store).await?;
        let dids_ks = store.keyspace(KS_DIDS)?;

        // Fails setup rather than warning (Keyring VTI-17): a warning here let a
        // moved service report success while serving its old DID.
        let did_id =
            match crate::bootstrap::import_own_did(&store, &dids_ks, &did_path, log_entry).await? {
                crate::bootstrap::OwnDidImport::Imported(result) => {
                    eprintln!("  Server DID imported!");
                    eprintln!("  DID:  {}", result.did_id);
                    eprintln!("  SCID: {}", result.scid);
                    result.did_id
                }
                crate::bootstrap::OwnDidImport::AlreadyPresent { did_id } => {
                    eprintln!("  Server DID already present: {did_id}");
                    did_id
                }
                crate::bootstrap::OwnDidImport::HeldByAnother { existing, minted } => {
                    return Err(Box::<dyn std::error::Error>::from(
                        crate::bootstrap::stale_own_did_message(
                            &did_path,
                            existing.as_deref(),
                            &minted,
                        ),
                    ));
                }
            };
        update_server_did_in_config(&output_path, &did_id)?;
        eprintln!("  server_did updated in {}", output_path.display());
    }

    // 15. Summary
    eprintln!();
    eprintln!("  Setup complete!");
    eprintln!();
    eprintln!("  Server DID: {}", outcome.integration_did);
    eprintln!("  Admin DID:  {}", outcome.admin_did);
    eprintln!();
    eprintln!("  This server is a read-only edge node. To manage DIDs,");
    eprintln!("  use the control plane (did-hosting-control) or the daemon (did-hosting-daemon).");
    eprintln!();
    eprintln!("  Next steps:");
    eprintln!("    1. Add this server's DID to the control plane ACL:");
    eprintln!(
        "       did-hosting-control add-acl --did {} --role service",
        outcome.integration_did
    );
    eprintln!("    2. Start the server:");
    eprintln!(
        "       did-hosting-server --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-server
    /// 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, Box<dyn std::error::Error>> {
    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 server reach its VTA?")
        .items(items)
        .default(0)
        .interact()?;
    Ok(match idx {
        0 => VtaMode::Online,
        1 => VtaMode::OfflineStart,
        2 => VtaMode::OfflineComplete,
        _ => VtaMode::SelfManaged,
    })
}

fn prompt_offline_prepare_paths() -> Result<(PathBuf, PathBuf), Box<dyn std::error::Error>> {
    let request: String = Input::new()
        .with_prompt("Bootstrap request file path")
        .default("bootstrap-request.json".into())
        .interact_text()?;
    let state: String = Input::new()
        .with_prompt("Pending state file path")
        .default("setup-offline-state.toml".into())
        .interact_text()?;
    Ok((PathBuf::from(request), PathBuf::from(state)))
}

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

/// Run the online VTA provision-integration round-trip:
/// prompt for VTA DID + context, mint an ephemeral did:key, print the
/// operator's `pnm contexts create` command, wait for confirmation,
/// then drive `vta_sdk::provision_client::run_provision`.
/// What [`run_online_provision`] gathered: the VTA provision outcome plus the
/// operator's mediator + transport choice. Both are needed downstream — the
/// choice shapes the minted DID's service block (so a mediator-configured
/// server advertises its transports) and populates the runtime config. The
/// mediator is chosen here, before the mint, precisely so it can be embedded
/// in the DID document rather than living only in config.
struct OnlineProvision {
    outcome: vta_setup::OnlineProvisionOutcome,
    mediator_did: Option<String>,
    didcomm: bool,
    tsp: bool,
}

async fn run_online_provision(
    public_url: &str,
    messages: Arc<dyn OperatorMessages>,
    preloaded_setup_key: Option<EphemeralSetupKey>,
) -> Result<OnlineProvision, 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()?;

    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
        }
    };

    // Mediator preference (runtime DIDComm with the control plane). Chosen
    // here, before the mint, so the selected mediator can be embedded in the
    // minted DID's service block — not just written to config. `vta_did` is
    // the operator-entered VTA DID above, so its mediator is discoverable
    // without the mint having happened.
    eprintln!();
    eprintln!("  A DIDComm mediator routes sync messages from the control plane.");
    eprintln!();
    let vta_mediator = vta_setup::resolve_vta_mediator(&vta_did).await;
    let mut mediator_options: Vec<String> = vec!["No mediator".into()];
    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(if vta_mediator.is_some() { 1 } else { 0 })
        .interact()?;
    let mediator_did = if mediator_options[mediator_idx].starts_with("No mediator") {
        None
    } else if mediator_options[mediator_idx].starts_with("Use VTA") {
        vta_mediator.clone()
    } else {
        let did: String = setup_prompts::prompt_long_value("Mediator DID", false)?;
        if did.is_empty() { None } else { Some(did) }
    };

    // Transport selection — only applies with a mediator (both TSP and DIDComm
    // ride the mediator socket); HTTP-only otherwise.
    let (didcomm, tsp) = if mediator_did.is_some() {
        setup_prompts::prompt_transport_selection()?.as_flags()
    } else {
        (false, false)
    };

    // The server's own DID advertises its messaging transport(s) when a
    // mediator is configured — the same shape the control plane and daemon
    // already mint, so a peer resolving this DID sees how to reach it over
    // TSP/DIDComm rather than depending on out-of-band config. With no
    // mediator the DID stays HTTP-only (`WebVHHosting` alone). `public_url`
    // carries the DID path in its path component — split it back out so the
    // shared builder folds it into the minted DID's URL.
    let (origin, did_path) = split_origin_and_did_path(public_url);
    let shape = vta_setup::WebvhDidShape::Hosted {
        origin: &origin,
        did_path: &did_path,
        mediator_did: mediator_did.as_deref(),
        // Advertise the transport(s) the operator just selected; ignored by
        // the builder when no mediator is configured.
        transport: TransportSelection::from_flags(didcomm, tsp).unwrap_or(TransportSelection::Both),
        remote: None,
    };
    let ask = vta_setup::build_webvh_provision_ask(
        &context_id,
        &shape,
        Some(&format!("did-hosting-server setup — {context_id}")),
    );

    eprintln!();
    eprintln!("  Provisioning server DID via VTA...");
    eprintln!();

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

    Ok(OnlineProvision {
        outcome,
        mediator_did,
        didcomm,
        tsp,
    })
}

// ---------------------------------------------------------------------------
// Offline setup wizard (air-gapped VTA)
//
// Same two-step pattern as `did-hosting-control setup-offline-prepare/complete`,
// with server-specific config: URL-derived DID path, control_did prompt,
// limits, root-DID import into the local store. See that module for the
// design rationale.
// ---------------------------------------------------------------------------

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

#[derive(Debug, Clone, Deserialize, Serialize)]
struct PendingServerSetupState {
    config_output: PathBuf,
    public_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,
    control_did: Option<String>,
    host: String,
    port: u16,
    log_level: String,
    log_format: LogFormat,
    data_dir: String,
    secrets: SecretsConfig,
}

/// Interactive offline-prepare for did-hosting-server: prompts for every
/// non-VTA setting, writes the bootstrap request file, persists the
/// ephemeral seed in the configured secrets backend, and serialises
/// the choices to a state TOML.
pub async fn run_setup_offline_prepare(
    config_path: Option<PathBuf>,
    request_out: PathBuf,
    state_out: PathBuf,
) -> Result<(), Box<dyn std::error::Error>> {
    eprintln!();
    eprintln!("  DID Hosting Server — Offline Setup (step 1/2)");
    eprintln!("  ========================================");
    eprintln!();
    eprintln!("  Captures all server settings and writes a sealed-bundle");
    eprintln!("  bootstrap request. No VTA connection is made. After the");
    eprintln!("  operator ferries the request to the VTA admin and receives");
    eprintln!("  a sealed reply, run `did-hosting-server setup-offline-complete`.");
    eprintln!();

    let default_path = config_path
        .as_ref()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "config.toml".to_string());

    let output_path: String = Input::new()
        .with_prompt("Configuration file path")
        .default(default_path)
        .interact_text()?;

    let config_output = PathBuf::from(&output_path);

    if config_output.exists() {
        let overwrite = Confirm::new()
            .with_prompt(format!(
                "{} already exists. Overwrite?",
                config_output.display()
            ))
            .default(false)
            .interact()?;
        if !overwrite {
            eprintln!("Setup cancelled.");
            return Ok(());
        }
    }

    eprintln!();
    let public_url =
        setup_prompts::prompt_long_value("Server URL (e.g. https://server1.example.com)", false)?;
    let public_url = public_url.trim_end_matches('/').to_string();

    // Origin + DID path from the URL's path component (matches the online
    // wizard). `public_url` (full) stays the server's identity; the split
    // feeds the shared ask builder below.
    let (origin, did_path) = split_origin_and_did_path(&public_url);

    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()?;

    eprintln!();
    eprintln!("  A DIDComm mediator routes sync messages from the control plane.");
    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)?;
    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()?
    } else {
        TransportSelection::Both
    };

    eprintln!();
    let control_did = Some(prompt_control_did()?);

    let host = setup_prompts::prompt_listen_host("0.0.0.0")?;
    let port = setup_prompts::prompt_listen_port(8530)?;

    let log_levels = ["info", "debug", "warn", "error", "trace"];
    let log_level_idx = Select::new()
        .with_prompt("Log level")
        .items(log_levels)
        .default(0)
        .interact()?;
    let log_level = log_levels[log_level_idx].to_string();

    let log_format = setup_prompts::prompt_log_format()?;

    let data_dir: String = Input::new()
        .with_prompt("Data directory")
        .default("data/did-hosting-server".to_string())
        .interact_text()?;

    let secrets = did_hosting_common::server::secret_store::wizard::prompt_secrets_backend(
        "did-hosting-server-secrets",
        "webvh",
    )
    .await?;

    // Package the bootstrap request via the shared builder. The rendered DID
    // exposes a `WebVHHosting` service at the server's public URL, and — when
    // a mediator is configured — advertises the selected messaging
    // transport(s) at it too, matching the online wizard and the control /
    // daemon setups. With no mediator it stays HTTP-only.
    let shape = vta_setup::WebvhDidShape::Hosted {
        origin: &origin,
        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-server setup — {context_id}")),
    );
    let info = vta_setup::write_offline_bootstrap_request(&request_out, &ask).await?;
    let secret_store =
        did_hosting_common::server::secret_store::create_secret_store(&secrets, &config_output)?;
    secret_store.set_bootstrap_seed(&info.seed).await?;

    let state = PendingServerSetupState {
        config_output: config_output.clone(),
        public_url,
        did_path,
        mediator_did,
        transport: transport.as_str().to_string(),
        control_did,
        host,
        port,
        log_level,
        log_format,
        data_dir,
        secrets,
    };
    let state_toml = toml::to_string_pretty(&state)?;
    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-server 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 + import the root DID per the state saved by prepare.
pub async fn run_setup_offline_complete(
    bundle_path: PathBuf,
    expect_digest: String,
    state_path: PathBuf,
) -> Result<(), Box<dyn std::error::Error>> {
    eprintln!();
    eprintln!("  DID Hosting Server — Offline Setup (step 2/2)");
    eprintln!("  ========================================");
    eprintln!();

    let state_toml = std::fs::read_to_string(&state_path)?;
    let state: PendingServerSetupState = toml::from_str(&state_toml)?;

    let armor = std::fs::read_to_string(&bundle_path)?;
    let secret_store = did_hosting_common::server::secret_store::create_secret_store(
        &state.secrets,
        &state.config_output,
    )?;
    let seed = secret_store
        .get_bootstrap_seed()
        .await?
        .ok_or("bootstrap seed missing from secret store — phase 1 may not have run")?;
    let result = vta_setup::open_offline_bootstrap_response(&armor, &expect_digest, &seed)?;

    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!();

    // See the interactive wizard above: unused by this edge, generated only
    // because `ServerSecrets`'s format is shared across every service.
    let jwt_signing_key = vta_setup::generate_ed25519_multibase();

    let (didcomm, tsp) = TransportSelection::parse(&state.transport)
        .map_err(|e| format!("invalid transport in state: {e}"))?
        .as_flags();
    let config = AppConfig {
        features: FeaturesConfig {
            didcomm,
            tsp,
            rest_api: false,
            ..Default::default()
        },
        server_did: Some(result.did.clone()),
        mediator_did: state.mediator_did.clone(),
        public_url: Some(state.public_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(),
        hosting: crate::config::HostingConfig::default(),
        secrets: state.secrets.clone(),
        limits: LimitsConfig::default(),
        replication: Default::default(),
        control_did: state.control_did.clone(),
        vta: VtaConfig {
            url: result.vta_url.clone(),
            did: Some(result.vta_did.clone()),
            context_id: None,
        },
        stats: crate::config::StatsConfig::default(),
        identity: Default::default(),
        config_path: state.config_output.clone(),
    };

    let toml_str = toml::to_string_pretty(&config)?;
    std::fs::write(&state.config_output, &toml_str)?;
    eprintln!(
        "  Configuration written to {}",
        state.config_output.display()
    );

    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(),
    };

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

    // Import the server's own DID into the local store at the derived path.
    // Mirrors the online wizard: import the server DID with `import_own_did`.
    if let Some(ref log_entry) = result.log_entry {
        eprintln!();
        eprintln!(
            "  Importing server DID into store at path '{}'...",
            state.did_path
        );

        let store = crate::store::Store::open(&config.store).await?;
        let dids_ks = store.keyspace(KS_DIDS)?;

        // Fails setup rather than warning (Keyring VTI-17): a warning here let a
        // moved service report success while serving its old DID.
        let did_id =
            match crate::bootstrap::import_own_did(&store, &dids_ks, &state.did_path, log_entry)
                .await?
            {
                crate::bootstrap::OwnDidImport::Imported(result) => {
                    eprintln!("  Server DID imported (scid={})", result.scid);
                    result.did_id
                }
                crate::bootstrap::OwnDidImport::AlreadyPresent { did_id } => {
                    eprintln!("  Server DID already present: {did_id}");
                    did_id
                }
                crate::bootstrap::OwnDidImport::HeldByAnother { existing, minted } => {
                    return Err(Box::<dyn std::error::Error>::from(
                        crate::bootstrap::stale_own_did_message(
                            &state.did_path,
                            existing.as_deref(),
                            &minted,
                        ),
                    ));
                }
            };
        update_server_did_in_config(&state.config_output, &did_id)?;
        eprintln!("  server_did updated in {}", state.config_output.display());
    } else {
        eprintln!();
        eprintln!("  Warning: sealed response carried no WebvhLog — server DID not imported.");
    }

    // 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(
        &state.secrets,
        &state.config_output,
    )?;
    if let Err(e) = post_secret_store.clear_bootstrap_seed().await {
        eprintln!("  Warning: failed to clear bootstrap seed: {e}");
    }

    cleanup_offline_artifacts(&state_path);

    eprintln!();
    eprintln!("  Setup complete!");
    eprintln!();
    eprintln!("  Server DID: {}", result.did);
    eprintln!();
    eprintln!("  Next steps:");
    eprintln!("    1. Add this server's DID to the control plane ACL:");
    eprintln!(
        "       did-hosting-control add-acl --did {} --role service",
        result.did
    );
    eprintln!("    2. Start the server:");
    eprintln!(
        "       did-hosting-server --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()
        );
    }
}

pub fn update_server_did_in_config(
    config_path: &PathBuf,
    server_did: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let contents = std::fs::read_to_string(config_path)?;
    let mut doc: toml::Value = toml::from_str(&contents)?;

    if let Some(table) = doc.as_table_mut() {
        table.insert(
            "server_did".to_string(),
            toml::Value::String(server_did.to_string()),
        );
    }

    std::fs::write(config_path, toml::to_string_pretty(&doc)?)?;
    Ok(())
}

/// The control plane's DID, which an edge requires: asked until one is given.
fn prompt_control_did() -> Result<String, Box<dyn std::error::Error>> {
    loop {
        let did = setup_prompts::prompt_long_value("Control plane DID", false)?;
        let did = did.trim().to_string();
        if did.starts_with("did:") {
            return Ok(did);
        }
        eprintln!("  A control plane DID (did:...) is required.");
    }
}