net-cli 0.38.1

Unified `net-mesh` command-line tool for the Net mesh
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
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
//! `net-mesh anchor` — the browser-facing anchor's operator surface
//! (plan §5 Layer 0, Stage 4b).
//!
//! This module owns the **browser bootstrap credential**: the
//! artefact an application hands a browser so it can reach an anchor
//! at all (an invite, the anchor Noise key the browser pins, the
//! NKpsk0 PSK, the trust domain that PSK defines, and the bootstrap
//! URL). See [`net_sdk::bootstrap_credential`] for the format and its
//! two lifetimes.
//!
//! ```text
//! net-mesh anchor credential mint    --root … --psk-hex … --anchor-noise-pubkey … --url …
//! net-mesh anchor credential inspect --credential <string|@path>
//! ```
//!
//! **The minted string contains the PSK.** `mint` therefore writes it
//! with the same 0600 staging discipline as `net-mesh org` uses for
//! key material, and refuses to overwrite an existing file without
//! `--force`. `inspect` never prints the PSK — only its trust-domain
//! id, which is a one-way function of it.

use std::path::PathBuf;
use std::time::Duration;

use clap::{Args, Subcommand};
use net_sdk::bootstrap_credential::{BrowserBootstrapCredential, Psk};
use net_sdk::enrollment::InviteToken;
use serde::Serialize;

use crate::commands::identity::{parse_entity_hex, read_identity_file};
use crate::commands::org::{publish_staged, stage_beside};
use crate::error::{generic, invalid_args, CliError};
use crate::parsers::hex_decode_32;
use crate::prelude::{emit_value, OutputFormat};

/// Default standing lifetime of the PSK half: 30 days. The invite
/// nonce's own default is minutes — the two are deliberately far
/// apart, which is the point of stating both in the format.
const DEFAULT_PSK_TTL_SECS: u64 = 30 * 24 * 3600;

/// Default lifetime of the single-use invite half: 15 minutes.
const DEFAULT_INVITE_TTL_SECS: u64 = 15 * 60;

#[derive(Subcommand, Debug)]
pub enum AnchorCommand {
    /// Browser bootstrap credentials (mint / inspect).
    #[command(subcommand)]
    Credential(CredentialCommand),
    /// List the RTC anchors this node has heard announce
    /// themselves, with their `rtc_addr` / `rtc_bootstrap`, plus
    /// `rtc_stun_addr` for an anchor that announced a separate
    /// STUN endpoint.
    ///
    /// Requires the `rtc-bootstrap` build: it reads the listing
    /// from a live daemon's anchor directory, and an anchor row a
    /// build cannot act on is a listing with nothing behind it.
    #[cfg(feature = "rtc-bootstrap")]
    Ls(LsArgs),
    /// Read an anchor's ICE attempt ledger: plan §10's
    /// `ice_direct / ice_attempted` deployment telemetry.
    ///
    /// **The denominator is ATTEMPTS, not sessions.** One attempt is
    /// one signalling dialog — the offer the anchor sent, or an
    /// offer it accepted (which on an anchor includes the bootstrap
    /// dialog of every browser that arrived). A caller that retries
    /// after a timeout spends two attempts; an ICE restart inside
    /// one dialog is one.
    ///
    /// The ratio is reported, never gated, and it is NOT a success
    /// rate for sessions: a relayed session is not a failed one —
    /// the routed path through an anchor is a supported disposition.
    /// Nor is it a per-pair fact; ask the pair whether a pair is
    /// direct.
    ///
    /// Requires the `rtc-bootstrap` build: the ledger is not fold
    /// state, so it is read from the live node that owns it.
    #[cfg(feature = "rtc-bootstrap")]
    Stats(StatsArgs),
    /// Serve the browser bootstrap listener on this node.
    ///
    /// Requires the `rtc-bootstrap` build, which is the one that
    /// carries an HTTP server at all.
    #[cfg(feature = "rtc-bootstrap")]
    Serve(Box<ServeArgs>),
}

/// `net-mesh anchor ls`.
#[cfg(feature = "rtc-bootstrap")]
#[derive(Args, Debug)]
pub struct LsArgs {
    /// Operator identity file.
    #[arg(long, value_name = "PATH")]
    pub identity: Option<PathBuf>,

    /// Supervisor node to query.
    #[arg(long, default_value_t = crate::prelude::DEFAULT_SUPERVISOR_NODE)]
    pub node: u64,

    /// How long to wait for the attached node to ingest the
    /// daemon's announcements before answering. An attach is a fresh
    /// session: the rows arrive as the announcements flood to it.
    #[arg(long = "wait-secs", default_value_t = 5)]
    pub wait_secs: u64,

    /// The daemon to attach to. Anchor rows come from
    /// signature-verified announcements a LIVE mesh has ingested, so
    /// this listing needs a mesh — the Deck client the CLI builds
    /// in-process has none (R6).
    #[command(flatten)]
    pub remote: crate::commands::aggregator::RemoteAttachArgs,
}

/// `net-mesh anchor stats`.
#[cfg(feature = "rtc-bootstrap")]
#[derive(Args, Debug)]
pub struct StatsArgs {
    /// Operator identity file.
    #[arg(long, value_name = "PATH")]
    pub identity: Option<PathBuf>,

    /// Supervisor node to query.
    #[arg(long, default_value_t = crate::prelude::DEFAULT_SUPERVISOR_NODE)]
    pub node: u64,

    /// How long to wait for the anchor to answer.
    #[arg(long = "wait-secs", default_value_t = 5)]
    pub wait_secs: u64,

    /// The anchor to ask. An ICE attempt ledger is the answering
    /// node's OWN and is never announced, so — unlike fold state —
    /// there is no local view of it to fall back on.
    #[command(flatten)]
    pub remote: crate::commands::aggregator::RemoteAttachArgs,
}

#[derive(Subcommand, Debug)]
pub enum CredentialCommand {
    /// Mint a browser bootstrap credential.
    Mint(MintArgs),
    /// Print a credential's fields. Never prints the PSK.
    Inspect(InspectArgs),
}

#[derive(Args, Debug)]
pub struct MintArgs {
    /// Inspect signer, PSK source and output without reading the PSK or minting.
    #[arg(long)]
    pub inspect_target: bool,
    /// The mesh root entity id (64 hex chars, optional `0x`) — the
    /// key a joining browser anchor-verifies its grant against.
    #[arg(long, value_name = "HEX")]
    pub root: String,

    /// The **issuer** identity file (TOML, from
    /// `net-mesh identity generate`) that signs this credential.
    ///
    /// The anchor is configured with its public half and verifies
    /// the signature before reading any other field, so the two
    /// lifetimes are the issuer's to set. A recipient holds the PSK
    /// and can re-encode anything — but cannot sign.
    #[arg(long = "issuer-identity", value_name = "PATH")]
    pub issuer_identity: PathBuf,

    /// Allow a permissive identity-file mode on Unix.
    #[arg(long)]
    pub insecure_permissions: bool,

    /// The anchor's Noise static X25519 **public** key (64 hex
    /// chars). This is the key the browser pins; it is never read
    /// out of the anchor's HTTP response.
    #[arg(long = "anchor-noise-pubkey", value_name = "HEX")]
    pub anchor_noise_pubkey: String,

    /// The trust domain's NKpsk0 PSK (64 hex chars). **A secret**:
    /// prefer `--psk-file`, which keeps it out of the shell history
    /// and the process table.
    #[arg(long = "psk-hex", value_name = "HEX", conflicts_with = "psk_file")]
    pub psk_hex: Option<String>,

    /// Read the PSK (64 hex chars) from a file instead of argv.
    #[arg(long = "psk-file", value_name = "PATH")]
    pub psk_file: Option<PathBuf>,

    /// The anchor's bootstrap listener URL, e.g.
    /// `https://anchor.example.com`. Must be `https://` (or
    /// `http://localhost` for development) — a browser cannot fetch
    /// anything else from a secure context.
    #[arg(long, value_name = "URL")]
    pub url: String,

    /// Lifetime of the single-use invite half, in seconds.
    #[arg(long = "invite-ttl-secs", default_value_t = DEFAULT_INVITE_TTL_SECS)]
    pub invite_ttl_secs: u64,

    /// Lifetime of the standing PSK half, in seconds.
    #[arg(long = "psk-ttl-secs", default_value_t = DEFAULT_PSK_TTL_SECS)]
    pub psk_ttl_secs: u64,

    /// Write the credential string here (0600). Without it the
    /// string goes to stdout, which is what a deployment pipeline
    /// usually wants.
    #[arg(long, value_name = "PATH")]
    pub out: Option<PathBuf>,

    /// Overwrite `--out` if it exists.
    #[arg(long)]
    pub force: bool,
}

#[derive(Args, Debug)]
pub struct InspectArgs {
    /// Inspect input selection without reading or decoding the credential.
    #[arg(long)]
    pub inspect_target: bool,
    /// The credential string, or `@PATH` to read it from a file.
    #[arg(long, value_name = "STRING|@PATH")]
    pub credential: String,

    /// Check the credential against this trust domain's PSK (64 hex
    /// chars) — the check an anchor makes before doing anything with
    /// a presented credential.
    #[arg(long = "psk-hex", value_name = "HEX")]
    pub psk_hex: Option<String>,
}

/// What `mint` reports. The credential string is the payload; every
/// other field is there so the operator can see what they minted
/// without parsing it back.
#[derive(Serialize)]
struct MintReport {
    credential: String,
    trust_domain: String,
    issuer: String,
    bootstrap_url: String,
    /// The single-use half's deadline (unix seconds).
    nonce_expires_at: u64,
    /// The standing half's deadline (unix seconds).
    psk_expires_at: u64,
    /// Present only when `--out` was given.
    #[serde(skip_serializing_if = "Option::is_none")]
    written_to: Option<String>,
}

/// What `inspect` reports. **No PSK field exists on this struct** —
/// the trust-domain id is the only thing derived from it that is
/// safe to print.
#[derive(Serialize)]
struct InspectReport {
    root: String,
    rendezvous: String,
    bootstrap_url: String,
    anchor_noise_pubkey: String,
    trust_domain: String,
    issuer: String,
    nonce_expires_at: u64,
    psk_expires_at: u64,
    /// `Ok` / the reason the credential is not presentable right now.
    status: String,
    /// Present only with `--psk-hex`: whether this credential belongs
    /// to that PSK's trust domain.
    #[serde(skip_serializing_if = "Option::is_none")]
    trust_domain_matches: Option<bool>,
}

