neverest 0.2.0

CLI to synchronize PIM collections: mail, contact, calendar…
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
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
//! # Configuration
//!
//! The TOML schema: each account holds named [`SourceConfig`]s over one
//! pimdir store, plus that store's settings.

use std::{
    collections::HashMap,
    fmt,
    io::{IsTerminal, stdin},
    path::PathBuf,
    time::Duration,
};

use anyhow::{Context, Result, bail};
use chrono::{DateTime, SecondsFormat, Utc};
use io_sasl::{
    login::SaslLoginCreds, mechanism::Sasl, rfc4505::anonymous::SaslAnonymousCreds,
    rfc4616::plain::SaslPlainCreds, rfc5801::SaslGs2ChannelBinding, rfc5802::SaslScramCreds,
    rfc7628::oauthbearer::SaslOauthbearerCreds, xoauth2::SaslXoauth2Creds,
};
use pimalaya_cli::printer::Printer;
use pimalaya_config::{
    command::CommandConfig,
    secret::{Secret, SecretResolver},
    toml as config_toml,
    toml::{TomlConfig, shell_expanded_string},
};
use pimalaya_stream::tls::{Rustls, RustlsCrypto, Tls, TlsProvider};
use serde::{Deserialize, Serialize};
use url::Url;

use crate::{cli::configure::offer_configuration, wizard::discover::CONFIG_SAMPLE_URL};

/// `skip_serializing_if` predicate omitting a defaulted field, so what the
/// wizard writes carries only what the user chose.
fn is_default<T: Default + PartialEq>(value: &T) -> bool {
    *value == T::default()
}

/// [`is_default`] for the HTTP ALPN list, whose default is not empty.
fn is_default_http_alpn(alpn: &[String]) -> bool {
    alpn == default_http_alpn().as_slice()
}

