did-hosting-control 0.10.1

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
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
use clap::{Parser, Subcommand};
use did_hosting_common::server::store::KS_SESSIONS;
use did_hosting_control::config::AppConfig;
use did_hosting_control::{health, secret_store, server, setup, setup_recipe, store};
use std::path::PathBuf;

#[derive(Parser)]
#[command(
    name = "did-hosting-control",
    about = "DID Hosting Control Plane — Unified Management",
    version
)]
struct Cli {
    /// Path to the configuration file
    #[arg(short, long, global = true)]
    config: Option<PathBuf>,

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

#[derive(Subcommand)]
enum Command {
    /// Run interactive setup wizard to generate config.toml.
    ///
    /// Headless mode (for CI / scripted setup):
    ///
    /// 1. Run with `--setup-key-out <path> --context <id>` to mint an
    ///    ephemeral did:key, persist it (chmod 0600), and print the
    ///    `pnm contexts create` command. Exits without further prompts.
    /// 2. Run again with `--setup-key-file <path>` to drive the rest of
    ///    the wizard reusing the persisted setup DID.
    Setup {
        /// Phase 1: mint an ephemeral did:key, persist to <path>, and
        /// print the `pnm contexts create` command + exit.
        #[arg(long, conflicts_with = "setup_key_file")]
        setup_key_out: Option<PathBuf>,
        /// Phase 2: reuse the setup DID persisted at <path>; skip the
        /// interactive "Has the context been created?" confirmation.
        #[arg(long, conflicts_with = "setup_key_out")]
        setup_key_file: Option<PathBuf>,
        /// Context id for phase 1's PNM command. Defaults to `webvh`.
        #[arg(long, default_value = "webvh", requires = "setup_key_out")]
        context: String,
        /// Path to a declarative setup recipe TOML. Drives the wizard
        /// non-interactively. See `examples/did-hosting-control-build.toml`.
        #[arg(long, value_name = "FILE")]
        from: Option<PathBuf>,
        /// Refuse to run when an existing setup is detected, unless this
        /// flag is set. Exit 4 protects issued JWTs / active VTA sessions.
        #[arg(long)]
        force_reprovision: bool,
        /// Explicit "no TTY available" flag. Requires `--from`.
        #[arg(long, requires = "from")]
        non_interactive: bool,
    },
    /// Teardown a control plane install: clears managed secrets and
    /// removes the config file (+ `.bak`, + `control-did.jsonl`).
    Uninstall {
        /// Skip the typed "DELETE" confirmation prompt. CI use only.
        #[arg(long)]
        yes: bool,
    },
    /// Run health check diagnostics
    Health,
    /// Add an ACL entry
    AddAcl {
        /// DID to add to the ACL
        #[arg(long)]
        did: String,
        /// Role (admin or owner)
        #[arg(long, default_value = "owner")]
        role: String,
        /// Optional label
        #[arg(long)]
        label: Option<String>,
    },
    /// List all ACL entries
    ListAcl,
    /// List the service's own identity generations (key material still honoured).
    IdentityList,
    /// List this service's established TSP relationships (offline; stop the
    /// service first).
    ///
    /// Each endpoint keeps its own half of every relationship; the mediator holds
    /// none, so resetting a peer pairing means clearing both ends.
    TspRelationshipList,
    /// Reset our half of a TSP relationship to `None`, so the next send to the
    /// peer re-invites (offline). Keeps the cached peer capability.
    TspRelationshipReset {
        /// The peer's DID (its TSP VID).
        #[arg(long)]
        peer: String,
        /// This service's VID for the pair. Needed only for a half-formed
        /// relationship, which `tsp-relationship-list` cannot show.
        #[arg(long)]
        our: Option<String>,
    },
    /// Delete TSP relationship records outright (offline).
    TspRelationshipDelete {
        /// The peer's DID (its TSP VID).
        #[arg(long, required_unless_present = "all", conflicts_with = "all")]
        peer: Option<String>,
        /// This service's VID for the pair. Needed only for a half-formed
        /// relationship, which `tsp-relationship-list` cannot show.
        #[arg(long, requires = "peer", conflicts_with = "all")]
        our: Option<String>,
        /// Delete every record, established or half-formed.
        #[arg(long)]
        all: bool,
        /// Confirm `--all`. Without it, only reports what would be deleted.
        #[arg(long, short = 'y')]
        yes: bool,
    },
    /// Rotate the service's own key-agreement key.
    ///
    /// Publishes a new DID log entry installing a fresh key-agreement key on a
    /// NEW verification-method fragment, and keeps the outgoing key honoured for
    /// the grace period so peers holding a cached DID document can still reach
    /// this service.
    ///
    /// The fresh fragment is not cosmetic: a kid identifies exactly one key, so
    /// reusing `#key-1` would make any grace period impossible.
    ///
    /// The service must be STOPPED (the store is exclusively locked).
    IdentityRotateKeys {
        /// Which keys to rotate: "ka" (default), "signing", or "both".
        ///
        /// "ka"      — the encryption key. This is what the grace period covers.
        /// "signing" — the DID's updateKeys: the authority to publish updates.
        ///             Revoked IMMEDIATELY; there is no grace period for it, and
        ///             for a compromised key that is exactly what you want.
        #[arg(long, default_value = "ka")]
        keys: String,
        /// X25519 key-agreement key to install (multibase). Generated if omitted.
        #[arg(long)]
        ka_key: Option<String>,
        /// Ed25519 signing key to install (multibase). Generated if omitted.
        #[arg(long)]
        signing_key: Option<String>,
        /// How long to keep honouring the outgoing key-agreement key ("1h", "0").
        /// Defaults to `[identity] rotation_grace_period`.
        #[arg(long)]
        grace: Option<String>,
    },
    /// Stop honouring a superseded identity generation immediately.
    ///
    /// The offline kill switch, for a compromised key. Messages still addressed
    /// to that generation's key-agreement key will no longer decrypt.
    ///
    /// The service must be stopped (the store is exclusively locked). For a
    /// LIVE service use the control plane's
    /// `POST /api/identity/generations/{id}/retire` or the UI button, which
    /// drops the key from the running process immediately.
    IdentityRetireNow {
        /// Generation id to retire (see `identity-list`).
        #[arg(long)]
        generation: u64,
    },
    /// Remove an ACL entry
    RemoveAcl {
        /// DID to remove from the ACL
        #[arg(long)]
        did: String,
    },
    /// Create a passkey enrollment invite
    Invite {
        /// DID to invite
        #[arg(long)]
        did: String,
        /// Role (admin or owner)
        #[arg(long, default_value = "owner")]
        role: String,
        /// Invite lifetime in hours (default: `auth.passkey_enrollment_ttl`)
        #[arg(long)]
        ttl_hours: Option<u64>,
    },
    /// Write an offline VTA bootstrap request (for air-gapped VTAs).
    ///
    /// Generates an ephemeral Ed25519 keypair and writes a JSON request
    /// the operator ferries to the VTA admin. Keep the companion seed
    /// file safe — it's needed to open the sealed response.
    VtaRequest {
        /// Path for the bootstrap-request.json file.
        #[arg(long, default_value = "bootstrap-request.json")]
        out: PathBuf,
        /// Path for the ephemeral seed (keep this secret; chmod 0600 on Unix).
        #[arg(long, default_value = "bootstrap-seed.bin")]
        seed: PathBuf,
        /// Operator-visible label identifying this request.
        #[arg(long, default_value = "did-hosting-control")]
        label: String,
        /// DID hosting URL. Bound to the `did-hosting-control` template's
        /// `URL` variable so the rendered DID exposes a `WebVHHosting`
        /// service at this URL.
        #[arg(long)]
        did_hosting_url: String,
        /// DIDComm mediator DID. Bound to the `did-hosting-control` template's
        /// `MEDIATOR_DID` variable so the rendered DID document advertises
        /// the right mediator endpoint.
        #[arg(long)]
        mediator_did: String,
        /// VTA context the integration will live in. Embedded as
        /// `contextHint` in the request so the VTA admin can run
        /// `vta bootstrap provision-integration` without `--context`.
        #[arg(long, default_value = "webvh")]
        context: String,
    },
    /// Step 1/2 of the offline (air-gapped VTA) setup wizard.
    ///
    /// Runs the interactive prompts, writes the bootstrap-request.json +
    /// ephemeral seed, and serialises the operator's answers to a state
    /// TOML file. After the VTA admin returns a sealed bundle, run
    /// `setup-offline-complete`.
    SetupOfflinePrepare {
        /// Path for the bootstrap-request.json file.
        #[arg(long, default_value = "bootstrap-request.json")]
        request: PathBuf,
        /// Path for the pending state file (plain TOML, no secrets).
        ///
        /// The ephemeral bootstrap seed is persisted to the configured
        /// secrets backend (keyring / AWS / GCP / plaintext-in-config),
        /// not to a file.
        #[arg(long, default_value = "setup-offline-state.toml")]
        state: PathBuf,
    },
    /// Step 2/2 of the offline setup wizard.
    ///
    /// Opens the sealed bundle with the seed saved during step 1, then
    /// persists the DID + keys + config + admin ACL per the choices
    /// captured in the state file.
    SetupOfflineComplete {
        /// Path to the ASCII-armored sealed bundle from the VTA admin.
        #[arg(long)]
        bundle: PathBuf,
        /// Expected SHA-256 digest (lowercase hex) of the armored
        /// ciphertext; communicated out-of-band.
        #[arg(long)]
        expect_digest: String,
        /// Path to the state file written by `setup-offline-prepare`.
        #[arg(long, default_value = "setup-offline-state.toml")]
        state: PathBuf,
    },
    /// Export this control plane's DID + signing/KA keys as an
    /// HPKE-sealed migration bundle. See `did-hosting-server export-sealed`
    /// for full semantics; the receiver opens with `import-sealed`.
    ExportSealed {
        /// Path to the receiver's bootstrap-request.json.
        #[arg(long)]
        request: PathBuf,
        /// Path for the ASCII-armored sealed output.
        #[arg(long, default_value = "sealed-export.txt")]
        out: PathBuf,
        /// Optional file to write the SHA-256 digest to. Always
        /// printed to stderr regardless.
        #[arg(long)]
        digest_out: Option<PathBuf>,
    },
    /// Open a sealed `DidSecrets` migration bundle and import the
    /// contained keys as this control plane's identity. Inverse of
    /// `export-sealed` on the sending side.
    ImportSealed {
        /// Path to the ASCII-armored sealed bundle.
        #[arg(long)]
        bundle: PathBuf,
        /// Expected SHA-256 digest of the armored ciphertext.
        #[arg(long)]
        expect_digest: String,
        /// Path to the ephemeral seed the receiver saved when
        /// generating the bootstrap-request.json.
        #[arg(long, default_value = "bootstrap-seed.bin")]
        seed: PathBuf,
        /// Optional Ed25519 public key of the producer (multibase-
        /// encoded, matches `#key-0` in the producer's DID document).
        /// When supplied, the bundle's `DidSigned` assertion is
        /// verified against it; omit to fall back to digest-only trust.
        #[arg(long)]
        producer_pubkey: Option<String>,
        /// Optional Ed25519 JWT signing key (multibase-encoded,
        /// auto-generated if omitted).
        #[arg(long)]
        jwt_key: Option<String>,
        /// Overwrite existing secrets without prompting.
        #[arg(long)]
        force: bool,
    },
    /// Open a sealed VTA bootstrap response (primitive — prefer
    /// `setup-offline-complete` for a full wizard-driven finish).
    ///
    /// Reads the armored bundle the operator ferried back, verifies the
    /// out-of-band digest, opens the HPKE sealed payload with the
    /// ephemeral seed, and emits the DID document + signed DID log for
    /// import via the did-hosting-server bootstrap-did / load-did commands.
    VtaOpen {
        /// Path to the ASCII-armored sealed bundle.
        #[arg(long)]
        bundle: PathBuf,
        /// Expected SHA-256 digest of the armored ciphertext (from the
        /// operator, out-of-band).
        #[arg(long)]
        expect_digest: String,
        /// Path to the ephemeral seed saved by `vta-request`.
        #[arg(long, default_value = "bootstrap-seed.bin")]
        seed: PathBuf,
        /// Where to write the rendered DID document as JSON.
        #[arg(long, default_value = "control-did.json")]
        did_doc_out: PathBuf,
        /// Where to write the signed DID log (JSONL). Omitted when the
        /// template didn't emit a WebvhLog output.
        #[arg(long, default_value = "control-did.jsonl")]
        did_log_out: PathBuf,
        /// Where to save the minted private signing + KA key pair plus
        /// VTA trust material (authorization VC, pinned VTA DID) as JSON.
        /// Feed into `did-hosting-control setup` to persist via the configured
        /// secret backend.
        #[arg(long, default_value = "control-secrets.json")]
        secrets_out: PathBuf,
    },
    /// Scrape this service's counters over the authenticated
    /// `server/metrics/0.1` Trust Task and print them as JSON.
    ///
    /// The counters live in the running service's process memory and are
    /// reachable only through this signed task — there is no unauthenticated
    /// scrape endpoint. Signs with the `--key` did:key (granted `MetricsReader`
    /// in the ACL) and POSTs to the running service's `POST /api/trust-tasks`.
    /// Only `counters` are returned (gauges require Admin and are omitted).
    /// Prints the counters as JSON on stdout, ready to pipe into a monitoring
    /// agent. A genuine refusal (an ungranted/revoked key) is reported as an
    /// error rather than an empty array.
    FetchMetrics {
        /// Path to the signer's did:key JSON file — the MetricsReader key,
        /// same format `setup --setup-key-out` writes.
        #[arg(long)]
        key: PathBuf,
        /// Base URL of the running service. Defaults to
        /// `http://<server.host>:<server.port>` from config (a wildcard bind
        /// such as `0.0.0.0` / `::` is dialled as loopback).
        #[arg(long)]
        url: Option<String>,
    },
}

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