/// One row of `net-mesh anchor ls`.
#[cfg(feature = "rtc-bootstrap")]
#[derive(serde::Serialize)]
struct AnchorRow {
    node: String,
    rtc_addr: Option<String>,
    /// The anchor's **separately announced STUN endpoint** (Stage
    /// 6), when it configured one. Omitted from the JSON otherwise:
    /// the overwhelming majority of anchors announce none, and a row
    /// for one of those must read exactly as it did before this
    /// field existed. The siblings keep emitting `null` — they
    /// predate the convention, and changing their rendering is a
    /// consumer-visible decision this slice does not make.
    #[serde(skip_serializing_if = "Option::is_none")]
    rtc_stun_addr: Option<String>,
    rtc_bootstrap: Option<String>,
    noise_pubkey: Option<String>,
}

/// What `net-mesh anchor stats` prints.
///
/// Every field the operator needs to read the ratio correctly is in
/// the row — the denominator, the residual, and the denominator's
/// own definition — because a ratio whose denominator is ambiguous
/// is a metric that gets misread for a year.
#[cfg(feature = "rtc-bootstrap")]
#[derive(serde::Serialize)]
struct IceStatsRow {
    /// The anchor that answered. The ledger is its own.
    node: String,
    /// `false` when that node has no RTC driver: it keeps no attempt
    /// ledger at all, and the counters below are placeholders rather
    /// than observations.
    rtc_configured: bool,
    /// **The denominator**: direct-path attempts, one per signalling
    /// dialog.
    ice_attempted: u64,
    /// Attempts that ended with an installed direct RTC endpoint.
    ice_direct: u64,
    /// Attempts that hit their deadline with ICE never connected —
    /// for a peer dialog, the pair stayed on the anchor. Not a
    /// failure.
    ice_relayed: u64,
    /// Attempts that ended for a reason other than their deadline.
    ice_failed: u64,
    /// Attempts still in flight. The outcome terms sum to
    /// `ice_attempted` only when this is zero.
    ice_pending: u64,
    /// `ice_direct / ice_attempted`, or `null` when nothing has been
    /// attempted. **`null` is not `0.0`** — no attempts is not zero
    /// per cent.
    ice_direct_ratio: Option<f64>,
    /// The ratio as an operator reads it out loud, denominator
    /// included (`"6/9 attempts (67%)"`), or the reason there is no
    /// number. Rendered, never parsed.
    ice_direct_display: String,
    /// What the denominator IS, carried with the numbers so the
    /// ratio cannot be quoted without it.
    denominator: &'static str,
    /// What the ratio does NOT mean.
    caveat: &'static str,
    /// Bootstrap requests refused by the per-source rate limit (an
    /// IPv6 source is charged by its /64). Absent from an anchor that
    /// predates the counter.
    #[serde(skip_serializing_if = "Option::is_none")]
    bootstrap_rate_limited: Option<u64>,
    /// Bootstrap requests refused because the limiter was full of live
    /// sources and this one was new. Absent from an older anchor.
    #[serde(skip_serializing_if = "Option::is_none")]
    bootstrap_rate_table_full: Option<u64>,
}

/// The one-line prose form of the denominator, printed with every
/// row.
#[cfg(feature = "rtc-bootstrap")]
const ICE_DENOMINATOR: &str = "ice_attempted = direct-path ATTEMPTS, one per signalling dialog \
     (the offer this anchor sent, or an offer it accepted — including each browser's bootstrap \
     dialog, and on a browser leaf its own bootstrap dialog with its anchor, so a page that went \
     direct with one peer reports TWO attempts). Not sessions, not peers: a retry after a timeout \
     spends two attempts, and an ICE restart inside one dialog is one. PER PARTICIPANT, never per \
     system: this is THIS node's own ledger. Two browsers going direct through one anchor is three \
     dialogs in the system, and no counter reports three — each browser reports two and this \
     anchor reports two. Summing ledgers across nodes double-counts every pair dialog.";

/// The one-line prose form of what the ratio is not.
#[cfg(feature = "rtc-bootstrap")]
const ICE_CAVEAT: &str = "Reported, never gated. NOT a success rate for sessions: a relayed \
     session is not a failed one — the routed path through an anchor is a supported disposition, \
     and ICE reaching `connected` is not a health gate. NOT a per-pair fact either: ask the pair \
     (`peer_endpoint`) whether a given pair is direct. `udp_blocked` is absent because a node \
     signalling over UDP cannot have UDP blocked; that term belongs to the browser leaf.";

pub async fn run(
    cmd: AnchorCommand,
    output: Option<OutputFormat>,
    config_path: Option<&std::path::Path>,
    profile_name: &str,
) -> Result<(), CliError> {
    match cmd {
        AnchorCommand::Credential(CredentialCommand::Mint(args)) if args.inspect_target => {
            let psk_source = psk_source(&args)?;
            let issuer = load_credential_issuer(&args).await?;
            let profile = crate::context::resolve_profile(config_path, profile_name).await?;
            let mut target = crate::target::TargetInspection::local(&profile, "offline");
            target.configured_identity(issuer.entity_id().as_bytes());
            target.source = Some(args.issuer_identity);
            target.destination = args.out;
            target.provenance("identity", "flag");
            target.provenance("source", "flag");
            target.provenance(
                "destination",
                if target.destination.is_some() {
                    "flag"
                } else {
                    "stdout"
                },
            );
            target.provenance("psk", psk_source);
            emit_value(
                OutputFormat::resolve_oneshot(output),
                &CredentialTargetInspection {
                    target,
                    psk_source,
                    psk_file: args.psk_file,
                    credential_stdout_on_execution: true,
                },
            )
            .map_err(|e| generic(format!("write inspection: {e}")))
        }
        AnchorCommand::Credential(CredentialCommand::Inspect(args)) if args.inspect_target => {
            let profile = crate::context::resolve_profile(config_path, profile_name).await?;
            let mut target = crate::target::TargetInspection::local(&profile, "offline");
            if let Some(path) = args.credential.strip_prefix('@') {
                target.source = Some(PathBuf::from(path));
                target.provenance("source", "file");
            } else {
                target.provenance("source", "inline");
            }
            let psk_source = if args.psk_hex.is_some() {
                "inline"
            } else {
                "unused"
            };
            target.provenance("psk", psk_source);
            emit_value(
                OutputFormat::resolve_oneshot(output),
                &CredentialTargetInspection {
                    target,
                    psk_source,
                    psk_file: None,
                    credential_stdout_on_execution: false,
                },
            )
            .map_err(|e| generic(format!("write inspection: {e}")))
        }
        AnchorCommand::Credential(CredentialCommand::Mint(args)) => run_mint(args, output).await,
        AnchorCommand::Credential(CredentialCommand::Inspect(args)) => {
            run_inspect(args, output).await
        }
        #[cfg(feature = "rtc-bootstrap")]
        AnchorCommand::Ls(args) => run_ls(args, output, config_path, profile_name).await,
        #[cfg(feature = "rtc-bootstrap")]
        AnchorCommand::Stats(args) => run_stats(args, output, config_path, profile_name).await,
        #[cfg(feature = "rtc-bootstrap")]
        AnchorCommand::Serve(args) => run_serve(*args, output, config_path, profile_name).await,
    }
}

#[derive(Serialize)]
struct CredentialTargetInspection {
    #[serde(flatten)]
    target: crate::target::TargetInspection,
    psk_source: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    psk_file: Option<PathBuf>,
    /// Mint's normal report includes the secret credential even with --out.
    credential_stdout_on_execution: bool,
}

fn psk_source(args: &MintArgs) -> Result<&'static str, CliError> {
    match (&args.psk_file, &args.psk_hex) {
        (Some(_), _) => Ok("file"),
        (None, Some(_)) => Ok("inline"),
        (None, None) => Err(invalid_args(
            "one of --psk-hex or --psk-file is required: the credential IS the PSK plus an invite",
        )),
    }
}

async fn load_credential_issuer(args: &MintArgs) -> Result<net_sdk::identity::Identity, CliError> {
    let issuer_file = read_identity_file(&args.issuer_identity, args.insecure_permissions).await?;
    let seed = hex_decode_32(&issuer_file.seed_hex)
        .map_err(|e| invalid_args(format!("--issuer-identity: seed_hex: {e}")))?;
    Ok(net_sdk::identity::Identity::from_seed(seed))
}

#[cfg(feature = "rtc-bootstrap")]
async fn run_ls(
    args: LsArgs,
    output: Option<OutputFormat>,
    config_path: Option<&std::path::Path>,
    profile_name: &str,
) -> Result<(), CliError> {
    use crate::context::{require_remote_attach, resolve_profile, CliContext};

    let profile = resolve_profile(config_path, profile_name).await?;
    // **R6: the rows come from a live mesh.** The in-process Deck
    // client is built with `mesh: None`, so `rtc_anchors()` on it was
    // structurally empty — the listing could never show an anchor no
    // matter how many announced. Attaching to the daemon is the same
    // path every other cross-node listing uses.
    let remote = require_remote_attach(&profile, &args.remote, || {
        invalid_args("anchor ls needs a live mesh target: pass --node-addr/--node-pubkey/--node-id/--psk-hex or set profile defaults")
    })?;
    if args.remote.inspect_target {
        return crate::target::inspect(
            &profile,
            &args.remote,
            args.identity.as_deref(),
            Some(&remote),
            "remote",
        )
        .await?
        .emit(output);
    }
    let target = remote.node_id;
    let ctx =
        CliContext::build_with_remote(&profile, args.identity.as_deref(), args.node, false, remote)
            .await?;
    // **Ask the node that has ingested the announcements.** The two
    // address fields are locally-filled fold projections that
    // deliberately do not travel, so a freshly attached client's own
    // view is empty by construction — which is precisely how this
    // listing used to be structurally empty. The anchor answers for
    // itself over `net.mesh.anchors`.
    let mesh = ctx.require_mesh()?;
    let raw = tokio::time::timeout(
        std::time::Duration::from_secs(args.wait_secs.max(1)),
        mesh.call_raw_bytes(
            target,
            net_sdk::rtc_bootstrap::ANCHOR_DIRECTORY_SERVICE,
            Vec::new(),
        ),
    )
    .await
    .map_err(|_| generic("the anchor directory did not answer in time"))?
    .map_err(|e| {
        generic(format!(
            "the anchor directory did not answer ({e}) — is this node running \
             `net-mesh anchor serve`?"
        ))
    })?;
    let rows: Vec<AnchorRow> =
        serde_json::from_slice::<Vec<net_sdk::rtc_bootstrap::AnchorDirectoryRow>>(&raw)
            .map_err(|e| generic(format!("the anchor directory's reply did not parse: {e}")))?
            .into_iter()
            .map(|row| AnchorRow {
                node: row.node,
                rtc_addr: row.rtc_addr,
                rtc_stun_addr: row.rtc_stun_addr,
                rtc_bootstrap: row.rtc_bootstrap,
                noise_pubkey: row.noise_pubkey,
            })
            .collect();
    emit_value(OutputFormat::resolve_oneshot(output), &rows)
        .map_err(|e| generic(format!("write anchor ls: {e}")))?;
    Ok(())
}