/// Splices the per-source shared fields (`collection`, `flag`, `item`,
/// `pool_size`) onto every protocol-specific config struct.
///
/// `collection` and `item` keep a serde alias on their old `mailbox` and
/// `message` spellings, so an existing mail configuration keeps loading.
macro_rules! source_config {
    (
        $(#[$struct_meta:meta])*
        pub struct $Name:ident {
            $(
                $(#[$field_meta:meta])*
                pub $field_name:ident: $field_ty:ty,
            )*
        }
    ) => {
        $(#[$struct_meta])*
        pub struct $Name {
            $(
                $(#[$field_meta])*
                pub $field_name: $field_ty,
            )*
            /// Which collections this source syncs, and what may be created
            /// or deleted on it.
            #[serde(default, alias = "mailbox", skip_serializing_if = "is_default")]
            pub collection: CollectionSourceConfig,
            /// Whether flag updates may be pushed to this source.
            #[serde(default, skip_serializing_if = "is_default")]
            pub flag: FlagSourcePermissions,
            /// Which item mutations may be pushed to this source.
            #[serde(default, alias = "message", skip_serializing_if = "is_default")]
            pub item: ItemSourcePermissions,
            /// Connection pool size override; the default is per backend.
            #[serde(default, skip_serializing_if = "Option::is_none")]
            pub pool_size: Option<usize>,
        }
    };
}

/// Generates a [`SourceConfig`] accessor forwarding to the shared field on
/// the source's backend variant, by value.
macro_rules! source_accessor {
    ($name:ident, $ty:ty) => {
        pub fn $name(&self) -> $ty {
            match &self.backend {
                SourceBackendConfig::Imap(c) => c.$name,
                SourceBackendConfig::Carddav(c) => c.$name,
                SourceBackendConfig::Caldav(c) => c.$name,
                SourceBackendConfig::Jmap(c) => c.$name,
                SourceBackendConfig::Gmail(c) => c.$name,
                SourceBackendConfig::Msgraph(c) => c.$name,
            }
        }
    };
}

/// [`source_accessor`] for a field too large to copy out.
macro_rules! source_ref_accessor {
    ($name:ident, $ty:ty) => {
        pub fn $name(&self) -> &$ty {
            match &self.backend {
                SourceBackendConfig::Imap(c) => &c.$name,
                SourceBackendConfig::Carddav(c) => &c.$name,
                SourceBackendConfig::Caldav(c) => &c.$name,
                SourceBackendConfig::Jmap(c) => &c.$name,
                SourceBackendConfig::Gmail(c) => &c.$name,
                SourceBackendConfig::Msgraph(c) => &c.$name,
            }
        }
    };
}

/// The whole configuration document: nothing but named accounts.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Config {
    /// The named accounts the document declares.
    pub accounts: HashMap<String, AccountConfig>,
}

impl TomlConfig for Config {
    type Account = AccountConfig;

    fn project_name() -> &'static str {
        env!("CARGO_PKG_NAME")
    }

    fn take_named_account(&mut self, name: &str) -> Option<(String, Self::Account)> {
        self.accounts.remove_entry(name)
    }

    fn take_default_account(&mut self) -> Option<(String, Self::Account)> {
        let name = self
            .accounts
            .iter()
            .find_map(|(name, account)| account.default.then(|| name.clone()))?;

        self.take_named_account(&name)
    }
}

impl Config {
    /// Loads `Config` from `config_paths`, offering the wizard when none is.
    ///
    /// A missing configuration is met with the wizard rather than an error:
    /// the command carries on either way, accepting giving it a chance to
    /// work and declining leaving it to fail on what it has not got.
    pub fn load_or_wizard(printer: &mut impl Printer, config_paths: &[PathBuf]) -> Result<Config> {
        if let Some(config) = Config::from_paths_or_default(config_paths)? {
            return Ok(config);
        }

        let target = Config::target_path(config_paths)?;

        // NOTE: a script and a JSON consumer cannot answer a prompt, so both
        // skip the offer and fail below.
        if !printer.is_json() && stdin().is_terminal() {
            offer_configuration(printer, config_paths, &target)?;
        }

        // NOTE: the wizard may print the account instead of writing it, so
        // having run it proves nothing and the lookup runs again.
        match Config::from_paths_or_default(config_paths)? {
            Some(config) => Ok(config),
            None => bail!(
                "No configuration found at {}, run `neverest configure` to generate one or write it by hand: {CONFIG_SAMPLE_URL}",
                target.display(),
            ),
        }
    }
}

/// Per-account configuration: named sources over one pimdir store.
///
/// An account is the hub: one store, one blob directory. A source's name
/// is its pimdir source id, so renaming one orphans its bindings, and a
/// backend written under the account is sugar for a source named after it.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct AccountConfig {
    /// Whether a command with no `-a` resolves to this account.
    #[serde(default, skip_serializing_if = "is_default")]
    pub default: bool,
    /// Named sources, the map key being the pimdir source id.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub sources: HashMap<String, SourceConfig>,
    /// Named targets, on the same terms as [`sources`](Self::sources).
    ///
    /// Absent means the local store is the destination. Named, not
    /// positional: a list would reassign every binding on a reorder, which
    /// is why `left` and `right` are gone and not worth reintroducing.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub targets: HashMap<String, SourceConfig>,
    /// Makes the `sources` side authoritative, the other's change discarded.
    ///
    /// Nothing is merged and no conflict is recorded. The other side is still
    /// enumerated every run, or every item would be re-pushed; its state
    /// decides what is left to do and never who wins.
    #[serde(default, skip_serializing_if = "is_default")]
    pub one_way: bool,
    /// Whether the store holds bodies, not spines and checkpoints alone.
    ///
    /// Unset takes the destination's answer: true with no targets, the store
    /// being what the account syncs into; false with targets, which asked to
    /// copy rather than to fill a disk. Set it to keep a copy of a migration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retain: Option<bool>,
    /// Direct-backend sugar: an IMAP source named after its protocol.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub imap: Option<ImapConfig>,
    /// Direct-backend sugar: a CardDAV source named after its protocol.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub carddav: Option<CarddavConfig>,
    /// Direct-backend sugar: a CalDAV source named after its protocol.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub caldav: Option<CaldavConfig>,
    /// Direct-backend sugar: a JMAP source named after its protocol.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub jmap: Option<JmapConfig>,
    /// Direct-backend sugar: a Gmail source named after its protocol.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gmail: Option<GmailConfig>,
    /// Direct-backend sugar: a Graph source named after its protocol.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub msgraph: Option<MsgraphConfig>,
    /// The send channel of the sugar source carrying mail, the flat
    /// spelling of `sources.<name>.smtp`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub smtp: Option<SmtpConfig>,
    /// The local pimdir store this account syncs through.
    ///
    /// Optional: the store is implicit, a per-account state directory, and
    /// is customised only here, never declared as a source.
    #[serde(default)]
    pub store: StoreConfig,
    /// How a run announces a content conflict it could not merge away.
    #[serde(default)]
    pub conflict: ConflictConfig,
    // TODO: item-level sync filters (date range, sender, subject).
    /// Item-level sync options.
    #[serde(default, alias = "message")]
    pub item: ItemSyncConfig,
    /// Max connections per source for concurrent body fetches, 4 by default.
    ///
    /// Keep it under the provider's per-account connection limit. `sync
    /// --connections N` overrides it for one run.
    #[serde(default)]
    pub connections: Option<usize>,
    /// Removed keys, kept so a configuration carrying one is refused by name
    /// rather than as an unknown field. See [`AccountConfig::validate`].
    #[serde(default, skip_serializing)]
    left: Option<RemovedKey>,
    #[serde(default, skip_serializing)]
    right: Option<RemovedKey>,
    #[serde(default, skip_serializing, alias = "mailbox")]
    collection: Option<RemovedKey>,
}

/// The account groups in reading order: the backend the wizard writes
/// first, the sync options it never writes last.
///
/// Serialized alphabetically a generated account would open on
/// `connections` and bury its backend under `conflict`.
const RENDER_ORDER: [&str; 16] = [
    "default",
    "imap",
    "carddav",
    "caldav",
    "jmap",
    "gmail",
    "msgraph",
    "smtp",
    "sources",
    "targets",
    "one-way",
    "retain",
    "store",
    "conflict",
    "item",
    "connections",
];

/// The keys naming what a backend group points at, lifted to the top of
/// their group.
///
/// Serialized alphabetically, `imap.server` would read under the
/// `imap.sasl` credential authenticating against it.
const ENDPOINT_KEYS: [&str; 2] = ["server", "user-id"];

impl AccountConfig {
    /// Renders this account as an `[accounts.<name>]` block, ready to write.
    ///
    /// What it adds to the serializer is reading order, dotted keys coming
    /// out alphabetically: groups are reordered ([`RENDER_ORDER`]), each
    /// endpoint is lifted to the top of its own ([`ENDPOINT_KEYS`]).
    pub fn render(&self, name: &str) -> Result<String> {
        // NOTE: borrowed rather than built into a `Config`, which would
        // mean cloning the account to render it. The emitter only looks
        // for an `accounts` table, so any shape carrying one will do.
        #[derive(Serialize)]
        struct AccountDocument<'a> {
            accounts: HashMap<&'a str, &'a AccountConfig>,
        }

        let document = AccountDocument {
            accounts: HashMap::from([(name, self)]),
        };
        let rendered = config_toml::to_string(&document)?;

        let (header, body) = match rendered.split_once('\n') {
            Some((header, body)) => (header, body),
            None => return Ok(rendered),
        };

        let mut groups: Vec<(String, Vec<&str>)> = Vec::new();

        for line in body.lines().filter(|line| !line.trim().is_empty()) {
            let key = line.split(['.', ' ']).next().unwrap_or(line).to_string();

            match groups.iter_mut().find(|(name, _)| *name == key) {
                Some((_, lines)) => lines.push(line),
                None => groups.push((key, vec![line])),
            }
        }

        groups.sort_by_key(|(key, _)| {
            RENDER_ORDER
                .iter()
                .position(|known| known == key)
                .unwrap_or(RENDER_ORDER.len())
        });

        let mut document = format!("{header}\n");

        for (index, (_, mut lines)) in groups.into_iter().enumerate() {
            if index > 0 {
                document.push('\n');
            }

            // NOTE: the endpoint is what the group is about, so it reads
            // first; the credentials and the quirks qualify it.
            lines.sort_by_key(|line| {
                let field = line.split(['.', ' ']).nth(1).unwrap_or_default();

                ENDPOINT_KEYS
                    .iter()
                    .position(|known| *known == field)
                    .unwrap_or(ENDPOINT_KEYS.len())
            });

            for line in lines {
                document.push_str(line);
                document.push('\n');
            }
        }

        Ok(document)
    }

    /// A single-source account, the only shape the wizard writes: one
    /// provider, one protocol, a store keeping every body.
    ///
    /// The `default` flag is left to the caller, which claims it only when
    /// no account already in the configuration holds it.
    pub fn with_source(source: SourceConfig) -> Self {
        let mut account = Self::default();
        account.set_direct_source(source);
        account
    }

    /// Writes `source` as the direct-backend sugar, replacing the backend of
    /// that protocol and lifting its send channel to the account `smtp`.
    pub fn set_direct_source(&mut self, source: SourceConfig) {
        let SourceConfig { backend, smtp } = source;

        self.smtp = smtp;

        match backend {
            SourceBackendConfig::Imap(config) => self.imap = Some(config),
            SourceBackendConfig::Carddav(config) => self.carddav = Some(config),
            SourceBackendConfig::Caldav(config) => self.caldav = Some(config),
            SourceBackendConfig::Jmap(config) => self.jmap = Some(config),
            SourceBackendConfig::Gmail(config) => self.gmail = Some(config),
            SourceBackendConfig::Msgraph(config) => self.msgraph = Some(config),
        }
    }

    /// Every configured source keyed by its id, the sugar folded into the
    /// explicit `sources` table.
    ///
    /// The sugar's source id is its protocol name, the same id the expanded
    /// form writes, so expanding an account by hand is a store no-op.
    pub fn sources(&self) -> Result<HashMap<String, SourceConfig>> {
        let mut sources = self.sources.clone();

        let sugar = [
            self.imap.clone().map(SourceBackendConfig::Imap),
            self.carddav.clone().map(SourceBackendConfig::Carddav),
            self.caldav.clone().map(SourceBackendConfig::Caldav),
            self.jmap.clone().map(SourceBackendConfig::Jmap),
            self.gmail.clone().map(SourceBackendConfig::Gmail),
            self.msgraph.clone().map(SourceBackendConfig::Msgraph),
        ];

        for backend in sugar.into_iter().flatten() {
            let name = backend.protocol().to_string();

            if sources.contains_key(&name) {
                bail!(
                    "Source {name} is declared both directly under the account and in the \
                     `sources` table; the direct form is sugar for `sources.{name}`, so keep one."
                );
            }

            sources.insert(name, SourceConfig::new(backend));
        }

        self.attach_send_channel(&mut sources)?;

        Ok(sources)
    }

    /// Hands the account `smtp` table to the one sugar source that could use
    /// it; a source in the explicit table carries its own.
    fn attach_send_channel(&self, sources: &mut HashMap<String, SourceConfig>) -> Result<()> {
        let Some(smtp) = &self.smtp else {
            return Ok(());
        };

        let mut candidates: Vec<_> = sources
            .iter()
            .filter(|(name, source)| {
                self.is_sugar(name) && source.carries_mail() && !source.sends_natively()
            })
            .map(|(name, _)| name.clone())
            .collect();
        candidates.sort();

        let [name] = candidates.as_slice() else {
            bail!(
                "The account-level `smtp` channel needs exactly one direct mail backend to \
                 complete, and this account has {}; move it under the source that sends, as \
                 `sources.<name>.smtp`.",
                candidates.len()
            );
        };

        sources
            .get_mut(name)
            .expect("candidate name comes from the map")
            .smtp = Some(smtp.clone());

        Ok(())
    }

    /// Whether that name came from the sugar rather than the explicit table.
    fn is_sugar(&self, name: &str) -> bool {
        !self.sources.contains_key(name)
    }

    /// Every endpoint the account opens, keyed by its pimdir source id.
    ///
    /// A target is a source handle of the same store: it enumerates, holds
    /// bindings and is written to. Only direction separates the two, which
    /// is [`AccountMode`] and not the seam that opens them.
    pub fn endpoints(&self) -> Result<HashMap<String, SourceConfig>> {
        let mut endpoints = self.sources()?;
        endpoints.extend(self.targets.clone());
        Ok(endpoints)
    }

    /// The account's mode: which endpoints, which way, whether bodies stay.
    ///
    /// Both `check` and the sync go through it, so what a run reports and
    /// what it does cannot drift apart. Every illegal arity is refused here,
    /// naming the cell reached and the nearest legal one.
    pub fn mode(&self) -> Result<AccountMode> {
        let sources = self.sources()?;
        let mut source_names: Vec<String> = sources.keys().cloned().collect();
        let mut target_names: Vec<String> = self.targets.keys().cloned().collect();
        source_names.sort();
        target_names.sort();

        match (source_names.len(), target_names.len(), self.one_way) {
            (0, _, _) => bail!(
                "This account declares no source. Write a backend directly under it \
                 (`imap.server = \"…\"`), or name one in its `sources` table."
            ),
            (_, 0, _) => {}
            (1, 1, _) => {}
            (1, _, true) => {}
            (1, n, false) => bail!(
                "One source and {n} targets is a one-way copy: add `one-way = true`. Without it \
                 each target would also write back, and propagating between {} endpoints has no \
                 resolution order for neverest to pick.",
                n + 1,
            ),
            (n, _, _) => bail!(
                "{n} sources and {} targets is not a shape neverest syncs. Either drop the \
                 targets, so every source syncs into the local store, or keep one source and \
                 copy it to the targets with `one-way = true`.",
                target_names.len(),
            ),
        }

        if target_names.is_empty() && self.retain == Some(false) {
            bail!(
                "`retain = false` with no target would sync to nowhere: the local store is this \
                 account's destination. Drop the key, or name the targets to copy to."
            );
        }

        let retain = self.retain.unwrap_or(target_names.is_empty());

        Ok(AccountMode {
            sources: source_names,
            targets: target_names,
            one_way: self.one_way,
            retain,
        })
    }

    /// Rejects an account a command cannot run: a removed key, no source, a
    /// source declaring what its backend cannot honour, two senders.
    ///
    /// Run by every command that opens an account, so a bad configuration is
    /// refused before a connection rather than halfway through a sync.
    pub fn validate(&self) -> Result<()> {
        self.reject_removed_keys()?;

        let sources = self.sources()?;

        if sources.is_empty() {
            bail!(
                "This account declares no source. Write a backend directly under it \
                 (`imap.server = \"…\"`), or name one in its `sources` table."
            );
        }

        for (name, source) in sources.iter().chain(&self.targets) {
            source.validate(name)?;
        }

        if let Some(name) = sources.keys().find(|name| self.targets.contains_key(*name)) {
            bail!(
                "{name} is both a source and a target. A name is the pimdir source id every \
                 binding it owns is recorded under, so one name cannot be two endpoints; rename \
                 one of them."
            );
        }

        // NOTE: called for its refusals: `check` and the sync read the same
        // mode.
        self.mode()?;

        let mut senders: Vec<_> = sources
            .iter()
            .filter(|(_, source)| source.smtp.is_some())
            .map(|(name, _)| name.clone())
            .collect();
        senders.sort();

        if senders.len() > 1 {
            bail!(
                "Sources {} each declare an `smtp` channel, and an account sends through one; \
                 keep the table on the source that sends and drop the others.",
                senders.join(", "),
            );
        }

        Ok(())
    }

    /// Refuses a key this version removed, naming what replaces it.
    ///
    /// Refused rather than ignored: silently honouring neither the old
    /// meaning nor the new one is how a configuration ends up doing the
    /// opposite of what it says.
    fn reject_removed_keys(&self) -> Result<()> {
        if self.left.is_some() || self.right.is_some() {
            bail!(
                "`left` and `right` are gone: an account names its endpoints and the direction \
                 between them. Write the authoritative one under `sources` and the other under \
                 `targets`, and add `one-way = true` to copy rather than merge; leaving it off \
                 keeps them syncing both ways, which is what the pair used to do."
            );
        }

        if self.collection.is_some() {
            bail!(
                "The account-level `collection` table is gone: a filter belongs to the source it \
                 filters, since an account may hold sources of several kinds. Write it as \
                 `sources.<name>.collection.filter`, or `<protocol>.collection.filter` under the \
                 account."
            );
        }

        let namespaced: Vec<_> = self
            .sources
            .iter()
            .chain(&self.targets)
            .filter(|(_, source)| source.declares_namespace())
            .map(|(name, _)| name.as_str())
            .collect();

        if !namespaced.is_empty() {
            bail!(
                "`collection.namespace` is gone, on {}: it said which sources met, which is now \
                 whether they sit under `sources` or `targets`, and it never said which way, \
                 which is now `one-way`. Drop it.",
                namespaced.join(", "),
            );
        }

        self.store.reject_removed_keys()
    }
}

