zc2 0.0.30

P2P compute broker with credit-based billing, WAL, and broker mesh support
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
//! VPN-join: connect zc to the zakuro WireGuard mesh.
//!
//! Public surface used by the rest of zc:
//!   - `connect(Preference) -> Result<ConnectionInfo, NetError>`
//!   - `status() -> Result<Option<ConnectionInfo>, NetError>`
//!   - `disconnect() -> Result<(), NetError>`
//!   - `run_cli(&[String])` — handler for `zc vpn …`
//!
//! Backends (native wg-quick, the Docker sidecar, and a host tunnel zc didn't
//! bring up) live behind the `Connector` trait so each is testable in isolation.

#![allow(dead_code)]

pub mod connector;
pub mod docker;
pub mod host;
pub mod native;
pub mod profile;
pub mod state;

use connector::{select_connector, Connector, Preference};
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicBool, Ordering};

/// Verbose diagnostics toggle for `zc vpn` (`--verbose`/`-v`). When on, the mesh
/// steps print backend selection, wg-quick output, and `wg show` so a failed
/// connect can be diagnosed without guessing.
static VERBOSE: AtomicBool = AtomicBool::new(false);
pub fn set_verbose(v: bool) {
    VERBOSE.store(v, Ordering::Relaxed);
}
pub fn verbose() -> bool {
    VERBOSE.load(Ordering::Relaxed)
}
/// Print a `[vpn]` diagnostic line to stderr, but only in verbose mode.
pub fn vlog(msg: &str) {
    if verbose() {
        eprintln!("  [vpn] {msg}");
    }
}

/// Which transport carried the tunnel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Backend {
    Native,
    Docker,
    /// A tunnel zc didn't bring up (the WireGuard app, wg-quick): recorded,
    /// never started or stopped by zc.
    Host,
}

impl Backend {
    pub fn label(&self) -> &'static str {
        match self {
            Backend::Native => "native",
            Backend::Docker => "docker",
            Backend::Host => "host",
        }
    }
}

/// Liveness of a single mesh peer, as seen from this node.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeerStatus {
    pub ip: String,
    pub last_handshake_secs: Option<u64>,
    pub reachable: bool,
}

/// The result of a successful connect / the current link state.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionInfo {
    pub backend: Backend,
    pub address: String, // e.g. "10.13.13.6/24"
    pub link: String,    // iface name (native) or container name (docker)
    pub peers: Vec<PeerStatus>,
    pub host_routable: bool,
    #[serde(default)]
    pub proxy: Option<String>, // "127.0.0.1:18888" when backend=Docker exposes a CONNECT proxy
    /// The inbound relay's version on a proxy sidecar (`RELAY_VERSION`), as
    /// its `zakuro.relay` label says; `None` for a sidecar from before the
    /// relay and for every other backend (mesh-routes §3).
    #[serde(default)]
    pub relay: Option<u32>,
}

/// How zc reaches the mesh subnet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MeshAccess {
    Host,
    Proxy(String), // host:port of the sidecar's HTTP CONNECT proxy
}

/// Errors surfaced by the vpn module.
#[derive(Debug)]
pub enum NetError {
    NoApiKey,
    Fetch(String),
    NoBackend,
    Backend(String),
    Profile(String),
    /// A host network change refused inside the unit-test binary; see
    /// [`host_ops_allowed`].
    Refused(String),
}

impl std::fmt::Display for NetError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NetError::NoApiKey => write!(f, "p2p requires ZAKURO_API_KEY (set it and retry)"),
            NetError::Fetch(e) => write!(f, "failed to fetch WireGuard profile: {}", e),
            NetError::NoBackend => {
                let hint = if cfg!(target_os = "macos") {
                    "install WireGuard (`brew install wireguard-tools wireguard-go`) then re-run with `sudo`, or start Docker Desktop"
                } else {
                    "install WireGuard (`sudo apt install wireguard-tools`) and run as root, or install Docker"
                };
                write!(f, "no usable backend: {hint}")
            }
            NetError::Backend(e) => write!(f, "tunnel backend error: {}", e),
            NetError::Profile(e) => write!(f, "invalid WireGuard profile: {}", e),
            NetError::Refused(e) => write!(f, "{}", e),
        }
    }
}

impl std::error::Error for NetError {}

/// Whether this process may change the host's network setup: bring a
/// WireGuard interface up or down, drive docker for the VPN helper, or chown
/// state back to the sudo user. Always, in a real binary.
#[cfg(not(test))]
pub(crate) fn host_ops_allowed(_what: &str) -> Result<(), NetError> {
    Ok(())
}

/// In the unit-test binary, only with `ZAKURO_TEST_REAL_VPN=1`. `wg-quick`
/// re-execs itself through `sudo` when it isn't root, so on a host with
/// passwordless sudo a test that reached it brought the real `zakuro0` down:
/// a `cargo test` on zakuro-dev on 2026-09-13 took that broker off the
/// staging mesh (zc#211).
#[cfg(test)]
pub(crate) fn host_ops_allowed(what: &str) -> Result<(), NetError> {
    if std::env::var("ZAKURO_TEST_REAL_VPN").as_deref() == Ok("1") {
        return Ok(());
    }
    Err(NetError::Refused(format!(
        "{what}: refused in unit tests (set ZAKURO_TEST_REAL_VPN=1 to allow)"
    )))
}

/// Which access mode a live connection provides.
fn access_of(info: &ConnectionInfo) -> Result<MeshAccess, NetError> {
    match (&info.proxy, info.host_routable) {
        (_, true) => Ok(MeshAccess::Host),
        (Some(p), false) => Ok(MeshAccess::Proxy(p.clone())),
        (None, false) => Err(NetError::Backend(
            "tunnel up but host cannot route and no proxy available".into(),
        )),
    }
}

/// True when the tunnel has a recent WireGuard handshake with the mesh server —
/// the authoritative "am I on the mesh" signal. The wg server exposes no TCP
/// service on its mesh IP, so a port probe is meaningless; the handshake is not.
/// Runs `wg show <iface> latest-handshakes` on the host (native) or inside the
/// sidecar (docker), retrying to give a just-started tunnel time to handshake.
fn mesh_handshake_ok(info: &ConnectionInfo) -> bool {
    use std::time::{Duration, SystemTime, UNIX_EPOCH};
    // A tunnel zc didn't bring up: `wg show` on it needs root, and its
    // interface still carrying the mesh address is the signal we have.
    if info.backend == Backend::Host {
        return local_mesh().is_some();
    }
    if host_ops_allowed("wg show latest-handshakes").is_err() {
        return false;
    }
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    for attempt in 0..5 {
        if attempt > 0 {
            std::thread::sleep(Duration::from_millis(1200));
        }
        let out = match info.backend {
            Backend::Native => std::process::Command::new("wg")
                .args(["show", "zakuro0", "latest-handshakes"])
                .output()
                .ok(),
            Backend::Docker => std::process::Command::new("docker")
                .args([
                    "exec",
                    &info.link,
                    "wg",
                    "show",
                    "zakuro0",
                    "latest-handshakes",
                ])
                .output()
                .ok(),
            Backend::Host => None, // returned above
        };
        let text = match out {
            Some(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).into_owned(),
            _ => continue,
        };
        // any peer with a handshake in the last 5 min counts as reachable
        let fresh = text
            .lines()
            .filter_map(|l| l.split_whitespace().nth(1))
            .filter_map(|s| s.parse::<u64>().ok())
            .any(|hs| hs > 0 && now.saturating_sub(hs) < 300);
        if fresh {
            return true;
        }
    }
    false
}

/// Testable core of `ensure`: the verify + connect functions are injected.
fn ensure_with(
    verify_fn: &dyn Fn(&ConnectionInfo) -> bool,
    connect_fn: &dyn Fn() -> Result<ConnectionInfo, NetError>,
    saved: Option<&ConnectionInfo>,
) -> Result<MeshAccess, NetError> {
    // 1./2. reuse a live path (host or container proxy) if it still verifies.
    if let Some(s) = saved {
        if verify_fn(s) {
            return access_of(s);
        }
    }
    // 3. bring it up, then 4. verify — no silent success.
    let info = connect_fn()?;
    if !verify_fn(&info) {
        return Err(NetError::Backend(
            "mesh probe failed — tunnel is up but no handshake with the mesh server".into(),
        ));
    }
    access_of(&info)
}

/// Verified mesh access: reuse a live path or bring the tunnel up, then verify
/// via the WireGuard handshake.
pub fn ensure(pref: Preference) -> Result<MeshAccess, NetError> {
    let saved = status()?; // None if stale/not running
    ensure_with(&mesh_handshake_ok, &|| connect(pref), saved.as_ref())
}

/// True for addresses inside the WireGuard mesh subnet 10.13.13.0/24.
pub fn is_mesh_ip(host: &str) -> bool {
    let p: Vec<&str> = host.split('.').collect();
    p.len() == 4 && p[0] == "10" && p[1] == "13" && p[2] == "13" && p[3].parse::<u8>().is_ok()
}