/// `net-mesh anchor stats` — the answering anchor's ICE attempt
/// ledger.
///
/// Remote by construction, and not for the reason `ls` is: an
/// attempt ledger is not fold state and is never announced, so there
/// is no local projection of it that could be read instead. The node
/// that owns the ledger is the only node that can answer for it.
#[cfg(feature = "rtc-bootstrap")]
async fn run_stats(
    args: StatsArgs,
    output: Option<OutputFormat>,
    config_path: Option<&std::path::Path>,
    profile_name: &str,
) -> Result<(), CliError> {
    use crate::context::{require_remote_attach, resolve_profile, CliContext};

    let profile = resolve_profile(config_path, profile_name).await?;
    let remote = require_remote_attach(&profile, &args.remote, || {
        invalid_args("anchor stats needs a live mesh target: pass --node-addr/--node-pubkey/--node-id/--psk-hex or set profile defaults")
    })?;
    if args.remote.inspect_target {
        return crate::target::inspect(
            &profile,
            &args.remote,
            args.identity.as_deref(),
            Some(&remote),
            "remote",
        )
        .await?
        .emit(output);
    }
    let target = remote.node_id;
    let ctx =
        CliContext::build_with_remote(&profile, args.identity.as_deref(), args.node, false, remote)
            .await?;
    let mesh = ctx.require_mesh()?;
    let raw = tokio::time::timeout(
        Duration::from_secs(args.wait_secs.max(1)),
        mesh.call_raw_bytes(
            target,
            net_sdk::rtc_bootstrap::ANCHOR_ICE_STATS_SERVICE,
            Vec::new(),
        ),
    )
    .await
    .map_err(|_| generic("the anchor's ICE stats did not answer in time"))?
    .map_err(|e| {
        generic(format!(
            "the anchor's ICE stats did not answer ({e}) — is this node running \
             `net-mesh anchor serve`?"
        ))
    })?;
    let stats = serde_json::from_slice::<net_sdk::rtc_bootstrap::AnchorIceStats>(&raw)
        .map_err(|e| generic(format!("the anchor's ICE stats reply did not parse: {e}")))?;
    let row = IceStatsRow {
        ice_direct_display: ice_direct_display(&stats),
        node: stats.node,
        rtc_configured: stats.rtc_configured,
        ice_attempted: stats.attempted,
        ice_direct: stats.direct,
        ice_relayed: stats.relayed,
        ice_failed: stats.failed,
        ice_pending: stats.pending,
        ice_direct_ratio: stats.direct_ratio,
        denominator: ICE_DENOMINATOR,
        caveat: ICE_CAVEAT,
        bootstrap_rate_limited: stats.bootstrap_rate_limited,
        bootstrap_rate_table_full: stats.bootstrap_rate_table_full,
    };
    emit_value(OutputFormat::resolve_oneshot(output), &row)
        .map_err(|e| generic(format!("write anchor stats: {e}")))?;
    Ok(())
}

/// The ratio spelled out with its denominator, or the reason there
/// is no ratio to spell.
///
/// Three distinct absences, never collapsed into a number:
/// "no rtc driver" (no ledger exists), "no attempts" (the ledger is
/// empty — **not** `0%`, which would report total failure where
/// nothing has happened), and the ratio itself, which always carries
/// `n/m attempts` so it cannot be quoted as a session success rate.
#[cfg(feature = "rtc-bootstrap")]
fn ice_direct_display(stats: &net_sdk::rtc_bootstrap::AnchorIceStats) -> String {
    if !stats.rtc_configured {
        return "no rtc driver — this node keeps no attempt ledger".to_string();
    }
    let Some(ratio) = stats.direct_ratio else {
        return "no attempts yet — no direct-path ratio exists (this is not 0%)".to_string();
    };
    let head = format!(
        "{}/{} attempts ({}%)",
        stats.direct,
        stats.attempted,
        (ratio * 100.0).round() as u64
    );
    if stats.pending == 0 {
        head
    } else {
        format!(
            "{head}, {} attempt(s) still in flight — the outcome terms sum to \
             ice_attempted only once that is 0",
            stats.pending
        )
    }
}

async fn run_mint(args: MintArgs, output: Option<OutputFormat>) -> Result<(), CliError> {
    let root = parse_entity_hex(&args.root)?;
    let anchor_noise_pubkey = hex_decode_32(&args.anchor_noise_pubkey)
        .map_err(|e| invalid_args(format!("--anchor-noise-pubkey: {e}")))?;
    let psk = Psk::new(read_psk(&args).await?);
    if args.invite_ttl_secs == 0 || args.psk_ttl_secs == 0 {
        return Err(invalid_args(
            "a zero TTL mints a credential that is already expired",
        ));
    }

    let issuer = load_credential_issuer(&args).await?;
    let invite = InviteToken::mint(
        &root,
        args.url.clone(),
        Duration::from_secs(args.invite_ttl_secs),
    );
    let credential = BrowserBootstrapCredential::mint(
        &issuer,
        invite,
        anchor_noise_pubkey,
        psk,
        args.url.clone(),
        Duration::from_secs(args.psk_ttl_secs),
    );
    // Mint through the parser: a credential this binary cannot read
    // back is not one a browser could use either (the URL check
    // lives there, so a bad `--url` fails here rather than at the
    // browser).
    let encoded = credential.encode();
    let parsed = BrowserBootstrapCredential::decode(&encoded).map_err(|e| {
        invalid_args(format!(
            "refusing to emit a credential that does not parse back: {e}"
        ))
    })?;

    let written_to = match args.out.as_ref() {
        None => None,
        Some(path) => {
            if path.exists() && !args.force {
                return Err(generic(format!(
                    "{} already exists; pass --force to overwrite",
                    path.display()
                )));
            }
            // `secret: true` — the string carries the PSK, so it gets
            // the same 0600 staging as key material.
            let tmp = stage_beside(path, encoded.as_bytes(), true).await?;
            publish_staged_or_replace(&tmp, path, args.force).await?;
            Some(path.display().to_string())
        }
    };

    emit_value(
        OutputFormat::resolve_oneshot(output),
        &MintReport {
            credential: encoded,
            trust_domain: parsed.trust_domain.to_string(),
            issuer: hex_string(parsed.issuer.as_bytes()),
            bootstrap_url: parsed.bootstrap_url.clone(),
            nonce_expires_at: parsed.nonce_expires_at(),
            psk_expires_at: parsed.psk_expires_at(),
            written_to,
        },
    )
    .map_err(|e| generic(format!("write anchor credential mint: {e}")))?;
    Ok(())
}

async fn run_inspect(args: InspectArgs, output: Option<OutputFormat>) -> Result<(), CliError> {
    let raw = match args.credential.strip_prefix('@') {
        Some(path) => tokio::fs::read_to_string(path)
            .await
            .map_err(|e| invalid_args(format!("--credential @{path}: {e}")))?,
        None => args.credential.clone(),
    };
    let credential = BrowserBootstrapCredential::decode(&raw)
        .map_err(|e| invalid_args(format!("--credential: {e}")))?;

    let trust_domain_matches = match args.psk_hex.as_deref() {
        None => None,
        Some(hex) => {
            let psk =
                Psk::new(hex_decode_32(hex).map_err(|e| invalid_args(format!("--psk-hex: {e}")))?);
            Some(credential.check_trust_domain(&psk).is_ok())
        }
    };
    let status = match credential.validate() {
        Ok(()) => "ok".to_string(),
        Err(e) => e.to_string(),
    };

    emit_value(
        OutputFormat::resolve_oneshot(output),
        &InspectReport {
            root: hex_string(credential.root().as_bytes()),
            rendezvous: credential.invite.rendezvous.clone(),
            bootstrap_url: credential.bootstrap_url.clone(),
            anchor_noise_pubkey: hex_string(&credential.anchor_noise_pubkey),
            trust_domain: credential.trust_domain.to_string(),
            issuer: hex_string(credential.issuer.as_bytes()),
            nonce_expires_at: credential.nonce_expires_at(),
            psk_expires_at: credential.psk_expires_at(),
            status,
            trust_domain_matches,
        },
    )
    .map_err(|e| generic(format!("write anchor credential inspect: {e}")))?;
    Ok(())
}

/// The PSK from `--psk-file` or `--psk-hex`, in that preference
/// order. Exactly one is required: minting without a PSK would
/// produce a credential no browser could handshake with.
async fn read_psk(args: &MintArgs) -> Result<[u8; 32], CliError> {
    psk_source(args)?;
    let hex = match (args.psk_file.as_ref(), args.psk_hex.as_ref()) {
        (Some(path), _) => tokio::fs::read_to_string(path)
            .await
            .map_err(|e| invalid_args(format!("--psk-file {}: {e}", path.display())))?,
        (None, Some(hex)) => hex.clone(),
        (None, None) => return Err(invalid_args(
            "one of --psk-hex or --psk-file is required: the credential IS the PSK plus an invite",
        )),
    };
    hex_decode_32(hex.trim()).map_err(|e| invalid_args(format!("psk: {e}")))
}

async fn publish_staged_or_replace(
    tmp: &std::path::Path,
    final_path: &std::path::Path,
    force: bool,
) -> Result<(), CliError> {
    if force && final_path.exists() {
        let tmp_owned = tmp.to_path_buf();
        let final_owned = final_path.to_path_buf();
        return tokio::task::spawn_blocking(move || std::fs::rename(&tmp_owned, &final_owned))
            .await
            .map_err(|e| generic(format!("publish task panicked: {e}")))?
            .map_err(|e| generic(format!("publishing the credential failed: {e}")));
    }
    publish_staged(tmp, final_path).await
}