/// Presence marker for a configuration key this version removed.
///
/// Deserializing accepts whatever the key held and discards it, so the
/// account refuses it by name with its replacement rather than as an
/// unknown field with no explanation.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct RemovedKey;

impl<'de> Deserialize<'de> for RemovedKey {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        serde::de::IgnoredAny::deserialize(deserializer)?;
        Ok(Self)
    }
}

/// The only part of conflict handling anybody configures.
///
/// Whether a run merges is not a setting: the three-way merge is a pure
/// function over bodies the store holds, and because nobody can swap it out
/// it resolves only what nobody disagreed about (see [`crate::kind::merge`]).
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ConflictConfig {
    /// The merger `conflict resolve --interactive` runs.
    ///
    /// Unset by default; a sync never runs it. The four paths are appended
    /// git-mergetool style, unless the command names {base}, {local}, {remote}
    /// or {output}: `tcard merge {base} {local} {remote} --output {output}`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub merger: Option<CommandConfig>,
}

/// The local pimdir store an account syncs through, the cache a frontend
/// reads. Implicit per account; this table only customises it.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct StoreConfig {
    /// The store directory, holding `pimdir.db` and `objects/`.
    ///
    /// Defaults to a per-account directory under the platform's state
    /// location: XDG on Linux and the BSDs, Application Support on macOS,
    /// `%LOCALAPPDATA%` on Windows.
    #[serde(default, deserialize_with = "shell_expanded_path_opt")]
    pub root: Option<PathBuf>,
    /// How long a retained item survives: `store.purge-after = "90d"`.
    ///
    /// A pimdir store never truly deletes: the row is retained, hidden but
    /// keeping its body, and neverest is the sweeper. Unset means never
    /// purge and `"0"` purges at once; there is deliberately no boolean.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub purge_after: Option<HumanDuration>,
    /// Removed keys, kept so a configuration carrying one is refused by
    /// name. See [`StoreConfig::reject_removed_keys`].
    #[serde(default, skip_serializing)]
    retention: Option<RemovedKey>,
    #[serde(default, skip_serializing)]
    hydration: Option<RemovedKey>,
}

impl StoreConfig {
    /// Refuses `retention` and `hydration`, now the account's `retain`.
    ///
    /// A three-point scale described a store holding only the bodies that
    /// happened to cross, which nothing asked for; mapping either key onto
    /// `retain` would guess, so both are refused by name.
    fn reject_removed_keys(&self) -> Result<()> {
        if self.retention.is_some() || self.hydration.is_some() {
            bail!(
                "`store.retention` and `store.hydration` are gone: whether the store keeps \
                 bodies is the account's `retain`, which is true when the store is the \
                 destination and false when targets are named."
            );
        }

        Ok(())
    }

    /// The RFC 3339 cutoff at `now`: an older retained item is reclaimed.
    ///
    /// `None` when `purge-after` is unset, or so large no instant precedes
    /// it, which means the same. The format matches what the store stamps
    /// `retained_at` with, so the comparison is plain lexicographic.
    pub fn purge_cutoff(&self, now: DateTime<Utc>) -> Option<String> {
        let after = chrono::Duration::from_std(self.purge_after?.0).ok()?;
        let cutoff = now.checked_sub_signed(after)?;
        Some(cutoff.to_rfc3339_opts(SecondsFormat::Millis, true))
    }
}

/// A human-written duration (`"90d"`, `"12h"`, `"2w"`), or a bare `"0"`.
///
/// A day is 86400 seconds and a week 7 days: a retention delay is not
/// calendar arithmetic, so no time zone or DST rule enters into it, and
/// months and years are refused for having no fixed length.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HumanDuration(pub Duration);

impl HumanDuration {
    /// Parses `"<integer><unit>"`, or a bare `"0"`.
    fn parse(raw: &str) -> Result<Self, String> {
        let raw = raw.trim();
        if raw.is_empty() {
            return Err(String::from("empty duration"));
        }

        let digits = raw.trim_end_matches(|c: char| c.is_ascii_alphabetic());
        let unit = &raw[digits.len()..];
        let count: u64 = digits
            .parse()
            .map_err(|_| format!("{raw} is not a `<number><unit>` duration (e.g. `90d`)"))?;

        let seconds = match unit {
            "s" => 1,
            "m" => 60,
            "h" => 3600,
            "d" => 86400,
            "w" => 7 * 86400,
            "" if count == 0 => 1,
            "" => {
                return Err(format!(
                    "duration {raw} misses its unit (`s`, `m`, `h`, `d` or `w`)"
                ));
            }
            other => {
                return Err(format!(
                    "unknown duration unit {other} in {raw} (expected `s`, `m`, `h`, `d` or `w`)"
                ));
            }
        };

        let total = count
            .checked_mul(seconds)
            .ok_or_else(|| format!("duration {raw} overflows"))?;
        Ok(Self(Duration::from_secs(total)))
    }
}

impl fmt::Display for HumanDuration {
    /// Renders back the largest unit dividing the duration evenly, so a
    /// round-trip through the config document is stable.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let secs = self.0.as_secs();
        if secs == 0 {
            return f.write_str("0");
        }
        for (unit, size) in [("w", 7 * 86400), ("d", 86400), ("h", 3600), ("m", 60)] {
            if secs.is_multiple_of(size) {
                return write!(f, "{}{unit}", secs / size);
            }
        }
        write!(f, "{secs}s")
    }
}

impl<'de> Deserialize<'de> for HumanDuration {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let raw = String::deserialize(deserializer)?;
        HumanDuration::parse(&raw).map_err(serde::de::Error::custom)
    }
}

impl Serialize for HumanDuration {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

/// What an account does: which endpoints, which direction, whether bodies stay.
///
/// Declared, never derived: the mode is the arity of `sources` and
/// `targets` plus the two flags, so no behaviour depends on a coincidence
/// between two sources.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccountMode {
    /// The source names, sorted, so a report reads the same twice.
    pub sources: Vec<String>,
    /// The target names, sorted; empty means the store is the destination.
    pub targets: Vec<String>,
    /// Whether the `sources` side is authoritative.
    pub one_way: bool,
    /// Whether the store holds bodies, resolved from the destination when
    /// the configuration left it unset.
    pub retain: bool,
}

impl AccountMode {
    /// Whether the local store is the destination rather than a remote.
    pub fn is_local(&self) -> bool {
        self.targets.is_empty()
    }

    /// Whether a crossing may be streamed rather than staged in the store.
    ///
    /// An internal choice, not a mode: what the user declared is `retain`,
    /// which both answers honour. It needs both endpoints on a protocol that
    /// takes a body straight from the other, so IMAP to IMAP today.
    pub fn streams(&self, sources: &HashMap<String, SourceConfig>) -> bool {
        !self.retain
            && !self.is_local()
            && self
                .sources
                .iter()
                .chain(&self.targets)
                .all(|name| sources.get(name).is_some_and(SourceConfig::is_streamable))
    }
}

impl fmt::Display for AccountMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let sources = self.sources.join(", ");

        if self.is_local() {
            let verb = if self.one_way {
                "overwrite the local store, discarding local edits"
            } else {
                "sync both ways with the local store"
            };

            return write!(f, "{sources} {verb}");
        }

        let targets = self.targets.join(", ");
        let body = if self.retain {
            ", keeping a local copy"
        } else {
            ", keeping no local copy"
        };

        if self.one_way {
            write!(f, "{sources} overwrites {targets}{body}")
        } else {
            write!(f, "{sources} and {targets} sync both ways{body}")
        }
    }
}