/// A local interface whose own IPv4 address is inside the mesh: this host is
/// on the mesh directly (mesh-routes §1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocalMesh {
    /// Bare IPv4, no prefix length.
    pub ip: String,
    /// `zakuro0`, `wg0`, `utun4`, … — or the name of the override variable.
    pub interface: String,
}

/// Pick this host's mesh address from its `(interface, address)` pairs. By
/// ADDRESS, not name: the WireGuard app and wg-quick on macOS name the tunnel
/// `utunN`. An interface that merely routes the mesh (another VPN whose own
/// address is elsewhere) doesn't count. `zakuro0`, then `wg*`, win ties.
pub(crate) fn pick_local_mesh(addrs: &[(String, std::net::IpAddr)]) -> Option<LocalMesh> {
    let rank = |name: &str| match name {
        "zakuro0" => 0,
        n if n.starts_with("wg") => 1,
        _ => 2,
    };
    addrs
        .iter()
        .filter(|(_, ip)| ip.is_ipv4() && is_mesh_ip(&ip.to_string()))
        .min_by_key(|(name, _)| rank(name))
        .map(|(name, ip)| LocalMesh {
            ip: ip.to_string(),
            interface: name.clone(),
        })
}

/// [`local_mesh`] as a pure function: the first non-empty override wins
/// (`ZAKURO_MESH_IP`, then legacy `ZAKURO_WIREGUARD_IP`), else `addrs`.
pub(crate) fn local_mesh_from(
    overrides: [(&str, Option<String>); 2],
    addrs: &[(String, std::net::IpAddr)],
) -> Option<LocalMesh> {
    for (var, value) in overrides {
        if let Some(ip) = value.filter(|v| !v.is_empty()) {
            return Some(LocalMesh {
                ip,
                interface: var.to_string(),
            });
        }
    }
    pick_local_mesh(addrs)
}

/// This host's own mesh address, if any: the overrides, then its interfaces
/// (`getifaddrs(3)`, no subprocess). Cheap enough to call per request.
pub fn local_mesh() -> Option<LocalMesh> {
    local_mesh_from(
        [
            ("ZAKURO_MESH_IP", std::env::var("ZAKURO_MESH_IP").ok()),
            (
                "ZAKURO_WIREGUARD_IP",
                std::env::var("ZAKURO_WIREGUARD_IP").ok(),
            ),
        ],
        &host_addresses(),
    )
}

#[cfg(unix)]
fn host_addresses() -> Vec<(String, std::net::IpAddr)> {
    ifaces::Interface::get_all()
        .map(|all| {
            all.into_iter()
                .filter_map(|i| i.addr.map(|a| (i.name, a.ip())))
                .collect()
        })
        .unwrap_or_default()
}

#[cfg(not(unix))]
fn host_addresses() -> Vec<(String, std::net::IpAddr)> {
    Vec::new()
}

/// The proxy route's inbound relay (mesh-routes §3): the zakuro-wg sidecar
/// forwards these TCP ports from its mesh address to the same ports on the
/// host. They're the agent's broker range: 9000, then 9001..=9010.
pub const RELAY_FIRST_PORT: u16 = 9000;
pub const RELAY_LAST_PORT: u16 = 9010;
/// The relay protocol version: the sidecar's `zakuro.relay` label and
/// `ConnectionInfo::relay`.
pub const RELAY_VERSION: u32 = 1;

/// True for a port the proxy route's relay carries.
pub fn relay_covers(port: u16) -> bool {
    (RELAY_FIRST_PORT..=RELAY_LAST_PORT).contains(&port)
}

/// How this host reaches the mesh right now (mesh-routes §1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Route {
    /// A local interface carries a mesh address: direct, QUIC included.
    Host {
        ip: String,
        interface: String,
    },
    /// Through the zakuro-wg sidecar: its CONNECT proxy out, its relay in.
    /// `relay` is false on a sidecar from before the relay (outbound only).
    Proxy {
        mesh_ip: String,
        connect_proxy: String,
        relay: bool,
    },
    None,
}

/// A [`Route`] without its details.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RouteKind {
    Host,
    Proxy,
    None,
}

impl RouteKind {
    /// The summary's `mesh.route` value.
    pub fn label(self) -> &'static str {
        match self {
            RouteKind::Host => "host",
            RouteKind::Proxy => "proxy",
            RouteKind::None => "none",
        }
    }
}

impl Route {
    pub fn kind(&self) -> RouteKind {
        match self {
            Route::Host { .. } => RouteKind::Host,
            Route::Proxy { .. } => RouteKind::Proxy,
            Route::None => RouteKind::None,
        }
    }

    pub fn is_proxy(&self) -> bool {
        matches!(self, Route::Proxy { .. })
    }

    /// The mesh address peers dial for a broker on `port` here (mesh-routes
    /// §4), or `None` when this route can't carry inbound mesh traffic to
    /// that port: the relay covers 9000..=9010 only, and a sidecar from
    /// before the relay (or one without it) covers nothing.
    pub fn advertised_ip(&self, port: u16) -> Option<String> {
        match self {
            Route::Host { ip, .. } => Some(ip.clone()),
            Route::Proxy {
                mesh_ip,
                relay: true,
                ..
            } if relay_covers(port) => Some(mesh_ip.clone()),
            Route::Proxy { .. } | Route::None => None,
        }
    }
}

/// [`route`] as a pure function. Host wins over Proxy: a host tunnel makes
/// the proxy unnecessary. The proxy counts only while it answers
/// (`proxy_alive`), because a stopped sidecar is no route.
pub(crate) fn route_from(
    local: Option<LocalMesh>,
    saved: Option<&ConnectionInfo>,
    proxy_alive: &dyn Fn(&str) -> bool,
) -> Route {
    if let Some(m) = local {
        return Route::Host {
            ip: m.ip,
            interface: m.interface,
        };
    }
    match saved {
        Some(s) if !s.host_routable => match &s.proxy {
            Some(p) if proxy_alive(p) => Route::Proxy {
                mesh_ip: s
                    .address
                    .split('/')
                    .next()
                    .unwrap_or(&s.address)
                    .to_string(),
                connect_proxy: p.clone(),
                relay: s.relay == Some(RELAY_VERSION),
            },
            _ => Route::None,
        },
        _ => Route::None,
    }
}

/// This host's mesh route, from live state: its interfaces, `connection.json`,
/// and one loopback connect to the sidecar's proxy. It never runs `docker`:
/// the agent calls this every reconcile tick, under launchd.
pub fn route() -> Route {
    route_from(local_mesh(), state::load().as_ref(), &proxy_accepts)
}

/// The sidecar's published CONNECT proxy accepts a connection: the container
/// is up.
fn proxy_accepts(addr: &str) -> bool {
    addr.parse::<std::net::SocketAddr>().is_ok_and(|a| {
        std::net::TcpStream::connect_timeout(&a, std::time::Duration::from_millis(300)).is_ok()
    })
}

/// The CONNECT proxy mesh-bound HTTP goes through: the saved sidecar's, and
/// only when no local interface is on the mesh (mesh-routes §1). There's no
/// liveness probe here: this runs per request, and a stopped sidecar fails
/// either way.
pub(crate) fn proxy_addr_from(
    local: Option<&LocalMesh>,
    saved: Option<ConnectionInfo>,
) -> Option<String> {
    if local.is_some() {
        return None;
    }
    saved.filter(|s| !s.host_routable).and_then(|s| s.proxy)
}

/// The sidecar CONNECT proxy address ("host:port") mesh-bound HTTP should
/// use: `None` on the host route or with no tunnel recorded. Callers building
/// their own `ureq::Agent` use this to route mesh traffic.
pub fn mesh_proxy_addr() -> Option<String> {
    proxy_addr_from(local_mesh().as_ref(), state::load())
}

/// The sidecar CONNECT proxy as a `ureq::Proxy`, for callers that assemble
/// their own agent config: `cfg.proxy(vpn::mesh_proxy())`. `None` when the
/// host routes into the mesh itself (native or hostnet docker) or when no
/// tunnel is recorded — a plain agent is then exactly right.
pub fn mesh_proxy() -> Option<ureq::Proxy> {
    mesh_proxy_addr().and_then(|p| ureq::Proxy::new(&format!("http://{}", p)).ok())
}