fn hex_string(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// `net-mesh anchor serve` — run a browser-facing anchor: an RTC
/// socket, the §12 admission contract, and the bootstrap listener.
#[cfg(feature = "rtc-bootstrap")]
#[derive(Args, Debug)]
pub struct ServeArgs {
    /// Resolve listeners/TLS paths without reading PSK/TLS files or starting services.
    #[arg(long)]
    pub inspect_target: bool,
    /// Mesh bind address for the node itself (default: 0.0.0.0:0).
    #[arg(long, value_name = "ADDR")]
    pub bind: Option<String>,

    /// The transport trust domain's PSK (64 hex chars), read from a
    /// file. The same PSK the credentials were minted against.
    #[arg(long = "psk-file", value_name = "PATH")]
    pub psk_file: PathBuf,

    /// Address for the HTTPS bootstrap listener (default: 0.0.0.0:8443).
    /// Repeatable: a dual-stack anchor listens on an IPv4 and an IPv6
    /// address, e.g. `--listen 0.0.0.0:443 --listen '[::]:443'`. Every
    /// listener serves one state, so the rate limits are one budget.
    #[arg(long = "listen", value_name = "ADDR")]
    pub listen: Vec<String>,

    /// The externally reachable base URL of that listener. It is
    /// published as `rtc_bootstrap` on the announcement, so it must
    /// be the name on the certificate.
    #[arg(long = "url", value_name = "URL")]
    pub url: String,

    /// Public address of the RTC/STUN socket, published as
    /// `rtc_addr`. Required behind NAT; without it a browser has no
    /// address to aim ICE at. Repeatable once per family on a
    /// dual-stack anchor: each public address advertises the
    /// `--rtc-bind` socket of its family.
    #[arg(long = "rtc-public-addr", value_name = "ADDR")]
    pub rtc_public_addr: Vec<String>,

    /// Bind address of the RTC socket. Pin it when `--rtc-public-addr`
    /// maps a fixed port. Repeatable once per family: an IPv4 and an
    /// IPv6 bind make a **dual-stack anchor**, whose sessions offer a
    /// candidate in each family, so players on IPv6-only networks can
    /// connect too. One bind of either family is a single-socket
    /// anchor, as before.
    #[arg(long = "rtc-bind", value_name = "ADDR")]
    pub rtc_bind: Vec<String>,

    /// Bind address of a SECOND UDP socket that answers STUN only,
    /// published as `rtc_stun_addr` on the announcement. Off by
    /// default: an anchor that passes neither this nor
    /// `--rtc-stun-public-addr` opens no second socket and
    /// announces no STUN endpoint.
    ///
    /// It exists because `--rtc-public-addr` is this anchor's ICE
    /// endpoint: a browser pairing WITH this anchor cannot gather
    /// against it, so the endpoint it gathers against has to be a
    /// distinct one. Use `:0` to let the OS pick — the announced
    /// value is the port the socket actually bound, never a guess.
    ///
    /// Repeatable once per family: a dual-stack anchor needs an IPv6
    /// STUN endpoint too, or a browser on an IPv6-only network that
    /// does not enumerate interfaces has no usable candidate at all.
    #[arg(long = "rtc-stun-bind", value_name = "ADDR")]
    pub rtc_stun_bind: Vec<String>,

    /// Public address of that STUN socket, published as
    /// `rtc_stun_addr`. Required behind NAT, and it must be a
    /// **distinct externally reachable endpoint** from
    /// `--rtc-public-addr` — two ports on this host is fine, a
    /// gateway mapping that lands both on one public tuple is not.
    /// Repeatable once per family, each advertising the
    /// `--rtc-stun-bind` socket of its own family.
    #[arg(long = "rtc-stun-public-addr", value_name = "ADDR")]
    pub rtc_stun_public_addr: Vec<String>,

    /// Browser sessions this anchor holds at once (default 1024). Every
    /// connected player is one, whatever its game, so a public anchor
    /// (`--open-games`) sizes this to its host.
    #[arg(long = "rtc-max-peers", value_name = "N")]
    pub rtc_max_peers: Option<usize>,

    /// Operator-supplied certificate chain (PEM). With `--tls-key`.
    #[arg(long = "tls-cert", value_name = "PATH", requires = "tls_key")]
    pub tls_cert: Option<PathBuf>,

    /// Operator-supplied private key (PEM).
    #[arg(long = "tls-key", value_name = "PATH")]
    pub tls_key: Option<PathBuf>,

    /// ACME directory URL (HTTP-01 on this same listener).
    /// Mutually exclusive with `--tls-cert`.
    #[arg(
        long = "acme-directory",
        value_name = "URL",
        conflicts_with = "tls_cert"
    )]
    pub acme_directory: Option<String>,

    /// ACME contact e-mail.
    #[arg(long = "acme-email", value_name = "EMAIL")]
    pub acme_email: Option<String>,

    /// Where issued certificates are cached. One subdirectory per
    /// domain (R4b).
    #[arg(long = "acme-cache", value_name = "DIR")]
    pub acme_cache: Option<PathBuf>,

    /// Address for the plaintext HTTP-01 challenge ingress, bound
    /// before ordering. Defaults to `0.0.0.0:80`, the port an ACME
    /// directory dials. Repeatable: an anchor whose name has an
    /// `AAAA` record needs an IPv6 one too (`--acme-challenge-addr
    /// '[::]:80'`), because the directory validates over IPv6 then.
    #[arg(long = "acme-challenge-addr", value_name = "ADDR")]
    pub acme_challenge_addr: Vec<String>,

    /// The issuer whose signature this anchor accepts on a
    /// credential (64 hex chars) — the public half of the key
    /// `anchor credential mint --issuer-identity` uses (R3). Optional
    /// with `--issuer-identity`, which implies it; given both, they
    /// must agree.
    #[arg(
        long = "credential-issuer",
        value_name = "HEX",
        required_unless_present = "issuer_identity"
    )]
    pub credential_issuer: Option<String>,

    /// The issuer's identity file (the PRIVATE key
    /// `anchor credential mint --issuer-identity` reads). Needed to
    /// issue visitor credentials with `--game`; every game's
    /// enrollment root is derived from it, so instances started with
    /// the same file admit the same visitors.
    #[arg(long = "issuer-identity", value_name = "PATH")]
    pub issuer_identity: Option<PathBuf>,

    /// Allow a permissive identity-file mode on Unix.
    #[arg(long)]
    pub insecure_permissions: bool,

    /// Admit browsers for this game: serve enrollment and issue
    /// anonymous visitor credentials at `POST <url>/credential` with
    /// `{"game": "<id>"}`. Repeatable, one per game. `ID:N` sets the
    /// game's issuance ceiling to N credentials per minute (default
    /// 600). Lowercase letters, digits, `.`, `-`, `_`. Needs
    /// `--issuer-identity`.
    #[arg(
        long = "game",
        value_name = "ID[:PER_MINUTE]",
        requires = "issuer_identity"
    )]
    pub game: Vec<String>,

    /// Admit **open games**: any game id, from any page, without a
    /// `--game` for it. An open game is keyed on the page's origin and
    /// the id together, so two sites that both call their game `chess`
    /// get two separate games. Any origin may then call the endpoints;
    /// `--allow-origin` still says which may use the `--game` games.
    /// STATE_FILE keeps the open games across restarts, so a page that
    /// reconnects after one still enrolls. Needs `--issuer-identity`.
    #[arg(
        long = "open-games",
        value_name = "STATE_FILE",
        requires = "issuer_identity"
    )]
    pub open_games: Option<PathBuf>,

    /// Open games held at once (default 8192). Past it a new game is
    /// refused until one has been idle for the invite lifetime; a game
    /// in use is never evicted.
    #[arg(long = "open-games-max", value_name = "N", requires = "open_games")]
    pub open_games_max: Option<usize>,

    /// Credentials per minute across ALL open games together (default
    /// 9000), so inventing game names cannot multiply the budget. Each
    /// open game also has the per-game ceiling of 600.
    #[arg(
        long = "open-games-per-minute",
        value_name = "N",
        requires = "open_games"
    )]
    pub open_games_per_minute: Option<u32>,

    /// Players one open game may have connected to this anchor at once,
    /// across all its lobbies and matches. Unset (the default), one
    /// game may use every session the anchor holds (`--rtc-max-peers`);
    /// set it to keep room for other games on a shared anchor.
    #[arg(
        long = "open-game-max-players",
        value_name = "N",
        requires = "open_games"
    )]
    pub open_game_max_players: Option<usize>,

    /// Per-source-IP `POST /credential` ceiling per minute (default 30).
    #[arg(long = "credentials-per-minute")]
    pub credentials_per_minute: Option<u32>,

    /// Print every game's counters as a JSON line this often, in
    /// seconds. 0 (the default) prints none.
    #[arg(long = "game-stats-secs", default_value_t = 0)]
    pub game_stats_secs: u64,

    /// Browser origins allowed to call the endpoints and open the
    /// trickle socket. Repeatable. **No wildcard** — an endpoint
    /// that takes a credential does not get one. Optional with
    /// `--open-games`, which admits every origin to its open games.
    #[arg(
        long = "allow-origin",
        value_name = "ORIGIN",
        required_unless_present = "open_games"
    )]
    pub allow_origin: Vec<String>,

    /// Per-source-IP `POST /rtc/offer` ceiling per minute.
    #[arg(long = "offers-per-minute")]
    pub offers_per_minute: Option<u32>,
}

/// What `serve` reports once it is up.
#[cfg(feature = "rtc-bootstrap")]
#[derive(serde::Serialize)]
struct ServeReport {
    node: String,
    listening_on: String,
    bootstrap_url: String,
    /// The endpoint this anchor announces as `rtc_addr`, read off
    /// the running node rather than echoed from the flag.
    rtc_addr: Option<String>,
    /// The announced STUN endpoint (Stage 6), **as resolved** — the
    /// operator's override when a second socket was bound, the
    /// address that socket actually bound when it was not, and
    /// absent when there is no second socket at all.
    ///
    /// Not an echo of `--rtc-stun-public-addr`. An override without
    /// a bind is refused at startup, and if it were merely echoed
    /// here the report would describe an endpoint nothing answers
    /// on; a `:0` bind, conversely, has no value to echo and a real
    /// one to report.
    ///
    /// **Deliberately asymmetric with its sibling**: this key is
    /// absent when no STUN endpoint was configured, while
    /// `rtc_addr` above still renders `null`. `rtc_addr` predates
    /// the omit-when-absent convention and a consumer parsing this
    /// report is entitled to the shape it already has, so changing
    /// it is a separate, consumer-visible decision — not a side
    /// effect of adding a field.
    #[serde(skip_serializing_if = "Option::is_none")]
    rtc_stun_addr: Option<String>,
    trust_domain: String,
    noise_pubkey: String,
    /// Games this anchor admits browsers for; absent without `--game`.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    games: Vec<String>,
    /// `true` when the anchor admits open games (`--open-games`);
    /// absent otherwise.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    open_games: bool,
    /// Where pages ask for a visitor credential; absent without
    /// `--game` or `--open-games`.
    #[serde(skip_serializing_if = "Option::is_none")]
    credential_endpoint: Option<String>,
    /// Listeners beyond `listening_on`. Absent with one listener, so a
    /// single-listener anchor's report is unchanged.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    also_listening_on: Vec<String>,
    /// Every published RTC endpoint, primary first, **only on a
    /// dual-stack anchor** that publishes one per family (the same
    /// rule as `GET /rtc/anchor`): absent otherwise, so a
    /// single-socket anchor's report is unchanged field for field and
    /// `rtc_addr` stays its complete answer.
    #[serde(skip_serializing_if = "Option::is_none")]
    rtc_addrs: Option<Vec<String>>,
}