/// `serde` helper: shell-expand an optional path.
///
/// TODO: replace with `pimalaya_config::toml::shell_expanded_path_opt`, the
/// optional twin of what the crate already ships. ortie hand-rolls the same
/// function, so the two copies exist only because the shared one does not.
fn shell_expanded_path_opt<'de, D>(deserializer: D) -> Result<Option<PathBuf>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw: Option<String> = Option::deserialize(deserializer)?;
    Ok(raw.map(|s| PathBuf::from(shellexpand::tilde(&s).into_owned())))
}

/// One source: the remote it talks to, plus the channel its sends leave by.
///
/// The channel belongs to the source and not the account, since sending
/// natively (Graph's `sendMail`) or needing a companion SMTP server is a
/// property of the provider. At most one source per account declares one.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SourceConfig {
    /// The one remote this source names.
    #[serde(flatten)]
    pub backend: SourceBackendConfig,
    /// The SMTP server this source's queued submit intents flush through.
    ///
    /// Only meaningful on a backend that cannot send by itself (IMAP), a
    /// Graph source using `sendMail` instead. Absent, and with no source
    /// sending natively, submit intents stay pending.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub smtp: Option<SmtpConfig>,
}

/// The remote backend behind a source; exactly one variant per source.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase", deny_unknown_fields)]
pub enum SourceBackendConfig {
    Imap(ImapConfig),
    Carddav(CarddavConfig),
    Caldav(CaldavConfig),
    Jmap(JmapConfig),
    Gmail(GmailConfig),
    Msgraph(MsgraphConfig),
}

impl SourceBackendConfig {
    /// The protocol table this backend is written under, which is also the
    /// id of the source the sugar builds from it.
    pub fn protocol(&self) -> &'static str {
        match self {
            Self::Imap(_) => "imap",
            Self::Carddav(_) => "carddav",
            Self::Caldav(_) => "caldav",
            Self::Jmap(_) => "jmap",
            Self::Gmail(_) => "gmail",
            Self::Msgraph(_) => "msgraph",
        }
    }
}

#[allow(dead_code)]
impl SourceConfig {
    /// Wraps a backend into a source with no send channel of its own.
    pub fn new(backend: SourceBackendConfig) -> Self {
        Self {
            backend,
            smtp: None,
        }
    }

    source_ref_accessor!(collection, CollectionSourceConfig);
    source_accessor!(flag, FlagSourcePermissions);
    source_accessor!(item, ItemSourcePermissions);
    source_accessor!(pool_size, Option<usize>);

    /// Whether this source carries the removed `collection.namespace` key.
    fn declares_namespace(&self) -> bool {
        self.collection().namespace.is_some()
    }

    /// Whether this source is the IMAP backend.
    pub fn is_imap(&self) -> bool {
        matches!(self.backend, SourceBackendConfig::Imap(_))
    }

    /// Whether this source talks HTTP, those sharing a smaller default pool.
    pub fn is_http(&self) -> bool {
        matches!(
            self.backend,
            SourceBackendConfig::Jmap(_)
                | SourceBackendConfig::Gmail(_)
                | SourceBackendConfig::Msgraph(_)
                | SourceBackendConfig::Carddav(_)
                | SourceBackendConfig::Caldav(_)
        )
    }

    /// Whether this source sends by itself: Graph's `sendMail` today.
    pub fn sends_natively(&self) -> bool {
        matches!(self.backend, SourceBackendConfig::Msgraph(_))
    }

    /// Whether this source can carry a send channel at all.
    ///
    /// A contacts or calendar source cannot: submission is a mail
    /// capability, so an `smtp` table there is an error, not a dead option.
    pub fn carries_mail(&self) -> bool {
        !matches!(
            self.backend,
            SourceBackendConfig::Carddav(_) | SourceBackendConfig::Caldav(_)
        )
    }

    /// Whether a body streams straight from this source to another rather
    /// than being staged on the way.
    ///
    /// Only an IMAP pairing can, so this gates [`AccountMode::streams`],
    /// an optimisation of the declared `retain` and never a mode of its own.
    pub fn is_streamable(&self) -> bool {
        self.is_imap()
    }

    /// Rejects a source whose declared options its backend cannot honour.
    pub fn validate(&self, name: &str) -> Result<()> {
        if self.smtp.is_some() && !self.carries_mail() {
            bail!(
                "The `sources.{name}.smtp` channel is a mail capability and this source syncs \
                 contacts; drop the table, or move it to the source that sends."
            );
        }

        Ok(())
    }

    /// Snapshots the per-source collection/flag/item permissions.
    pub fn permissions(&self) -> SourcePermissions {
        SourcePermissions {
            collection: self.collection().permissions(),
            flag: self.flag(),
            item: self.item(),
        }
    }
}

/// Per-source permission triple gating which sync hunks may materialize.
#[derive(Clone, Copy, Debug)]
pub struct SourcePermissions {
    /// What the source lets a run do to its collection set.
    pub collection: CollectionPermissions,
    /// Whether the source takes flag updates.
    pub flag: FlagSourcePermissions,
    /// What the source lets a run do to its items.
    pub item: ItemSourcePermissions,
}

/// Item-level sync options; none is settled yet.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ItemSyncConfig {}

/// Collection-name filter: include-list, exclude-list, or keep all.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum CollectionFilter {
    /// Every collection the source lists.
    #[default]
    All,
    /// Only the named collections.
    Include(Vec<String>),
    /// Every collection but the named ones.
    Exclude(Vec<String>),
}

/// A source's collection-level configuration: which collections it syncs,
/// and what it may do to the collection set.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct CollectionSourceConfig {
    /// Whether the sync may create a collection on this source.
    ///
    /// It and `delete` grant by default, unlike the `item` block, which must
    /// be declared in full: this table also carries `filter`, and demanding a
    /// permission pair from someone writing a filter would be a trap.
    #[serde(default = "default_true")]
    pub create: bool,
    /// Whether the sync may delete one on this source.
    #[serde(default = "default_true")]
    pub delete: bool,
    /// Removed key, kept so a configuration carrying it is refused by name.
    ///
    /// Which endpoints meet is now the account's arity, and which way is
    /// [`AccountConfig::one_way`].
    #[serde(default, skip_serializing)]
    namespace: Option<RemovedKey>,
    /// Collection-name filter for this source.
    ///
    /// Per source, because an account may hold several kinds and a mailbox
    /// include-list means nothing to a contacts source. Filters are
    /// therefore asymmetric: a collection may sync on one source only.
    #[serde(default, alias = "filters", skip_serializing_if = "is_default")]
    pub filter: CollectionFilter,
}

impl CollectionSourceConfig {
    /// The copyable permission pair, the only part the sync seam gates on.
    pub fn permissions(&self) -> CollectionPermissions {
        CollectionPermissions {
            create: self.create,
            delete: self.delete,
        }
    }
}

impl Default for CollectionSourceConfig {
    fn default() -> Self {
        Self {
            create: true,
            delete: true,
            namespace: None,
            filter: CollectionFilter::default(),
        }
    }
}

/// Per-source collection permissions gating collection-set mutations.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CollectionPermissions {
    /// Whether a run may create a collection here.
    pub create: bool,
    /// Whether a run may delete one.
    pub delete: bool,
}

impl Default for CollectionPermissions {
    fn default() -> Self {
        Self {
            create: true,
            delete: true,
        }
    }
}

/// Per-source flag permissions, gating flag propagation.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct FlagSourcePermissions {
    /// Whether a run may push a flag change here.
    pub update: bool,
}

impl Default for FlagSourcePermissions {
    fn default() -> Self {
        Self { update: true }
    }
}

/// Per-source item permissions gating item mutations.
///
/// `create` and `delete` are required once the block is declared at all;
/// `update` defaults to true, added later so an older configuration keeps
/// parsing. It bites on mutable content alone, mail bodies being immutable.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ItemSourcePermissions {
    /// Whether a run may create an item here.
    pub create: bool,
    /// Whether a run may delete one.
    pub delete: bool,
    /// Whether a run may replace an item's body here.
    #[serde(default = "default_true")]
    pub update: bool,
}

impl Default for ItemSourcePermissions {
    fn default() -> Self {
        Self {
            create: true,
            delete: true,
            update: true,
        }
    }
}

/// `serde` default for a permission that grants by default.
fn default_true() -> bool {
    true
}

source_config! {
    /// An IMAP source (RFC 9051), each mailbox a collection.
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(rename_all = "kebab-case", deny_unknown_fields)]
    pub struct ImapConfig {
        /// The server, a bare authority or a full URL.
        pub server: String,
        /// How the connection is secured.
        #[serde(default)]
        pub tls: TlsConfig,
        /// Whether a plain connection is upgraded with STARTTLS.
        #[serde(default, skip_serializing_if = "is_default")]
        pub starttls: bool,
        /// ALPN identifiers offered during the TLS handshake.
        ///
        /// Unset takes io-imap's own default (`["imap"]`), which owns it;
        /// `[]` skips ALPN.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub alpn: Option<Vec<String>>,
        /// The one SASL mechanism the session authenticates with.
        pub sasl: Option<SaslConfig>,
    }
}

