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
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
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
use clap::{Parser, Subcommand};
use did_hosting_common::server::store::KS_DIDS;
use did_hosting_server::config::AppConfig;
use did_hosting_server::{
    backup, bootstrap, health, secret_store, server, setup, setup_recipe, store,
};
use std::path::PathBuf;

#[derive(Parser)]
#[command(name = "did-hosting-server", about = "DID Hosting Server", 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-server-build.toml`.
        /// For `vta_mode = "online"` also pass `--setup-key-file <path>`
        /// (Phase 2). For `offline-complete`, the recipe carries the
        /// bundle path + digest.
        #[arg(long, value_name = "FILE")]
        from: Option<PathBuf>,
        /// Refuse to run when an existing setup is detected, unless this
        /// flag is set. Without it, the wizard exits 4 to protect issued
        /// JWTs and active VTA sessions.
        #[arg(long)]
        force_reprovision: bool,
        /// Explicit "no TTY available" flag. Requires `--from`. With this
        /// set, missing required recipe fields fail fast instead of
        /// dropping into prompts (which would hang in CI).
        #[arg(long, requires = "from")]
        non_interactive: bool,
    },
    /// Teardown a server install: clears managed secrets from the
    /// configured backend, removes the config file (and `.bak`).
    Uninstall {
        /// Skip the typed "DELETE" confirmation prompt. CI use only.
        #[arg(long)]
        yes: bool,
    },
    /// Run health check diagnostics
    Health,
    /// 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,
    },
    /// Export server data to a backup file
    Backup {
        /// Output file path (use "-" for stdout)
        #[arg(short, long, default_value = "webvh-backup.json")]
        output: String,
    },
    /// Restore server data from a backup file
    Restore {
        /// Input backup file path
        #[arg(short, long)]
        input: String,
    },
    /// Load a DID at an arbitrary path (e.g., "services/control")
    LoadDid {
        /// Path to store the DID at (e.g., "services/control")
        #[arg(long)]
        path: String,
        /// Path to the did.jsonl file
        #[arg(long)]
        did_log: PathBuf,
        /// Optional did-witness.json file
        #[arg(long)]
        did_witness: Option<PathBuf>,
    },
    /// Recreate a DID at a given path (deletes existing, creates new, updates config)
    RecreateDid {
        /// DID path/mnemonic to recreate (e.g. "webvh/server1")
        #[arg(long)]
        path: String,
    },
    /// Bootstrap a DID for this server (defaults to root .well-known)
    BootstrapDid {
        /// DID path/mnemonic to bootstrap (e.g. "my-org", "services/auth")
        /// Defaults to ".well-known" (the root DID for this server)
        #[arg(long, default_value = ".well-known")]
        path: String,
        /// Path to an existing did.jsonl file to import
        #[arg(long)]
        did_log: Option<PathBuf>,
        /// Path to an existing did-witness.json file to import (requires --did-log)
        #[arg(long)]
        did_witness: Option<PathBuf>,
        /// Witness service URL for requesting a proof (auto-bootstrap only)
        #[arg(long, requires = "witness_did")]
        witness_url: Option<String>,
        /// Witness ID to use when requesting a proof (auto-bootstrap only)
        #[arg(long)]
        witness_id: Option<String>,
        /// The witness server's own DID (its `server_did`), required with
        /// --witness-url. The sign-in is addressed to it, and the witness
        /// server refuses one addressed elsewhere. This is not --witness-id,
        /// which names one of the witnesses that server hosts.
        #[arg(long)]
        witness_did: Option<String>,
    },
    /// Recover a soft-deleted DID
    RecoverDid {
        /// DID path/mnemonic to recover (e.g. "webvh/server1")
        #[arg(long)]
        path: String,
    },
    /// Dump the DID log (did.jsonl) for a given path
    DumpDid {
        /// DID path/mnemonic to dump (e.g. ".well-known", "my-org")
        #[arg(long)]
        path: String,
        /// Also dump the witness proof (did-witness.json)
        #[arg(long)]
        witness: bool,
    },
    /// List all DIDs in the store
    ListDids,
    /// Remove a DID and all its data from the store
    RemoveDid {
        /// DID path/mnemonic to remove (e.g. "glenn", ".well-known")
        #[arg(long)]
        path: String,
    },
    /// Export this server's DID + signing/KA keys as an HPKE-sealed
    /// migration bundle.
    ///
    /// Reads the receiver's `bootstrap-request.json` (same shape that
    /// `vta-request` or `setup-offline-prepare` produces), loads the
    /// existing server identity from the configured secret store,
    /// wraps the keys as a `DidSecrets` payload, and seals to the
    /// receiver's ephemeral X25519 pubkey. Prints a SHA-256 digest
    /// that the receiver MUST verify out-of-band before opening —
    /// the current `PinnedOnly` producer assertion has no in-band
    /// integrity anchor.
    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 server'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 (from
        /// the operator, out-of-band).
        #[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 PinnedOnly trust.
        #[arg(long)]
        producer_pubkey: Option<String>,
        /// Overwrite existing secrets without prompting.
        #[arg(long)]
        force: bool,
    },
    /// Import secrets from a VTA secrets bundle or individual keys
    ImportSecrets {
        /// Base64url-encoded VTA secrets bundle (from `vta create-did-webvh`)
        #[arg(long, group = "source")]
        vta_bundle: Option<String>,
        /// Ed25519 signing key (multibase-encoded)
        #[arg(long, group = "source")]
        signing_key: Option<String>,
        /// X25519 key agreement key (multibase-encoded, required with --signing-key)
        #[arg(long)]
        ka_key: Option<String>,
        /// VTA credential bundle (base64url-encoded, optional)
        #[arg(long)]
        vta_credential: Option<String>,
        /// Overwrite existing secrets without prompting
        #[arg(long)]
        force: bool,
    },
    /// 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 per the choices captured in the
    /// state file, and imports the server's own DID into the local store.
    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,
    },
    /// 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-server")]
        label: String,
        /// Public URL where this server serves DIDs. Bound to the
        /// `did-hosting-daemon` template's `URL` variable so the rendered DID
        /// exposes a `WebVHHosting` service at this URL. Runtime DIDComm
        /// (sync from the control plane) uses the daemon's separately
        /// configured mediator and is not embedded in this DID document.
        #[arg(long)]
        public_url: 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,
        /// DIDComm mediator DID to advertise on this server's DID. When set,
        /// the rendered DID exposes a `TSPTransport` and/or `DIDCommMessaging`
        /// service at this mediator (per `--transport`), so peers can reach
        /// the server over messaging without out-of-band config — matching
        /// the interactive setup and the control / daemon deployments. Omit
        /// for an HTTP-only DID.
        #[arg(long)]
        mediator_did: Option<String>,
        /// Which messaging transport(s) to advertise at `--mediator-did`:
        /// `both`, `tsp`, or `didcomm`. Ignored when no mediator is given.
        #[arg(long, default_value = "both")]
        transport: String,
    },
    /// Open a sealed VTA bootstrap response.
    ///
    /// 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 `did-hosting-server bootstrap-did` / `import-secrets`.
    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 = "server-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 = "server-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 the multibase keys into `did-hosting-server import-secrets`.
        #[arg(long, default_value = "server-secrets.json")]
        secrets_out: PathBuf,
    },
}