/// Parse `--game` values: `ID` or `ID:PER_MINUTE`.
#[cfg(feature = "rtc-bootstrap")]
fn parse_games(values: &[String]) -> Result<Vec<net_sdk::game_anchor::GameConfig>, CliError> {
    values
        .iter()
        .map(|value| {
            let (id, limit) = match value.split_once(':') {
                Some((id, n)) => (
                    id,
                    Some(n.parse::<u32>().map_err(|_| {
                        invalid_args(format!("--game {value}: the per-minute ceiling is not a number"))
                    })?),
                ),
                None => (value.as_str(), None),
            };
            if !net_sdk::game_anchor::is_valid_game_id(id) {
                return Err(invalid_args(format!(
                    "--game {id:?}: use lowercase letters, digits, '.', '-' and '_' (at most {} bytes)",
                    net_sdk::game_anchor::MAX_GAME_ID_LEN
                )));
            }
            let mut config = net_sdk::game_anchor::GameConfig::new(id);
            if let Some(limit) = limit {
                config.issue_per_minute = limit;
            }
            Ok(config)
        })
        .collect()
}

/// Parse a repeatable address flag that allows **at most one value
/// per family**, returning `(IPv4, IPv6)`.
///
/// Two of one family is refused rather than resolved: the anchor
/// routes a datagram to the socket of its destination's family, so
/// two sockets of one family would leave that choice ambiguous.
#[cfg(feature = "rtc-bootstrap")]
fn one_per_family(
    flag: &str,
    values: &[String],
) -> Result<(Option<std::net::SocketAddr>, Option<std::net::SocketAddr>), CliError> {
    let mut v4 = None;
    let mut v6 = None;
    for value in values {
        let addr: std::net::SocketAddr = value
            .parse()
            .map_err(|e| invalid_args(format!("{flag} {value}: {e}")))?;
        let slot = if addr.is_ipv4() { &mut v4 } else { &mut v6 };
        if let Some(previous) = slot.replace(addr) {
            return Err(invalid_args(format!(
                "{flag} is given twice for one address family ({previous} and {addr}); it \
                 takes at most one IPv4 and one IPv6 address"
            )));
        }
    }
    Ok((v4, v6))
}

/// Parse a repeatable address flag, or its default when not given.
#[cfg(feature = "rtc-bootstrap")]
fn addrs_or_default(
    flag: &str,
    values: &[String],
    default: &str,
) -> Result<Vec<std::net::SocketAddr>, CliError> {
    if values.is_empty() {
        return Ok(vec![default.parse().map_err(|e| {
            invalid_args(format!("{flag} default {default}: {e}"))
        })?]);
    }
    values
        .iter()
        .map(|value| {
            value
                .parse()
                .map_err(|e| invalid_args(format!("{flag} {value}: {e}")))
        })
        .collect()
}

#[cfg(feature = "rtc-bootstrap")]
/// `anchor serve`'s browser-session ceiling. Higher than the core's
/// own default (256): an anchor exists to hold browser sessions, and
/// every connected player is one, whatever its game.
const DEFAULT_ANCHOR_MAX_PEERS: usize = 1024;

/// The RTC driver configuration `serve` runs with, from the
/// operator's flags.
///
/// Its own function so the flag → config mapping is a thing a test
/// can read without binding a socket or starting a mesh: every
/// address here is operator input, and the failure mode worth
/// guarding is a flag that parses fine and lands on nothing.
///
/// Two pairs, and they are not interchangeable:
///
/// * `--rtc-bind` / `--rtc-public-addr` → the ICE/RTC socket. It
///   keeps `serve_stun = true`, which is what answers the
///   diagnostic `UdpBlocked` probe aimed at `rtc_addr`. Each flag
///   takes at most one address per family; an IPv4 and an IPv6
///   `--rtc-bind` make a dual-stack anchor with a second, IPv6 RTC
///   socket, and each public address advertises the socket of its
///   own family.
/// * `--rtc-stun-bind` / `--rtc-stun-public-addr` → the SECOND,
///   STUN-only socket announced as `rtc_stun_addr` (Stage 6),
///   additional to the first and never a replacement for it.
///   Neither flag given: no second socket, nothing announced.
#[cfg(feature = "rtc-bootstrap")]
fn rtc_config_from_args(args: &ServeArgs) -> Result<net::adapter::net::rtc::RtcConfig, CliError> {
    let mut rtc = net::adapter::net::rtc::RtcConfig::new().with_bootstrap_url(args.url.clone());
    let max_peers = args.rtc_max_peers.unwrap_or(DEFAULT_ANCHOR_MAX_PEERS);
    if max_peers == 0 {
        return Err(invalid_args("--rtc-max-peers must be at least 1"));
    }
    rtc.max_peers = max_peers;
    rtc.serve_stun = true;
    let (bind, bind_v6) = one_per_family("--rtc-bind", &args.rtc_bind)?;
    let (public, public_v6) = one_per_family("--rtc-public-addr", &args.rtc_public_addr)?;
    match (bind, bind_v6) {
        // An IPv4 and an IPv6 bind: a dual-stack anchor. Each public
        // address advertises the socket of its own family.
        (Some(bind), Some(bind_v6)) => {
            rtc.bind_addr = Some(bind);
            rtc.bind_addr_v6 = Some(bind_v6);
            rtc.public_addr = public;
            rtc.public_addr_v6 = public_v6;
        }
        // One socket, of either family: as before, one public address
        // at most, and it advertises that socket.
        (single, single_v6) => {
            rtc.bind_addr = single.or(single_v6);
            if public.is_some() && public_v6.is_some() {
                return Err(invalid_args(
                    "--rtc-public-addr names an IPv4 and an IPv6 address, but only one --rtc-bind socket exists; give an --rtc-bind of each family for a dual-stack anchor",
                ));
            }
            rtc.public_addr = public.or(public_v6);
        }
    }
    // The STUN-only sockets follow the same per-family rule as the RTC
    // sockets: an IPv4 and an IPv6 bind make one endpoint per family,
    // and one bind of either family is the single endpoint it was.
    let (stun_bind, stun_bind_v6) = one_per_family("--rtc-stun-bind", &args.rtc_stun_bind)?;
    let (stun_public, stun_public_v6) =
        one_per_family("--rtc-stun-public-addr", &args.rtc_stun_public_addr)?;
    match (stun_bind, stun_bind_v6) {
        (Some(bind), Some(bind_v6)) => {
            rtc.stun_addr = Some(bind);
            rtc.stun_addr_v6 = Some(bind_v6);
            rtc.stun_public_addr = stun_public;
            rtc.stun_public_addr_v6 = stun_public_v6;
        }
        (single, single_v6) => {
            rtc.stun_addr = single.or(single_v6);
            if stun_public.is_some() && stun_public_v6.is_some() {
                return Err(invalid_args(
                    "--rtc-stun-public-addr names an IPv4 and an IPv6 address, but only one \
                     --rtc-stun-bind socket exists; give an --rtc-stun-bind of each family",
                ));
            }
            rtc.stun_public_addr = stun_public.or(stun_public_v6);
        }
    }
    Ok(rtc)
}

#[cfg(feature = "rtc-bootstrap")]
fn resolve_serve(args: &ServeArgs) -> Result<ResolvedServe, CliError> {
    use net_sdk::rtc_bootstrap::{AcmeConfig, BootstrapTls};
    let bind: std::net::SocketAddr = args
        .bind
        .as_deref()
        .unwrap_or("0.0.0.0:0")
        .parse()
        .map_err(|e| invalid_args(format!("--bind: {e}")))?;
    let listen = addrs_or_default("--listen", &args.listen, "0.0.0.0:8443")?;
    let issuer = args
        .credential_issuer
        .as_deref()
        .map(parse_entity_hex)
        .transpose()?;
    parse_games(&args.game)?;
    let challenge = addrs_or_default(
        "--acme-challenge-addr",
        &args.acme_challenge_addr,
        "0.0.0.0:80",
    )?;

    let tls = match (&args.tls_cert, &args.tls_key, &args.acme_directory) {
        (Some(cert), Some(key), None) => BootstrapTls::Operator {
            cert_pem: cert.clone(),
            key_pem: key.clone(),
        },
        (None, _, Some(directory)) => {
            let domain = args
                .url
                .trim_start_matches("https://")
                .split('/')
                .next()
                .unwrap_or_default()
                .to_string();
            let acme = AcmeConfig::new(
                directory.clone(),
                domain,
                args.acme_email.clone().ok_or_else(|| {
                    invalid_args("--acme-email is required with --acme-directory")
                })?,
                // One subdirectory per domain inside this path (R4b).
                args.acme_cache
                    .clone()
                    .unwrap_or_else(|| std::env::temp_dir().join("net-mesh-acme")),
            );
            BootstrapTls::Acme(acme)
        }
        _ => {
            return Err(invalid_args(
                "browser-trusted TLS is required: pass --tls-cert/--tls-key, or \
                 --acme-directory/--acme-email. There is no self-signed mode, because \
                 a browser refuses one",
            ))
        }
    };

    let mut rtc = rtc_config_from_args(args)?;
    // Resolve the documented RTC default once, rather than having inspection
    // invent an address separately from the config consumed by the builder.
    rtc.bind_addr
        .get_or_insert_with(|| std::net::SocketAddr::new(bind.ip(), 0));
    if rtc.stun_public_addr.is_some() && rtc.stun_addr.is_none() {
        return Err(invalid_args(
            "--rtc-stun-public-addr requires --rtc-stun-bind",
        ));
    }
    Ok(ResolvedServe {
        bind,
        listen,
        issuer,
        challenge,
        tls,
        rtc,
    })
}