source_config! {
    /// A CardDAV source (RFC 6352), each address book a collection.
    ///
    /// The server URL is the entry point only: the principal and the
    /// address book home set are discovered from it.
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(rename_all = "kebab-case", deny_unknown_fields)]
    pub struct CarddavConfig {
        /// The DAV entry point.
        ///
        /// A bare authority (`dav.example.org[:port]`, read as
        /// `https://<authority>`) or a full URL, `http://` included for a
        /// server on a trusted network.
        pub server: String,
        /// How the connection is secured.
        #[serde(default)]
        pub tls: TlsConfig,
        /// ALPN identifiers offered during the TLS handshake, `["http/1.1"]`
        /// by default; `[]` skips ALPN.
        #[serde(
            default = "default_http_alpn",
            skip_serializing_if = "is_default_http_alpn"
        )]
        /// ALPN identifiers offered during the TLS handshake.
        pub alpn: Vec<String>,
        /// How the DAV session authenticates.
        pub auth: DavAuthConfig,
    }
}

source_config! {
    /// A CalDAV source (RFC 4791), each calendar a collection.
    ///
    /// The server URL is the entry point only: the principal and the
    /// calendar home set are discovered from it.
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(rename_all = "kebab-case", deny_unknown_fields)]
    pub struct CaldavConfig {
        /// The DAV entry point.
        ///
        /// A bare authority (`dav.example.org[:port]`, read as
        /// `https://<authority>`) or a full URL, `http://` included for a
        /// server on a trusted network.
        pub server: String,
        /// How the connection is secured.
        #[serde(default)]
        pub tls: TlsConfig,
        /// ALPN identifiers offered during the TLS handshake, `["http/1.1"]`
        /// by default; `[]` skips ALPN.
        #[serde(
            default = "default_http_alpn",
            skip_serializing_if = "is_default_http_alpn"
        )]
        /// ALPN identifiers offered during the TLS handshake.
        pub alpn: Vec<String>,
        /// How the DAV session authenticates.
        pub auth: DavAuthConfig,
    }
}

/// DAV authentication: HTTP Basic, or a bearer token for a provider
/// fronting DAV with OAuth 2.0.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum DavAuthConfig {
    /// A username and a password, HTTP Basic.
    Basic {
        #[serde(deserialize_with = "shell_expanded_string")]
        username: String,
        password: Secret,
    },
    /// A bearer token the client formats itself.
    Bearer { token: Secret },
}

#[cfg(feature = "dav")]
impl DavAuthConfig {
    /// Resolves the configured secret and converts to io-webdav's auth.
    ///
    /// The resolver keeps an account's CardDAV and CalDAV sides, which
    /// usually name one password entry, from unlocking it twice. It runs
    /// where the account is built ([`crate::account`]), never per connection.
    pub fn try_into_dav_auth(
        self,
        resolver: &mut SecretResolver,
    ) -> Result<io_webdav::rfc4918::WebdavAuth> {
        use io_http::{rfc6750::bearer::HttpAuthBearer, rfc7617::basic::HttpAuthBasic};
        use io_webdav::rfc4918::WebdavAuth;
        use secrecy::ExposeSecret;

        Ok(match self {
            Self::Basic { username, password } => WebdavAuth::Basic(HttpAuthBasic::new(
                username,
                resolver.resolve(password)?.expose_secret(),
            )),
            Self::Bearer { token } => WebdavAuth::Bearer(HttpAuthBearer::new(
                resolver.resolve(token)?.expose_secret(),
            )),
        })
    }
}

source_config! {
    /// A JMAP source (RFC 8620), each mailbox a collection.
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(rename_all = "kebab-case", deny_unknown_fields)]
    pub struct JmapConfig {
        /// The server, a bare authority or a full URL.
        pub server: String,
        /// How the connection is secured.
        #[serde(default)]
        pub tls: TlsConfig,
        /// ALPN identifiers offered during the TLS handshake, `["http/1.1"]`
        /// by default; `[]` skips ALPN.
        #[serde(
            default = "default_http_alpn",
            skip_serializing_if = "is_default_http_alpn"
        )]
        /// ALPN identifiers offered during the TLS handshake.
        pub alpn: Vec<String>,
        /// How the JMAP session authenticates.
        pub auth: JmapAuthConfig,
        /// The JMAP identity a submission is sent under.
        pub identity_id: Option<String>,
        /// The mailbox a submitted draft is written to.
        pub drafts_mailbox_id: Option<String>,
    }
}

/// How a JMAP session authenticates.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum JmapAuthConfig {
    /// A verbatim `Authorization` header value.
    Header(Secret),
    /// A bearer token the client formats itself.
    Bearer { token: Secret },
    /// A username and a password, HTTP Basic.
    Basic {
        #[serde(deserialize_with = "shell_expanded_string")]
        username: String,
        password: Secret,
    },
}

source_config! {
    /// A Gmail REST API source, its labels exposed as mailboxes.
    ///
    /// The API host is fixed, so only the mailbox owner, TLS and the
    /// OAuth 2.0 credential are configurable.
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(rename_all = "kebab-case", deny_unknown_fields)]
    pub struct GmailConfig {
        /// Gmail user id, `me` by default: the authenticated user.
        #[serde(default = "default_gmail_user_id")]
        pub user_id: String,
        /// How the connection is secured.
        #[serde(default)]
        pub tls: TlsConfig,
        /// ALPN identifiers offered during the TLS handshake, `["http/1.1"]`
        /// by default; `[]` skips ALPN.
        #[serde(
            default = "default_http_alpn",
            skip_serializing_if = "is_default_http_alpn"
        )]
        /// ALPN identifiers offered during the TLS handshake.
        pub alpn: Vec<String>,
        /// How the Gmail session authenticates.
        pub auth: GmailAuthConfig,
    }
}

/// Gmail authentication: OAuth 2.0 bearer tokens only.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct GmailAuthConfig {
    /// OAuth 2.0 bearer token, the `Bearer ` prefix added by the client.
    ///
    /// Refreshing it is the caller's responsibility.
    pub token: Secret,
}

source_config! {
    /// A Microsoft Graph source, its mail folders exposed as mailboxes.
    ///
    /// The API host is fixed, so only the mailbox owner, TLS and the
    /// OAuth 2.0 credential are configurable.
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[serde(rename_all = "kebab-case", deny_unknown_fields)]
    pub struct MsgraphConfig {
        /// Graph user id, `me` by default: the authenticated user.
        #[serde(default = "default_msgraph_user_id")]
        pub user_id: String,
        /// How the connection is secured.
        #[serde(default)]
        pub tls: TlsConfig,
        /// ALPN identifiers offered during the TLS handshake, `["http/1.1"]`
        /// by default; `[]` skips ALPN.
        #[serde(
            default = "default_http_alpn",
            skip_serializing_if = "is_default_http_alpn"
        )]
        /// ALPN identifiers offered during the TLS handshake.
        pub alpn: Vec<String>,
        /// How the Graph session authenticates.
        pub auth: MsgraphAuthConfig,
    }
}

/// Microsoft Graph authentication: OAuth 2.0 bearer tokens only, neverest
/// never running an OAuth flow itself.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct MsgraphAuthConfig {
    /// OAuth 2.0 bearer token, the `Bearer ` prefix added by the client.
    ///
    /// Acquiring and refreshing it is the caller's job: point
    /// `token.command` at any command printing a valid token, ortie say.
    pub token: Secret,
}

/// The SMTP server a source's queued sends flush through.
///
/// The shape mirrors [`ImapConfig`] field for field, submission being the
/// other half of the same mail account: a bare authority or a URL, the same
/// TLS block, and a `sasl` table naming one mechanism.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SmtpConfig {
    /// The submission server.
    ///
    /// A bare authority (`smtp.example.org[:port]`, read as
    /// `smtps://<authority>`), a cleartext `smtp://` URL, usually with
    /// `starttls`, or an `smtps://` URL for implicit TLS.
    pub server: String,
    /// How the connection is secured.
    #[serde(default)]
    pub tls: TlsConfig,
    /// Upgrades a plain `smtp://` connection via STARTTLS.
    #[serde(default, skip_serializing_if = "is_default")]
    pub starttls: bool,
    /// ALPN identifiers offered during the TLS handshake.
    ///
    /// Unset takes io-smtp's own default (`["smtp"]`, the token RFC 7595
    /// registers), which owns it; `[]` skips ALPN.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alpn: Option<Vec<String>>,
    /// The mechanism the session authenticates with, one [`SaslConfig`].
    ///
    /// Omit it for an unauthenticated relay, which stops after `EHLO` and
    /// sends no `AUTH` at all.
    pub sasl: Option<SaslConfig>,
}

/// Resolves a `server` into a URL, `scheme` filling in for a value with none.
///
/// The presence of `://` tells them apart, and it has to: a bare authority
/// is not a relative URL, `url` reading `dav.example.org:8443` as a scheme
/// with a path, which parses cleanly and carries no host.
#[cfg_attr(
    not(any(feature = "imap", feature = "smtp", feature = "dav")),
    allow(dead_code)
)]
pub fn server_url(server: &str, scheme: &str) -> Result<Url> {
    let url = if server.contains("://") {
        Url::parse(server)
    } else {
        Url::parse(&format!("{scheme}://{server}"))
    };

    url.with_context(|| format!("Cannot parse {server} as a server URL"))
}

fn default_gmail_user_id() -> String {
    String::from("me")
}

fn default_msgraph_user_id() -> String {
    String::from("me")
}

/// Default ALPN list for the HTTP backends: their APIs ride on HTTP/1.1.
fn default_http_alpn() -> Vec<String> {
    vec![String::from("http/1.1")]
}

/// How a connection is secured, shared by every backend.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct TlsConfig {
    /// Which TLS provider to use, the build's own default when unset.
    pub provider: Option<TlsProviderConfig>,
    /// Options the rustls provider reads.
    #[serde(default)]
    pub rustls: RustlsConfig,
    /// Path to an extra CA certificate to trust, shell-expanded.
    #[serde(default, deserialize_with = "shell_expanded_path_opt")]
    pub cert: Option<PathBuf>,
}