#[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_wizard(cli.config, 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"));
            match setup_recipe::run_uninstall(&config_path, yes).await {
                Ok(()) => {}
                Err(e) => {
                    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::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::Backup { output }) => {
            if let Err(e) = backup::run_backup(cli.config, output).await {
                eprintln!("Backup error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::Restore { input }) => {
            if let Err(e) = backup::run_restore(cli.config, input).await {
                eprintln!("Restore error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::LoadDid {
            path,
            did_log,
            did_witness,
        }) => {
            if let Err(e) = run_load_did(cli.config, path, did_log, did_witness).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::RecreateDid { path }) => {
            if let Err(e) = run_recreate_did(cli.config, path).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::RecoverDid { path }) => {
            if let Err(e) = run_recover_did(cli.config, path).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::ImportSecrets {
            vta_bundle,
            signing_key,
            ka_key,
            vta_credential,
            force,
        }) => {
            if let Err(e) = run_import_secrets(
                cli.config,
                vta_bundle,
                signing_key,
                ka_key,
                vta_credential,
                force,
            )
            .await
            {
                eprintln!("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,
            force,
        }) => {
            if let Err(e) = run_import_sealed(
                cli.config,
                bundle,
                expect_digest,
                seed,
                producer_pubkey,
                force,
            )
            .await
            {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::SetupOfflinePrepare { request, state }) => {
            if let Err(e) = setup::run_setup_offline_prepare(cli.config, 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::VtaRequest {
            out,
            seed,
            label,
            public_url,
            context,
            mediator_did,
            transport,
        }) => {
            // `public_url` carries the DID path; split it back out so the
            // shared builder folds it identically to the wizard. The DID
            // advertises its messaging transport(s) when `--mediator-did` is
            // given, and stays HTTP-only otherwise.
            let transport =
                match did_hosting_common::server::config::TransportSelection::parse(&transport) {
                    Ok(t) => t,
                    Err(e) => {
                        eprintln!("Error: {e}");
                        std::process::exit(1);
                    }
                };
            let (origin, did_path) =
                did_hosting_common::server::setup_recipe::split_origin_and_did_path(&public_url);
            let shape = did_hosting_common::server::vta_setup::WebvhDidShape::Hosted {
                origin: &origin,
                did_path: &did_path,
                mediator_did: mediator_did.as_deref(),
                transport,
                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-server",
                &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::ImportSecrets {
                    binary: "did-hosting-server",
                },
            ) {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::BootstrapDid {
            path,
            did_log,
            did_witness,
            witness_url,
            witness_id,
            witness_did,
        }) => {
            if let Err(e) = run_bootstrap_did(
                cli.config,
                path,
                did_log,
                did_witness,
                witness_url,
                witness_id,
                witness_did,
            )
            .await
            {
                eprintln!("Bootstrap error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::DumpDid { path, witness }) => {
            if let Err(e) = run_dump_did(cli.config, path, witness).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::ListDids) => {
            if let Err(e) = run_list_dids(cli.config).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Command::RemoveDid { path }) => {
            if let Err(e) = run_remove_did(cli.config, path).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        None => run_server(cli.config).await,
    }
}

async fn run_load_did(
    config_path: Option<PathBuf>,
    path: String,
    did_log: PathBuf,
    did_witness: Option<PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let store = store::Store::open(&config.store).await?;
    let dids_ks = store.keyspace(KS_DIDS)?;

    let jsonl = std::fs::read_to_string(&did_log)
        .map_err(|e| format!("failed to read {}: {e}", did_log.display()))?;

    let witness_content = match &did_witness {
        Some(wp) => Some(
            std::fs::read_to_string(wp)
                .map_err(|e| format!("failed to read {}: {e}", wp.display()))?,
        ),
        None => None,
    };

    let result =
        bootstrap::import_did_at_path(&store, &dids_ks, &path, &jsonl, witness_content.as_deref())
            .await?;

    store.persist().await?;

    eprintln!();
    eprintln!("  DID loaded at path '{path}'!");
    eprintln!();
    eprintln!("  DID:  {}", result.did_id);
    eprintln!("  SCID: {}", result.scid);
    eprintln!("  Path: {path}/did.jsonl");
    eprintln!();

    Ok(())
}

async fn run_recover_did(
    config_path: Option<PathBuf>,
    mnemonic: String,
) -> Result<(), Box<dyn std::error::Error>> {
    use did_hosting_common::did_ops::DidRecord;

    let config = AppConfig::load(config_path)?;
    let store_instance = store::Store::open(&config.store).await?;
    let dids_ks = store_instance.keyspace(KS_DIDS)?;

    let did_key = format!("did:{mnemonic}");
    let mut record: DidRecord = dids_ks
        .get(did_key.as_str())
        .await?
        .ok_or(format!("DID not found at path '{mnemonic}'"))?;

    if record.deleted_at.is_none() {
        eprintln!("  DID at path '{mnemonic}' is not deleted.");
        return Ok(());
    }

    record.deleted_at = None;
    dids_ks.insert(did_key.as_str(), &record).await?;
    store_instance.persist().await?;

    eprintln!();
    eprintln!("  DID recovered at path '{mnemonic}'!");
    if let Some(ref did_id) = record.did_id {
        eprintln!("  DID: {did_id}");
    }
    eprintln!();

    Ok(())
}

async fn run_recreate_did(
    config_path: Option<PathBuf>,
    mnemonic: String,
) -> Result<(), Box<dyn std::error::Error>> {
    use affinidi_tdk::secrets_resolver::secrets::Secret;

    let config = AppConfig::load(config_path)?;
    let config_file = config.config_path.clone();

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

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

    // Delete existing DID at this path if it exists
    let did_key = did_hosting_server::did_ops::did_key(&mnemonic);
    if dids_ks.contains_key(did_key.clone()).await? {
        // Remove the DID record and its content
        dids_ks.remove(did_key).await?;
        dids_ks
            .remove(did_hosting_server::did_ops::content_log_key(&mnemonic))
            .await?;
        dids_ks
            .remove(did_hosting_server::did_ops::content_witness_key(&mnemonic))
            .await?;
        // Remove owner index entry (owner is "system" for bootstrapped DIDs)
        dids_ks
            .remove(did_hosting_server::did_ops::owner_key("system", &mnemonic))
            .await?;
        eprintln!("  Removed existing DID at path '{mnemonic}'");
    }

    // Create new DID
    let secret_store = secret_store::create_secret_store(&config)?;
    let secrets = secret_store
        .get()
        .await?
        .ok_or("no secrets found — run `did-hosting-server setup` first")?;

    let signing_secret = Secret::from_multibase(&secrets.signing_key, None)
        .map_err(|e| format!("invalid signing_key: {e}"))?;
    let ka_secret = Secret::from_multibase(&secrets.key_agreement_key, None).ok();

    // Discover mediator from VTA DID for the DIDCommMessaging service
    let mediator_uri = if let Some(ref vta_did) = config.mediator_did {
        use did_hosting_common::server::didcomm_profile::resolve_mediator_did;
        resolve_mediator_did(vta_did, None).await
    } else {
        None
    };

    let result = bootstrap::bootstrap_did(
        &store,
        &dids_ks,
        &signing_secret,
        ka_secret.as_ref(),
        mediator_uri.as_deref(),
        config.features.didcomm,
        config.features.tsp,
        public_url,
        &mnemonic,
    )
    .await?;

    store.persist().await?;

    // Update server_did in config file
    setup::update_server_did_in_config(&config_file, &result.did_id)?;

    let url_path = if mnemonic == ".well-known" {
        ".well-known/did.jsonl".to_string()
    } else {
        format!("{mnemonic}/did.jsonl")
    };

    eprintln!();
    eprintln!("  DID recreated at path '{mnemonic}'!");
    eprintln!();
    eprintln!("  DID:   {}", result.did_id);
    eprintln!("  SCID:  {}", result.scid);
    eprintln!("  JSONL: {public_url}/{url_path}");
    eprintln!();
    eprintln!("  config.toml updated with new server_did.");
    eprintln!();

    Ok(())
}

async fn run_bootstrap_did(
    config_path: Option<PathBuf>,
    mnemonic: String,
    did_log: Option<PathBuf>,
    did_witness: Option<PathBuf>,
    witness_url: Option<String>,
    witness_id: Option<String>,
    witness_did: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    use affinidi_tdk::secrets_resolver::secrets::Secret;

    if did_witness.is_some() && did_log.is_none() {
        return Err("--did-witness requires --did-log".into());
    }

    let config = AppConfig::load(config_path)?;

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

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

    // Check if DID already exists at this path
    let did_key = did_hosting_server::did_ops::did_key(&mnemonic);
    if dids_ks.contains_key(did_key).await? {
        eprintln!();
        eprintln!("  DID at path '{mnemonic}' already exists.");
        eprintln!("  No action taken.");
        eprintln!();
        return Ok(());
    }

    let result = if let Some(log_path) = did_log {
        // Import from existing files
        let jsonl = std::fs::read_to_string(&log_path)
            .map_err(|e| format!("failed to read {}: {e}", log_path.display()))?;

        let witness_content = match &did_witness {
            Some(path) => Some(
                std::fs::read_to_string(path)
                    .map_err(|e| format!("failed to read {}: {e}", path.display()))?,
            ),
            None => None,
        };

        let result = bootstrap::import_did_at_path(
            &store,
            &dids_ks,
            &mnemonic,
            &jsonl,
            witness_content.as_deref(),
        )
        .await?;

        if did_witness.is_some() {
            eprintln!("  Witness data imported.");
        }

        result
    } else {
        // Auto-bootstrap: generate a new DID
        let secret_store = secret_store::create_secret_store(&config)?;
        let secrets = secret_store
            .get()
            .await?
            .ok_or("no secrets found — run `did-hosting-server setup` first")?;

        let signing_secret = Secret::from_multibase(&secrets.signing_key, None)
            .map_err(|e| format!("invalid signing_key: {e}"))?;
        let ka_secret = Secret::from_multibase(&secrets.key_agreement_key, None).ok();

        // Discover mediator from VTA DID for the DIDCommMessaging service
        let mediator_uri = if let Some(ref vta_did) = config.mediator_did {
            use did_hosting_common::server::didcomm_profile::resolve_mediator_did;
            resolve_mediator_did(vta_did, None).await
        } else {
            None
        };

        let result = bootstrap::bootstrap_did(
            &store,
            &dids_ks,
            &signing_secret,
            ka_secret.as_ref(),
            mediator_uri.as_deref(),
            config.features.didcomm,
            config.features.tsp,
            public_url,
            &mnemonic,
        )
        .await?;

        // Optional: request witness proof
        if let (Some(w_url), Some(w_id), Some(w_did)) = (witness_url, witness_id, witness_did) {
            eprintln!("  Requesting witness proof...");
            eprintln!("  NOTE: the DID must already be served (by a running server) for the");
            eprintln!("  witness to resolve it and verify the request.");
            match bootstrap::request_witness_proof(&w_url, &w_did, &w_id, &result, &signing_secret)
                .await
            {
                Ok(witness_file) => {
                    dids_ks
                        .insert_raw(
                            did_hosting_server::did_ops::content_witness_key(&mnemonic),
                            witness_file.into_bytes(),
                        )
                        .await?;
                    eprintln!("  Witness proof stored.");
                }
                Err(e) => {
                    eprintln!("  Warning: witness proof request failed: {e}");
                    eprintln!("  The DID was created but has no witness proof.");
                }
            }
        }

        result
    };

    store.persist().await?;

    let is_root = mnemonic == ".well-known";
    let url_path = if is_root {
        ".well-known/did.jsonl".to_string()
    } else {
        format!("{mnemonic}/did.jsonl")
    };

    eprintln!();
    if is_root {
        eprintln!("  Root DID bootstrapped!");
    } else {
        eprintln!("  DID bootstrapped at path '{mnemonic}'!");
    }
    eprintln!();
    eprintln!("  DID:   {}", result.did_id);
    eprintln!("  SCID:  {}", result.scid);
    eprintln!("  JSONL: {public_url}/{url_path}");
    eprintln!();
    if is_root && config.server_did.is_none() {
        eprintln!("  Hint: set server_did in your config.toml:");
        eprintln!("    server_did = \"{}\"", result.did_id);
        eprintln!();
    }

    Ok(())
}

async fn run_dump_did(
    config_path: Option<PathBuf>,
    mnemonic: String,
    witness: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    use did_hosting_common::did_ops::{content_log_key, content_witness_key, did_key};

    let config = AppConfig::load(config_path)?;
    let store_handle = store::Store::open(&config.store).await?;
    let dids_ks = store_handle.keyspace(KS_DIDS)?;

    // Verify the DID exists
    let _: did_hosting_common::did_ops::DidRecord = dids_ks
        .get(did_key(&mnemonic))
        .await?
        .ok_or(format!("DID not found at path '{mnemonic}'"))?;

    // Dump did.jsonl to stdout
    let log_bytes = dids_ks
        .get_raw(content_log_key(&mnemonic))
        .await?
        .ok_or(format!("no log content for path '{mnemonic}'"))?;
    let log = String::from_utf8(log_bytes)
        .map_err(|_| format!("invalid UTF-8 in log content for '{mnemonic}'"))?;
    print!("{log}");

    // Optionally dump witness
    if witness {
        if let Some(witness_bytes) = dids_ks.get_raw(content_witness_key(&mnemonic)).await? {
            let witness_str = String::from_utf8(witness_bytes)
                .map_err(|_| format!("invalid UTF-8 in witness content for '{mnemonic}'"))?;
            eprintln!("--- did-witness.json ---");
            print!("{witness_str}");
        } else {
            eprintln!("(no witness content)");
        }
    }

    Ok(())
}

async fn run_list_dids(config_path: Option<PathBuf>) -> Result<(), Box<dyn std::error::Error>> {
    use did_hosting_common::did_ops::DidRecord;

    let config = AppConfig::load(config_path)?;
    let store_handle = store::Store::open(&config.store).await?;
    let dids_ks = store_handle.keyspace(KS_DIDS)?;

    let raw = dids_ks.prefix_iter_raw("did:").await?;

    if raw.is_empty() {
        eprintln!("  No DIDs in store.");
        return Ok(());
    }

    eprintln!("  {:<25} {:<15} {:<60}", "PATH", "VERSIONS", "DID ID");
    eprintln!("  {}", "-".repeat(100));

    for (_key, value) in &raw {
        if let Ok(record) = serde_json::from_slice::<DidRecord>(value) {
            let did_id = record.did_id.as_deref().unwrap_or("(unpublished)");
            let deleted = if record.deleted_at.is_some() {
                " [deleted]"
            } else {
                ""
            };
            let disabled = if record.disabled { " [disabled]" } else { "" };
            eprintln!(
                "  {:<25} {:<15} {}{}{}",
                record.mnemonic, record.version_count, did_id, deleted, disabled
            );
        }
    }

    eprintln!();
    eprintln!("  Total: {} DIDs", raw.len());

    Ok(())
}

async fn run_remove_did(
    config_path: Option<PathBuf>,
    path: String,
) -> Result<(), Box<dyn std::error::Error>> {
    use did_hosting_common::did_ops::{
        DidRecord, content_log_key, content_witness_key, did_key, owner_key,
    };

    let config = AppConfig::load(config_path)?;
    let store_handle = store::Store::open(&config.store).await?;
    let dids_ks = store_handle.keyspace(KS_DIDS)?;

    let record: Option<DidRecord> = dids_ks.get(did_key(&path)).await?;
    let record = match record {
        Some(r) => r,
        None => {
            eprintln!("  DID not found at path '{path}'");
            std::process::exit(1);
        }
    };

    let did_id = record.did_id.as_deref().unwrap_or("(unpublished)");
    eprintln!("  Removing DID at path '{path}'");
    eprintln!("  DID ID: {did_id}");
    eprintln!("  Owner:  {}", record.owner);

    let mut batch = store_handle.batch();
    batch.remove(&dids_ks, did_key(&path));
    batch.remove(&dids_ks, content_log_key(&path));
    batch.remove(&dids_ks, content_witness_key(&path));
    batch.remove(&dids_ks, owner_key(&record.owner, &path));
    batch.commit().await?;

    eprintln!("  DID removed.");
    Ok(())
}

async fn run_import_secrets(
    config_path: Option<PathBuf>,
    vta_bundle: Option<String>,
    signing_key: Option<String>,
    ka_key: Option<String>,
    vta_credential: 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;
    use vta_sdk::did_secrets::DidSecretsBundle;
    use vta_sdk::keys::KeyType;

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

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

    let (resolved_signing, resolved_ka, resolved_vta_cred) =
        if let Some(ref bundle_str) = vta_bundle {
            // vta-sdk 0.5 dropped DidSecretsBundle::decode — operators still
            // paste a base64url blob, so deserialize inline:
            // base64url → JSON → bundle.
            use base64::Engine;
            use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64;
            let bundle_json = BASE64
                .decode(bundle_str.as_bytes())
                .map_err(|e| format!("failed to decode VTA secrets bundle base64: {e}"))?;
            let bundle: DidSecretsBundle = serde_json::from_slice(&bundle_json)
                .map_err(|e| format!("failed to decode VTA secrets bundle: {e}"))?;

            let mut signing = None;
            let mut ka = None;

            for entry in &bundle.secrets {
                match entry.key_type {
                    KeyType::Ed25519 if signing.is_none() => {
                        signing = Some(entry.private_key_multibase.clone());
                    }
                    KeyType::X25519 if ka.is_none() => {
                        ka = Some(entry.private_key_multibase.clone());
                    }
                    _ => {}
                }
            }

            let signing = signing.ok_or("VTA bundle contains no Ed25519 signing key")?;
            let ka = ka.ok_or("VTA bundle contains no X25519 key agreement key")?;

            eprintln!("  VTA bundle decoded for DID: {}", bundle.did);
            eprintln!("  Found {} secret(s)", bundle.secrets.len());

            (signing, ka, vta_credential)
        } else if let Some(signing) = signing_key {
            let ka = ka_key.ok_or("--ka-key is required when using --signing-key")?;
            (signing, ka, vta_credential)
        } else {
            return Err("provide either --vta-bundle or --signing-key + --ka-key".into());
        };

    // Validate keys by attempting to parse them
    Secret::from_multibase(&resolved_signing, None)
        .map_err(|e| format!("invalid signing key: {e}"))?;
    Secret::from_multibase(&resolved_ka, None)
        .map_err(|e| format!("invalid key agreement key: {e}"))?;

    // `ServerSecrets` carries a `jwt_signing_key` for every service alike (one
    // shared storage format); this edge has no JWT-based session auth to sign
    // with it (deleted along with the rest of its REST management surface —
    // see `did-hosting-server`'s module docs), so there is nothing here worth
    // exposing an operator override for. Always freshly generated.
    let jwt_signing_key = generate_ed25519_multibase();

    // Carry forward any retired key material.
    //
    // `retired` holds the keys of identity generations that are superseded but
    // still inside their grace period — the ones peers with a cached DID document
    // are still encrypting to. Blanking it here would silently destroy that
    // overlap: the generation records would survive, their key material would
    // not, and the service would come back unable to decrypt traffic still
    // addressed to the old key.
    let retired = match secret_store.get().await {
        Ok(Some(existing)) => existing.retired,
        _ => Vec::new(),
    };
    if !retired.is_empty() {
        eprintln!(
            "  Preserving {} retired key(s) — superseded generations still inside their grace period.",
            retired.len()
        );
    }

    let server_secrets = secret_store::ServerSecrets {
        signing_key: resolved_signing,
        key_agreement_key: resolved_ka,
        jwt_signing_key,
        vta_credential: resolved_vta_cred,
        retired,
    };

    secret_store.set(&server_secrets).await?;

    eprintln!();
    eprintln!("  Secrets imported successfully!");
    eprintln!();
    if secret_store::is_plaintext_backend(&config.secrets) {
        eprintln!("  WARNING: secrets stored in plaintext — not for production use.");
        eprintln!();
    }

    Ok(())
}

async fn run_server(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-server --config <path>");
            eprintln!();
            eprintln!("Or run the setup wizard:");
            eprintln!("  did-hosting-server 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) => {
            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-server setup` first");
            std::process::exit(1);
        }
        Err(e) => {
            eprintln!("Error loading secrets: {e}");
            std::process::exit(1);
        }
    };

    if secret_store::is_plaintext_backend(&config.secrets) {
        tracing::warn!("============================================================");
        tracing::warn!("  PLAINTEXT SECRETS MODE - INSECURE");
        tracing::warn!("  Server secrets are stored as plaintext in the config file.");
        tracing::warn!("  DO NOT use this in production.");
        tracing::warn!("  For production, recompile with a secure backend:");
        tracing::warn!("    keyring, aws-secrets, or gcp-secrets");
        tracing::warn!("============================================================");
    }

    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!("server error: {e}");
        std::process::exit(1);
    }
}

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

    // Load the existing signing + KA keys from the configured secret store.
    let secret_store = secret_store::create_secret_store(&config)?;
    let secrets = secret_store
        .get()
        .await?
        .ok_or("no secrets found — run setup or import-secrets 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))?;
    }

    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!();
    // Extract the Ed25519 public-key multibase so the operator can
    // share it with the receiver (for DidSigned verification).
    let producer_pub = affinidi_tdk::secrets_resolver::secrets::Secret::from_multibase(
        &secrets.signing_key,
        None,
    )?
    .get_public_keymultibase()?;

    eprintln!("  Producer assertion mode: DidSigned. The bundle is signed by");
    eprintln!("  this server's `#key-0` Ed25519 key. Receivers who pin the");
    eprintln!("  producer pubkey via --producer-pubkey get cryptographic");
    eprintln!("  verification; without it the OOB digest stays the only anchor.");
    eprintln!();
    eprintln!("  Producer pubkey (share with receiver — matches #key-0):");
    eprintln!("    {producer_pub}");
    eprintln!();
    eprintln!("  Next steps on the receiver:");
    eprintln!(
        "    did-hosting-server 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>,
    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());
    }

    // Decode the optional producer pubkey (multibase-encoded Ed25519
    // public) for DidSigned verification. None falls back to
    // digest-only trust (accepts any assertion variant, unverified).
    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(),
    )?;

    // Sanity-check the keys parse before writing anything.
    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}"))?;

    // See `run_import_secrets`: this edge never reads its own JWT signing
    // key back (its REST session auth was deleted with the rest of its
    // management surface), so nothing here needs an operator override.
    let jwt_signing_key = generate_ed25519_multibase();

    // Carry forward any retired key material.
    //
    // `retired` holds the keys of identity generations that are superseded but
    // still inside their grace period — the ones peers with a cached DID document
    // are still encrypting to. Blanking it here would silently destroy that
    // overlap: the generation records would survive, their key material would
    // not, and the service would come back unable to decrypt traffic still
    // addressed to the old key.
    let retired = match secret_store.get().await {
        Ok(Some(existing)) => existing.retired,
        _ => Vec::new(),
    };
    if !retired.is_empty() {
        eprintln!(
            "  Preserving {} retired key(s) — superseded generations still inside their grace period.",
            retired.len()
        );
    }

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

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

/// Decode a multibase-encoded Ed25519 public key into the raw 32-byte
/// array. Accepts both the bare-key form (32 bytes after multibase
/// decode) and the multicodec-prefixed form (34 bytes, leading
/// 0xED 0x01).
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}██╗   ██╗{magenta}██╗  ██╗{reset}
{cyan}██║    ██║{magenta}██╔════╝{yellow}██╔══██╗{cyan}██║   ██║{magenta}██║  ██║{reset}
{cyan}██║ █╗ ██║{magenta}█████╗  {yellow}██████╔╝{cyan}██║   ██║{magenta}███████║{reset}
{cyan}██║███╗██║{magenta}██╔══╝  {yellow}██╔══██╗{cyan}╚██╗ ██╔╝{magenta}██╔══██║{reset}
{cyan}╚███╔███╔╝{magenta}███████╗{yellow}██████╔╝{cyan} ╚████╔╝ {magenta}██║  ██║{reset}
{cyan} ╚══╝╚══╝ {magenta}╚══════╝{yellow}╚═════╝ {cyan}  ╚═══╝  {magenta}╚═╝  ╚═╝{reset}
{dim}  DID Hosting Server 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(())
}