#[cfg(feature = "rtc-bootstrap")]
struct ResolvedServe {
    bind: std::net::SocketAddr,
    /// Every HTTPS listener, the primary first. Never empty.
    listen: Vec<std::net::SocketAddr>,
    /// `None` when only `--issuer-identity` names it (read at start).
    issuer: Option<net_sdk::identity::EntityId>,
    /// Every HTTP-01 challenge listener, the primary first. Never empty.
    challenge: Vec<std::net::SocketAddr>,
    tls: net_sdk::rtc_bootstrap::BootstrapTls,
    rtc: net::adapter::net::rtc::RtcConfig,
}

#[cfg(feature = "rtc-bootstrap")]
#[derive(Serialize)]
struct ServeInspection {
    #[serde(flatten)]
    target: crate::target::TargetInspection,
    listen: std::net::SocketAddr,
    /// Listeners beyond `listen` (a dual-stack anchor's IPv6 one).
    /// Absent when there are none, so a single-listener anchor's
    /// inspection is unchanged.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    listen_additional: Vec<std::net::SocketAddr>,
    rtc_bind: Option<std::net::SocketAddr>,
    rtc_public_addr: Option<std::net::SocketAddr>,
    /// The dual-stack anchor's IPv6 RTC socket. Absent without one.
    #[serde(skip_serializing_if = "Option::is_none")]
    rtc_bind_v6: Option<std::net::SocketAddr>,
    /// Its public override. Absent without one.
    #[serde(skip_serializing_if = "Option::is_none")]
    rtc_public_addr_v6: Option<std::net::SocketAddr>,
    rtc_stun_bind: Option<std::net::SocketAddr>,
    rtc_stun_public_addr: Option<std::net::SocketAddr>,
    tls: &'static str,
    tls_cert: Option<PathBuf>,
    tls_key: Option<PathBuf>,
    acme_cache: Option<PathBuf>,
    acme_challenge_bind: Option<std::net::SocketAddr>,
    /// Challenge listeners beyond `acme_challenge_bind`. Absent when
    /// there are none, or without ACME.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    acme_challenge_bind_additional: Vec<std::net::SocketAddr>,
    /// Absent when only `--issuer-identity` names the issuer: inspection
    /// reads no secret files.
    #[serde(skip_serializing_if = "Option::is_none")]
    credential_issuer_fingerprint: Option<String>,
}

#[cfg(feature = "rtc-bootstrap")]
async fn run_serve(
    args: ServeArgs,
    output: Option<OutputFormat>,
    config_path: Option<&std::path::Path>,
    profile_name: &str,
) -> Result<(), CliError> {
    use net_sdk::rtc_bootstrap::{serve_bootstrap, AcmeState, BootstrapConfig, BootstrapTls};
    use net_sdk::Mesh;
    let resolved = resolve_serve(&args)?;
    if args.inspect_target {
        let profile = crate::context::resolve_profile(config_path, profile_name).await?;
        let mut target = crate::target::TargetInspection::standalone_service(
            &profile,
            resolved.bind.to_string(),
        );
        for (name, explicit) in [
            ("bind", args.bind.is_some()),
            ("listen", !args.listen.is_empty()),
            ("rtc_bind", !args.rtc_bind.is_empty()),
        ] {
            target.provenance(name, if explicit { "flag" } else { "default" });
        }
        target.provenance("psk", "flag");
        target.provenance("credential_issuer", "flag");
        target.provenance("tls", "flag");
        target.provenance(
            "rtc_public_addr",
            if !args.rtc_public_addr.is_empty() {
                "flag"
            } else {
                "runtime"
            },
        );
        target.provenance(
            "rtc_stun_bind",
            if !args.rtc_stun_bind.is_empty() {
                "flag"
            } else {
                "unused"
            },
        );
        let (tls, tls_cert, tls_key, acme_cache) = match &resolved.tls {
            BootstrapTls::Operator { cert_pem, key_pem } => (
                "operator",
                Some(cert_pem.clone()),
                Some(key_pem.clone()),
                None,
            ),
            BootstrapTls::Acme(config) => ("acme", None, None, Some(config.cache_dir.clone())),
        };
        for (name, explicit) in [
            ("acme_cache", args.acme_cache.is_some()),
            ("acme_challenge_bind", !args.acme_challenge_addr.is_empty()),
        ] {
            target.provenance(
                name,
                if tls != "acme" {
                    "unused"
                } else if explicit {
                    "flag"
                } else {
                    "default"
                },
            );
        }
        return emit_value(
            OutputFormat::resolve_oneshot(output),
            &ServeInspection {
                target,
                listen: resolved.listen[0],
                listen_additional: resolved.listen[1..].to_vec(),
                rtc_bind: resolved.rtc.bind_addr,
                rtc_public_addr: resolved.rtc.public_addr,
                rtc_bind_v6: resolved.rtc.bind_addr_v6,
                rtc_public_addr_v6: resolved.rtc.public_addr_v6,
                rtc_stun_bind: resolved.rtc.stun_addr,
                rtc_stun_public_addr: resolved.rtc.stun_public_addr,
                tls,
                tls_cert,
                tls_key,
                acme_cache,
                acme_challenge_bind: if tls == "acme" {
                    Some(resolved.challenge[0])
                } else {
                    None
                },
                acme_challenge_bind_additional: if tls == "acme" {
                    resolved.challenge[1..].to_vec()
                } else {
                    Vec::new()
                },
                credential_issuer_fingerprint: resolved
                    .issuer
                    .as_ref()
                    .map(|issuer| crate::target::public_fingerprint(issuer.as_bytes())),
            },
        )
        .map_err(|e| generic(format!("write anchor target inspection: {e}")));
    }
    let psk_hex = tokio::fs::read_to_string(&args.psk_file)
        .await
        .map_err(|e| invalid_args(format!("--psk-file {}: {e}", args.psk_file.display())))?;
    let psk = hex_decode_32(psk_hex.trim()).map_err(|e| invalid_args(format!("psk: {e}")))?;

    // The issuer: named by its public half, its identity file, or both
    // (which must agree — a listener verifying one key while issuing
    // under another would refuse every credential it hands out).
    let issuer_identity = match &args.issuer_identity {
        Some(path) => {
            let file = read_identity_file(path, args.insecure_permissions).await?;
            let seed = hex_decode_32(&file.seed_hex)
                .map_err(|e| invalid_args(format!("--issuer-identity: seed_hex: {e}")))?;
            Some(net_sdk::identity::Identity::from_seed(seed))
        }
        None => None,
    };
    let issuer = match (resolved.issuer.clone(), &issuer_identity) {
        (Some(named), Some(identity)) if &named != identity.entity_id() => {
            return Err(invalid_args(
                "--credential-issuer is not the public half of --issuer-identity",
            ))
        }
        (Some(named), _) => named,
        (None, Some(identity)) => identity.entity_id().clone(),
        (None, None) => {
            return Err(invalid_args(
                "one of --credential-issuer or --issuer-identity is required",
            ))
        }
    };
    let games = parse_games(&args.game)?;

    let mesh = Mesh::builder(&resolved.bind.to_string(), &psk)
        .map_err(|e| generic(format!("mesh builder: {e}")))?
        .rtc(resolved.rtc)
        .build()
        .await
        .map_err(|e| generic(format!("starting the anchor: {e}")))?;
    mesh.start();

    let sdk_psk = Psk::new(psk);
    let mut listener_config = BootstrapConfig::new(
        resolved.listen[0],
        sdk_psk.clone(),
        issuer,
        resolved.tls,
        args.allow_origin
            .first()
            .cloned()
            .unwrap_or_else(|| args.url.clone()),
    );
    listener_config.allowed_origins = args.allow_origin.clone();
    listener_config.ws_allowed_origins = args.allow_origin.clone();
    listener_config.any_origin = args.open_games.is_some();
    listener_config.acme = AcmeState::new();
    listener_config.additional_bind_addrs = resolved.listen[1..].to_vec();
    listener_config.acme_challenge_addr = resolved.challenge[0];
    listener_config.additional_acme_challenge_addrs = resolved.challenge[1..].to_vec();
    if let Some(limit) = args.offers_per_minute {
        listener_config.offers_per_ip_per_minute = limit;
    }

    // R6: operator tooling reads the anchors THIS node has ingested.
    let _directory = net_sdk::rtc_bootstrap::serve_anchor_directory(&mesh)
        .map_err(|e| generic(format!("serving the anchor directory: {e}")))?;
    // Stage 6 slice 5: and the anchor's own ICE attempt ledger, for
    // the same reason the directory is a service — the ledger is not
    // fold state, so only the node that owns it can answer for it.
    let _ice_stats = net_sdk::rtc_bootstrap::serve_anchor_ice_stats(&mesh)
        .map_err(|e| generic(format!("serving the anchor ICE stats: {e}")))?;
    // Browsers for registered (and open) games: real enrollment (a
    // game's visitors are rooted at that game) and anonymous credentials.
    let mut _enrollment = None;
    let mut _game_stats = None;
    let admits_games = !games.is_empty() || args.open_games.is_some();
    if let (true, Some(identity)) = (admits_games, &issuer_identity) {
        let mut registry = net_sdk::game_anchor::GameRegistry::from_identity(identity, games)
            .map_err(|e| invalid_args(format!("--game: {e}")))?;
        if let Some(state_file) = &args.open_games {
            let mut open = net_sdk::game_anchor::OpenGames::new(Some(state_file.clone()));
            if let Some(max) = args.open_games_max {
                open.capacity = max;
            }
            if let Some(limit) = args.open_games_per_minute {
                open.total_per_minute = limit;
            }
            if let Some(players) = args.open_game_max_players {
                open.max_players_per_game = Some(players);
            }
            registry = registry.with_open_games(open).map_err(|e| {
                generic(format!(
                    "--open-games: reading {}: {e}",
                    state_file.display()
                ))
            })?;
        }
        let registry = std::sync::Arc::new(registry);
        _enrollment = Some(
            net_sdk::game_anchor::serve_game_enrollment(
                &mesh,
                std::sync::Arc::clone(&registry),
                net_sdk::game_anchor::DEFAULT_GRANT_TTL,
            )
            .map_err(|e| generic(format!("serving enrollment: {e}")))?,
        );
        let mut issuance = net_sdk::rtc_bootstrap::CredentialIssuance::new(
            std::sync::Arc::clone(&registry),
            identity.clone(),
            args.url.clone(),
        );
        if let Some(limit) = args.credentials_per_minute {
            issuance.per_ip_per_minute = limit;
        }
        listener_config.credential_issuance = Some(issuance);
        if args.game_stats_secs > 0 {
            let every = std::time::Duration::from_secs(args.game_stats_secs);
            _game_stats = Some(tokio::spawn(async move {
                let mut tick = tokio::time::interval(every);
                tick.tick().await;
                loop {
                    tick.tick().await;
                    let mut line = serde_json::json!({ "game_stats": registry.stats() });
                    if let Some(open) = registry.open_stats() {
                        line["open_games"] = serde_json::json!(open);
                    }
                    println!("{line}");
                }
            }));
        }
    }

    let node = std::sync::Arc::clone(mesh.node());
    let handle = serve_bootstrap(node, listener_config)
        .await
        .map_err(|e| generic(format!("starting the bootstrap listener: {e}")))?;

    emit_value(
        OutputFormat::resolve_oneshot(output),
        &ServeReport {
            node: format!("{:#x}", mesh.node().node_id()),
            listening_on: handle.local_addr().to_string(),
            bootstrap_url: args.url.clone(),
            // **The resolved endpoints, read off the node.** These
            // used to echo the two flags back, which made the
            // report agree with the operator's intent rather than
            // with what the anchor serves: `--rtc-stun-public-addr`
            // without `--rtc-stun-bind` printed an endpoint no
            // socket answered on. The node's accessors are the
            // same ones the signed announcement is built from, so
            // the report and the announcement cannot disagree.
            rtc_addr: mesh.node().rtc_public_addr().map(|a| a.to_string()),
            rtc_stun_addr: mesh.node().rtc_public_stun_addr().map(|a| a.to_string()),
            trust_domain: sdk_psk.trust_domain().to_string(),
            noise_pubkey: hex_string(mesh.node().public_key()),
            games: args
                .game
                .iter()
                .map(|g| g.split(':').next().unwrap_or_default().to_string())
                .collect(),
            open_games: args.open_games.is_some(),
            credential_endpoint: (!args.game.is_empty() || args.open_games.is_some())
                .then(|| format!("{}/credential", args.url.trim_end_matches('/'))),
            also_listening_on: handle.local_addrs()[1..]
                .iter()
                .map(|addr| addr.to_string())
                .collect(),
            rtc_addrs: net_sdk::rtc_bootstrap::published_rtc_addrs(mesh.node()),
        },
    )
    .map_err(|e| generic(format!("write anchor serve: {e}")))?;

    // Serve until interrupted; the listener owns its own accept loop.
    tokio::signal::ctrl_c()
        .await
        .map_err(|e| generic(format!("waiting for ctrl-c: {e}")))?;
    if let Some(task) = _game_stats {
        task.abort();
    }
    handle.shutdown().await;
    Ok(())
}