/// Which TLS implementation carries the connection.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum TlsProviderConfig {
    /// The rustls provider.
    Rustls,
    /// The platform's own TLS stack.
    NativeTls,
}

/// Options the rustls provider reads.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct RustlsConfig {
    /// Which crypto backend rustls uses, its default when unset.
    pub crypto: Option<RustlsCryptoConfig>,
}

/// Which crypto backend rustls uses.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum RustlsCryptoConfig {
    /// The aws-lc-rs backend.
    Aws,
    /// The ring backend.
    Ring,
}

#[cfg_attr(
    not(any(feature = "imap", feature = "msgraph", feature = "smtp")),
    allow(dead_code)
)]
impl TlsConfig {
    /// Builds the runtime [`Tls`] handle the connect helpers expect.
    ///
    /// `alpn` is the protocol-level list, empty to skip ALPN. The schema
    /// never exposes `tls.rustls.alpn`: the per-protocol `*.alpn` field is
    /// folded in here.
    pub fn into_tls(self, alpn: Vec<String>) -> Tls {
        Tls {
            provider: self.provider.map(|p| match p {
                TlsProviderConfig::Rustls => TlsProvider::Rustls,
                TlsProviderConfig::NativeTls => TlsProvider::NativeTls,
            }),
            rustls: Rustls {
                crypto: self.rustls.crypto.map(|c| match c {
                    RustlsCryptoConfig::Aws => RustlsCrypto::Aws,
                    RustlsCryptoConfig::Ring => RustlsCrypto::Ring,
                }),
                alpn,
            },
            cert: self.cert,
        }
    }
}

/// The one SASL mechanism a session authenticates with.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum SaslConfig {
    /// Authenticates nobody, for a relay taking anonymous mail.
    Anonymous(SaslAnonymousConfig),
    /// The legacy LOGIN exchange.
    Login(SaslLoginConfig),
    /// A username and a password in one message.
    Plain(SaslPlainConfig),
    /// A bearer token in the GS2 header.
    Oauthbearer(SaslOauthbearerConfig),
    /// A bearer token in the vendors' own spelling.
    Xoauth2(SaslXoauth2Config),
    /// A salted challenge, so the password never crosses.
    #[serde(rename = "scram-sha-256")]
    ScramSha256(SaslScramSha256Config),
}

/// The ANONYMOUS mechanism (RFC 4505), which authenticates nobody.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SaslAnonymousConfig {
    /// The trace message the mechanism carries, if any.
    pub message: Option<String>,
}

/// The legacy LOGIN mechanism, a username and a password.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SaslLoginConfig {
    /// The identity the mechanism authenticates as.
    #[serde(deserialize_with = "shell_expanded_string")]
    pub username: String,
    /// The password, resolved once per run.
    pub password: Secret,
}

/// The PLAIN mechanism (RFC 4616).
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SaslPlainConfig {
    /// The authorization identity, where it differs from the
    /// authentication one.
    pub authzid: Option<String>,
    /// The authentication identity.
    #[serde(deserialize_with = "shell_expanded_string")]
    #[serde(alias = "username")]
    pub authcid: String,
    /// The password, resolved once per run.
    #[serde(alias = "password")]
    pub passwd: Secret,
}

/// The OAUTHBEARER mechanism (RFC 7628).
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SaslOauthbearerConfig {
    /// The identity the mechanism authenticates as.
    #[serde(deserialize_with = "shell_expanded_string")]
    pub username: String,
    /// The access token, resolved once per run.
    pub token: Secret,
}

/// The XOAUTH2 mechanism, Google and Microsoft's predecessor to OAUTHBEARER.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SaslXoauth2Config {
    /// The identity the mechanism authenticates as.
    #[serde(deserialize_with = "shell_expanded_string")]
    pub username: String,
    /// The access token, resolved once per run.
    pub token: Secret,
}

/// The SCRAM-SHA-256 mechanism (RFC 7677), which sends no password.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct SaslScramSha256Config {
    /// The identity the mechanism authenticates as.
    #[serde(deserialize_with = "shell_expanded_string")]
    pub username: String,
    /// The password, resolved once per run.
    pub password: Secret,
}

#[cfg_attr(not(any(feature = "imap", feature = "smtp")), allow(dead_code))]
impl SaslConfig {
    /// Resolves the SASL config into a runtime [`Sasl`].
    ///
    /// `host` and `port` come from the live server URL and only OAUTHBEARER
    /// uses them, in the GS2 header. The resolver keeps an account's IMAP
    /// and SMTP tables, which usually name one entry, from unlocking twice.
    pub fn try_into_sasl(
        self,
        host: impl ToString,
        port: u16,
        resolver: &mut SecretResolver,
    ) -> Result<Sasl> {
        Ok(match self {
            SaslConfig::Anonymous(c) => Sasl::Anonymous(SaslAnonymousCreds { message: c.message }),
            SaslConfig::Login(c) => Sasl::Login(SaslLoginCreds {
                username: c.username,
                password: resolver.resolve(c.password)?,
            }),
            SaslConfig::Plain(c) => Sasl::Plain(SaslPlainCreds {
                authzid: c.authzid,
                authcid: c.authcid,
                passwd: resolver.resolve(c.passwd)?,
            }),
            SaslConfig::Oauthbearer(c) => Sasl::Oauthbearer(SaslOauthbearerCreds {
                username: c.username,
                host: host.to_string(),
                port,
                token: resolver.resolve(c.token)?,
            }),
            SaslConfig::Xoauth2(c) => Sasl::Xoauth2(SaslXoauth2Creds {
                username: c.username,
                token: resolver.resolve(c.token)?,
            }),
            SaslConfig::ScramSha256(c) => Sasl::ScramSha256(SaslScramCreds {
                username: c.username,
                password: resolver.resolve(c.password)?,
                nonce: Vec::new(),
                channel_binding: SaslGs2ChannelBinding::Unsupported,
            }),
        })
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use super::*;

    #[test]
    fn a_generated_config_renders_as_dotted_keys_under_one_header() {
        let account: AccountConfig = toml::from_str(
            r#"
            default = true
            msgraph.user-id = "me"
            msgraph.auth.token.command = ["ortie", "token", "show", "-a", "msgraph"]
            "#,
        )
        .unwrap();

        let config = Config {
            accounts: HashMap::from([(String::from("outlook"), account)]),
        };

        assert_eq!(
            config_toml::to_string(&config).unwrap(),
            r#"[accounts.outlook]
default = true
msgraph.auth.token.command = ["ortie", "token", "show", "-a", "msgraph"]
msgraph.user-id = "me"
"#
        );
    }

    #[test]
    fn msgraph_auth_is_bearer_token_only() {
        let config: MsgraphConfig = toml::from_str(
            r#"
            auth.token.raw = "tok"
            "#,
        )
        .unwrap();
        assert_eq!(config.user_id, "me");

        let config: MsgraphConfig = toml::from_str(
            r#"
            user-id = "user@example.org"
            auth.token.command = ["ortie", "-a", "msgraph", "token", "show", "--auto-refresh"]
            "#,
        )
        .unwrap();
        assert_eq!(config.user_id, "user@example.org");

        let err = toml::from_str::<MsgraphConfig>(
            r#"
            [auth.device-code]
            client-id = "id"
            "#,
        )
        .unwrap_err();
        assert!(err.to_string().contains("device-code"));
    }

    /// The store cannot tell the two spellings apart, so expanding an
    /// account by hand never orphans a binding.
    #[test]
    fn the_direct_backend_sugar_expands_to_the_same_source() {
        let sugar: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            imap.item.create = true
            imap.item.delete = false
            "#,
        )
        .unwrap();

        let explicit: AccountConfig = toml::from_str(
            r#"
            sources.imap.imap.server = "imaps://imap.example.org:993"
            sources.imap.imap.item.create = true
            sources.imap.imap.item.delete = false
            "#,
        )
        .unwrap();

        let sugar = sugar.sources().unwrap();
        let explicit = explicit.sources().unwrap();

        assert_eq!(sugar.keys().collect::<Vec<_>>(), vec!["imap"]);
        assert_eq!(explicit.keys().collect::<Vec<_>>(), vec!["imap"]);
        assert!(!sugar["imap"].permissions().item.delete);
        assert!(!explicit["imap"].permissions().item.delete);
    }

    #[test]
    fn a_protocol_declared_both_ways_is_refused() {
        let account: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            sources.imap.imap.server = "imaps://other.example.org:993"
            "#,
        )
        .unwrap();