    print_banner();

    match cli.command {
        Some(Command::Setup {
            setup_key_out,
            setup_key_file,
            context,
            from,
            force_reprovision,
            non_interactive: _,
        }) => {
            if let Some(path) = setup_key_out {
                if let Err(e) = setup::run_setup_phase1(&path, &context).await {
                    eprintln!("Setup error: {e}");
                    std::process::exit(1);
                }
            } else if let Some(recipe_path) = from {
                match setup_recipe::run_from_recipe(&recipe_path, setup_key_file, force_reprovision)
                    .await
                {
                    Ok(()) => {}
                    Err(e) => {
                        eprintln!("Setup error: {e}");
                        std::process::exit(setup_recipe::map_exit_code(&e));
                    }
                }
            } else if let Err(e) = setup::run_setup(setup_key_file).await {
                eprintln!("Setup error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::Uninstall { yes }) => {
            let config_path = cli
                .config
                .clone()
                .unwrap_or_else(|| PathBuf::from("config.toml"));
            if let Err(e) = setup_recipe::run_uninstall(&config_path, yes).await {
                eprintln!("Uninstall error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::Health) => {
            if let Err(e) = health::run_health(cli.config).await {
                eprintln!("Health check error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::AddAcl { did, role, label }) => {
            if let Err(e) = run_add_acl(cli.config, did, role, label).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::ListAcl) => {
            if let Err(e) = run_list_acl(cli.config).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::FetchMetrics { key, url }) => {
            if let Err(e) = run_fetch_metrics(cli.config, key, url).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::IdentityRotateKeys {
            keys,
            ka_key,
            signing_key,
            grace,
        }) => {
            if let Err(e) =
                run_identity_rotate_keys(cli.config, keys, ka_key, signing_key, grace).await
            {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::TspRelationshipList) => {
            if let Err(e) = run_tsp_relationship_list(cli.config).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::TspRelationshipReset { peer, our }) => {
            if let Err(e) = run_tsp_relationship_reset(cli.config, peer, our).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::TspRelationshipDelete {
            peer,
            our,
            all,
            yes,
        }) => {
            if let Err(e) = run_tsp_relationship_delete(cli.config, peer, our, all, yes).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::IdentityList) => {
            if let Err(e) = run_identity_list(cli.config).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::IdentityRetireNow { generation }) => {
            if let Err(e) = run_identity_retire_now(cli.config, generation).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::RemoveAcl { did }) => {
            if let Err(e) = run_remove_acl(cli.config, did).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::Invite {
            did,
            role,
            ttl_hours,
        }) => {
            if let Err(e) = run_invite(cli.config, did, role, ttl_hours).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::SetupOfflinePrepare { request, state }) => {
            if let Err(e) = setup::run_setup_offline_prepare(request, state).await {
                eprintln!("Setup error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::SetupOfflineComplete {
            bundle,
            expect_digest,
            state,
        }) => {
            if let Err(e) = setup::run_setup_offline_complete(bundle, expect_digest, state).await {
                eprintln!("Setup error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::ExportSealed {
            request,
            out,
            digest_out,
        }) => {
            if let Err(e) = run_export_sealed(cli.config, request, out, digest_out).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::ImportSealed {
            bundle,
            expect_digest,
            seed,
            producer_pubkey,
            jwt_key,
            force,
        }) => {
            if let Err(e) = run_import_sealed(
                cli.config,
                bundle,
                expect_digest,
                seed,
                producer_pubkey,
                jwt_key,
                force,
            )
            .await
            {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::VtaRequest {
            out,
            seed,
            label,
            did_hosting_url,
            mediator_did,
            context,
        }) => {
            // `did_hosting_url` may already carry the DID path; split it back
            // out so the shared builder folds it identically to the wizard.
            let (origin, did_path) =
                did_hosting_common::server::setup_recipe::split_origin_and_did_path(
                    &did_hosting_url,
                );
            let shape = did_hosting_common::server::vta_setup::WebvhDidShape::Hosted {
                origin: &origin,
                did_path: &did_path,
                mediator_did: Some(mediator_did.as_str()),
                // The low-level offline-request CLI has no transport flag;
                // default to advertising both (prior behaviour).
                transport: did_hosting_common::server::config::TransportSelection::Both,
                remote: None,
            };
            let ask = did_hosting_common::server::vta_setup::build_webvh_provision_ask(
                &context,
                &shape,
                Some(&label),
            );
            if let Err(e) = did_hosting_common::server::vta_setup::run_offline_request_cli(
                &out,
                &seed,
                "did-hosting-control",
                &ask,
            )
            .await
            {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::VtaOpen {
            bundle,
            expect_digest,
            seed,
            did_doc_out,
            did_log_out,
            secrets_out,
        }) => {
            if let Err(e) = did_hosting_common::server::vta_setup::run_offline_open_cli(
                &bundle,
                &expect_digest,
                &seed,
                &did_doc_out,
                &did_log_out,
                &secrets_out,
                did_hosting_common::server::vta_setup::OfflineOpenNextStep::Setup {
                    binary: "did-hosting-control",
                },
            ) {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        None => run_control(cli.config).await,
    }
}

async fn run_control(config_path: Option<PathBuf>) {
    let config = match AppConfig::load(config_path) {
        Ok(config) => config,
        Err(e) => {
            eprintln!("Error: {e}");
            eprintln!();
            eprintln!("Create a config.toml or specify one:");
            eprintln!("  did-hosting-control --config <path>");
            eprintln!("  did-hosting-control setup");
            std::process::exit(1);
        }
    };

    did_hosting_common::server::config::init_tracing(&config.log);

    // Load secrets from the configured backend
    let secret_store = match secret_store::create_secret_store(&config) {
        Ok(s) => s,
        Err(e) => {
            tracing::error!("failed to create secret store: {e}");
            eprintln!("Error: {e}");
            std::process::exit(1);
        }
    };

    let secrets = match secret_store.get().await {
        Ok(Some(s)) => {
            tracing::info!("secrets loaded from secret store");
            s
        }
        Ok(None) => {
            eprintln!("Error: no secrets found — run `did-hosting-control setup` first");
            std::process::exit(1);
        }
        Err(e) => {
            eprintln!("Error loading secrets: {e}");
            std::process::exit(1);
        }
    };

    let store = store::Store::open_with(&config.store, &config.fjall)
        .await
        .expect("failed to open store");

    if let Err(e) = server::run(config, store, secrets).await {
        tracing::error!("control plane error: {e}");
        std::process::exit(1);
    }
}

async fn run_add_acl(
    config_path: Option<PathBuf>,
    did: String,
    role_str: String,
    label: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    did_hosting_common::server::cli_acl::run_add_acl(
        &config.store,
        did,
        role_str,
        label,
        None,
        None,
    )
    .await
}

async fn run_list_acl(config_path: Option<PathBuf>) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    did_hosting_common::server::cli_acl::run_list_acl(&config.store).await
}

/// Scrape this control plane's counters. A thin wrapper over the shared
/// [`did_hosting_common::server::cli_metrics::fetch_metrics`] — the same command
/// the daemon exposes — supplying control's own `server_did` and bind address.
async fn run_fetch_metrics(
    config_path: Option<PathBuf>,
    key_path: PathBuf,
    url: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let to = config
        .server_did
        .clone()
        .ok_or("server_did is not configured; this service has not completed provisioning")?;
    did_hosting_common::server::cli_metrics::fetch_metrics(
        &to,
        key_path.as_path(),
        url,
        &config.server.host,
        config.server.port,
    )
    .await
}

async fn run_remove_acl(
    config_path: Option<PathBuf>,
    did: String,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    did_hosting_common::server::cli_acl::run_remove_acl(&config.store, did).await
}

async fn run_invite(
    config_path: Option<PathBuf>,
    did: String,
    role: String,
    ttl_hours: Option<u64>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;

    let base_url = config
        .public_url
        .as_deref()
        .ok_or("public_url must be set in config for enrollment invites")?;

    let enrollment_ttl = match ttl_hours {
        Some(hours) => hours * 3600,
        None => config.auth.passkey_enrollment_ttl,
    };

    let store = store::Store::open(&config.store).await?;
    let sessions_ks = store.keyspace(KS_SESSIONS)?;

    did_hosting_common::server::passkey::run_cli_invite(
        &sessions_ks,
        base_url,
        enrollment_ttl,
        &did,
        &role,
    )
    .await?;

    Ok(())
}

async fn run_export_sealed(
    config_path: Option<PathBuf>,
    request: PathBuf,
    out: PathBuf,
    digest_out: Option<PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;

    let producer_did = config
        .server_did
        .clone()
        .ok_or("server_did not set in config — run setup first")?;

    let secret_store = secret_store::create_secret_store(&config)?;
    let secrets = secret_store
        .get()
        .await?
        .ok_or("no secrets found — run setup first")?;

    let info = did_hosting_common::server::vta_setup::export_sealed_did_secrets(
        &request,
        &out,
        &producer_did,
        &producer_did,
        secrets.signing_key.clone(),
        secrets.key_agreement_key.clone(),
        did_hosting_common::server::vta_setup::ExportAssertionMode::DidSigned {
            signing_key_multibase: secrets.signing_key.clone(),
            verification_method: format!("{producer_did}#key-0"),
        },
    )
    .await?;

    if let Some(ref digest_path) = digest_out {
        if let Some(parent) = digest_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(digest_path, format!("{}\n", info.digest))?;
    }

    let producer_pub = affinidi_tdk::secrets_resolver::secrets::Secret::from_multibase(
        &secrets.signing_key,
        None,
    )?
    .get_public_keymultibase()?;

    eprintln!();
    eprintln!("  Sealed export ready.");
    eprintln!();
    eprintln!("  Out:            {}", info.out_path.display());
    eprintln!("  Recipient DID:  {}", info.recipient_did);
    eprintln!("  Bundle id:      {}", info.bundle_id_hex);
    eprintln!();
    eprintln!("  SHA-256 digest (send OOB to receiver):");
    eprintln!("    {}", info.digest);
    if let Some(ref p) = digest_out {
        eprintln!("  Digest also written to {}", p.display());
    }
    eprintln!();
    eprintln!("  Producer assertion mode: DidSigned. The bundle is signed by");
    eprintln!("  this control plane's `#key-0` Ed25519 key. Receivers who pin");
    eprintln!("  the pubkey get cryptographic verification; without it the OOB");
    eprintln!("  digest stays the only anchor.");
    eprintln!();
    eprintln!("  Producer pubkey (share with receiver — matches #key-0):");
    eprintln!("    {producer_pub}");
    eprintln!();
    eprintln!("  Next on the receiver:");
    eprintln!(
        "    did-hosting-control import-sealed --bundle {} \\\n      --expect-digest {} \\\n      --producer-pubkey {producer_pub}",
        info.out_path.display(),
        info.digest
    );
    eprintln!();

    Ok(())
}

async fn run_import_sealed(
    config_path: Option<PathBuf>,
    bundle: PathBuf,
    expect_digest: String,
    seed: PathBuf,
    producer_pubkey: Option<String>,
    jwt_key: Option<String>,
    force: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    use affinidi_tdk::secrets_resolver::secrets::Secret;
    use did_hosting_common::server::vta_setup::{
        generate_ed25519_multibase, open_sealed_did_secrets,
    };

    let config = AppConfig::load(config_path)?;
    let secret_store = secret_store::create_secret_store(&config)?;

    if !force && let Ok(Some(_)) = secret_store.get().await {
        return Err("secrets already exist — use --force to overwrite".into());
    }

    let expected_pubkey_bytes = match producer_pubkey.as_deref() {
        Some(mb) => Some(decode_ed25519_pubkey_multibase(mb)?),
        None => None,
    };

    let armor =
        std::fs::read_to_string(&bundle).map_err(|e| format!("read {}: {e}", bundle.display()))?;
    let result = open_sealed_did_secrets(
        &armor,
        &expect_digest,
        &seed,
        expected_pubkey_bytes.as_ref(),
    )?;

    Secret::from_multibase(&result.signing_key_multibase, None)
        .map_err(|e| format!("invalid signing key in bundle: {e}"))?;
    Secret::from_multibase(&result.key_agreement_multibase, None)
        .map_err(|e| format!("invalid key-agreement key in bundle: {e}"))?;

    let resolved_jwt = match jwt_key {
        Some(key) => {
            Secret::from_multibase(&key, None)
                .map_err(|e| format!("invalid JWT signing key: {e}"))?;
            key
        }
        None => {
            eprintln!("  Generated JWT signing key.");
            generate_ed25519_multibase()
        }
    };

    let server_secrets = secret_store::ServerSecrets {
        signing_key: result.signing_key_multibase,
        key_agreement_key: result.key_agreement_multibase,
        jwt_signing_key: resolved_jwt,
        vta_credential: None,
        retired: Vec::new(),
    };

    secret_store.set(&server_secrets).await?;

    eprintln!();
    eprintln!("  Sealed bundle opened and imported.");
    eprintln!();
    eprintln!("  DID:            {}", result.did);
    if result.assertion_verified {
        eprintln!(
            "  Producer DID:   {} (DidSigned — signature verified)",
            result.producer_did
        );
    } else {
        eprintln!(
            "  Producer DID:   {} (informational — no producer pubkey supplied)",
            result.producer_did
        );
    }
    eprintln!();
    eprintln!(
        "  Note: update server_did in config.toml to {} if not already set.",
        result.did
    );
    eprintln!();

    Ok(())
}

fn decode_ed25519_pubkey_multibase(mb: &str) -> Result<[u8; 32], Box<dyn std::error::Error>> {
    let (_, raw) =
        multibase::decode(mb).map_err(|e| format!("invalid producer pubkey multibase: {e}"))?;
    let pk_bytes: &[u8] = if raw.len() == 34 && raw[0] == 0xed && raw[1] == 0x01 {
        &raw[2..]
    } else {
        &raw[..]
    };
    pk_bytes
        .try_into()
        .map_err(|_| "producer pubkey is not a 32-byte Ed25519 key".into())
}

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}██████╗ {cyan}██╗     {reset}
{cyan}██╔═══╝{magenta} ╚══██╔══╝{yellow}██╔══██╗{cyan}██║     {reset}
{cyan}██║    {magenta}    ██║   {yellow}██████╔╝{cyan}██║     {reset}
{cyan}██║    {magenta}    ██║   {yellow}██╔══██╗{cyan}██║     {reset}
{cyan}╚██████╗{magenta}   ██║   {yellow}██║  ██║{cyan}███████╗{reset}
{cyan} ╚═════╝{magenta}   ╚═╝   {yellow}╚═╝  ╚═╝{cyan}╚══════╝{reset}
{dim}  DID Hosting Control Plane v{version}{reset}
"#,
        version = env!("CARGO_PKG_VERSION"),
    );
}

/// `identity-list` — show which key material this service still honours.
async fn run_tsp_relationship_list(
    config_path: Option<PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    did_hosting_common::server::cli_tsp::run_list(&config.store).await
}

async fn run_tsp_relationship_reset(
    config_path: Option<PathBuf>,
    peer: String,
    our: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    use did_hosting_common::server::cli_tsp::{Target, run_reset};
    let config = AppConfig::load(config_path)?;
    run_reset(&config.store, Target::Peer { peer, our }).await
}

async fn run_tsp_relationship_delete(
    config_path: Option<PathBuf>,
    peer: Option<String>,
    our: Option<String>,
    all: bool,
    yes: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    use did_hosting_common::server::cli_tsp::{Target, run_delete};
    let config = AppConfig::load(config_path)?;
    let target = match peer {
        Some(peer) if !all => Target::Peer { peer, our },
        _ => Target::All,
    };
    run_delete(&config.store, target, yes).await
}

async fn run_identity_list(config_path: Option<PathBuf>) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    did_hosting_common::server::cli_identity::run_list_generations(&config.store).await
}

/// `identity-retire-now` — the offline kill switch.
///
/// Opens the store directly, so it only works against a *stopped* service. A
/// live service must be retired through the control plane's REST endpoint (or
/// the UI button), which drops the key from the running process's secrets
/// resolver — deleting a record on disk would not.
async fn run_identity_retire_now(
    config_path: Option<PathBuf>,
    generation: u64,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    did_hosting_common::server::cli_identity::run_retire_generation(
        &config.store,
        &config.secrets,
        &config.config_path,
        generation,
    )
    .await
}

/// `identity-rotate-keys` — rotate the service's own keys, offline.
///
/// Writes the new DID log entry, the new key material (carrying the outgoing key
/// into the retired set in the same write), and the generation records. The
/// service comes back up already holding both key-agreement keys.
async fn run_identity_rotate_keys(
    config_path: Option<PathBuf>,
    keys: String,
    ka_key: Option<String>,
    signing_key: Option<String>,
    grace: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    use did_hosting_common::server::identity_rotate::{RotateKeys, rotate_keys};
    use did_hosting_common::server::secret_store::create_secret_store;
    use did_hosting_common::server::store::Store;

    let config = AppConfig::load(config_path)?;
    let server_did = config
        .server_did
        .as_deref()
        .ok_or("server_did is not set — this service has no identity to rotate")?;

    let which = RotateKeys::parse(&keys)?;
    let grace_secs = match grace.as_deref() {
        Some(s) => did_hosting_common::server::pending_purge::parse_grace_string(s)
            .map_err(|e| format!("invalid --grace: {e}"))?,
        None => config.identity.rotation_grace_secs(),
    };

    let store = Store::open(&config.store).await?;
    let secret_store = create_secret_store(&config.secrets, &config.config_path)?;

    let report = rotate_keys(
        &store,
        secret_store.as_ref(),
        server_did,
        which,
        ka_key.as_deref(),
        signing_key.as_deref(),
        grace_secs,
    )
    .await?;

    eprintln!();
    eprintln!("  Rotated keys for {}", report.did);

    if report.which != RotateKeys::Signing {
        eprintln!("    key agreement (new) : {}", report.new_ka_kid);
        if grace_secs > 0 {
            eprintln!(
                "    key agreement (old) : {}  — honoured for {}m",
                report.retired_ka_kid,
                grace_secs / 60
            );
        } else {
            eprintln!(
                "    key agreement (old) : {}  — RETIRED IMMEDIATELY, no grace period",
                report.retired_ka_kid
            );
        }
    }

    if report.which != RotateKeys::KeyAgreement {
        eprintln!("    signing       (new) : {}", report.new_signing_kid);
        eprintln!("    signing       (old) : {}", report.retired_signing_kid);
        eprintln!();
        eprintln!("  The old signing key's authority to publish DID updates is REVOKED as of");
        eprintln!("  this log entry — it can no longer sign an update the chain will accept.");
        eprintln!("  There is no grace period for a signing key and there cannot be: peers");
        eprintln!("  holding a cached DID document will reject signatures made with the new");
        eprintln!("  key until they re-resolve.");
    }

    eprintln!();
    eprintln!(
        "    generation {} -> {}",
        report.retired_generation, report.new_generation
    );
    eprintln!("    did.jsonl now has {} entries", report.version_count);
    eprintln!();
    if grace_secs > 0 && report.which != RotateKeys::Signing {
        eprintln!("  Start the service. It will honour BOTH key-agreement keys, so peers");
        eprintln!("  holding a cached DID document can still reach it until the old one expires.");
    } else {
        eprintln!("  Start the service.");
    }
    eprintln!();

    Ok(())
}