/// Stage 6 — the operator surface of the separately announced STUN
/// endpoint: the two flags that configure it, and the JSON that
/// reports it.
///
/// Behind `rtc-bootstrap` because `ServeArgs` is: the verbs that
/// announce and read the endpoint only exist in that build.
/// Run: `cargo test -p net-cli --features rtc-bootstrap anchor`.
#[cfg(all(test, feature = "rtc-bootstrap"))]
mod tests {
    use super::*;

    /// `ServeArgs` parsed from argv, with only the four flags the
    /// parser requires supplied. `extra` is the thing under test.
    fn serve_args(extra: &[&str]) -> ServeArgs {
        use clap::Parser;

        /// `ServeArgs` is a flattened `Args`, so it needs a
        /// `Parser` root to be parsed standalone.
        #[derive(Parser)]
        struct Root {
            #[command(flatten)]
            serve: ServeArgs,
        }

        let mut argv = vec![
            "net-mesh",
            "--psk-file",
            "psk.hex",
            "--url",
            "https://anchor.example.com",
            "--credential-issuer",
            "00",
            "--allow-origin",
            "https://app.example.com",
        ];
        argv.extend_from_slice(extra);
        Root::parse_from(argv).serve
    }

    /// `ServeArgs` from exactly `argv` (after the program name), or the
    /// parser's refusal.
    fn try_serve_args(argv: &[&str]) -> Result<ServeArgs, clap::Error> {
        use clap::Parser;
        #[derive(Parser)]
        struct Root {
            #[command(flatten)]
            serve: ServeArgs,
        }
        let mut full = vec!["net-mesh"];
        full.extend_from_slice(argv);
        Root::try_parse_from(full).map(|root| root.serve)
    }

    const BASE: [&str; 6] = [
        "--psk-file",
        "psk.hex",
        "--url",
        "https://anchor.example.com",
        "--allow-origin",
        "https://app.example.com",
    ];

    /// An anchor holds 1024 browser sessions unless told otherwise,
    /// `--rtc-max-peers` overrides it, and zero is refused.
    #[test]
    fn the_session_ceiling_defaults_to_1024_and_zero_is_refused() {
        let bare = rtc_config_from_args(&serve_args(&[])).expect("defaults parse");
        assert_eq!(bare.max_peers, 1024);
        let set = rtc_config_from_args(&serve_args(&["--rtc-max-peers", "32"])).expect("parses");
        assert_eq!(set.max_peers, 32);
        assert!(rtc_config_from_args(&serve_args(&["--rtc-max-peers", "0"])).is_err());
    }

    /// `--open-games` makes `--allow-origin` optional (every origin may
    /// use the open games) and, like `--game`, needs the identity file;
    /// its limits are refused without it. Without `--open-games`,
    /// `--allow-origin` is still required.
    #[test]
    fn open_games_make_the_origin_list_optional_and_need_the_key() {
        let open = [
            "--psk-file",
            "psk.hex",
            "--url",
            "https://anchor.example.com",
            "--issuer-identity",
            "issuer.json",
            "--open-games",
            "open-games.txt",
            "--open-games-max",
            "10",
            "--open-game-max-players",
            "32",
        ];
        let args = try_serve_args(&open).expect("no --allow-origin needed");
        assert!(args.allow_origin.is_empty());
        assert_eq!(
            args.open_games.as_deref(),
            Some(std::path::Path::new("open-games.txt"))
        );
        assert_eq!(
            (args.open_games_max, args.open_game_max_players),
            (Some(10), Some(32))
        );
        assert!(
            try_serve_args(&open[..6]).is_err(),
            "without --open-games, --allow-origin is required"
        );
        let mut no_key = open[..4].to_vec();
        no_key.extend(["--credential-issuer", "00", "--open-games", "x"]);
        assert!(try_serve_args(&no_key).is_err(), "open games need the key");
        let mut limit_alone = BASE.to_vec();
        limit_alone.extend(["--credential-issuer", "00", "--open-games-max", "10"]);
        assert!(
            try_serve_args(&limit_alone).is_err(),
            "a limit needs --open-games"
        );
    }

    /// The issuer is named by its public half, its identity file, or
    /// both — but by one of them; and `--game` needs the identity file,
    /// because issuing credentials needs the private key.
    #[test]
    fn serve_names_its_issuer_one_way_or_the_other_and_game_needs_the_key() {
        assert!(try_serve_args(&BASE).is_err(), "no issuer at all");
        let mut with_key = BASE.to_vec();
        with_key.extend([
            "--issuer-identity",
            "issuer.json",
            "--game",
            "alpha",
            "--game",
            "beta:5",
        ]);
        let args = try_serve_args(&with_key).expect("identity file alone names the issuer");
        assert_eq!(args.credential_issuer, None);
        assert_eq!(args.game, ["alpha", "beta:5"]);
        let mut game_without_key = BASE.to_vec();
        game_without_key.extend(["--credential-issuer", "00", "--game", "alpha"]);
        assert!(
            try_serve_args(&game_without_key).is_err(),
            "--game requires --issuer-identity"
        );
    }

    #[test]
    fn game_flags_parse_ids_and_ceilings_and_refuse_bad_ones() {
        let games = parse_games(&["alpha".into(), "beta.2:5".into()]).unwrap();
        assert_eq!(games[0], net_sdk::game_anchor::GameConfig::new("alpha"));
        assert_eq!(
            (games[1].id.as_str(), games[1].issue_per_minute),
            ("beta.2", 5)
        );
        for bad in ["Alpha", "net-lobby:x", "a:many", ""] {
            assert!(parse_games(&[bad.into()]).is_err(), "{bad:?}");
        }
    }

    /// The two STUN flags land on the two `RtcConfig` fields that
    /// open and announce the second socket — and an anchor that
    /// passes neither configures nothing, which is what keeps the
    /// endpoint off unless an operator asks for it.
    ///
    /// The `serve_stun` assertion is not incidental: the new socket
    /// is ADDITIONAL. The RTC socket keeps answering the diagnostic
    /// `UdpBlocked` probe aimed at `rtc_addr`, so a change that
    /// moved STUN duty to the second socket would break the probe's
    /// classification while every assertion about the new fields
    /// still passed.
    ///
    /// Inverse receipt: drop either `if let` in
    /// [`rtc_config_from_args`] and the matching `Some` assertion
    /// fails — the flag parses, prints in `--help`, and reaches
    /// nothing, which is the failure mode an operator cannot see.
    #[test]
    fn the_stun_flags_reach_the_rtc_config_and_are_absent_by_default() {
        let configured = rtc_config_from_args(&serve_args(&[
            "--rtc-stun-bind",
            "0.0.0.0:3479",
            "--rtc-stun-public-addr",
            "203.0.113.7:3479",
        ]))
        .expect("both flags parse");
        assert_eq!(
            configured.stun_addr,
            Some("0.0.0.0:3479".parse().expect("addr")),
            "--rtc-stun-bind is the SECOND socket's bind"
        );
        assert_eq!(
            configured.stun_public_addr,
            Some("203.0.113.7:3479".parse().expect("addr")),
            "--rtc-stun-public-addr is the endpoint that gets announced"
        );

        let bare = rtc_config_from_args(&serve_args(&[])).expect("no STUN flags parse");
        assert_eq!(
            bare.stun_addr, None,
            "no flag, no second socket: an anchor that configures nothing announces \
             nothing"
        );
        assert_eq!(bare.stun_public_addr, None);
        assert!(
            bare.serve_stun,
            "the RTC socket still answers STUN — it is the diagnostic UdpBlocked \
             probe's target, and the second socket is additional to it, never a \
             replacement"
        );

        // The ICE pair is untouched by the STUN pair, and vice
        // versa: four flags, four fields, no aliasing.
        let both_pairs = rtc_config_from_args(&serve_args(&[
            "--rtc-bind",
            "0.0.0.0:7101",
            "--rtc-public-addr",
            "203.0.113.7:7101",
            "--rtc-stun-bind",
            "0.0.0.0:3479",
        ]))
        .expect("all four parse");
        assert_eq!(
            both_pairs.bind_addr,
            Some("0.0.0.0:7101".parse().expect("addr"))
        );
        assert_eq!(
            both_pairs.public_addr,
            Some("203.0.113.7:7101".parse().expect("addr"))
        );
        assert_eq!(
            both_pairs.stun_addr,
            Some("0.0.0.0:3479".parse().expect("addr"))
        );
        assert_eq!(
            both_pairs.stun_public_addr, None,
            "a bind without a public address announces the socket's own resolved \
             endpoint, decided in the driver — not here"
        );
    }