        let err = account.sources().unwrap_err().to_string();
        assert!(err.contains("declared both"), "got {err}");
    }

    #[test]
    fn several_sources_of_one_protocol_live_under_one_account() {
        let account: AccountConfig = toml::from_str(
            r#"
            sources.fastmail.imap.server = "imaps://imap.fastmail.com:993"
            sources.gmail.imap.server = "imaps://imap.gmail.com:993"
            sources.dav.carddav.server = "https://carddav.fastmail.com/"
            sources.dav.carddav.auth.basic.username = "user"
            sources.dav.carddav.auth.basic.password.raw = "pw"
            "#,
        )
        .unwrap();

        account.validate().unwrap();
        let sources = account.sources().unwrap();
        assert_eq!(sources.len(), 3);
    }

    /// Mail and contacts under one account is the case the whole change exists
    /// for: their kinds differ, so nothing forces them to agree.
    #[test]
    fn mail_and_contacts_sit_under_one_account() {
        let account: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.fastmail.com:993"
            carddav.server = "https://carddav.fastmail.com/"
            carddav.auth.basic.username = "user"
            carddav.auth.basic.password.raw = "pw"
            smtp.server = "smtps://smtp.fastmail.com:465"
            "#,
        )
        .unwrap();

        account.validate().unwrap();
        let sources = account.sources().unwrap();

        assert!(sources["imap"].is_imap());
        assert!(sources["imap"].smtp.is_some(), "the channel completes mail");
        assert!(!sources["carddav"].carries_mail());
        assert!(sources["carddav"].smtp.is_none());
    }

    /// The legal cells of the matrix, and what each resolves `retain` to.
    #[test]
    fn the_mode_is_the_arity_and_the_two_flags() {
        let local: AccountConfig = toml::from_str(
            r#"
            sources.fastmail.imap.server = "imaps://imap.fastmail.com:993"
            sources.gmail.imap.server = "imaps://imap.gmail.com:993"
            "#,
        )
        .unwrap();
        let mode = local.mode().unwrap();
        assert!(mode.is_local());
        assert!(!mode.one_way);
        assert!(mode.retain, "the store is the destination");

        let mirror: AccountConfig = toml::from_str(
            r#"
            sources.a.imap.server = "imaps://a.example.org:993"
            targets.b.imap.server = "imaps://b.example.org:993"
            "#,
        )
        .unwrap();
        let mode = mirror.mode().unwrap();
        assert!(!mode.is_local());
        assert!(!mode.one_way, "two-way remote to remote is the default");
        assert!(!mode.retain, "a named target asked to copy, not to store");

        let copy: AccountConfig = toml::from_str(
            r#"
            one-way = true
            retain = true
            sources.a.imap.server = "imaps://a.example.org:993"
            targets.b.imap.server = "imaps://b.example.org:993"
            targets.c.imap.server = "imaps://c.example.org:993"
            "#,
        )
        .unwrap();
        let mode = copy.mode().unwrap();
        assert_eq!(mode.targets, vec!["b", "c"]);
        assert!(mode.one_way);
        assert!(mode.retain, "migrating while keeping a local copy");
    }

    /// Several targets have no resolution order without an authority, so the
    /// cell is refused rather than syncing them pairwise in map order.
    #[test]
    fn many_targets_without_one_way_are_refused() {
        let account: AccountConfig = toml::from_str(
            r#"
            sources.a.imap.server = "imaps://a.example.org:993"
            targets.b.imap.server = "imaps://b.example.org:993"
            targets.c.imap.server = "imaps://c.example.org:993"
            "#,
        )
        .unwrap();

        let err = account.mode().unwrap_err().to_string();
        assert!(err.contains("one-way = true"), "got {err}");
    }

    /// Several sources are the local case, so naming a target alongside them
    /// is a cell with no meaning rather than a fan-in.
    #[test]
    fn many_sources_with_a_target_are_refused() {
        let account: AccountConfig = toml::from_str(
            r#"
            sources.a.imap.server = "imaps://a.example.org:993"
            sources.b.imap.server = "imaps://b.example.org:993"
            targets.c.imap.server = "imaps://c.example.org:993"
            "#,
        )
        .unwrap();

        let err = account.mode().unwrap_err().to_string();
        assert!(err.contains("not a shape neverest syncs"), "got {err}");
    }

    /// With no target the store is the destination, so refusing to keep
    /// bodies would sync to nowhere.
    #[test]
    fn refusing_to_retain_with_no_target_is_refused() {
        let account: AccountConfig = toml::from_str(
            r#"
            retain = false
            imap.server = "imaps://imap.example.org:993"
            "#,
        )
        .unwrap();

        let err = account.mode().unwrap_err().to_string();
        assert!(err.contains("sync to nowhere"), "got {err}");
    }

    /// Streaming is an optimisation of `retain = false`, never a mode: it
    /// needs both endpoints on a protocol that can take a body from the other.
    #[test]
    fn only_an_imap_pairing_streams_a_crossing() {
        let imap: AccountConfig = toml::from_str(
            r#"
            one-way = true
            sources.a.imap.server = "imaps://a.example.org:993"
            targets.b.imap.server = "imaps://b.example.org:993"
            "#,
        )
        .unwrap();
        assert!(imap.mode().unwrap().streams(&imap.endpoints().unwrap()));

        let dav: AccountConfig = toml::from_str(
            r#"
            one-way = true
            sources.a.carddav.server = "https://a.example.org/"
            sources.a.carddav.auth.bearer.token.raw = "tok"
            targets.b.carddav.server = "https://b.example.org/"
            targets.b.carddav.auth.bearer.token.raw = "tok"
            "#,
        )
        .unwrap();
        assert!(
            !dav.mode().unwrap().streams(&dav.endpoints().unwrap()),
            "a DAV crossing is staged and released, which `retain` cannot tell apart",
        );
    }

    #[test]
    fn a_removed_key_is_refused_by_name_with_its_replacement() {
        let account: AccountConfig = toml::from_str(
            r#"
            left.imap.server = "imaps://imap.example.org:993"
            right.imap.server = "imaps://imap.other.org:993"
            "#,
        )
        .unwrap();
        let err = account.validate().unwrap_err().to_string();
        assert!(err.contains("`targets`"), "got {err}");
        assert!(err.contains("one-way"), "got {err}");

        let account: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            collection.filter.include = ["INBOX"]
            "#,
        )
        .unwrap();
        let err = account.validate().unwrap_err().to_string();
        assert!(err.contains("collection.filter"), "got {err}");

        let account: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            store.retention = "retain"
            "#,
        )
        .unwrap();
        let err = account.validate().unwrap_err().to_string();
        assert!(err.contains("the account's `retain`"), "got {err}");

        let account: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            store.hydration = "full"
            "#,
        )
        .unwrap();
        assert!(account.validate().is_err());
    }

    #[test]
    fn an_account_with_no_source_is_refused() {
        let account: AccountConfig = toml::from_str("default = true").unwrap();
        let err = account.validate().unwrap_err().to_string();
        assert!(err.contains("no source"), "got {err}");
    }

    #[test]
    fn one_source_at_most_carries_the_send_channel() {
        let account: AccountConfig = toml::from_str(
            r#"
            sources.a.imap.server = "imaps://a.example.org:993"
            sources.a.smtp.server = "smtps://a.example.org:465"
            sources.b.imap.server = "imaps://b.example.org:993"
            sources.b.smtp.server = "smtps://b.example.org:465"
            "#,
        )
        .unwrap();

        let err = account.validate().unwrap_err().to_string();
        assert!(err.contains("a, b"), "got {err}");

        let account: AccountConfig = toml::from_str(
            r#"
            sources.a.imap.server = "imaps://a.example.org:993"
            sources.a.smtp.server = "smtps://a.example.org:465"
            sources.b.imap.server = "imaps://b.example.org:993"
            "#,
        )
        .unwrap();
        account.validate().unwrap();
    }

    /// The flat `smtp` table completes the one direct mail backend. With none
    /// or several it names nothing, and guessing would be worse than refusing.
    #[test]
    fn the_flat_send_channel_needs_one_direct_mail_backend() {
        let account: AccountConfig = toml::from_str(
            r#"
            carddav.server = "https://dav.example.org/"
            carddav.auth.bearer.token.raw = "tok"
            smtp.server = "smtps://smtp.example.org:465"
            "#,
        )
        .unwrap();
        let err = account.validate().unwrap_err().to_string();
        assert!(err.contains("exactly one direct mail backend"), "got {err}");

        let account: AccountConfig = toml::from_str(
            r#"
            sources.a.imap.server = "imaps://a.example.org:993"
            smtp.server = "smtps://a.example.org:465"
            "#,
        )
        .unwrap();
        let err = account.validate().unwrap_err().to_string();
        assert!(err.contains("exactly one direct mail backend"), "got {err}");
    }

    /// The send channel spells its credentials as the sync side does, and
    /// omits the table for a relay that takes no `AUTH`.
    #[test]
    fn the_send_channel_names_a_sasl_mechanism() {
        let account: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            smtp.server = "smtp.example.org"
            smtp.sasl.xoauth2.username = "user@example.org"
            smtp.sasl.xoauth2.token.command = ["ortie", "token", "read", "example"]
            "#,
        )
        .unwrap();

        let smtp = account.smtp.as_ref().expect("a declared channel");
        assert_eq!(smtp.server, "smtp.example.org");
        assert!(matches!(smtp.sasl, Some(SaslConfig::Xoauth2(_))));

        let relay: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            smtp.server = "smtp://127.0.0.1:2525"
            "#,
        )
        .unwrap();
        assert!(relay.smtp.expect("a declared channel").sasl.is_none());
    }

    /// Ignoring the retired flat spelling would open an unauthenticated
    /// session against a server that requires one, so it is refused.
    #[test]
    fn the_flat_login_and_password_spelling_is_refused() {
        let err = toml::from_str::<AccountConfig>(
            r#"
            imap.server = "imaps://imap.example.org:993"
            smtp.server = "smtps://smtp.example.org:465"
            smtp.login = "user@example.org"
            smtp.password.raw = "pw"
            "#,
        )
        .unwrap_err()
        .to_string();

        assert!(err.contains("login"), "got {err}");
    }

    /// A bare authority with a port used to reach a backend as a hostless
    /// URL, `url` reading `dav.example.org:8443` as a scheme and a path.
    #[test]
    fn a_server_resolves_from_an_authority_with_or_without_a_port() {
        for (server, scheme, host, port) in [
            (
                "dav.example.org:8443",
                "https",
                "dav.example.org",
                Some(8443),
            ),
            ("dav.example.org", "https", "dav.example.org", None),
            (
                "imap.example.org:143",
                "imaps",
                "imap.example.org",
                Some(143),
            ),
            ("smtp.example.org", "smtps", "smtp.example.org", None),
        ] {
            let url = server_url(server, scheme).unwrap();
            assert_eq!(url.scheme(), scheme, "{server}");
            assert_eq!(url.host_str(), Some(host), "{server}");
            assert_eq!(url.port(), port, "{server}");
        }
    }

    /// A value carrying a scheme is used verbatim, so an explicit
    /// cleartext or non-default port survives the resolution.
    #[test]
    fn a_server_carrying_a_scheme_is_left_alone() {
        let url = server_url("http://127.0.0.1:5232/dav/", "https").unwrap();
        assert_eq!(url.scheme(), "http");
        assert_eq!(url.port(), Some(5232));
        assert_eq!(url.path(), "/dav/");

        let url = server_url("imap://example.org:143", "imaps").unwrap();
        assert_eq!(url.scheme(), "imap");
    }

    #[test]
    fn the_pre_generic_pim_sync_spellings_still_load() {
        let account: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            imap.mailbox.create = false
            imap.mailbox.delete = false
            imap.message.create = true
            imap.message.delete = false
            "#,
        )
        .unwrap();

        let sources = account.sources().unwrap();
        let perms = sources["imap"].permissions();
        assert!(!perms.collection.create);
        assert!(!perms.collection.delete);
        assert!(perms.item.create);
        assert!(!perms.item.delete);
        assert!(perms.flag.update);
        assert!(perms.item.update);

        let account: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            imap.collection.create = false
            imap.collection.delete = false
            imap.collection.filter.include = ["INBOX"]
            imap.item.create = true
            imap.item.delete = false
            "#,
        )
        .unwrap();
        let sources = account.sources().unwrap();
        assert_eq!(
            sources["imap"].collection().filter,
            CollectionFilter::Include(vec![String::from("INBOX")])
        );
        let perms = sources["imap"].permissions();
        assert!(!perms.collection.create);
        assert!(!perms.collection.delete);
        assert!(perms.item.create);
        assert!(!perms.item.delete);
    }

    #[test]
    fn item_update_is_denied_only_when_asked_for() {
        let account: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            imap.item.create = true
            imap.item.delete = true
            imap.item.update = false
            "#,
        )
        .unwrap();
        let sources = account.sources().unwrap();
        let perms = sources["imap"].permissions();
        assert!(perms.item.create);
        assert!(perms.item.delete);
        assert!(!perms.item.update);

        let account: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            imap.item.create = true
            imap.item.delete = true
            "#,
        )
        .unwrap();
        let sources = account.sources().unwrap();
        assert!(sources["imap"].permissions().item.update);
    }

    /// Every path key expands once, at deserialize, so no call site can read
    /// a literal `./~/…` directory. A document re-serialized after that
    /// carries the expansion and reloads to the same value.
    #[test]
    fn a_tilde_path_is_expanded_at_deserialize() {
        let home = PathBuf::from(shellexpand::tilde("~").into_owned());

        let store: StoreConfig = toml::from_str(r#"root = "~/store""#).unwrap();
        assert_eq!(store.root, Some(home.join("store")));

        let tls: TlsConfig = toml::from_str(r#"cert = "~/ca.pem""#).unwrap();
        assert_eq!(tls.cert, Some(home.join("ca.pem")));

        let reloaded: TlsConfig = toml::from_str(&toml::to_string(&tls).unwrap()).unwrap();
        assert_eq!(reloaded.cert, tls.cert);

        // NOTE: an absent key never reaches the deserializer, so it stays
        // absent rather than expanding an empty path.
        let tls: TlsConfig = toml::from_str("").unwrap();
        assert_eq!(tls.cert, None);
    }

    #[test]
    fn the_documented_sample_still_loads() {
        let raw = fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/config.sample.toml"))
            .expect("read the sample");
        let config: Config = toml::from_str(&raw).expect("the sample must parse");

        let account = config.accounts.get("example").expect("the sample account");
        account.validate().expect("the sample must validate");
        assert!(account.sources().unwrap()["imap"].is_imap());
    }

    #[test]
    fn the_purge_delay_is_a_human_duration_and_drives_the_cutoff() {
        let now: DateTime<Utc> = "2026-08-07T12:00:00Z".parse().unwrap();

        let account: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            "#,
        )
        .unwrap();
        assert!(account.store.purge_after.is_none());
        assert!(account.store.purge_cutoff(now).is_none());

        let account: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            store.purge-after = "90d"
            "#,
        )
        .unwrap();
        assert_eq!(
            account.store.purge_cutoff(now).as_deref(),
            Some("2026-05-09T12:00:00.000Z")
        );

        let account: AccountConfig = toml::from_str(
            r#"
            imap.server = "imaps://imap.example.org:993"
            store.purge-after = "0"
            "#,
        )
        .unwrap();
        assert_eq!(
            account.store.purge_cutoff(now).as_deref(),
            Some("2026-08-07T12:00:00.000Z")
        );

        let err = toml::from_str::<AccountConfig>(
            r#"
            imap.server = "imaps://imap.example.org:993"
            store.purge-after = "90 days"
            "#,
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("90 days"), "{err}");
    }

    #[test]
    fn a_human_duration_round_trips_through_the_document() {
        for (raw, secs) in [
            ("0", 0),
            ("45s", 45),
            ("30m", 1800),
            ("12h", 43200),
            ("90d", 7776000),
            ("2w", 1209600),
        ] {
            let parsed = HumanDuration::parse(raw).expect(raw);
            assert_eq!(parsed.0.as_secs(), secs, "{raw}");
            assert_eq!(parsed.to_string(), raw, "{raw}");
        }

        assert_eq!(HumanDuration(Duration::from_secs(86400)).to_string(), "1d");
        assert_eq!(
            HumanDuration(Duration::from_secs(90061)).to_string(),
            "90061s"
        );

        assert!(HumanDuration::parse("").is_err());
        assert!(HumanDuration::parse("90").is_err());
        assert!(HumanDuration::parse("90y").is_err());
        assert!(HumanDuration::parse("d").is_err());
    }

    #[test]
    fn a_source_pairs_one_backend_with_its_send_channel() {
        let account: AccountConfig = toml::from_str(
            r#"
            msgraph.auth.token.raw = "tok"
            "#,
        )
        .unwrap();
        let sources = account.sources().unwrap();
        assert!(sources["msgraph"].sends_natively());
        assert!(sources["msgraph"].smtp.is_none());

        let err = toml::from_str::<AccountConfig>(
            r#"
            sources.a.imapp.server = "imaps://imap.example.org:993"
            "#,
        )
        .unwrap_err();
        assert!(
            err.to_string()
                .contains("no variant of enum SourceBackendConfig")
        );

        let account: AccountConfig = toml::from_str(
            r#"
            sources.a.imap.server = "imaps://imap.example.org:993"
            sources.a.msgraph.auth.token.raw = "tok"
            "#,
        )
        .unwrap();
        assert!(account.sources().unwrap()["a"].is_imap());
    }

    /// The DAV sources are the non-mail ones, so they are where the account
    /// shape stops being mail-shaped.
    #[cfg(feature = "dav")]
    #[test]
    fn a_dav_source_carries_no_send_channel() {
        let account: AccountConfig = toml::from_str(
            r#"
            carddav.server = "https://dav.example.org/"
            carddav.auth.basic.username = "user"
            carddav.auth.basic.password.raw = "pw"
            caldav.server = "https://dav.example.org/"
            caldav.auth.basic.username = "user"
            caldav.auth.basic.password.raw = "pw"
            "#,
        )
        .unwrap();

        let sources = account.sources().unwrap();
        for name in ["carddav", "caldav"] {
            assert!(!sources[name].carries_mail(), "{name} does not submit");
            assert!(!sources[name].sends_natively());
        }
        account.validate().unwrap();

        let account: AccountConfig = toml::from_str(
            r#"
            sources.dav.carddav.server = "https://dav.example.org/"
            sources.dav.carddav.auth.bearer.token.raw = "tok"
            sources.dav.smtp.server = "smtps://smtp.example.org:465"
            "#,
        )
        .unwrap();

        let err = account.validate().unwrap_err().to_string();
        assert!(err.contains("`sources.dav.smtp`"), "got {err}");
    }

    /// The removed key is refused by name on whichever endpoint carries it,
    /// rather than being ignored and leaving the account doing something else.
    #[test]
    fn a_declared_namespace_is_refused_by_name() {
        let account: AccountConfig = toml::from_str(
            r#"
            sources.a.imap.server = "imaps://a.example.org:993"
            sources.a.imap.collection.namespace = "mail"
            "#,
        )
        .unwrap();

        let err = account.validate().unwrap_err().to_string();
        assert!(err.contains("`collection.namespace` is gone"), "got {err}");
        assert!(err.contains("one-way"), "got {err}");
    }

    /// A name is the pimdir source id its bindings are recorded under, so one
    /// name cannot be two endpoints.
    #[test]
    fn a_name_used_twice_is_refused() {
        let account: AccountConfig = toml::from_str(
            r#"
            sources.a.imap.server = "imaps://a.example.org:993"
            targets.a.imap.server = "imaps://b.example.org:993"
            "#,
        )
        .unwrap();

        let err = account.validate().unwrap_err().to_string();
        assert!(err.contains("both a source and a target"), "got {err}");
    }
}