/// Ask the hub for the mesh's shared peer key and store it locally so a
/// broker started here (`zc share`, `zc broker`) can act as a full peer.
/// Best-effort: an older hub without `/api/broker/config/mesh` (404) or a
/// missing key is not an error — the tunnel is up either way, the broker
/// just stays a client of the mesh rather than a peer.
pub fn sync_mesh_peer_key() {
    crate::credentials::load_into_env();
    let Ok(api_key) = std::env::var("ZAKURO_API_KEY") else {
        return;
    };
    if api_key.trim().is_empty() {
        return;
    }
    let api_url = crate::credentials::default_api_url();
    let endpoint = format!("{}/api/broker/config/mesh", api_url.trim_end_matches('/'));
    let resp = match ureq::get(&endpoint)
        .config()
        .timeout_global(Some(std::time::Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", &api_key)
        .call()
    {
        Ok(r) => r,
        Err(e) => {
            vlog(&format!("mesh peer key: request failed ({e})"));
            return;
        }
    };
    let status = resp.status().as_u16();
    if status != 200 {
        vlog(&format!(
            "mesh peer key: hub answered HTTP {status}; not stored"
        ));
        return;
    }
    let Ok(text) = resp.into_body().read_to_string() else {
        return;
    };
    let key = serde_json::from_str::<serde_json::Value>(&text)
        .ok()
        .and_then(|v| {
            v.get("peer_key")
                .and_then(|k| k.as_str())
                .map(str::to_string)
        })
        .filter(|k| !k.trim().is_empty());
    match key {
        Some(k) => match crate::credentials::save_mesh_peer_key(&k) {
            Ok(()) => vlog("mesh peer key stored"),
            Err(e) => eprintln!("  ⚠ could not store the mesh peer key: {e}"),
        },
        None => vlog("mesh peer key: hub response carried no peer_key"),
    }
}

/// HTTP agent for mesh-bound requests: through the sidecar's CONNECT proxy on
/// the proxy route, direct otherwise.
pub fn mesh_agent(timeout: std::time::Duration) -> ureq::Agent {
    agent_via(timeout, mesh_proxy_addr())
}

fn agent_via(timeout: std::time::Duration, proxy: Option<String>) -> ureq::Agent {
    let mut cfg = ureq::Agent::config_builder()
        .timeout_connect(Some(timeout))
        .timeout_global(Some(timeout));
    if let Some(p) = proxy {
        if let Ok(proxy) = ureq::Proxy::new(&format!("http://{}", p)) {
            cfg = cfg.proxy(Some(proxy));
        }
    }
    ureq::Agent::new_with_config(cfg.build())
}

/// What `zc connect` does with what it finds (mesh-routes §0, §2, §3).
#[derive(Debug)]
pub(crate) enum ConnectPlan {
    /// A live connection that is still current: return it as is.
    Reuse(ConnectionInfo),
    /// A tunnel zc didn't start already gives this host a mesh address:
    /// record it and start nothing. `sidecar_left_up` notes a sidecar
    /// that is now unused.
    UseHost {
        mesh: LocalMesh,
        sidecar_left_up: bool,
    },
    /// The zakuro-wg sidecar is outdated (`reason`): recreate it, which drops
    /// the mesh once.
    RecreateSidecar { reason: &'static str },
    /// A live `shared` sidecar on a device with a node key: fetch the profile
    /// once and recreate the sidecar only if the hub now names this device
    /// ([`check_shared`]); otherwise keep this connection.
    CheckShared(ConnectionInfo),
    /// Nothing zc can reuse is up, or --docker/--native asked for a backend
    /// the recorded host tunnel isn't: bring a tunnel up.
    Fresh,
}

/// What `connect` makes of a running zakuro-wg sidecar (mesh-routes §0, §3).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SidecarCheck {
    /// Keep it as is, with no profile fetch.
    Current,
    /// Recreate it, for this reason.
    Outdated(&'static str),
    /// It carries the account's `shared` identity and this device has a node
    /// key: ask the hub (one profile fetch) whether the device has its own
    /// identity now.
    AskHub,
}

/// Whether a running zakuro-wg sidecar is current, given this device's node
/// fingerprint (`None`: no node key). It must carry the right mesh identity
/// (`zakuro.node`, §0) and, in proxy mode, the inbound relay (`zakuro.relay`,
/// §3); one recreate covers both. The rules run in order, and the first that
/// applies wins.
pub(crate) fn sidecar_outdated(
    labels: Option<&docker::SidecarLabels>,
    this_node: Option<&str>,
) -> SidecarCheck {
    let Some(labels) = labels else {
        return SidecarCheck::Outdated("has no readable zakuro labels");
    };
    // Every sidecar zc creates since per-device identities is labeled,
    // `shared` included, so this recreates an older sidecar once, never on
    // every connect.
    let Some(node) = labels.node.as_deref() else {
        return SidecarCheck::Outdated("predates per-device mesh identities");
    };
    let shared = node == docker::NODE_SHARED;
    // A vanished key (`this_node == None`) keeps a per-device sidecar (ruling
    // K1): recreating it would downgrade the device to the shared identity.
    if !shared && this_node.is_some_and(|this| this != node) {
        return SidecarCheck::Outdated("carries another device's mesh identity");
    }
    // Before the hub is asked: a `shared` sidecar without the relay is
    // recreated anyway, and the recreate's own profile fetch picks up a
    // per-device identity if the hub has one.
    if labels.mode == docker::Mode::Proxy && labels.relay != Some(RELAY_VERSION) {
        return SidecarCheck::Outdated("predates the mesh relay");
    }
    // A shared sidecar asks the hub only when this device has a key to send:
    // without one, the fetch would get the shared profile back anyway.
    if shared && this_node.is_some() {
        return SidecarCheck::AskHub;
    }
    SidecarCheck::Current
}

/// Ruling K1: the sidecar carries a per-device identity but this device's
/// node key is gone. The tunnel is kept, and `connect` prints a hint.
fn node_key_vanished(labels: Option<&docker::SidecarLabels>, this_node: Option<&str>) -> bool {
    this_node.is_none()
        && labels
            .and_then(|l| l.node.as_deref())
            .is_some_and(|n| n != docker::NODE_SHARED)
}

/// The K1 hint `connect` prints before carrying out `plan`: only on the paths
/// that keep or rebuild the sidecar. On the host path (`UseHost`) the sidecar
/// is unused and no profile is fetched, so neither this hint nor
/// `fetch_wg_profile`'s "no node key yet" is printed there.
fn key_hint(
    plan: &ConnectPlan,
    labels: Option<&docker::SidecarLabels>,
    this_node: Option<&str>,
) -> Option<&'static str> {
    match plan {
        ConnectPlan::Reuse(_)
        | ConnectPlan::RecreateSidecar { .. }
        | ConnectPlan::CheckShared(_) => node_key_vanished(labels, this_node)
            .then_some("⚠ this device's node key is missing; run zc login to recreate it"),
        ConnectPlan::UseHost { .. } | ConnectPlan::Fresh => None,
    }
}

/// [`connect`]'s decision, as a pure function of what it found: the live
/// connection, the sidecar's labels when that connection is the sidecar,
/// this host's own mesh address ([`local_mesh`]) and this device's node
/// fingerprint (`None`: no node key).
pub(crate) fn plan_connect(
    pref: Preference,
    existing: Option<ConnectionInfo>,
    labels: Option<&docker::SidecarLabels>,
    host: Option<LocalMesh>,
    this_node: Option<&str>,
) -> ConnectPlan {
    // Someone else's tunnel (the WireGuard app, wg-quick) gives this host a
    // mesh address: a plain `zc connect` records it and starts nothing (§2).
    // An explicit --docker/--native still gets that backend.
    let host = host.filter(|_| pref == Preference::Auto);
    let Some(e) = existing else {
        return match host {
            Some(mesh) => ConnectPlan::UseHost {
                mesh,
                sidecar_left_up: false,
            },
            None => ConnectPlan::Fresh,
        };
    };
    match (e.backend, host) {
        // zc's own native tunnel is the host route already (its `utunN` or
        // `zakuro0` is what `host` found); keep it native so `zc disconnect`
        // still takes it down.
        (Backend::Native, _) => ConnectPlan::Reuse(e),
        // zc's hostnet sidecar: the host route too, but its identity may be old.
        (Backend::Docker, _) if e.host_routable => sidecar_plan(e, labels, this_node),
        // A proxy sidecar and a host tunnel: use the tunnel and leave the
        // sidecar up, unused (ruling R10). Nothing is recreated.
        (Backend::Docker, Some(mesh)) => ConnectPlan::UseHost {
            mesh,
            sidecar_left_up: true,
        },
        (Backend::Docker, None) => sidecar_plan(e, labels, this_node),
        // A recorded host tunnel is recorded again while it's up, at its
        // current address. With --docker/--native (M4), or once the tunnel is
        // gone, bring a tunnel up instead of handing the record back.
        (Backend::Host, Some(mesh)) => ConnectPlan::UseHost {
            mesh,
            sidecar_left_up: false,
        },
        (Backend::Host, None) => ConnectPlan::Fresh,
    }
}

/// [`plan_connect`] for a live zakuro-wg sidecar.
fn sidecar_plan(
    e: ConnectionInfo,
    labels: Option<&docker::SidecarLabels>,
    this_node: Option<&str>,
) -> ConnectPlan {
    match sidecar_outdated(labels, this_node) {
        SidecarCheck::Current => ConnectPlan::Reuse(e),
        SidecarCheck::Outdated(reason) => ConnectPlan::RecreateSidecar { reason },
        SidecarCheck::AskHub => ConnectPlan::CheckShared(e),
    }
}

/// [`ConnectPlan::CheckShared`]: fetch the profile once. When the hub now
/// names this device, recreate the sidecar from that very profile; otherwise
/// (an older hub, or no answer) keep the live `shared` sidecar. A failed fetch
/// never fails the connect; only a failed recreate does, since it has already
/// removed the old sidecar. `fetch` and `recreate` are injected so the
/// no-churn rule is tested without a hub or Docker.
fn check_shared(
    info: ConnectionInfo,
    fetch: &dyn Fn() -> Result<profile::WgProfile, NetError>,
    recreate: &dyn Fn(&profile::WgProfile) -> Result<ConnectionInfo, NetError>,
) -> Result<ConnectionInfo, NetError> {
    match fetch() {
        Ok(p) if p.node.is_some() => {
            eprintln!(
                "  ↻ this device now has its own mesh identity on the hub; recreating the zakuro-wg sidecar"
            );
            recreate(&p)
        }
        Ok(_) => Ok(info),
        Err(e) => {
            vlog(&format!(
                "could not ask the hub for this device's mesh identity ({e}); keeping the zakuro-wg sidecar"
            ));
            Ok(info)
        }
    }
}

/// Connect to the mesh using the given backend preference.
pub fn connect(pref: Preference) -> Result<ConnectionInfo, NetError> {
    let existing = status()?;
    // One `docker inspect`, and only when the connection is the sidecar.
    let labels = match &existing {
        Some(e) if e.backend == Backend::Docker => docker::DockerConnector.sidecar_labels(),
        _ => None,
    };
    // Read-only: a connect never creates the node key.
    let this_node = profile::device_fingerprint();
    let plan = plan_connect(
        pref,
        existing,
        labels.as_ref(),
        local_mesh(),
        this_node.as_deref(),
    );
    if let Some(hint) = key_hint(&plan, labels.as_ref(), this_node.as_deref()) {
        eprintln!("  {hint}");
    }
    let info = match plan {
        // Idempotent: a live, current connection is returned as is.
        ConnectPlan::Reuse(info) => info,
        // Record the host tunnel; start and stop nothing (§2). No profile is
        // fetched, so `fetch_wg_profile`'s no-node-key hint stays quiet too.
        ConnectPlan::UseHost {
            mesh,
            sidecar_left_up,
        } => {
            if sidecar_left_up {
                eprintln!(
                    "  the zakuro-wg container is still running but no longer used; `docker rm -f zakuro-wg` removes it"
                );
            }
            host::record(&mesh)
        }
        ConnectPlan::RecreateSidecar { reason } => {
            eprintln!("  ↻ the zakuro-wg container {reason}; recreating it (the mesh drops once)");
            docker::DockerConnector.connect(&profile::fetch_wg_profile()?)?
        }
        ConnectPlan::CheckShared(info) => check_shared(info, &profile::fetch_wg_profile, &|p| {
            docker::DockerConnector.connect(p)
        })?,
        ConnectPlan::Fresh => {
            let profile = profile::fetch_wg_profile()?;
            select_connector(pref)?.connect(&profile)?
        }
    };
    // The peer key is synced on every path: a machine that connected before
    // the hub served the key (or before this build) would otherwise never get
    // it, and its broker would sit on the mesh unable to peer. Same credential,
    // same moment: a machine that can join the tunnel can also run a broker
    // that peers on it.
    sync_mesh_peer_key();
    Ok(info)
}

/// Current connection (None if not connected).
pub fn status() -> Result<Option<ConnectionInfo>, NetError> {
    if let Some(saved) = state::load() {
        let c = select_for_backend(saved.backend);
        if let Ok(Some(info)) = c.status() {
            return Ok(Some(info));
        }
        return Ok(None);
    }
    // No state file. A live tunnel may still exist (the file was deleted, or a
    // different HOME/ZAKURO_STATE_DIR wrote it): adopt it from the backend —
    // the docker helper rebuilds its info from container labels — instead of
    // reporting "not connected" and letting `connect` tear a working tunnel
    // down to build the same one again.
    if let Ok(Some(info)) = docker::DockerConnector.status() {
        return Ok(Some(info));
    }
    if let Ok(Some(info)) = native::NativeConnector.status() {
        return Ok(Some(info));
    }
    Ok(None)
}

/// Fetch this node's WireGuard profile and render it as wg-quick conf text.
/// Lets a host hand the conf to an isolated VPN container (`zc vpn conf`)
/// without bringing up an interface itself.
pub fn conf() -> Result<String, NetError> {
    profile::fetch_wg_profile()?.to_conf()
}

/// Disconnect whichever backend is active.
pub fn disconnect() -> Result<(), NetError> {
    if let Some(saved) = state::load() {
        select_for_backend(saved.backend).disconnect()?;
    } else {
        // Best-effort: tear down both, ignore errors.
        let _ = docker::DockerConnector.disconnect();
        let _ = native::NativeConnector.disconnect();
    }
    Ok(())
}

fn select_for_backend(b: Backend) -> Box<dyn connector::Connector> {
    match b {
        Backend::Native => Box::new(native::NativeConnector),
        Backend::Docker => Box::new(docker::DockerConnector),
        Backend::Host => Box::new(host::HostConnector),
    }
}

fn parse_pref(args: &[String]) -> Preference {
    if args.iter().any(|a| a == "--native") {
        Preference::Native
    } else if args.iter().any(|a| a == "--docker") {
        Preference::Docker
    } else {
        Preference::Auto
    }
}

/// Render a one-line human summary of a connection.
fn render(info: &ConnectionInfo) -> String {
    let reachable = info.peers.iter().filter(|p| p.reachable).count();
    let access = match &info.proxy {
        Some(p) if !info.host_routable => format!("proxy {}", p),
        _ => "host".to_string(),
    };
    format!(
        "connected to zakuro mesh — {} · {} · {} peer(s), {} reachable · access: {}",
        info.address,
        info.backend.label(),
        info.peers.len(),
        reachable,
        access,
    )
}

/// What `zc connect` prints for a connection (mesh-routes §2).
fn connect_line(info: &ConnectionInfo) -> String {
    match info.backend {
        Backend::Host => format!("Using the host VPN ({}, {})", info.link, info.address),
        Backend::Native | Backend::Docker => render(info),
    }
}

/// What `zc disconnect` prints, given the connection it found recorded
/// (`None`: nothing was recorded, so both zc-owned backends were torn down).
/// A host tunnel is only forgotten: whoever brought it up still owns it.
fn disconnect_message(saved: Option<&ConnectionInfo>) -> String {
    match saved {
        Some(info) if info.backend == Backend::Host => format!(
            "forgot the host VPN connection ({}, {}); the tunnel itself is managed outside zc and stays up",
            info.link, info.address
        ),
        _ => "disconnected from zakuro mesh".to_string(),
    }
}

/// CLI entry point for `zc vpn …`. `args` is everything after `vpn`.
pub fn run_cli(args: &[String]) {
    use colored::Colorize;
    set_verbose(args.iter().any(|a| a == "--verbose" || a == "-v"));
    let sub = args.first().map(|s| s.as_str()).unwrap_or("status");
    match sub {
        "connect" | "up" => match connect(parse_pref(args)) {
            Ok(info) => println!("  {} {}", "".green(), connect_line(&info)),
            Err(e) => {
                eprintln!("  {} {}", "".red(), e);
                std::process::exit(1);
            }
        },
        "ensure" => match ensure(parse_pref(args)) {
            Ok(MeshAccess::Host) => {
                println!("  {} mesh verified via host tunnel", "".green())
            }
            Ok(MeshAccess::Proxy(p)) => {
                println!("  {} mesh verified via container proxy {}", "".green(), p)
            }
            Err(e) => {
                eprintln!("  {} {}", "".red(), e);
                std::process::exit(1);
            }
        },
        "disconnect" | "down" => {
            // Read before `disconnect` clears it: the message depends on it.
            let saved = state::load();
            match disconnect() {
                Ok(()) => println!("  {} {}", "".green(), disconnect_message(saved.as_ref())),
                Err(e) => {
                    eprintln!("  {} {}", "".red(), e);
                    std::process::exit(1);
                }
            }
        }
        "status" => match status() {
            Ok(Some(info)) => println!("  {}", render(&info)),
            Ok(None) => println!("  not connected (local mode)"),
            Err(e) => {
                eprintln!("  {} {}", "".red(), e);
                std::process::exit(1);
            }
        },
        "conf" => match conf() {
            Ok(text) => print!("{}", text),
            Err(e) => {
                eprintln!("  {} {}", "".red(), e);
                std::process::exit(1);
            }
        },
        other => {
            eprintln!(
                "usage: zc vpn [connect [--native|--docker] | ensure | disconnect | status | conf] (got '{}')",
                other
            );
            std::process::exit(1);
        }
    }
}

/// Shared [`Route`] fixtures for tests across `vpn`, `agent::mesh` and the
/// QUIC route tests, so each doesn't declare its own.
#[cfg(test)]
pub(crate) mod fixtures {
    use super::Route;

    /// A Host route on a `utun4`-style interface with a mesh address.
    pub(crate) fn host_route() -> Route {
        Route::Host {
            ip: "10.13.13.7".into(),
            interface: "utun4".into(),
        }
    }

    /// A Proxy route through a container sidecar, relay included.
    pub(crate) fn proxy_route() -> Route {
        Route::Proxy {
            mesh_ip: "10.13.13.7".into(),
            connect_proxy: "127.0.0.1:18888".into(),
            relay: true,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::vpn::connector::Preference;

    #[test]
    fn parse_pref_reads_flags() {
        assert_eq!(parse_pref(&["connect".into()]), Preference::Auto);
        assert_eq!(
            parse_pref(&["connect".into(), "--native".into()]),
            Preference::Native
        );
        assert_eq!(
            parse_pref(&["connect".into(), "--docker".into()]),
            Preference::Docker
        );
    }

    const SAMPLE_PROFILE: &str = r#"{
        "interface": { "private_key": "MKCl4DM7FbX1sFUiFd8VqKzdIGUMwJ28rTgFYezsclc=", "address": "10.13.13.6/24" },
        "peer": { "public_key": "/Lzp+YIUBrNgdABzyR221uhfx2uOWi4m5ZAdgxXzhFs=",
                  "endpoint": "144.202.121.242:51822", "allowed_ips": "10.13.13.0/24",
                  "persistent_keepalive": 25 }
    }"#;

    #[test]
    fn connection_info_proxy_roundtrip_and_default() {
        // old state files (no proxy key) still parse
        let legacy = r#"{"backend":"Docker","address":"10.13.13.6/24","link":"zakuro-wg",
                         "peers":[],"host_routable":false}"#;
        let info: ConnectionInfo = serde_json::from_str(legacy).unwrap();
        assert!(info.proxy.is_none());
        assert!(info.relay.is_none());
        let with = ConnectionInfo {
            proxy: Some("127.0.0.1:18888".into()),
            ..info
        };
        let back: ConnectionInfo =
            serde_json::from_str(&serde_json::to_string(&with).unwrap()).unwrap();
        assert_eq!(back.proxy.as_deref(), Some("127.0.0.1:18888"));
    }

    #[test]
    fn ensure_ladder_reuse_host_reuse_proxy_then_connect() {
        use std::cell::Cell;
        // 1. saved native host connection that still verifies → Host (no connect)
        let native_saved = ConnectionInfo {
            backend: Backend::Native,
            address: "10.13.13.6/24".into(),
            link: "zakuro0".into(),
            peers: vec![],
            host_routable: true,
            proxy: None,
            relay: None,
        };
        let r = ensure_with(&|_| true, &|| Err(NetError::NoBackend), Some(&native_saved)).unwrap();
        assert!(matches!(r, MeshAccess::Host));
        // 2. saved docker+proxy connection that still verifies → Proxy (no connect)
        let saved = ConnectionInfo {
            backend: Backend::Docker,
            address: "10.13.13.6/24".into(),
            link: "zakuro-wg".into(),
            peers: vec![],
            host_routable: false,
            proxy: Some("127.0.0.1:18888".into()),
            relay: None,
        };
        let r = ensure_with(&|_| true, &|| Err(NetError::NoBackend), Some(&saved)).unwrap();
        assert!(matches!(r, MeshAccess::Proxy(ref p) if p == "127.0.0.1:18888"));
        // 3. saved no longer verifies → connect_fn runs; its result must verify too.
        //    verify keeps failing → Err (no silent success).
        let called = Cell::new(false);
        let err = ensure_with(
            &|_| false,
            &|| {
                called.set(true);
                Ok(saved.clone())
            },
            Some(&saved),
        )
        .unwrap_err();
        assert!(called.get());
        assert!(format!("{err}").contains("mesh probe failed"));
        // 4. fresh connect that verifies → Proxy
        let r = ensure_with(&|_| true, &|| Ok(saved.clone()), None).unwrap();
        assert!(matches!(r, MeshAccess::Proxy(_)));
    }

    #[test]
    fn mesh_ip_detection() {
        assert!(is_mesh_ip("10.13.13.4"));
        assert!(is_mesh_ip("10.13.13.254"));
        assert!(!is_mesh_ip("100.82.173.52")); // wireguard
        assert!(!is_mesh_ip("192.168.0.23"));
        assert!(!is_mesh_ip("10.13.14.4"));
        assert!(!is_mesh_ip("localhost"));
    }

    #[test]
    fn mesh_agent_uses_connect_proxy_when_state_has_one() {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        // fake peer: replies to any HTTP request
        let peer = TcpListener::bind("127.0.0.1:0").unwrap();
        let peer_port = peer.local_addr().unwrap().port();
        std::thread::spawn(move || {
            for s in peer.incoming().flatten() {
                let mut s = s;
                let mut b = [0u8; 1024];
                let _ = s.read(&mut b);
                let _ = s.write_all(
                    b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok",
                );
            }
        });
        // mini CONNECT proxy: accepts CONNECT, tunnels to the fake peer
        let proxy = TcpListener::bind("127.0.0.1:0").unwrap();
        let proxy_addr = proxy.local_addr().unwrap();
        std::thread::spawn(move || {
            for c in proxy.incoming().flatten() {
                let mut c = c;
                // read the CONNECT request line + headers (loop until CRLFCRLF)
                let mut req = Vec::new();
                let mut b = [0u8; 256];
                loop {
                    match c.read(&mut b) {
                        Ok(0) | Err(_) => break,
                        Ok(n) => {
                            req.extend_from_slice(&b[..n]);
                            if req.windows(4).any(|w| w == b"\r\n\r\n") {
                                break;
                            }
                        }
                    }
                }
                // only a CONNECT to the mesh peer should ever arrive here
                if !String::from_utf8_lossy(&req).starts_with("CONNECT 10.13.13.9:9000") {
                    continue;
                }
                c.write_all(b"HTTP/1.1 200 Connection established\r\n\r\n")
                    .unwrap();
                let mut up = std::net::TcpStream::connect(("127.0.0.1", peer_port)).unwrap();
                let mut c2 = c.try_clone().unwrap();
                let mut up2 = up.try_clone().unwrap();
                std::thread::spawn(move || {
                    let _ = std::io::copy(&mut c2, &mut up);
                });
                let _ = std::io::copy(&mut up2, &mut c);
            }
        });
        // state with proxy → agent must route through it. `ZAKURO_STATE_DIR` is
        // process-global: every test that moves it holds HOME_ENV_LOCK, or it
        // races `state::tests::save_load_clear_roundtrip` (zc#211).
        let _env = crate::credentials::HOME_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let prev_state_dir = std::env::var_os("ZAKURO_STATE_DIR");
        let dir = std::env::temp_dir().join(format!("zc-vpn-agent-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::env::set_var("ZAKURO_STATE_DIR", &dir);
        state::save(&ConnectionInfo {
            backend: Backend::Docker,
            address: "10.13.13.6/24".into(),
            link: "zakuro-wg".into(),
            peers: vec![],
            host_routable: false,
            proxy: Some(proxy_addr.to_string()),
            relay: None,
        })
        .unwrap();
        // Resolved as on a Docker Desktop Mac, with no host tunnel. Through
        // `mesh_agent` this test would go direct on a host that has a mesh
        // interface (zakuro-dev) and dial the real mesh.
        let agent = agent_via(
            std::time::Duration::from_secs(3),
            proxy_addr_from(None, state::load()),
        );
        let body = agent
            .get("http://10.13.13.9:9000/health")
            .call()
            .unwrap()
            .into_body()
            .read_to_string()
            .unwrap();
        assert_eq!(body, "ok");
        match prev_state_dir {
            Some(v) => std::env::set_var("ZAKURO_STATE_DIR", v),
            None => std::env::remove_var("ZAKURO_STATE_DIR"),
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn conf_renders_wg_quick_from_profile_file() {
        let dir = std::env::temp_dir().join(format!("zc-vpn-conf-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("wg.json");
        std::fs::write(&path, SAMPLE_PROFILE).unwrap();
        // file hatch requires the explicit opt-in (see profile::fetch_wg_profile)
        std::env::set_var("ZAKURO_ALLOW_FILE_PROFILE", "1");
        std::env::set_var("ZAKURO_WG_PROFILE_FILE", &path);

        let conf = super::conf().expect("conf renders");
        assert!(conf.contains("[Interface]"));
        assert!(conf.contains("Address = 10.13.13.6/24"));
        assert!(conf.contains("[Peer]"));
        assert!(conf.contains("Endpoint = 144.202.121.242:51822"));

        std::env::remove_var("ZAKURO_ALLOW_FILE_PROFILE");
        std::env::remove_var("ZAKURO_WG_PROFILE_FILE");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// zc#211: host network changes are refused inside the unit-test binary.
    /// No test sets `ZAKURO_TEST_REAL_VPN`: one that opted in would open the
    /// door for every test running beside it.
    #[test]
    fn host_ops_are_refused_in_unit_tests() {
        let err = host_ops_allowed("wg-quick down").unwrap_err();
        assert!(matches!(err, NetError::Refused(_)));
        assert!(err.to_string().contains("ZAKURO_TEST_REAL_VPN"), "{err}");
    }

    const THIS_NODE: &str = "0123456789abcdef";

    /// A live proxy-mode sidecar connection, as `connection.json` holds it.
    fn docker_proxy() -> ConnectionInfo {
        ConnectionInfo {
            backend: Backend::Docker,
            address: "10.13.13.7/24".into(),
            link: "zakuro-wg".into(),
            peers: vec![],
            host_routable: false,
            proxy: Some("127.0.0.1:18888".into()),
            relay: Some(RELAY_VERSION),
        }
    }

    /// The proxy sidecar's labels, relay included, carrying `node`: `None` on
    /// a sidecar from before per-device identities, `Some("shared")` on one built from the
    /// shared profile.
    fn sidecar(node: Option<&str>) -> docker::SidecarLabels {
        docker::SidecarLabels {
            mode: docker::Mode::Proxy,
            address: "10.13.13.7/24".into(),
            proxy: Some("127.0.0.1:18888".into()),
            node: node.map(str::to_string),
            relay: Some(RELAY_VERSION),
        }
    }

    /// A profile as the hub answers it; `node` is the fingerprint it echoed.
    fn hub_profile(node: Option<&str>) -> profile::WgProfile {
        let mut p: profile::WgProfile = serde_json::from_str(SAMPLE_PROFILE).unwrap();
        p.node = node.map(str::to_string);
        p
    }

    /// `plan_connect` for a plain `zc connect` (no --docker/--native) on a
    /// device with a node key.
    fn plan(
        existing: Option<ConnectionInfo>,
        labels: Option<&docker::SidecarLabels>,
        host: Option<LocalMesh>,
    ) -> ConnectPlan {
        plan_connect(Preference::Auto, existing, labels, host, Some(THIS_NODE))
    }

    /// zc's own native tunnel, as `connection.json` holds it.
    fn native() -> ConnectionInfo {
        ConnectionInfo {
            backend: Backend::Native,
            link: "zakuro0".into(),
            host_routable: true,
            proxy: None,
            relay: None,
            ..docker_proxy()
        }
    }

    #[test]
    fn connect_starts_fresh_with_nothing_up() {
        assert!(matches!(plan(None, None, None), ConnectPlan::Fresh));
        assert!(matches!(
            plan_connect(Preference::Auto, None, None, None, None),
            ConnectPlan::Fresh
        ));
    }

    #[test]
    fn a_sidecar_from_before_per_device_identities_is_recreated() {
        let old = sidecar(None);
        let p = plan(Some(docker_proxy()), Some(&old), None);
        assert!(
            matches!(p, ConnectPlan::RecreateSidecar { reason } if reason.contains("per-device")),
            "{p:?}"
        );
        // Once, with or without a key: the new one carries a `zakuro.node` label.
        let p = plan_connect(
            Preference::Auto,
            Some(docker_proxy()),
            Some(&old),
            None,
            None,
        );
        assert!(matches!(p, ConnectPlan::RecreateSidecar { .. }), "{p:?}");
    }

    #[test]
    fn a_sidecar_with_another_devices_identity_is_recreated() {
        let other = sidecar(Some("fedcba9876543210"));
        let p = plan(Some(docker_proxy()), Some(&other), None);
        assert!(
            matches!(p, ConnectPlan::RecreateSidecar { reason } if reason.contains("another device")),
            "{p:?}"
        );
    }

    #[test]
    fn a_sidecar_whose_labels_cannot_be_read_is_recreated() {
        let p = plan(Some(docker_proxy()), None, None);
        assert!(matches!(p, ConnectPlan::RecreateSidecar { .. }), "{p:?}");
    }

    #[test]
    fn a_sidecar_with_this_devices_identity_is_reused_without_asking_the_hub() {
        let current = sidecar(Some(THIS_NODE));
        assert_eq!(
            sidecar_outdated(Some(&current), Some(THIS_NODE)),
            SidecarCheck::Current
        );
        let p = plan(Some(docker_proxy()), Some(&current), None);
        assert!(
            matches!(p, ConnectPlan::Reuse(_)),
            "never CheckShared: {p:?}"
        );
    }

    #[test]
    fn a_current_sidecar_and_a_native_tunnel_are_reused() {
        let current = sidecar(Some(THIS_NODE));
        assert!(matches!(
            plan(Some(docker_proxy()), Some(&current), None),
            ConnectPlan::Reuse(_)
        ));
        assert!(matches!(
            plan(Some(native()), None, None),
            ConnectPlan::Reuse(_)
        ));
        assert!(matches!(
            plan_connect(Preference::Auto, Some(native()), None, None, None),
            ConnectPlan::Reuse(_)
        ));
    }

    /// Ruling K1: recreating would downgrade the device to the shared identity.
    #[test]
    fn a_per_device_sidecar_is_kept_when_the_node_key_vanished() {
        let mine = sidecar(Some(THIS_NODE));
        assert_eq!(sidecar_outdated(Some(&mine), None), SidecarCheck::Current);
        assert!(matches!(
            plan_connect(
                Preference::Auto,
                Some(docker_proxy()),
                Some(&mine),
                None,
                None
            ),
            ConnectPlan::Reuse(_)
        ));
        assert!(
            node_key_vanished(Some(&mine), None),
            "connect() prints the zc login hint"
        );
        assert!(!node_key_vanished(Some(&mine), Some(THIS_NODE)));
        assert!(
            !node_key_vanished(Some(&sidecar(Some(docker::NODE_SHARED))), None),
            "a shared sidecar never carried this device's key"
        );
        assert!(!node_key_vanished(None, None));
    }

    #[test]
    fn without_a_node_key_a_shared_sidecar_is_current_and_the_hub_is_not_asked() {
        let shared = sidecar(Some(docker::NODE_SHARED));
        assert_eq!(sidecar_outdated(Some(&shared), None), SidecarCheck::Current);
        // Reuse: `connect` makes no profile fetch on this path.
        let p = plan_connect(
            Preference::Auto,
            Some(docker_proxy()),
            Some(&shared),
            None,
            None,
        );
        assert!(matches!(p, ConnectPlan::Reuse(_)), "{p:?}");
    }

    #[test]
    fn with_a_node_key_a_shared_sidecar_asks_the_hub() {
        let shared = sidecar(Some(docker::NODE_SHARED));
        assert_eq!(
            sidecar_outdated(Some(&shared), Some(THIS_NODE)),
            SidecarCheck::AskHub
        );
        let p = plan(Some(docker_proxy()), Some(&shared), None);
        assert!(matches!(p, ConnectPlan::CheckShared(_)), "{p:?}");
    }

    /// The no-churn rule: an older hub keeps answering the shared profile, and
    /// the `shared` sidecar must survive every `zc connect` against it.
    #[test]
    fn a_shared_sidecar_is_kept_while_the_hub_answers_the_shared_profile() {
        use std::cell::Cell;
        let shared = sidecar(Some(docker::NODE_SHARED));
        let ConnectPlan::CheckShared(live) = plan(Some(docker_proxy()), Some(&shared), None) else {
            panic!("a shared sidecar with a node key asks the hub");
        };
        let (fetches, recreates) = (Cell::new(0), Cell::new(0));
        let info = check_shared(
            live,
            &|| {
                fetches.set(fetches.get() + 1);
                Ok(hub_profile(None))
            },
            &|_| {
                recreates.set(recreates.get() + 1);
                Err(NetError::NoBackend)
            },
        )
        .expect("the live sidecar is kept");
        assert_eq!(fetches.get(), 1, "one profile fetch per connect");
        assert_eq!(recreates.get(), 0, "no recreate while the hub is old");
        assert_eq!(info.address, docker_proxy().address);
    }

    #[test]
    fn a_shared_sidecar_is_kept_when_the_hub_cannot_be_asked() {
        use std::cell::Cell;
        let (fetches, recreates) = (Cell::new(0), Cell::new(0));
        let info = check_shared(
            docker_proxy(),
            &|| {
                fetches.set(fetches.get() + 1);
                Err(NetError::Fetch("connection refused".into()))
            },
            &|_| {
                recreates.set(recreates.get() + 1);
                Err(NetError::NoBackend)
            },
        )
        .expect("a failed fetch never fails the connect");
        assert_eq!(fetches.get(), 1);
        assert_eq!(recreates.get(), 0);
        assert_eq!(info.address, docker_proxy().address);
    }

    #[test]
    fn a_shared_sidecar_is_recreated_from_the_profile_that_names_this_device() {
        use std::cell::{Cell, RefCell};
        let (fetches, recreates) = (Cell::new(0), Cell::new(0));
        let built_from = RefCell::new(None);
        let info = check_shared(
            docker_proxy(),
            &|| {
                fetches.set(fetches.get() + 1);
                Ok(hub_profile(Some(THIS_NODE)))
            },
            &|p| {
                recreates.set(recreates.get() + 1);
                *built_from.borrow_mut() = p.node.clone();
                Ok(ConnectionInfo {
                    address: p.interface.address.clone(),
                    ..docker_proxy()
                })
            },
        )
        .expect("recreated");
        assert_eq!(fetches.get(), 1, "the profile that answered is reused");
        assert_eq!(recreates.get(), 1);
        assert_eq!(built_from.borrow().as_deref(), Some(THIS_NODE));
        assert_eq!(
            info.address, "10.13.13.6/24",
            "connect returns the recreated sidecar's connection"
        );
    }

    fn ip(s: &str) -> std::net::IpAddr {
        s.parse().unwrap()
    }

    #[test]
    fn local_mesh_is_found_by_address_on_a_utun() {
        let addrs = vec![
            ("lo0".to_string(), ip("127.0.0.1")),
            ("en0".to_string(), ip("192.168.0.23")),
            ("utun4".to_string(), ip("10.13.13.7")),
        ];
        assert_eq!(
            pick_local_mesh(&addrs),
            Some(LocalMesh {
                ip: "10.13.13.7".into(),
                interface: "utun4".into()
            })
        );
    }

    #[test]
    fn local_mesh_prefers_zakuro0_then_wg_names() {
        let addrs = vec![
            ("utun3".to_string(), ip("10.13.13.9")),
            ("wg0".to_string(), ip("10.13.13.8")),
            ("zakuro0".to_string(), ip("10.13.13.7")),
        ];
        assert_eq!(pick_local_mesh(&addrs).unwrap().interface, "zakuro0");
        assert_eq!(pick_local_mesh(&addrs[..2]).unwrap().interface, "wg0");
    }

    /// The user's "home" WireGuard tunnel on utun4 (address 10.100.0.2) may
    /// route 10.13.13.0/24, but its own address isn't in the mesh: that's no
    /// Host route.
    #[test]
    fn a_route_via_another_vpn_is_not_host() {
        let addrs = vec![
            ("utun4".to_string(), ip("10.100.0.2")),
            ("en0".to_string(), ip("192.168.1.5")),
        ];
        assert_eq!(pick_local_mesh(&addrs), None);
    }

    #[test]
    fn local_mesh_ignores_other_subnets_and_ipv6() {
        let addrs = vec![
            ("utun3".to_string(), ip("fe80::1")),
            ("utun5".to_string(), ip("10.13.14.7")),
            ("tailscale0".to_string(), ip("100.82.173.52")),
        ];
        assert_eq!(pick_local_mesh(&addrs), None);
    }

    #[test]
    fn local_mesh_env_overrides_keep_their_precedence() {
        let utun = vec![("utun4".to_string(), ip("10.13.13.7"))];
        let over = |mesh: Option<&str>, wg: Option<&str>| {
            [
                ("ZAKURO_MESH_IP", mesh.map(str::to_string)),
                ("ZAKURO_WIREGUARD_IP", wg.map(str::to_string)),
            ]
        };
        assert_eq!(
            local_mesh_from(over(Some("10.13.13.42"), Some("10.13.13.43")), &utun),
            Some(LocalMesh {
                ip: "10.13.13.42".into(),
                interface: "ZAKURO_MESH_IP".into()
            })
        );
        assert_eq!(
            local_mesh_from(over(None, Some("10.13.13.43")), &utun),
            Some(LocalMesh {
                ip: "10.13.13.43".into(),
                interface: "ZAKURO_WIREGUARD_IP".into()
            })
        );
        assert_eq!(
            local_mesh_from(over(Some(""), None), &utun)
                .unwrap()
                .interface,
            "utun4",
            "an empty override is no override"
        );
        assert_eq!(local_mesh_from(over(None, None), &[]), None);
    }

    fn utun() -> LocalMesh {
        LocalMesh {
            ip: "10.13.13.7".into(),
            interface: "utun4".into(),
        }
    }

    #[test]
    fn route_host_beats_proxy() {
        let r = route_from(Some(utun()), Some(&docker_proxy()), &|_| {
            panic!("a host tunnel needs no proxy probe")
        });
        assert_eq!(
            r,
            Route::Host {
                ip: "10.13.13.7".into(),
                interface: "utun4".into()
            }
        );
    }

    #[test]
    fn route_proxy_needs_a_live_connect_proxy() {
        let saved = docker_proxy();
        assert_eq!(
            route_from(None, Some(&saved), &|p| p == "127.0.0.1:18888"),
            Route::Proxy {
                mesh_ip: "10.13.13.7".into(),
                connect_proxy: "127.0.0.1:18888".into(),
                relay: true
            }
        );
        assert_eq!(
            route_from(None, Some(&saved), &|_| false),
            Route::None,
            "a stopped sidecar is no route"
        );
    }

    #[test]
    fn route_proxy_reports_a_sidecar_without_the_relay() {
        let old = ConnectionInfo {
            relay: None,
            ..docker_proxy()
        };
        assert!(matches!(
            route_from(None, Some(&old), &|_| true),
            Route::Proxy { relay: false, .. }
        ));
    }

    #[test]
    fn route_none_without_a_tunnel() {
        assert_eq!(route_from(None, None, &|_| true), Route::None);
        let gone = ConnectionInfo {
            backend: Backend::Native,
            link: "zakuro0".into(),
            host_routable: true,
            proxy: None,
            ..docker_proxy()
        };
        assert_eq!(
            route_from(None, Some(&gone), &|_| true),
            Route::None,
            "a recorded native tunnel whose interface is gone"
        );
    }

    #[test]
    fn route_kinds_carry_the_summary_labels() {
        assert_eq!(fixtures::host_route().kind().label(), "host");
        let proxy = fixtures::proxy_route();
        assert_eq!(proxy.kind().label(), "proxy");
        assert!(proxy.is_proxy());
        assert_eq!(Route::None.kind().label(), "none");
    }

    #[test]
    fn the_connect_proxy_is_used_only_without_a_host_tunnel() {
        assert_eq!(
            proxy_addr_from(None, Some(docker_proxy())).as_deref(),
            Some("127.0.0.1:18888")
        );
        assert_eq!(
            proxy_addr_from(Some(&utun()), Some(docker_proxy())),
            None,
            "host wins"
        );
        assert_eq!(proxy_addr_from(None, None), None);
    }

    #[test]
    fn proxy_accepts_only_a_listening_address() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap().to_string();
        assert!(proxy_accepts(&addr));
        drop(listener);
        assert!(!proxy_accepts(&addr));
        assert!(!proxy_accepts("not an address"));
    }

    #[test]
    fn relay_covers_the_agents_broker_range() {
        assert!(relay_covers(9000) && relay_covers(9010));
        assert!(!relay_covers(8999) && !relay_covers(9011) && !relay_covers(54321));
    }

    #[test]
    fn a_proxy_sidecar_without_the_relay_is_recreated() {
        let old = docker::SidecarLabels {
            relay: None,
            ..sidecar(Some(THIS_NODE))
        };
        let p = plan(Some(docker_proxy()), Some(&old), None);
        assert!(
            matches!(p, ConnectPlan::RecreateSidecar { reason } if reason.contains("relay")),
            "{p:?}"
        );
    }

    /// The relay rule runs before the ask-the-hub rule: a `shared` proxy
    /// sidecar from before the relay is recreated at once, with no profile
    /// fetch first to ask the hub.
    #[test]
    fn a_shared_sidecar_without_the_relay_is_recreated_without_asking_the_hub() {
        let old = docker::SidecarLabels {
            relay: None,
            ..sidecar(Some(docker::NODE_SHARED))
        };
        assert_eq!(
            sidecar_outdated(Some(&old), Some(THIS_NODE)),
            SidecarCheck::Outdated("predates the mesh relay"),
            "not AskHub"
        );
        let p = plan(Some(docker_proxy()), Some(&old), None);
        assert!(
            matches!(p, ConnectPlan::RecreateSidecar { reason } if reason.contains("relay")),
            "{p:?}"
        );
        assert_eq!(
            sidecar_outdated(Some(&old), None),
            SidecarCheck::Outdated("predates the mesh relay"),
            "with no node key too"
        );
    }

    #[test]
    fn a_hostnet_sidecar_needs_no_relay() {
        let hostnet = docker::SidecarLabels {
            mode: docker::Mode::HostNet,
            proxy: None,
            relay: None,
            ..sidecar(Some(THIS_NODE))
        };
        assert_eq!(
            sidecar_outdated(Some(&hostnet), Some(THIS_NODE)),
            SidecarCheck::Current
        );
        let shared = docker::SidecarLabels {
            node: Some(docker::NODE_SHARED.into()),
            ..hostnet
        };
        assert_eq!(
            sidecar_outdated(Some(&shared), Some(THIS_NODE)),
            SidecarCheck::AskHub,
            "the relay rule is proxy-only, so a shared hostnet sidecar still asks the hub"
        );
    }

    #[test]
    fn connect_uses_a_host_tunnel_instead_of_starting_the_sidecar() {
        let p = plan(None, None, Some(utun()));
        assert!(
            matches!(&p, ConnectPlan::UseHost { mesh, sidecar_left_up: false } if mesh.interface == "utun4"),
            "{p:?}"
        );
    }

    /// Ruling R10: the host tunnel is recorded and the sidecar is left up,
    /// with a hint. Even an outdated sidecar isn't recreated.
    #[test]
    fn connect_prefers_a_host_tunnel_over_a_running_sidecar() {
        let current = sidecar(Some(THIS_NODE));
        let p = plan(Some(docker_proxy()), Some(&current), Some(utun()));
        assert!(
            matches!(
                p,
                ConnectPlan::UseHost {
                    sidecar_left_up: true,
                    ..
                }
            ),
            "{p:?}"
        );
        let p = plan(Some(docker_proxy()), Some(&sidecar(None)), Some(utun()));
        assert!(
            matches!(
                p,
                ConnectPlan::UseHost {
                    sidecar_left_up: true,
                    ..
                }
            ),
            "{p:?}"
        );
    }

    /// zc's own native tunnel is what `local_mesh` finds on that host: it
    /// stays recorded as native, so `zc disconnect` still takes it down.
    #[test]
    fn zcs_own_native_tunnel_stays_native() {
        assert!(matches!(
            plan(Some(native()), None, Some(utun())),
            ConnectPlan::Reuse(i) if i.backend == Backend::Native
        ));
    }

    #[test]
    fn an_explicit_backend_skips_the_host_tunnel() {
        for pref in [Preference::Docker, Preference::Native] {
            let p = plan_connect(pref, None, None, Some(utun()), Some(THIS_NODE));
            assert!(matches!(p, ConnectPlan::Fresh), "{pref:?}: {p:?}");
        }
        let current = sidecar(Some(THIS_NODE));
        let p = plan_connect(
            Preference::Docker,
            Some(docker_proxy()),
            Some(&current),
            Some(utun()),
            Some(THIS_NODE),
        );
        assert!(
            matches!(&p, ConnectPlan::Reuse(i) if i.backend == Backend::Docker),
            "--docker keeps the sidecar: {p:?}"
        );
    }

    /// M4: --docker/--native with a host connection recorded brings that
    /// backend up; reusing the host connection would ignore the flag.
    #[test]
    fn an_explicit_backend_replaces_a_recorded_host_connection() {
        for pref in [Preference::Docker, Preference::Native] {
            let recorded = host::info_for(&utun());
            let p = plan_connect(pref, Some(recorded), None, Some(utun()), Some(THIS_NODE));
            assert!(matches!(p, ConnectPlan::Fresh), "{pref:?}: {p:?}");
        }
    }

    /// A plain `zc connect` records a live host tunnel again, at its current
    /// address, and brings a tunnel up once it's gone.
    #[test]
    fn a_recorded_host_connection_follows_the_host_tunnel() {
        let recorded = host::info_for(&utun());
        let moved = LocalMesh {
            ip: "10.13.13.8".into(),
            interface: "utun5".into(),
        };
        let p = plan(Some(recorded.clone()), None, Some(moved));
        assert!(
            matches!(&p, ConnectPlan::UseHost { mesh, sidecar_left_up: false } if mesh.ip == "10.13.13.8"),
            "{p:?}"
        );
        assert!(matches!(
            plan(Some(recorded), None, None),
            ConnectPlan::Fresh
        ));
    }

    #[test]
    fn a_hostnet_sidecar_still_needs_this_devices_identity() {
        let hostnet = ConnectionInfo {
            host_routable: true,
            proxy: None,
            relay: None,
            ..docker_proxy()
        };
        let labels = docker::SidecarLabels {
            mode: docker::Mode::HostNet,
            proxy: None,
            relay: None,
            ..sidecar(None)
        };
        let p = plan(Some(hostnet), Some(&labels), Some(utun()));
        assert!(matches!(p, ConnectPlan::RecreateSidecar { .. }), "{p:?}");
    }

    /// A hostnet sidecar's `zakuro0` is the address `local_mesh` finds. With
    /// no node key, a `shared` one is reused as zc's own: no profile fetch,
    /// and no switch to the host backend.
    #[test]
    fn without_a_node_key_a_shared_hostnet_sidecar_is_reused() {
        let hostnet = ConnectionInfo {
            host_routable: true,
            proxy: None,
            relay: None,
            ..docker_proxy()
        };
        let labels = docker::SidecarLabels {
            mode: docker::Mode::HostNet,
            proxy: None,
            relay: None,
            ..sidecar(Some(docker::NODE_SHARED))
        };
        let zakuro0 = LocalMesh {
            ip: "10.13.13.7".into(),
            interface: "zakuro0".into(),
        };
        let p = plan_connect(
            Preference::Auto,
            Some(hostnet),
            Some(&labels),
            Some(zakuro0),
            None,
        );
        assert!(
            matches!(&p, ConnectPlan::Reuse(i) if i.backend == Backend::Docker),
            "{p:?}"
        );
    }

    #[test]
    fn a_host_tunnel_is_recorded_as_a_routable_host_connection() {
        let info = host::info_for(&utun());
        assert_eq!(info.backend, Backend::Host);
        assert_eq!(
            (info.address.as_str(), info.link.as_str()),
            ("10.13.13.7", "utun4")
        );
        assert!(info.host_routable && info.proxy.is_none() && info.relay.is_none());
        assert_eq!(
            connect_line(&info),
            "Using the host VPN (utun4, 10.13.13.7)"
        );
        assert_eq!(Backend::Host.label(), "host");
        assert_eq!(access_of(&info).unwrap(), MeshAccess::Host);
        // `connection.json` spells it "Host", and it reads back.
        let json = serde_json::to_value(&info).unwrap();
        assert_eq!(json["backend"], "Host");
        let back: ConnectionInfo = serde_json::from_value(json).unwrap();
        assert_eq!(back.backend, Backend::Host);
        // The other backends keep the summary line.
        assert_eq!(connect_line(&docker_proxy()), render(&docker_proxy()));
    }

    /// On the host path the sidecar is unused: a vanished node key prints no
    /// hint there. The same sidecar without a host tunnel still gets K1's.
    #[test]
    fn the_host_path_prints_no_node_key_hint() {
        let mine = sidecar(Some(THIS_NODE));
        let p = plan_connect(
            Preference::Auto,
            Some(docker_proxy()),
            Some(&mine),
            Some(utun()),
            None,
        );
        assert!(
            matches!(
                p,
                ConnectPlan::UseHost {
                    sidecar_left_up: true,
                    ..
                }
            ),
            "{p:?}"
        );
        assert_eq!(key_hint(&p, Some(&mine), None), None);
        let p = plan_connect(
            Preference::Auto,
            Some(docker_proxy()),
            Some(&mine),
            None,
            None,
        );
        assert!(matches!(p, ConnectPlan::Reuse(_)), "{p:?}");
        assert_eq!(
            key_hint(&p, Some(&mine), None),
            Some("⚠ this device's node key is missing; run zc login to recreate it")
        );
    }

    #[test]
    fn disconnect_says_a_host_tunnel_is_only_forgotten() {
        assert_eq!(
            disconnect_message(Some(&host::info_for(&utun()))),
            "forgot the host VPN connection (utun4, 10.13.13.7); the tunnel itself is managed outside zc and stays up"
        );
        for owned in [Some(docker_proxy()), Some(native()), None] {
            assert_eq!(
                disconnect_message(owned.as_ref()),
                "disconnected from zakuro mesh"
            );
        }
    }

    #[test]
    fn the_host_route_advertises_the_host_address_on_any_port() {
        let host = fixtures::host_route();
        assert_eq!(host.advertised_ip(9000).as_deref(), Some("10.13.13.7"));
        assert_eq!(host.advertised_ip(54321).as_deref(), Some("10.13.13.7"));
    }

    #[test]
    fn the_proxy_route_advertises_the_container_address_only_inside_the_relay_range() {
        let proxy = fixtures::proxy_route();
        assert_eq!(proxy.advertised_ip(9000).as_deref(), Some("10.13.13.7"));
        assert_eq!(proxy.advertised_ip(9010).as_deref(), Some("10.13.13.7"));
        assert_eq!(proxy.advertised_ip(9011), None, "out of the relay range");
        assert_eq!(proxy.advertised_ip(54321), None, "out of the relay range");
    }

    #[test]
    fn a_proxy_route_without_the_relay_advertises_nothing() {
        let without_relay = match fixtures::proxy_route() {
            Route::Proxy {
                mesh_ip,
                connect_proxy,
                ..
            } => Route::Proxy {
                mesh_ip,
                connect_proxy,
                relay: false,
            },
            other => panic!("expected the Proxy route fixture, got {other:?}"),
        };
        assert_eq!(without_relay.advertised_ip(9000), None);
    }

    #[test]
    fn no_route_advertises_nothing() {
        assert_eq!(Route::None.advertised_ip(9000), None);
    }
}