    /// An unparseable address is refused by the flag that carried
    /// it, named, with the invalid-args exit code — not silently
    /// dropped into an anchor that then announces nothing.
    #[test]
    fn a_malformed_stun_address_names_the_flag_that_carried_it() {
        for (flag, value) in [
            ("--rtc-stun-bind", "not-an-address"),
            ("--rtc-stun-public-addr", "203.0.113.7"),
        ] {
            let err = rtc_config_from_args(&serve_args(&[flag, value]))
                .expect_err("a malformed address must be refused");
            assert_eq!(err.kind(), crate::error::ExitCodeKind::InvalidArgs);
            assert!(
                err.to_string().contains(flag),
                "the refusal must name the flag the operator typed: {err}"
            );
        }
    }

    /// The listing row omits the STUN endpoint entirely when the
    /// anchor announced none: a row for one of the anchors that has
    /// not opted in is byte-identical to the row this command
    /// printed before Stage 6.
    ///
    /// Inverse receipt: remove the `skip_serializing_if` and the
    /// first assertion fails with `"rtc_stun_addr": null` in the
    /// row — a key every consumer of `anchor ls` would now have to
    /// account for to describe an anchor that has nothing to do
    /// with STUN.
    #[test]
    fn the_listing_row_omits_the_stun_endpoint_unless_the_anchor_announced_one() {
        let row = AnchorRow {
            node: "0x1".to_string(),
            rtc_addr: Some("203.0.113.7:7101".to_string()),
            rtc_stun_addr: None,
            rtc_bootstrap: Some("https://anchor.example.com".to_string()),
            noise_pubkey: None,
        };
        assert_eq!(
            serde_json::to_string(&row).expect("serialize"),
            r#"{"node":"0x1","rtc_addr":"203.0.113.7:7101","rtc_bootstrap":"https://anchor.example.com","noise_pubkey":null}"#,
            "the row an anchor without a STUN endpoint produces, key for key"
        );

        let announced = AnchorRow {
            rtc_stun_addr: Some("203.0.113.7:3479".to_string()),
            ..row
        };
        let json: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&announced).expect("serialize"))
                .expect("parse");
        assert_eq!(
            json["rtc_stun_addr"], "203.0.113.7:3479",
            "and the announced endpoint travels under its own key, beside rtc_addr"
        );
        assert_eq!(
            json["rtc_addr"], "203.0.113.7:7101",
            "which is a different endpoint, and stays one"
        );
    }

    /// `serve`'s report echoes the PUBLIC STUN address the operator
    /// configured, and omits the key when there was none.
    ///
    /// **Deliberately asymmetric**, and pinned here so the
    /// asymmetry is a decision rather than a drift: `rtc_addr`
    /// still renders `null` when unset because it did before this
    /// field existed and a consumer parsing this report is
    /// entitled to the shape it has. The new key is absent
    /// instead.
    #[test]
    fn the_serve_report_echoes_the_announced_stun_endpoint_and_omits_the_key_without_one() {
        let base = ServeReport {
            node: "0x1".to_string(),
            listening_on: "0.0.0.0:8443".to_string(),
            bootstrap_url: "https://anchor.example.com".to_string(),
            rtc_addr: None,
            rtc_stun_addr: None,
            trust_domain: "td".to_string(),
            noise_pubkey: "ab".to_string(),
            games: vec![],
            open_games: false,
            credential_endpoint: None,
            also_listening_on: vec![],
            rtc_addrs: None,
        };
        let json = serde_json::to_string(&base).expect("serialize");
        assert!(
            !json.contains("also_listening_on")
                && !json.contains("rtc_addrs")
                && !json.contains("open_games"),
            "a single-listener, single-socket anchor reports neither dual-stack key: {json}"
        );
        assert!(
            !json.contains("games") && !json.contains("credential_endpoint"),
            "an anchor without --game reports neither key: {json}"
        );
        assert!(
            !json.contains("rtc_stun_addr"),
            "an anchor that configured no STUN endpoint reports no such key: {json}"
        );
        assert!(
            json.contains(r#""rtc_addr":null"#),
            "…while its sibling keeps the shape it already had, null and all: {json}"
        );

        let announced = ServeReport {
            rtc_addr: Some("203.0.113.7:7101".to_string()),
            rtc_stun_addr: Some("203.0.113.7:3479".to_string()),
            ..base
        };
        let json: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&announced).expect("serialize"))
                .expect("parse");
        assert_eq!(json["rtc_stun_addr"], "203.0.113.7:3479");
        assert_eq!(
            json["rtc_addr"], "203.0.113.7:7101",
            "the two endpoints are reported separately because they ARE separate"
        );
    }

    /// The dual-stack flags: an `--rtc-bind` of each family makes the
    /// second socket, each `--rtc-public-addr` advertises the socket of
    /// its family, and one bind of either family is the single-socket
    /// anchor it always was.
    #[test]
    fn rtc_binds_of_each_family_make_a_dual_stack_anchor() {
        let dual = rtc_config_from_args(&serve_args(&[
            "--rtc-bind",
            "[::]:7101",
            "--rtc-bind",
            "0.0.0.0:7101",
            "--rtc-public-addr",
            "[2001:db8::7]:7101",
            "--rtc-public-addr",
            "203.0.113.7:7101",
        ]))
        .expect("dual-stack flags");
        assert_eq!(dual.bind_addr, Some("0.0.0.0:7101".parse().unwrap()));
        assert_eq!(dual.bind_addr_v6, Some("[::]:7101".parse().unwrap()));
        assert_eq!(dual.public_addr, Some("203.0.113.7:7101".parse().unwrap()));
        assert_eq!(
            dual.public_addr_v6,
            Some("[2001:db8::7]:7101".parse().unwrap()),
            "each public address advertises the socket of its own family, whatever the \
             flag order"
        );
        assert_eq!(dual.validate(), None);

        let single_v6 = rtc_config_from_args(&serve_args(&[
            "--rtc-bind",
            "[::]:7101",
            "--rtc-public-addr",
            "[2001:db8::7]:7101",
        ]))
        .expect("one IPv6 socket");
        assert_eq!(
            (single_v6.bind_addr, single_v6.bind_addr_v6),
            (Some("[::]:7101".parse().unwrap()), None),
            "one IPv6 bind is still the primary socket, as before"
        );
        assert_eq!(
            single_v6.public_addr,
            Some("[2001:db8::7]:7101".parse().unwrap())
        );
    }

    #[test]
    fn stun_binds_of_each_family_make_a_stun_endpoint_per_family() {
        let dual = rtc_config_from_args(&serve_args(&[
            "--rtc-stun-bind",
            "[::]:3479",
            "--rtc-stun-bind",
            "0.0.0.0:3479",
            "--rtc-stun-public-addr",
            "[2001:db8::7]:3479",
            "--rtc-stun-public-addr",
            "203.0.113.7:3479",
        ]))
        .expect("per-family STUN flags");
        assert_eq!(dual.stun_addr, Some("0.0.0.0:3479".parse().unwrap()));
        assert_eq!(dual.stun_addr_v6, Some("[::]:3479".parse().unwrap()));
        assert_eq!(
            dual.stun_public_addr,
            Some("203.0.113.7:3479".parse().unwrap())
        );
        assert_eq!(
            dual.stun_public_addr_v6,
            Some("[2001:db8::7]:3479".parse().unwrap())
        );
        assert!(
            rtc_config_from_args(&serve_args(&[
                "--rtc-stun-bind",
                "0.0.0.0:3479",
                "--rtc-stun-bind",
                "127.0.0.1:3480",
            ]))
            .is_err(),
            "two STUN sockets of one family are refused"
        );
    }

    #[test]
    fn two_rtc_addresses_of_one_family_are_refused() {
        for flags in [
            ["--rtc-bind", "0.0.0.0:7101", "--rtc-bind", "127.0.0.1:7102"],
            [
                "--rtc-public-addr",
                "[2001:db8::1]:1",
                "--rtc-public-addr",
                "[2001:db8::2]:1",
            ],
        ] {
            assert!(
                rtc_config_from_args(&serve_args(&flags)).is_err(),
                "{flags:?} must be refused: two sockets of one family is ambiguous"
            );
        }
        assert!(
            rtc_config_from_args(&serve_args(&[
                "--rtc-bind",
                "0.0.0.0:7101",
                "--rtc-public-addr",
                "203.0.113.7:7101",
                "--rtc-public-addr",
                "[2001:db8::7]:7101",
            ]))
            .is_err(),
            "an IPv6 public address with no IPv6 socket is refused"
        );
    }

    /// `ServeArgs` that `resolve_serve` accepts: a real issuer key and
    /// an operator certificate, plus `extra`.
    fn resolvable_serve_args(extra: &[&str]) -> ServeArgs {
        let issuer = hex_string(
            net_sdk::identity::Identity::from_seed([0x61; 32])
                .entity_id()
                .as_bytes(),
        );
        let mut argv = vec![
            "--psk-file",
            "psk.hex",
            "--url",
            "https://anchor.example.com",
            "--credential-issuer",
            issuer.as_str(),
            "--allow-origin",
            "https://app.example.com",
            "--tls-cert",
            "c.pem",
            "--tls-key",
            "k.pem",
        ];
        argv.extend_from_slice(extra);
        try_serve_args(&argv).expect("serve args parse")
    }

    #[test]
    fn listen_and_acme_challenge_addresses_are_repeatable() {
        let resolved = resolve_serve(&resolvable_serve_args(&[
            "--listen",
            "0.0.0.0:443",
            "--listen",
            "[::]:443",
        ]))
        .expect("resolves");
        assert_eq!(
            resolved.listen,
            vec![
                "0.0.0.0:443".parse::<std::net::SocketAddr>().unwrap(),
                "[::]:443".parse().unwrap()
            ]
        );
        assert_eq!(
            resolved.challenge,
            vec!["0.0.0.0:80".parse::<std::net::SocketAddr>().unwrap()],
            "the challenge default is unchanged"
        );
        let defaulted = resolve_serve(&resolvable_serve_args(&[])).expect("resolves");
        assert_eq!(
            defaulted.listen,
            vec!["0.0.0.0:8443".parse::<std::net::SocketAddr>().unwrap()],
            "the listen default is unchanged"
        );
    }
}