kanzo 0.4.3

Self-hosted kanban for humans and agents. One 5.0 MB binary, starts in 3 ms, zero setup.
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
use std::collections::{HashMap, HashSet};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail};
use axum::body::Bytes;
use axum::extract::{ConnectInfo, DefaultBodyLimit, Path, Query, Request, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::middleware::{self, Next};
use axum::response::{Html, IntoResponse, Response};
use axum::routing::{any, delete, get, patch, post};
use axum::{Extension, Json, Router};
use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;

use crate::home::Home;
use crate::push::Push;
use crate::share::{self, Change, Net};
use crate::store::{self, Error, ImagesOf, Store, TaskPatch};
use crate::{sync, update};

const INDEX: &str = include_str!("index.html");
const IMAGE_LIMIT: usize = 25 * 1024 * 1024;
const APP_JS: &str = include_str!("app.js");
const SW_JS: &str = include_str!("sw.js");
const ZH_CN_JS: &str = include_str!("zh-cn.js");
const LOGO: &[u8] = include_bytes!("logo.png");
const ICON: &[u8] = include_bytes!("icon.png");
const CHANGELOG: &str = include_str!("../CHANGELOG.md");
const MANIFEST: &str = r##"{"id":"/","name":"Kanzo","start_url":"/","display":"standalone","background_color":"#ffffff","icons":[{"src":"/icon.png","sizes":"192x192 512x512","type":"image/png"}]}"##;

/// Scripts only from this server, so even a bug in the Markdown renderer cannot run injected script.
/// The one inline script, which sets the theme before the first paint, runs by its hash.
const CSP: &str = "default-src 'none'; script-src 'self' 'sha256-qbmIwOLWfXjTJcvp/pTTPC8bx25itrEad7276b6Vh5A='; style-src 'self' 'unsafe-inline'; img-src 'self' data:; \
                   connect-src 'self'; manifest-src 'self'; worker-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";

pub async fn serve(home: Home, open: bool) -> Result<()> {
    let port = home.config.port;
    let guard = Arc::new(Guard::new(port, home.config.listen, Net::load(&home), home.config.hosts.clone()));
    let url = format!("http://localhost:{port}");
    let listener = match TcpListener::bind(SocketAddr::new(guard.address(), port)).await {
        Ok(l) => l,
        Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => {
            if share::is_kanzo(&format!("127.0.0.1:{port}")).await {
                println!("Kanzo is already running at {url}");
                if open {
                    open_board(&url, port);
                }
                return Ok(());
            }
            bail!("port {port} is used by another program; choose another with --port or in config.toml");
        }
        Err(e) => return Err(e).context(format!("cannot listen on {} port {port}", guard.address())),
    };
    #[cfg(windows)]
    exit_with_console();
    println!("Kanzo board at {url}, data in {}", home.dir.display());
    match guard.net() {
        Net::Private => {}
        Net::Joined(host) => println!("It also shows the board at {host}."),
        _ => {
            println!("{}", guard.status().message());
            println!("Anyone who can reach port {port} can read and change this board.");
        }
    }
    if home.config.mcp_http {
        println!("MCP over HTTP at {url}/mcp");
    }
    if open {
        // It waits to see if there's an app, which must not hold up the board.
        let url = url.clone();
        tokio::task::spawn_blocking(move || open_board(&url, port));
    }
    // Cancelling this also ends open MCP streams, which would otherwise hold up shutdown.
    let shutdown = CancellationToken::new();
    let push = Arc::new(Push::load(&home));
    tokio::spawn(crate::push::watch(push.clone(), home.clone(), shutdown.clone()));
    let app = router(home.clone(), guard.clone(), shutdown.clone(), push);
    let serve = |listener, stop: CancellationToken| {
        let app = app.clone().into_make_service_with_connect_info::<SocketAddr>();
        tokio::spawn(
            axum::serve(listener, app).with_graceful_shutdown(async move { stop.cancelled().await }).into_future(),
        )
    };
    let mut running = Vec::new();
    // `localhost` is ::1 before 127.0.0.1 on many Linux systems, and not every
    // client (busybox wget, older Node) falls back, so listen on ::1 as well.
    if let IpAddr::V4(ip) = home.config.listen
        && (ip.is_loopback() || ip.is_unspecified())
        && let Ok(v6) = TcpListener::bind(SocketAddr::new(Ipv6Addr::LOCALHOST.into(), port)).await
    {
        running.push(serve(v6, shutdown.clone()));
    }
    let stopper = shutdown.clone();
    tokio::spawn(async move {
        stop_signal().await;
        stopper.cancel();
    });
    #[cfg(unix)]
    tokio::spawn(restart_when_replaced());
    let mut listener = listener;
    loop {
        let rebind = shutdown.child_token();
        *guard.rebind.lock().unwrap() = rebind.clone();
        running.push(serve(listener, rebind.clone()));
        rebind.cancelled().await;
        if shutdown.is_cancelled() {
            break;
        }
        listener = match listen_again(guard.address(), port).await {
            Ok(l) => l,
            Err(e) => {
                eprintln!("kanzo: cannot listen on {}: {e}", guard.address());
                listen_again(home.config.listen, port).await?
            }
        };
    }
    for task in running {
        task.await??;
    }
    Ok(())
}

/// However Kanzo was updated, from Settings, `kanzo update` or a package manager, the board
/// restarts on the new program, keeping its port and data folder. Open pages then reload.
#[cfg(unix)]
async fn restart_when_replaced() {
    let Some(exe) = update::Exe::current() else { return };
    let mut tick = tokio::time::interval(Duration::from_secs(3));
    loop {
        tick.tick().await;
        if !exe.changed() {
            continue;
        }
        let check = exe.clone();
        let Ok(Some(new)) = tokio::task::spawn_blocking(move || check.replacement().map(|p| p.to_path_buf())).await
        else {
            continue;
        };
        println!("Kanzo was updated; restarting the board.");
        eprintln!("kanzo: updated, but cannot restart: {}", update::restart(&new));
        return;
    }
}

/// The old listener takes a moment to let go of the port.
async fn listen_again(ip: IpAddr, port: u16) -> std::io::Result<TcpListener> {
    for _ in 0..100 {
        match TcpListener::bind(SocketAddr::new(ip, port)).await {
            Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => tokio::time::sleep(Duration::from_millis(20)).await,
            bound => return bound,
        }
    }
    TcpListener::bind(SocketAddr::new(ip, port)).await
}

async fn stop_signal() {
    #[cfg(unix)]
    {
        use tokio::signal::unix::{SignalKind, signal};
        match signal(SignalKind::terminate()) {
            Ok(mut term) => tokio::select! {
                _ = tokio::signal::ctrl_c() => {}
                _ = term.recv() => {}
            },
            Err(_) => {
                let _ = tokio::signal::ctrl_c().await;
            }
        }
    }
    #[cfg(not(unix))]
    {
        let _ = tokio::signal::ctrl_c().await;
    }
}

fn router(home: Home, guard: Arc<Guard>, shutdown: CancellationToken, push: Arc<Push>) -> Router {
    // A joined board sends its agents to the shared one, while its page shows both boards.
    let mut agents = Router::new();
    if home.config.mcp_http {
        agents = agents
            .nest_service("/mcp", crate::mcp::http_service(home.clone(), shutdown.clone()))
            .route_layer(middleware::from_fn_with_state(guard.clone(), forward));
    }
    let board = Router::new()
        .route("/images/{file}", get(image_file))
        .route("/api/changes", get(changes))
        // Shutdown also answers waiting readers, which would otherwise hold it up.
        .route("/api/events", get(events).layer(Extension(shutdown)))
        .route("/api/board", get(board))
        .route("/api/search", get(search))
        .route("/api/projects", get(projects).post(create_project))
        .route("/api/projects/{slug}", patch(update_project).delete(delete_project))
        .route("/api/projects/{slug}/repos", post(link_repo).delete(unlink_repo))
        .route("/api/projects/{slug}/move", post(move_project))
        .route("/api/tasks", post(create_task))
        .route("/api/tasks/bulk", post(bulk_tasks))
        .route("/api/tasks/move", post(move_tasks))
        .route("/api/tasks/{id}", get(get_task).patch(update_task).delete(delete_task))
        .route("/api/tasks/{id}/move", post(move_task))
        .route("/api/tasks/{id}/comments", post(add_comment))
        .route("/api/comments/{id}", delete(delete_comment))
        .route("/api/images", post(save_image).layer(DefaultBodyLimit::max(IMAGE_LIMIT)))
        .route("/api/images/{id}", delete(delete_image))
        .route("/api/tasks/{id}/images", post(attach_image))
        .route("/api/sync", get(sync_status).post(sync_now).put(sync_repo))
        .route("/api/settings", patch(update_settings));
    // This computer's browsers, wherever its page shows: it pushes what the board it follows escalates.
    let notifications = Router::new()
        .route("/api/push", get(push_key).post(push_add).delete(push_remove))
        .route("/api/push/pending", post(push_pending))
        .route_layer(middleware::from_fn(no_guests))
        .layer(Extension(push));
    Router::new()
        .route("/", get(|| async { Html(INDEX) }))
        .route("/app.js", get(|| async { ([(header::CONTENT_TYPE, "text/javascript; charset=utf-8")], APP_JS) }))
        .route("/sw.js", get(|| async { ([(header::CONTENT_TYPE, "text/javascript; charset=utf-8")], SW_JS) }))
        .route(
            "/i18n/zh-cn.js",
            get(|| async { ([(header::CONTENT_TYPE, "text/javascript; charset=utf-8")], ZH_CN_JS) }),
        )
        .route("/logo.png", get(|| async { ([(header::CONTENT_TYPE, "image/png")], LOGO) }))
        .route("/icon.png", get(|| async { ([(header::CONTENT_TYPE, "image/png")], ICON) }))
        .route("/changelog.md", get(|| async { ([(header::CONTENT_TYPE, "text/markdown; charset=utf-8")], CHANGELOG) }))
        .route(
            "/manifest.webmanifest",
            get(|| async { ([(header::CONTENT_TYPE, "application/manifest+json")], MANIFEST) }),
        )
        .route("/api/ping", get(|| async { "kanzo" }))
        .route("/api/update", get(update_status).post(update_now))
        .route(
            "/api/network",
            get(network).post(change_network).route_layer(middleware::from_fn_with_state(guard.clone(), this_computer)),
        )
        // The files are on this computer, whichever board the task is on.
        .route("/api/open", post(open_file).route_layer(middleware::from_fn_with_state(guard.clone(), this_computer)))
        .route("/remote/{*path}", any(remote))
        .merge(board)
        .merge(notifications)
        .merge(agents)
        .layer(Extension(guard.clone()))
        .layer(middleware::from_fn_with_state(guard, protect))
        .layer(middleware::map_response(stamp_version))
        .with_state(Arc::new(home))
}

/// Pages compare it with the version they loaded with, and reload after an update. Set on
/// the way out, so a joined board's forwarded replies carry this computer's version, not the host's.
async fn stamp_version(mut res: Response) -> Response {
    res.headers_mut().insert("x-kanzo-version", HeaderValue::from_static(update::CURRENT));
    res
}

/// DNS rebinding needs a domain name the attacker controls, so the board only accepts
/// `localhost`, IP addresses, the names in `hosts` and, when it listens on the network, this machine's own names.
struct Guard {
    port: u16,
    listen: IpAddr,
    net: Mutex<Net>,
    guests: Mutex<HashMap<IpAddr, (Instant, Option<String>)>>,
    names: OnceLock<Vec<String>>,
    hosts: Vec<String>,
    rebind: Mutex<CancellationToken>,
}

/// A guest's board asks every 2 seconds while it's on screen.
const GUEST_GONE: Duration = Duration::from_secs(30);

impl Guard {
    fn new(port: u16, listen: IpAddr, net: Net, hosts: Vec<String>) -> Self {
        Self {
            port,
            listen,
            net: Mutex::new(net),
            guests: Mutex::default(),
            names: OnceLock::new(),
            hosts: hosts.into_iter().map(|h| h.trim_end_matches('.').to_string()).collect(),
            rebind: Mutex::default(),
        }
    }

    fn net(&self) -> Net {
        self.net.lock().unwrap().clone()
    }

    fn lan(&self) -> bool {
        self.net() == Net::Sharing
    }

    fn address(&self) -> IpAddr {
        if self.lan() && self.listen.is_loopback() { Ipv4Addr::UNSPECIFIED.into() } else { self.listen }
    }

    fn set(&self, net: Net) {
        let before = self.address();
        *self.net.lock().unwrap() = net;
        if self.address() != before {
            self.rebind.lock().unwrap().cancel();
        }
        if !self.lan() {
            self.guests.lock().unwrap().clear();
        }
    }

    fn guests(&self) -> Vec<share::Guest> {
        let mut guests = self.guests.lock().unwrap();
        guests.retain(|_, (seen, _)| seen.elapsed() < GUEST_GONE);
        let mut list: Vec<share::Guest> =
            guests.iter().map(|(ip, (_, name))| share::Guest { name: name.clone(), address: *ip }).collect();
        list.sort_by_key(|g| g.address);
        list
    }

    fn status(&self) -> share::Status {
        share::Status::new(&self.net(), self.port, self.guests())
    }

    fn names(&self) -> &[String] {
        self.names.get_or_init(|| {
            use std::process::Command;
            let run = |cmd: &mut Command| crate::home::output(cmd).ok().map(|n| n.to_ascii_lowercase());
            // macOS keeps its Bonjour name apart; `hostname` there can be a DHCP address.
            let found =
                [run(Command::new("scutil").args(["--get", "LocalHostName"])), run(&mut Command::new("hostname"))];
            let mut names = Vec::new();
            for full in found.into_iter().flatten().filter(|n| !n.is_empty() && n.parse::<IpAddr>().is_err()) {
                let short = full.split('.').next().unwrap_or_default().to_string();
                for name in [format!("{short}.local"), full, short] {
                    if !names.contains(&name) {
                        names.push(name);
                    }
                }
            }
            names
        })
    }

    /// A reverse proxy serves the board, so a request from 127.0.0.1 may come from anyone.
    fn proxied(&self) -> bool {
        !self.hosts.is_empty()
    }

    /// One of `hosts`, on any port: the proxy in front decides which.
    fn listed(&self, host: &str) -> bool {
        let name = split_host(host).0;
        !name.is_empty() && self.hosts.iter().any(|h| h.eq_ignore_ascii_case(name))
    }

    fn allows(&self, host: &str) -> bool {
        if self.listed(host) {
            return true;
        }
        let (name, port) = split_host(host);
        if port.is_some_and(|p| p.parse() != Ok(self.port)) {
            return false;
        }
        let ip = name.parse::<IpAddr>().ok();
        if name.eq_ignore_ascii_case("localhost") || ip.is_some_and(|ip| ip.is_loopback()) {
            return true;
        }
        self.lan() && (ip.is_some() || self.names().iter().any(|n| n.eq_ignore_ascii_case(name)))
    }
}

/// A `Host` header's name, without brackets or a trailing dot, and its port.
fn split_host(host: &str) -> (&str, Option<&str>) {
    let (name, port) = match host.rsplit_once(':') {
        Some((n, p)) if !p.contains(']') => (n, Some(p)),
        _ => (host, None),
    };
    (name.trim_start_matches('[').trim_end_matches(']').trim_end_matches('.'), port)
}

fn host(req: &Request) -> &str {
    req.headers().get(header::HOST).and_then(|h| h.to_str().ok()).unwrap_or("")
}

fn guest(req: &Request) -> Option<IpAddr> {
    req.extensions().get::<ConnectInfo<SocketAddr>>().map(|c| c.0.ip()).filter(|ip| !ip.is_loopback())
}

async fn forward(State(guard): State<Arc<Guard>>, req: Request, next: Next) -> Response {
    match guard.net() {
        Net::Joined(host) => share::forward(&host, req).await,
        _ => next.run(req).await,
    }
}

/// The shared board, for the page of a board that joined it: `/remote/api/board` is its `/api/board`.
async fn remote(Extension(guard): Extension<Arc<Guard>>, mut req: Request) -> Response {
    let Net::Joined(host) = guard.net() else {
        return fail(StatusCode::NOT_FOUND, "this board has not joined another").into_response();
    };
    let path = req.uri().path_and_query().map_or("/", |p| p.as_str());
    let path = path.strip_prefix("/remote").unwrap_or(path);
    match path.parse() {
        Ok(uri) => *req.uri_mut() = uri,
        Err(e) => return fail(StatusCode::BAD_REQUEST, e).into_response(),
    }
    share::forward(&host, req).await
}

/// A reverse proxy here connects from 127.0.0.1 for whoever reaches it, so a request for one
/// of `hosts` counts as from another computer too. So does one the proxy says it forwarded:
/// a proxy that passes on its visitor's `Host` would otherwise let `Host: localhost` through.
/// Push needs a secure page, which a guest on the network never has, over plain http: nobody
/// there can add browsers for this computer to push to, or read what they'd show.
async fn no_guests(req: Request, next: Next) -> Response {
    if guest(&req).is_some() {
        return fail(StatusCode::FORBIDDEN, "notifications are for this computer's browsers").into_response();
    }
    next.run(req).await
}

async fn this_computer(State(guard): State<Arc<Guard>>, req: Request, next: Next) -> Response {
    let forwarded = ["forwarded", "x-forwarded-for", "x-forwarded-host"].iter().any(|h| req.headers().contains_key(*h));
    if guest(&req).is_some() || guard.listed(host(&req)) || (guard.proxied() && forwarded) {
        return fail(StatusCode::FORBIDDEN, "only the computer with the board can do that").into_response();
    }
    next.run(req).await
}

async fn protect(State(guard): State<Arc<Guard>>, req: Request, next: Next) -> Response {
    let guest = guest(&req);
    let ok = {
        let host = host(&req);
        // Behind a proxy the browser may well be on https.
        let schemes: &[&str] = if guard.listed(host) { &["http://", "https://"] } else { &["http://"] };
        let same_origin = |o: &str| {
            schemes.iter().any(|s| {
                o.len() == s.len() + host.len()
                    && o.as_bytes()[..s.len()].eq_ignore_ascii_case(s.as_bytes())
                    && o.as_bytes()[s.len()..].eq_ignore_ascii_case(host.as_bytes())
            })
        };
        let origin = req.headers().get(header::ORIGIN).and_then(|h| h.to_str().ok());
        guard.allows(host) && origin.is_none_or(same_origin) && (guest.is_none() || guard.lan())
    };
    if let Some(ip) = guest.filter(|_| ok) {
        let name =
            req.headers().get(share::COMPUTER_HEADER).map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned());
        let mut guests = guard.guests.lock().unwrap();
        let guest = guests.entry(ip).or_insert((Instant::now(), None));
        guest.0 = Instant::now();
        if name.is_some() {
            guest.1 = name;
        }
    }
    let mut res = if ok {
        next.run(req).await
    } else {
        (StatusCode::FORBIDDEN, "kanzo does not answer requests from other sites").into_response()
    };
    let headers = res.headers_mut();
    headers.insert(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(CSP));
    headers.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
    headers.insert(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer"));
    headers.entry(header::CACHE_CONTROL).or_insert(HeaderValue::from_static("no-cache"));
    res
}

type Shared = State<Arc<Home>>;

async fn with_store<T: Serialize + Send + 'static>(
    home: Arc<Home>,
    f: impl FnOnce(&Home, &Store) -> store::Result<T> + Send + 'static,
) -> Response {
    reply(blocking(move || f(&home, &home.store()?)).await)
}

fn reply<T: Serialize>(result: Result<store::Result<T>, Fail>) -> Response {
    let error = match result {
        Ok(Ok(v)) => return Json(v).into_response(),
        Ok(Err(e)) => e,
        Err(e) => return e.into_response(),
    };
    let code = match error {
        Error::NotFound(_) => StatusCode::NOT_FOUND,
        Error::Invalid(_) => StatusCode::BAD_REQUEST,
        Error::Busy(_) => StatusCode::SERVICE_UNAVAILABLE,
        Error::Db(_) => StatusCode::INTERNAL_SERVER_ERROR,
    };
    fail(code, error).into_response()
}

type Reply = Result<Response, Fail>;

pub struct Fail(StatusCode, String);

pub fn fail(code: StatusCode, error: impl std::fmt::Display) -> Fail {
    Fail(code, error.to_string())
}

impl IntoResponse for Fail {
    fn into_response(self) -> Response {
        (self.0, Json(json!({ "error": self.1 }))).into_response()
    }
}

async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Result<T, Fail> {
    tokio::task::spawn_blocking(f).await.map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, e))
}

/// The database file's identity is part of it so a board pulled by `kanzo sync` always reloads.
fn change_token(home: &Home, s: &Store) -> store::Result<String> {
    Ok(format!("{}-{}", s.changes()?, home.db_identity()))
}

#[derive(Serialize)]
struct Changes {
    changes: String,
    guests: Option<usize>,
    /// The shared board this one joined, so its page shows it, or stops, from the next check.
    joined: Option<String>,
}

async fn changes(State(home): Shared, Extension(guard): Extension<Arc<Guard>>) -> Response {
    let guests = guard.lan().then(|| guard.guests().len());
    let joined = match guard.net() {
        Net::Joined(host) => Some(host),
        _ => None,
    };
    with_store(home, move |h, s| Ok(Changes { changes: change_token(h, s)?, guests, joined })).await
}

#[derive(Serialize)]
struct Projects {
    changes: String,
    projects: Vec<store::Project>,
}

/// The sidebar of a board that joined another lists both boards' projects, without their tasks.
async fn projects(State(home): Shared) -> Response {
    with_store(home, move |h, s| Ok(Projects { changes: change_token(h, s)?, projects: s.list_projects()? })).await
}

#[derive(Deserialize)]
struct EventsQuery {
    /// The `last` cursor of the previous reply. Without it, the reply only says where to start.
    since: Option<String>,
    project: Option<String>,
    /// Seconds to hold the request open until an event comes (long polling), at most 25.
    #[serde(default)]
    wait: u64,
}

const EVENTS_PER_REPLY: usize = 500;
const EVENTS_WAIT_MAX: u64 = 25;

fn read_events(s: &Store, q: &EventsQuery) -> store::Result<store::EventPage> {
    let project = match &q.project {
        Some(p) => Some(s.find_project(p)?.id),
        None => None,
    };
    s.events_after(q.since.as_deref(), project, EVENTS_PER_REPLY)
}

/// Lets a service react to the board as it changes, like starting an agent for a new task,
/// without polling the whole board: `GET /api/events?since=<last>&wait=25` in a loop.
async fn events(
    State(home): Shared,
    Extension(shutdown): Extension<CancellationToken>,
    Query(q): Query<EventsQuery>,
) -> Response {
    let q = Arc::new(q);
    let deadline = tokio::time::Instant::now() + Duration::from_secs(q.wait.min(EVENTS_WAIT_MAX));
    // The board is read again only once a write has changed it, which costs a waiting reader as
    // little as a visible board's poll: opening the board every half second cost four times that.
    let mut read = None;
    loop {
        let stamp = home.db_stamp();
        let last = q.since.is_none() || tokio::time::Instant::now() >= deadline || shutdown.is_cancelled();
        if last || read != Some(stamp) {
            read = Some(stamp);
            let (h, query) = (home.clone(), q.clone());
            let result = blocking(move || read_events(&h.store()?, &query)).await;
            let nothing_new = matches!(&result, Ok(Ok(e)) if e.events.is_empty() && !e.reset);
            if !nothing_new || last {
                return reply(result);
            }
        }
        // With nothing new, look again every half second until the wait is over.
        tokio::select! {
            _ = tokio::time::sleep(Duration::from_millis(500)) => {}
            _ = shutdown.cancelled() => {}
        }
    }
}

async fn push_key(Extension(push): Extension<Arc<Push>>) -> Response {
    reply(blocking(move || push.public_key().map(|key| json!({ "key": key }))).await)
}

async fn push_add(Extension(push): Extension<Arc<Push>>, Json(b): Json<crate::push::Browser>) -> Response {
    reply(blocking(move || push.add(b).map(|added| json!({ "renew": !added }))).await)
}

#[derive(Deserialize)]
struct Endpoint {
    endpoint: String,
}

async fn push_remove(Extension(push): Extension<Arc<Push>>, Json(e): Json<Endpoint>) -> Response {
    reply(blocking(move || push.remove(&e.endpoint).map(|()| json!({}))).await)
}

/// What a browser's service worker shows when a push wakes it: only what still waits for you,
/// so a task handled meanwhile, as while the browser was closed, stays quiet.
async fn push_pending(State(home): Shared, Extension(push): Extension<Arc<Push>>, Json(e): Json<Endpoint>) -> Response {
    let mut pending = push.take(&e.endpoint);
    if !pending.tasks.is_empty()
        && let Some(now) = crate::push::escalated_now(&home).await
    {
        pending.tasks.retain(|t| now.iter().any(|n| n.id == t.id && n.shared == t.shared));
    }
    Json(pending).into_response()
}

/// The done column only grows, and every change reloads the board.
const DONE_SHOWN: usize = 50;

#[derive(Deserialize)]
struct BoardQuery {
    project: Option<String>,
    done: Option<String>,
    #[serde(default)]
    q: String,
}

#[derive(Serialize)]
struct Board {
    changes: String,
    done_hidden: usize,
    events_kept: i64,
    hidden_properties: Vec<String>,
    projects: Vec<store::Project>,
    statuses: Vec<String>,
    tasks: Vec<store::Task>,
    version: &'static str,
}

async fn board(State(home): Shared, Query(q): Query<BoardQuery>) -> Response {
    with_store(home, move |h, s| {
        let project = match q.project.as_deref().filter(|p| !p.is_empty() && *p != "all") {
            Some(slug) => Some(s.find_project(slug)?),
            None => None,
        };
        let keep_done = (q.done.as_deref() != Some("all")).then_some(DONE_SHOWN);
        let (mut tasks, done_hidden) = s.list_tasks_keeping_done(project.map(|p| p.id), None, keep_done)?;
        if !q.q.trim().is_empty() {
            let found: HashSet<i64> = s.search(&q.q, None)?.into_iter().map(|t| t.id).collect();
            tasks.retain(|t| found.contains(&t.id));
        }
        Ok(Board {
            changes: change_token(h, s)?,
            done_hidden,
            events_kept: s.events_kept()?,
            hidden_properties: s.hidden_properties()?,
            projects: s.list_projects()?,
            statuses: s.statuses().to_vec(),
            tasks,
            version: update::CURRENT,
        })
    })
    .await
}

#[derive(Deserialize)]
struct SearchQuery {
    #[serde(default)]
    q: String,
}

async fn search(State(home): Shared, Query(q): Query<SearchQuery>) -> Response {
    with_store(home, move |_, s| s.search(&q.q, Some(30))).await
}

#[derive(Deserialize)]
struct NewProject {
    slug: String,
    #[serde(default)]
    name: String,
    repo: Option<String>,
}

async fn create_project(State(home): Shared, Json(p): Json<NewProject>) -> Response {
    with_store(home, move |_, s| s.create_project(&p.slug, &p.name, p.repo.as_deref())).await
}

#[derive(Deserialize)]
struct ProjectPatch {
    name: Option<String>,
    color: Option<String>,
}

async fn update_project(State(home): Shared, Path(slug): Path<String>, Json(p): Json<ProjectPatch>) -> Response {
    with_store(home, move |_, s| {
        let mut project = None;
        if let Some(name) = &p.name {
            project = Some(s.rename_project(&slug, name)?);
        }
        if let Some(color) = &p.color {
            project = Some(s.set_project_color(&slug, color)?);
        }
        project.map_or_else(|| s.find_project(&slug), Ok)
    })
    .await
}

#[derive(Deserialize)]
struct ProjectMove {
    before: Option<String>,
}

async fn move_project(State(home): Shared, Path(slug): Path<String>, Json(m): Json<ProjectMove>) -> Response {
    with_store(home, move |_, s| s.move_project(&slug, m.before.as_deref())).await
}

#[derive(Deserialize)]
struct RepoLink {
    repo: String,
}

async fn link_repo(State(home): Shared, Path(slug): Path<String>, Json(r): Json<RepoLink>) -> Response {
    with_store(home, move |_, s| s.link_repo(&slug, &r.repo)).await
}

async fn unlink_repo(State(home): Shared, Path(slug): Path<String>, Json(r): Json<RepoLink>) -> Response {
    with_store(home, move |_, s| s.unlink_repo(&slug, &r.repo)).await
}

async fn delete_project(State(home): Shared, Path(slug): Path<String>) -> Response {
    with_store(home, move |h, s| {
        let project = s.find_project(&slug)?;
        h.deleting_images(s, ImagesOf::Project(project.id), || s.delete_project(&slug))
    })
    .await
}

#[derive(Deserialize)]
struct NewTask {
    project: String,
    title: String,
    description: Option<String>,
}

async fn create_task(State(home): Shared, Json(t): Json<NewTask>) -> Response {
    with_store(home, move |_, s| {
        let project = s.find_project(&t.project)?;
        s.create_task_in(project.id, &t.title, TaskPatch { description: t.description, ..Default::default() })
    })
    .await
}

#[derive(Deserialize)]
#[serde(untagged)]
enum Settings {
    Backlog { backlog: bool },
    Property { property: String, visible: bool },
    EventsKept { events_kept: i64 },
}

async fn update_settings(State(home): Shared, Json(r): Json<Settings>) -> Response {
    with_store(home, move |_, s| match r {
        Settings::Backlog { backlog } => s.set_backlog(backlog),
        Settings::Property { property, visible } => s.set_property(&property, visible),
        Settings::EventsKept { events_kept } => s.set_events_kept(events_kept),
    })
    .await
}

#[derive(Serialize)]
struct TaskReply {
    blocks: Vec<store::TaskLink>,
    comments: Vec<store::Comment>,
    images: Vec<store::Image>,
    task: store::Task,
    waits_on: Vec<store::TaskLink>,
}

async fn get_task(State(home): Shared, Path(id): Path<i64>) -> Response {
    with_store(home, move |_, s| {
        Ok(TaskReply {
            blocks: s.task_links(id, true)?,
            comments: s.list_comments(id)?,
            images: s.list_images(id)?,
            task: s.get_task(id)?,
            waits_on: s.task_links(id, false)?,
        })
    })
    .await
}

#[derive(Deserialize)]
struct Patch {
    title: Option<String>,
    description: Option<String>,
    status: Option<String>,
    project: Option<String>,
    tags: Option<String>,
    human: Option<bool>,
    priority: Option<String>,
    url: Option<String>,
    waits_on: Option<String>,
}

async fn update_task(State(home): Shared, Path(id): Path<i64>, Json(p): Json<Patch>) -> Response {
    with_store(home, move |_, s| {
        let project_id = p.project.map(|slug| s.find_project(&slug)).transpose()?.map(|p| p.id);
        s.update_task(
            id,
            TaskPatch {
                title: p.title,
                description: p.description,
                status: p.status,
                project_id,
                tags: p.tags,
                human: p.human,
                priority: p.priority,
                url: p.url,
                waits_on: p.waits_on,
                escalated: None,
            },
        )
    })
    .await
}

#[derive(Deserialize)]
struct Move {
    status: String,
    before: Option<i64>,
}

async fn move_task(State(home): Shared, Path(id): Path<i64>, Json(m): Json<Move>) -> Response {
    with_store(home, move |_, s| s.move_task(id, &m.status, m.before)).await
}

#[derive(Deserialize)]
struct MoveMany {
    ids: Vec<i64>,
    status: String,
    before: Option<i64>,
}

async fn move_tasks(State(home): Shared, Json(m): Json<MoveMany>) -> Response {
    with_store(home, move |_, s| s.move_tasks(&m.ids, &m.status, m.before)).await
}

async fn delete_task(State(home): Shared, Path(id): Path<i64>) -> Response {
    with_store(home, move |h, s| h.deleting_images(s, ImagesOf::Task(id), || s.delete_task(id))).await
}

#[derive(Deserialize)]
struct Bulk {
    ids: Vec<i64>,
    status: Option<String>,
    #[serde(default)]
    add_tags: String,
    #[serde(default)]
    remove_tags: String,
    #[serde(default)]
    delete: bool,
}

async fn bulk_tasks(State(home): Shared, Json(b): Json<Bulk>) -> Response {
    with_store(home, move |h, s| {
        if b.delete {
            h.deleting_images(s, ImagesOf::Tasks(b.ids.clone()), || s.delete_tasks(&b.ids))
        } else {
            s.update_tasks(&b.ids, b.status.as_deref(), &b.add_tags, &b.remove_tags)
        }
    })
    .await
}

#[derive(Deserialize)]
struct NewComment {
    #[serde(default)]
    body: String,
    #[serde(default)]
    images: Vec<String>,
}

async fn add_comment(State(home): Shared, Path(id): Path<i64>, Json(c): Json<NewComment>) -> Response {
    with_store(home, move |h, s| {
        for file in &c.images {
            image_saved(h, file)?;
        }
        s.add_comment(id, "me", &c.body, &c.images)
    })
    .await
}

#[derive(Deserialize)]
struct Attach {
    file: String,
}

async fn attach_image(State(home): Shared, Path(id): Path<i64>, Json(a): Json<Attach>) -> Response {
    with_store(home, move |h, s| {
        image_saved(h, &a.file)?;
        s.add_image(id, &a.file)
    })
    .await
}

async fn delete_image(State(home): Shared, Path(id): Path<i64>) -> Response {
    with_store(home, move |h, s| h.deleting_images(s, ImagesOf::Image(id), || s.delete_image(id))).await
}

fn image_saved(home: &Home, file: &str) -> store::Result<()> {
    if store::valid_image_file(file) && home.images().join(file).is_file() {
        Ok(())
    } else {
        Err(Error::Invalid(format!("no saved image {file:?}; paste it again")))
    }
}

/// Named by its content's hash, so it never changes and can be cached for good.
async fn image_file(State(home): Shared, Path(file): Path<String>) -> Response {
    let ext = file.rsplit_once('.').map(|(_, ext)| ext);
    let Some((_, mime)) = store::IMAGE_TYPES.iter().find(|(e, _)| Some(*e) == ext) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    if !store::valid_image_file(&file) {
        return StatusCode::NOT_FOUND.into_response();
    }
    let path = home.images().join(&file);
    match tokio::task::spawn_blocking(move || std::fs::read(path)).await {
        Ok(Ok(bytes)) => {
            ([(header::CONTENT_TYPE, *mime), (header::CACHE_CONTROL, "public, max-age=31536000, immutable")], bytes)
                .into_response()
        }
        _ => StatusCode::NOT_FOUND.into_response(),
    }
}

async fn delete_comment(State(home): Shared, Path(id): Path<i64>) -> Response {
    with_store(home, move |h, s| h.deleting_images(s, ImagesOf::Comment(id), || s.delete_comment(id))).await
}

async fn save_image(State(home): Shared, headers: HeaderMap, body: Bytes) -> Reply {
    let mime = headers.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok());
    let Some((ext, _)) = store::IMAGE_TYPES.iter().find(|(_, m)| Some(*m) == mime) else {
        return Err(fail(StatusCode::BAD_REQUEST, "paste a PNG, JPEG, GIF or WebP image"));
    };
    if body.is_empty() {
        return Err(fail(StatusCode::BAD_REQUEST, "the image is empty"));
    }
    let path = blocking(move || -> std::io::Result<std::path::PathBuf> {
        use std::hash::{Hash, Hasher};
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        body.hash(&mut hasher);
        let path = home.images().join(format!("{:016x}.{ext}", hasher.finish()));
        if !path.exists() {
            crate::home::write_whole(&path, &body)?;
        }
        Ok(path)
    })
    .await?
    .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, format!("cannot save the image: {e}")))?;
    let file = path.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
    Ok(Json(json!({ "file": file, "path": path.display().to_string() })).into_response())
}

async fn network(Extension(guard): Extension<Arc<Guard>>) -> Response {
    Json(guard.status()).into_response()
}

async fn change_network(
    State(home): Shared,
    Extension(guard): Extension<Arc<Guard>>,
    Json(change): Json<Change>,
) -> Response {
    match share::change(&home, change).await {
        Ok(net) => {
            guard.set(net);
            Json(guard.status()).into_response()
        }
        Err(e) => fail(StatusCode::BAD_REQUEST, e).into_response(),
    }
}

#[derive(Deserialize)]
struct OpenFile {
    path: std::path::PathBuf,
}

async fn open_file(State(home): Shared, Json(o): Json<OpenFile>) -> Reply {
    blocking(move || home.open_file(&o.path)).await?.map_err(|e| fail(StatusCode::BAD_REQUEST, e))?;
    Ok(Json(json!({})).into_response())
}

#[derive(Deserialize)]
struct SyncRequest {
    #[serde(default)]
    keep: Option<String>,
}

async fn sync_now(State(home): Shared, Json(r): Json<SyncRequest>) -> Reply {
    let keep = match r.keep.as_deref() {
        Some("local") => Some(sync::Keep::Local),
        Some("remote") => Some(sync::Keep::Remote),
        _ => None,
    };
    let synced = blocking(move || sync::sync(&home, keep, false)).await?;
    Ok(match synced {
        Ok(message) => Json(json!({ "message": message })).into_response(),
        Err(e) => match e.downcast_ref::<sync::Diverged>() {
            Some(d) => (StatusCode::CONFLICT, Json(json!({ "error": d.message, "diverged": true, "first": d.first })))
                .into_response(),
            None => fail(StatusCode::INTERNAL_SERVER_ERROR, format!("{e:#}")).into_response(),
        },
    })
}

async fn sync_status(State(home): Shared) -> Response {
    let remote = blocking(move || sync::remote_url(&home)).await.ok().flatten();
    Json(json!({ "remote": remote })).into_response()
}

#[derive(Deserialize)]
struct SyncRepo {
    url: String,
}

async fn sync_repo(State(home): Shared, Json(r): Json<SyncRepo>) -> Reply {
    let remote = blocking(move || sync::set_remote(&home, &r.url, false))
        .await?
        .map_err(|e| fail(StatusCode::BAD_REQUEST, format!("{e:#}")))?;
    Ok(Json(json!({ "remote": remote })).into_response())
}

#[derive(Deserialize)]
struct UpdateQuery {
    now: Option<String>,
}

async fn update_status(Query(q): Query<UpdateQuery>) -> Response {
    let now = q.now.is_some();
    let latest = blocking(move || update::latest(now)).await.ok().flatten();
    let available = latest.clone().filter(|v| update::newer(v));
    let command = update::updated_by();
    Json(json!({ "current": update::CURRENT, "latest": latest, "available": available, "command": command }))
        .into_response()
}

async fn update_now(State(home): Shared) -> Reply {
    // `can_restart` runs schtasks on Windows, so it waits off the async thread too.
    let dir = home.dir.clone();
    let (restart, installed) = blocking(move || (update::can_restart(&dir), update::install())).await?;
    let exe = installed.map_err(|error| fail(StatusCode::INTERNAL_SERVER_ERROR, error))?;
    if restart {
        tokio::spawn(async move {
            // Let the answer reach the board first.
            tokio::time::sleep(Duration::from_millis(300)).await;
            // Blocking: on Windows it waits for the service to stop this process.
            if let Ok(e) = tokio::task::spawn_blocking(move || update::restart(&exe)).await {
                eprintln!("kanzo: updated, but cannot restart: {e}");
            }
        });
    }
    Ok(Json(json!({ "restarting": restart })).into_response())
}

/// Windows doesn't stop the program when its console goes away: the service's conhost
/// when the task is stopped, or the window the board was started in.
#[cfg(windows)]
fn exit_with_console() {
    unsafe extern "system" {
        fn GetConsoleProcessList(list: *mut u32, count: u32) -> u32;
    }
    // SAFETY: room for one process id, as `count` says; it returns 0 without a console.
    let attached = || unsafe { GetConsoleProcessList(&mut 0, 1) } != 0;
    if attached() {
        std::thread::spawn(move || {
            while attached() {
                std::thread::sleep(Duration::from_secs(1));
            }
            std::process::exit(0);
        });
    }
}

/// The installed app if there is one, or else a browser tab. An app opens the address it was
/// installed from, so only on the default port, where that's this board.
fn open_board(url: &str, port: u16) {
    let app = cfg!(target_os = "macos")
        && port == crate::home::DEFAULT_PORT
        && std::process::Command::new("open")
            .args(["-a", "Kanzo"])
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok_and(|s| s.success());
    if !app {
        open_browser(url);
    }
}

fn open_browser(url: &str) {
    let opener = if cfg!(target_os = "macos") {
        "open"
    } else if cfg!(windows) {
        "explorer"
    } else {
        let desktop = ["DISPLAY", "WAYLAND_DISPLAY"].iter().any(|v| std::env::var_os(v).is_some_and(|v| !v.is_empty()));
        if !desktop {
            return;
        }
        "xdg-open"
    };
    if std::process::Command::new(opener).arg(url).spawn().is_err() {
        eprintln!("Open {url} in your browser.");
    }
}

#[cfg(test)]
mod tests {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    use super::*;

    #[test]
    fn changelog_is_for_this_version() {
        let heading = format!("## {}", update::CURRENT);
        assert!(
            CHANGELOG.lines().next() == Some(heading.as_str()),
            "CHANGELOG.md should start with the notes for this release"
        );
    }

    #[test]
    fn changelog_links_each_change() {
        for line in CHANGELOG.lines().filter(|l| l.starts_with("- ")) {
            assert!(
                line.ends_with(')') && line.contains("](https://github.com/emanuele-em/kanzo/"),
                "should end with a link to its pull request or commit, after any `thanks @name`: {line}"
            );
        }
    }

    #[test]
    fn the_board_script_uses_no_logical_assignment() {
        // Chrome 85, Firefox 79 and Safari 14 brought these in. On the older browsers the board
        // supports, one of them is a syntax error that stops the whole script.
        for op in ["??=", "||=", "&&="] {
            assert!(!APP_JS.contains(op), "app.js uses {op}: write it out, as in `if (x === null) x = y;`");
        }
    }

    #[test]
    fn csp_allows_the_inline_theme_script() {
        use base64::Engine;
        use sha2::Digest;
        let script = INDEX.split("<script>").nth(1).and_then(|s| s.split("</script>").next()).unwrap();
        let hash = base64::engine::general_purpose::STANDARD.encode(sha2::Sha256::digest(script));
        assert!(CSP.contains(&format!("'sha256-{hash}'")), "put 'sha256-{hash}' in CSP's script-src");
    }

    /// The status of a board's answer to `head`, its request line and headers with `PORT` for
    /// its port, and a JSON `body`, sent from `from`.
    async fn status(home: &Home, net: Net, hosts: &[&str], from: Option<IpAddr>, head: &str, body: &str) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let hosts = hosts.iter().map(|h| h.to_string()).collect();
        let guard = Arc::new(Guard::new(port, Ipv4Addr::LOCALHOST.into(), net, hosts));
        let mut app = router(home.clone(), guard, CancellationToken::new(), Arc::new(Push::load(home)));
        if let Some(ip) = from {
            app = app.layer(Extension(ConnectInfo(SocketAddr::new(ip, 1))));
        }
        tokio::spawn(async move { axum::serve(listener, app).await });
        let mut conn = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.unwrap();
        let head = head.replace("PORT", &port.to_string());
        let request =
            format!("{head}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", body.len());
        conn.write_all(request.as_bytes()).await.unwrap();
        let mut reply = String::new();
        conn.read_to_string(&mut reply).await.unwrap();
        reply.split(' ').nth(1).unwrap().to_string()
    }

    /// The status and body of `GET path` on a board for this computer.
    async fn get_from(home: &Home, path: &str) -> (String, serde_json::Value) {
        get_stopping(home, path, CancellationToken::new()).await
    }

    async fn get_stopping(home: &Home, path: &str, shutdown: CancellationToken) -> (String, serde_json::Value) {
        let (code, body) = get_text(home, path, shutdown).await;
        (code, serde_json::from_str(&body).unwrap_or(serde_json::Value::Null))
    }

    async fn get_text(home: &Home, path: &str, shutdown: CancellationToken) -> (String, String) {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let guard = Arc::new(Guard::new(port, Ipv4Addr::LOCALHOST.into(), Net::Private, Vec::new()));
        let app = router(home.clone(), guard, shutdown, Arc::new(Push::load(home)));
        tokio::spawn(async move { axum::serve(listener, app).await });
        let mut conn = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.unwrap();
        conn.write_all(format!("GET {path} HTTP/1.0\r\nHost: 127.0.0.1:{port}\r\n\r\n").as_bytes()).await.unwrap();
        let mut reply = String::new();
        conn.read_to_string(&mut reply).await.unwrap();
        let (head, body) = reply.split_once("\r\n\r\n").unwrap();
        (head.split(' ').nth(1).unwrap().to_string(), body.to_string())
    }

    fn test_home(tmp: &tempfile::TempDir) -> Home {
        let home = Home::open(tmp.path().to_path_buf()).unwrap();
        home.store().unwrap().migrate().unwrap();
        home
    }

    fn cursor(reply: &serde_json::Value) -> String {
        reply["last"].as_str().unwrap().to_string()
    }

    #[test]
    fn events_tell_a_reader_what_changed_since_it_last_asked() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let home = test_home(&tmp);
            let s = home.store().unwrap();
            let p = s.create_project("api", "", None).unwrap();
            s.create_task(p.id, "old", "").unwrap();

            let (code, start) = get_from(&home, "/api/events").await;
            assert_eq!(code, "200");
            assert_eq!(start["events"], json!([]), "a new reader starts now");
            let last = cursor(&start);

            let t = s.create_task(p.id, "new", "").unwrap();
            let patch = TaskPatch { title: Some("renamed".into()), status: Some("doing".into()), ..Default::default() };
            s.update_task(t.id, patch).unwrap();
            let (code, got) = get_from(&home, &format!("/api/events?since={last}")).await;
            assert_eq!(code, "200");
            let kinds: Vec<_> = got["events"].as_array().unwrap().iter().map(|e| e["kind"].as_str().unwrap()).collect();
            assert_eq!(kinds, ["task.created", "task.moved"], "a move with a new title is one event");
            assert_eq!(got["events"][1]["task"], format!("api#{}", t.id));
            assert_eq!(got["events"][1]["from"], "todo");
            assert_eq!(got["events"][1]["to"], "doing");
            let next = cursor(&got);

            let (_, none) = get_from(&home, &format!("/api/events?since={next}&wait=1")).await;
            assert_eq!(none["events"], json!([]));
            assert_eq!(cursor(&none), next, "nothing new keeps the place");

            let (_, all) = get_from(&home, "/api/events?since=0").await;
            assert_eq!(all["events"].as_array().unwrap().len(), 3, "0 reads from the oldest kept event");

            let (code, _) = get_from(&home, "/api/events?since=0&project=nope").await;
            assert_eq!(code, "404");
            let (code, _) = get_from(&home, "/api/events?since=12").await;
            assert_eq!(code, "400", "a cursor is not a bare id");
        });
    }

    #[test]
    fn a_quiet_project_moves_its_reader_to_the_newest_event() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let home = test_home(&tmp);
            let s = home.store().unwrap();
            let a = s.create_project("api", "", None).unwrap();
            s.create_project("web", "", None).unwrap();
            let (_, start) = get_from(&home, "/api/events").await;
            s.create_task(a.id, "elsewhere", "").unwrap();
            let (_, got) = get_from(&home, &format!("/api/events?since={}&project=web", cursor(&start))).await;
            assert_eq!(got["events"], json!([]));
            let (_, newest) = get_from(&home, "/api/events").await;
            assert_eq!(cursor(&got), cursor(&newest));
        });
    }

    #[test]
    fn a_reader_that_cannot_go_on_is_told_to_start_over() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let home = test_home(&tmp);
            let s = home.store().unwrap();
            let p = s.create_project("api", "", None).unwrap();
            s.create_task(p.id, "one", "").unwrap();
            let (_, start) = get_from(&home, "/api/events").await;
            let here = cursor(&start);
            let id: i64 = here.split_once('.').unwrap().0.parse().unwrap();

            let (_, ahead) = get_from(&home, &format!("/api/events?since={}.1&wait=10", id + 50)).await;
            assert_eq!(ahead["reset"], true, "a board that is behind answers at once");
            assert_eq!(cursor(&ahead), here);

            let (_, fine) = get_from(&home, &format!("/api/events?since={here}")).await;
            assert_eq!(fine.get("reset"), None);

            // Another copy of the board with the same ids, and more events than the reader saw.
            s.conn_for_tests().execute("UPDATE events SET nonce = nonce + 1", []).unwrap();
            s.create_task(p.id, "two", "").unwrap();
            let (_, diverged) = get_from(&home, &format!("/api/events?since={here}")).await;
            assert_eq!(diverged["reset"], true, "a replaced board is reported");
            assert_eq!(diverged["events"], json!([]));
            let (_, newest) = get_from(&home, "/api/events").await;
            assert_eq!(cursor(&diverged), cursor(&newest), "and the reader goes on from the newest");

            let (_, back) = get_from(&home, &format!("/api/events?since={}", cursor(&newest))).await;
            s.conn_for_tests().execute("DELETE FROM events", []).unwrap();
            let (_, dropped) = get_from(&home, &format!("/api/events?since={}", cursor(&back))).await;
            assert_eq!(dropped["reset"], true, "dropped events are reported");
        });
    }

    #[test]
    fn a_waiting_reader_gets_the_event_as_it_happens() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let home = test_home(&tmp);
            let pid = home.store().unwrap().create_project("api", "", None).unwrap().id;
            let (_, start) = get_from(&home, "/api/events").await;

            let writer = home.clone();
            tokio::spawn(async move {
                tokio::time::sleep(Duration::from_millis(700)).await;
                tokio::task::spawn_blocking(move || writer.store().unwrap().create_task(pid, "live", "").unwrap())
                    .await
                    .unwrap();
            });
            let began = Instant::now();
            let (code, got) = get_from(&home, &format!("/api/events?since={}&wait=10", cursor(&start))).await;
            assert_eq!(code, "200");
            assert_eq!(got["events"][0]["kind"], "task.created");
            assert!(began.elapsed() < Duration::from_secs(5), "answers when the event comes, not after the wait");
        });
    }

    #[test]
    fn every_write_changes_the_counter_a_waiting_reader_watches() {
        let tmp = tempfile::tempdir().unwrap();
        let home = test_home(&tmp);
        let s = home.store().unwrap();
        let p = s.create_project("api", "", None).unwrap();
        let mut seen = vec![home.db_stamp().1.unwrap()];
        let t = s.create_task(p.id, "first", "").unwrap();
        seen.push(home.db_stamp().1.unwrap());
        s.add_comment(t.id, "agent", "on it", &[]).unwrap();
        seen.push(home.db_stamp().1.unwrap());
        seen.dedup();
        assert_eq!(seen.len(), 3, "{seen:?}");
        assert_eq!(crate::home::change_counter(&tmp.path().join("nope.db")), None);
    }

    #[test]
    fn a_change_the_counter_misses_still_comes_when_the_wait_ends() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let home = test_home(&tmp);
            let pid = home.store().unwrap().create_project("api", "", None).unwrap().id;
            let (_, start) = get_from(&home, "/api/events").await;
            let writer = home.clone();
            // Between two of the wait's looks, half a second apart: a write that leaves the
            // counter as it was, as if it had never bumped it.
            tokio::spawn(async move {
                tokio::time::sleep(Duration::from_millis(250)).await;
                tokio::task::spawn_blocking(move || {
                    use std::io::{Seek, SeekFrom, Write};
                    let before = writer.db_stamp().1.unwrap();
                    writer.store().unwrap().create_task(pid, "unseen", "").unwrap();
                    let mut file = std::fs::OpenOptions::new().write(true).open(writer.db_path()).unwrap();
                    file.seek(SeekFrom::Start(24)).unwrap();
                    file.write_all(&before).unwrap();
                })
                .await
                .unwrap();
            });
            let began = Instant::now();
            let (_, got) = get_from(&home, &format!("/api/events?since={}&wait=2", cursor(&start))).await;
            assert_eq!(got["events"][0]["kind"], "task.created", "{got}");
            // On Windows the file's identity is its modified time, which the write changed, so the
            // wait saw it at once. Elsewhere only the counter could have told, and it didn't.
            if cfg!(unix) {
                assert!(began.elapsed() >= Duration::from_millis(1900), "only when the wait ended");
            }
        });
    }

    fn escalate(home: &Home, title: &str) -> i64 {
        let s = home.store().unwrap();
        let p = match s.find_project("api") {
            Ok(p) => p,
            Err(_) => s.create_project("api", "", None).unwrap(),
        };
        let id = s.create_task(p.id, title, "").unwrap().id;
        s.update_task(id, TaskPatch { escalated: Some(true), ..Default::default() }).unwrap();
        id
    }

    /// Waits up to `secs` for `push` to have something for the browser at `endpoint`.
    async fn pushed(push: &Push, endpoint: &str, secs: u64) -> Vec<crate::push::Escalation> {
        let until = Instant::now() + Duration::from_secs(secs);
        while Instant::now() < until {
            let tasks = push.take(endpoint).tasks;
            if !tasks.is_empty() {
                return tasks;
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
        Vec::new()
    }

    #[test]
    fn a_browser_subscribes_and_only_this_computer_may() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let home = test_home(&tmp);
            let (code, key) = get_from(&home, "/api/push").await;
            assert_eq!((code.as_str(), key["key"].as_str().map(str::len)), ("200", Some(87)), "{key}");
            let head = |method: &str| format!("{method} /api/push HTTP/1.0\r\nHost: 127.0.0.1:PORT");
            let browser = r#"{"endpoint":"https://push.example/a","lang":"en"}"#;
            assert_eq!(status(&home, Net::Private, &[], None, &head("POST"), browser).await, "200");
            let insecure = r#"{"endpoint":"http://push.example/a"}"#;
            assert_eq!(status(&home, Net::Private, &[], None, &head("POST"), insecure).await, "400");
            let gone = r#"{"endpoint":"https://push.example/a"}"#;
            assert_eq!(status(&home, Net::Private, &[], None, &head("DELETE"), gone).await, "200");
            assert!(Push::load(&home).is_empty());

            let guest = Some(IpAddr::from([192, 168, 1, 9]));
            assert_eq!(status(&home, Net::Sharing, &[], guest, &head("POST"), browser).await, "403");
            assert!(Push::load(&home).is_empty(), "a guest on the network adds nothing");

            // One its push service refused is told to subscribe anew.
            std::fs::write(home.dir.join(crate::push::FILE), r#"{"gone":["https://push.example/a"]}"#).unwrap();
            let refused = crate::push::Browser { endpoint: "https://push.example/a".into(), lang: "en".into() };
            let res = push_add(Extension(Arc::new(Push::load(&home))), Json(refused)).await;
            let body = axum::body::to_bytes(res.into_body(), 1 << 10).await.unwrap();
            assert_eq!(serde_json::from_slice::<serde_json::Value>(&body).unwrap(), json!({ "renew": true }));

            let (code, worker) = get_text(&home, "/sw.js", CancellationToken::new()).await;
            assert!(code == "200" && worker.contains("notificationclick"), "{code}");
            assert!(CSP.contains("worker-src 'self'"), "the page may register it");
        });
    }

    #[test]
    fn a_worker_gets_only_what_still_waits_for_you() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let home = test_home(&tmp);
            let push = Arc::new(Push::load(&home));
            push.public_key().unwrap();
            let endpoint = "https://127.0.0.1:9/never";
            push.add(crate::push::Browser { endpoint: endpoint.into(), lang: "en".into() }).unwrap();
            let (handled, waiting) = (escalate(&home, "Handled"), escalate(&home, "Waiting"));
            let now = crate::push::escalated_now(&home).await.unwrap();
            push.notify(&now);
            home.store().unwrap().move_task(handled, "done", None).unwrap();

            let asks = Json(Endpoint { endpoint: endpoint.into() });
            let res = push_pending(State(Arc::new(home.clone())), Extension(push.clone()), asks).await;
            let body = axum::body::to_bytes(res.into_body(), 1 << 16).await.unwrap();
            let pending: serde_json::Value = serde_json::from_slice(&body).unwrap();
            let ids: Vec<i64> =
                pending["tasks"].as_array().unwrap().iter().map(|t| t["id"].as_i64().unwrap()).collect();
            assert_eq!((pending["lang"].as_str(), ids), (Some("en"), vec![waiting]));
        });
    }

    #[test]
    fn the_watcher_pushes_a_new_escalation_on_this_board() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let home = test_home(&tmp);
            escalate(&home, "Before");
            let push = Arc::new(Push::load(&home));
            push.public_key().unwrap();
            let endpoint = "https://127.0.0.1:9/never";
            push.add(crate::push::Browser { endpoint: endpoint.into(), lang: "en".into() }).unwrap();
            let stop = CancellationToken::new();
            tokio::spawn(crate::push::watch(push.clone(), home.clone(), stop.clone()));
            // Its first look, two seconds in, learns what is escalated already.
            tokio::time::sleep(Duration::from_millis(2500)).await;
            let id = escalate(&home, "After");
            let tasks = pushed(&push, endpoint, 5).await;
            assert_eq!(tasks.iter().map(|t| (t.id, t.shared)).collect::<Vec<_>>(), [(id, false)]);
            stop.cancel();
        });
    }

    #[test]
    fn a_joined_computer_follows_the_shared_boards_escalations() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let (host_tmp, guest_tmp) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
            let host = test_home(&host_tmp);
            let before = escalate(&host, "Before");
            let port = serve_board(&host, Net::Sharing).await;
            let guest = test_home(&guest_tmp);
            std::fs::write(guest.dir.join(share::FILE), format!("join 127.0.0.1:{port}\n")).unwrap();
            let now = crate::push::escalated_now(&guest).await.unwrap();
            assert_eq!(now.iter().map(|t| (t.id, t.shared)).collect::<Vec<_>>(), [(before, true)]);

            let push = Arc::new(Push::load(&guest));
            push.public_key().unwrap();
            let endpoint = "https://127.0.0.1:9/never";
            push.add(crate::push::Browser { endpoint: endpoint.into(), lang: "en".into() }).unwrap();
            let stop = CancellationToken::new();
            tokio::spawn(crate::push::watch(push.clone(), guest.clone(), stop.clone()));
            tokio::time::sleep(Duration::from_millis(500)).await;
            let id = escalate(&host, "After");
            let tasks = pushed(&push, endpoint, 5).await;
            assert_eq!(tasks.iter().map(|t| (t.id, t.shared)).collect::<Vec<_>>(), [(id, true)]);
            stop.cancel();
        });
    }

    #[test]
    fn settings_change_how_many_events_are_kept() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let home = test_home(&tmp);
            let (_, board) = get_from(&home, "/api/board").await;
            assert_eq!(board["events_kept"], 1000);

            let patch = "PATCH /api/settings HTTP/1.0\r\nHost: 127.0.0.1:PORT";
            assert_eq!(status(&home, Net::Private, &[], None, patch, r#"{"events_kept":300}"#).await, "200");
            let (_, board) = get_from(&home, "/api/board").await;
            assert_eq!(board["events_kept"], 300);
            assert_eq!(status(&home, Net::Private, &[], None, patch, r#"{"events_kept":50}"#).await, "400");
        });
    }

    #[test]
    fn shutdown_answers_a_waiting_reader() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let home = test_home(&tmp);
            let (_, start) = get_from(&home, "/api/events").await;
            let shutdown = CancellationToken::new();
            let stop = shutdown.clone();
            tokio::spawn(async move {
                tokio::time::sleep(Duration::from_millis(300)).await;
                stop.cancel();
            });
            let began = Instant::now();
            let path = format!("/api/events?since={}&wait=20", cursor(&start));
            let (code, got) = get_stopping(&home, &path, shutdown).await;
            assert_eq!(code, "200");
            assert_eq!(got["events"], json!([]));
            assert!(began.elapsed() < Duration::from_secs(3), "answers on shutdown, not after the wait");
        });
    }

    /// The status of asking a board to open `path`, from `from`.
    async fn open_from(home: &Home, from: Option<IpAddr>, path: &str) -> String {
        let body = json!({ "path": path }).to_string();
        status(home, Net::Sharing, &[], from, "POST /api/open HTTP/1.0\r\nHost: 127.0.0.1:PORT", &body).await
    }

    #[test]
    fn only_this_computer_opens_a_file_and_only_a_file() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let mut home = Home::open(tmp.path().to_path_buf()).unwrap();
            home.config.editor = Some("true".into());
            let file = tmp.path().join("notes.md");
            std::fs::write(&file, "").unwrap();
            let file = file.to_str().unwrap();

            let guest = Some(IpAddr::from([192, 168, 1, 9]));
            assert_eq!(open_from(&home, guest, file).await, "403");
            assert_eq!(open_from(&home, None, "notes.md").await, "400");
            assert_eq!(open_from(&home, None, tmp.path().to_str().unwrap()).await, "400");
            assert_eq!(open_from(&home, None, &format!("{file}.missing")).await, "400");
            #[cfg(unix)]
            assert_eq!(open_from(&home, None, file).await, "200");
        });
    }

    /// A board for `home` on a free port, on the network the way `net` says.
    async fn serve_board(home: &Home, net: Net) -> u16 {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let guard = Arc::new(Guard::new(port, Ipv4Addr::LOCALHOST.into(), net, Vec::new()));
        let app = router(home.clone(), guard, CancellationToken::new(), Arc::new(Push::load(home)));
        tokio::spawn(
            async move { axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await },
        );
        port
    }

    /// The status and body of `GET path` on the board at `port`.
    async fn get(port: u16, path: &str) -> (u16, String) {
        let mut conn = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.unwrap();
        let head = format!("GET {path} HTTP/1.0\r\nHost: 127.0.0.1:{port}\r\n\r\n");
        conn.write_all(head.as_bytes()).await.unwrap();
        let mut reply = Vec::new();
        conn.read_to_end(&mut reply).await.unwrap();
        let reply = String::from_utf8_lossy(&reply).into_owned();
        let status = reply.split(' ').nth(1).unwrap().parse().unwrap();
        let body = reply.split_once("\r\n\r\n").map_or("", |(_, b)| b).to_string();
        (status, body)
    }

    fn slugs(body: &str) -> Vec<String> {
        let value: serde_json::Value = serde_json::from_str(body).unwrap();
        value["projects"].as_array().unwrap().iter().map(|p| p["slug"].as_str().unwrap().to_string()).collect()
    }

    /// A host sharing a board with project `api`, and a guest joined to it with its own project `mine`.
    async fn joined_boards() -> (tempfile::TempDir, tempfile::TempDir, u16, u16) {
        let host_dir = tempfile::tempdir().unwrap();
        let host = Home::open(host_dir.path().to_path_buf()).unwrap();
        host.store().unwrap().create_project("api", "API", None).unwrap();
        let host_port = serve_board(&host, Net::Sharing).await;

        let guest_dir = tempfile::tempdir().unwrap();
        let guest = Home::open(guest_dir.path().to_path_buf()).unwrap();
        guest.store().unwrap().create_project("mine", "Mine", None).unwrap();
        let guest_port = serve_board(&guest, Net::Joined(format!("127.0.0.1:{host_port}"))).await;
        (host_dir, guest_dir, host_port, guest_port)
    }

    #[test]
    fn a_joined_board_keeps_showing_its_own_projects() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let (_host_dir, _guest_dir, _, guest) = joined_boards().await;
            let (status, body) = get(guest, "/api/board").await;
            assert_eq!(status, 200, "{body}");
            assert_eq!(slugs(&body), ["mine"]);
        });
    }

    #[test]
    fn a_joined_board_reaches_the_shared_one_under_remote() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let (_host_dir, _guest_dir, _, guest) = joined_boards().await;
            let (status, body) = get(guest, "/remote/api/board").await;
            assert_eq!(status, 200, "{body}");
            assert_eq!(slugs(&body), ["api"]);
            let (status, body) = get(guest, "/remote/api/projects").await;
            assert_eq!(status, 200, "{body}");
            assert_eq!(slugs(&body), ["api"]);
        });
    }

    #[test]
    fn only_a_joined_board_has_a_remote_one() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let home = Home::open(tmp.path().to_path_buf()).unwrap();
            let port = serve_board(&home, Net::Private).await;
            let (status, body) = get(port, "/remote/api/board").await;
            assert_eq!(status, 404, "{body}");
            assert!(body.contains("not joined"), "{body}");
        });
    }

    #[test]
    fn projects_lists_a_board_without_its_tasks() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let home = Home::open(tmp.path().to_path_buf()).unwrap();
            home.store().unwrap().create_project("web", "Web", None).unwrap();
            let port = serve_board(&home, Net::Private).await;
            let (status, body) = get(port, "/api/projects").await;
            assert_eq!(status, 200, "{body}");
            assert_eq!(slugs(&body), ["web"]);
            let value: serde_json::Value = serde_json::from_str(&body).unwrap();
            assert!(value["changes"].is_string(), "{body}");
            assert!(value.get("tasks").is_none(), "{body}");
        });
    }

    #[test]
    fn a_joined_board_sees_the_update_the_shared_one_can_take() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            update::pretend_latest("999.0.0");
            let (_host_dir, _guest_dir, _, guest) = joined_boards().await;
            let (status, body) = get(guest, "/remote/api/update").await;
            assert_eq!(status, 200, "{body}");
            let value: serde_json::Value = serde_json::from_str(&body).unwrap();
            assert_eq!(value["current"], update::CURRENT, "{body}");
            assert_eq!(value["available"], "999.0.0", "{body}");
        });
    }

    #[test]
    fn changes_say_which_board_this_one_joined() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let (_host_dir, _guest_dir, host, guest) = joined_boards().await;
            let (_, body) = get(guest, "/api/changes").await;
            let value: serde_json::Value = serde_json::from_str(&body).unwrap();
            assert_eq!(value["joined"], format!("127.0.0.1:{host}"), "{body}");
            let (_, body) = get(host, "/api/changes").await;
            let value: serde_json::Value = serde_json::from_str(&body).unwrap();
            assert!(value["joined"].is_null(), "{body}");
        });
    }

    #[test]
    fn a_listed_host_reaches_the_board_but_not_this_computer() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let mut home = Home::open(tmp.path().to_path_buf()).unwrap();
            home.config.editor = Some("true".into());
            let file = tmp.path().join("notes.md");
            std::fs::write(&file, "").unwrap();
            let open = json!({ "path": file }).to_string();
            // A reverse proxy on this computer: every request comes from 127.0.0.1.
            let proxied = async |hosts: &[&str], head: &str, body: &str| {
                status(&home, Net::Private, hosts, None, head, body).await
            };
            let listed = &["board.example.ts.net"];

            for origin in ["", "\r\nOrigin: https://board.example.ts.net", "\r\nOrigin: http://board.example.ts.net"] {
                let head = format!("GET /api/board HTTP/1.0\r\nHost: board.example.ts.net{origin}");
                assert_eq!(proxied(listed, &head, "").await, "200", "{origin}");
            }
            for head in [
                "GET /api/board HTTP/1.0\r\nHost: other.example.ts.net",
                "GET /api/board HTTP/1.0\r\nHost: board.example.ts.net\r\nOrigin: https://evil.com",
                "GET /api/board HTTP/1.0\r\nHost: board.example.ts.net\r\nOrigin: https://other.example.ts.net",
                // https is only for the listed names.
                "GET /api/board HTTP/1.0\r\nHost: 127.0.0.1:PORT\r\nOrigin: https://127.0.0.1:PORT",
            ] {
                assert_eq!(proxied(listed, head, "").await, "403", "{head}");
            }
            assert_eq!(proxied(&[], "GET /api/board HTTP/1.0\r\nHost: board.example.ts.net", "").await, "403");

            assert_eq!(proxied(listed, "POST /api/open HTTP/1.0\r\nHost: board.example.ts.net", &open).await, "403");
            assert_eq!(proxied(listed, "GET /api/network HTTP/1.0\r\nHost: board.example.ts.net", "").await, "403");
            let off = json!({ "change": "off" }).to_string();
            assert_eq!(proxied(listed, "POST /api/network HTTP/1.0\r\nHost: board.example.ts.net", &off).await, "403");
            assert_eq!(proxied(listed, "GET /api/network HTTP/1.0\r\nHost: 127.0.0.1:PORT", "").await, "200");
        });
    }

    #[test]
    fn a_proxy_cant_pass_a_visitor_off_as_this_computer() {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async {
            let tmp = tempfile::tempdir().unwrap();
            let mut home = Home::open(tmp.path().to_path_buf()).unwrap();
            home.config.editor = Some("true".into());
            let file = tmp.path().join("notes.md");
            std::fs::write(&file, "").unwrap();
            let open = json!({ "path": file }).to_string();
            let listed = &["board.example.ts.net"];
            // A proxy that passes on whatever Host its visitor sent, from 127.0.0.1.
            for forwarded in
                ["X-Forwarded-For: 203.0.113.9", "Forwarded: for=203.0.113.9", "X-Forwarded-Host: board.example.ts.net"]
            {
                for host in ["localhost:PORT", "127.0.0.1:PORT"] {
                    let open_head = format!("POST /api/open HTTP/1.0\r\nHost: {host}\r\n{forwarded}");
                    let network_head = format!("GET /api/network HTTP/1.0\r\nHost: {host}\r\n{forwarded}");
                    assert_eq!(
                        status(&home, Net::Private, listed, None, &open_head, &open).await,
                        "403",
                        "{open_head}"
                    );
                    assert_eq!(
                        status(&home, Net::Private, listed, None, &network_head, "").await,
                        "403",
                        "{network_head}"
                    );
                }
            }
            // This computer's own browser sends none of them.
            let head = "GET /api/network HTTP/1.0\r\nHost: localhost:PORT";
            assert_eq!(status(&home, Net::Private, listed, None, head, "").await, "200");
        });
    }

    #[test]
    fn hosts() {
        let local = Guard::new(4242, Ipv4Addr::LOCALHOST.into(), Net::Private, Vec::new());
        for ok in ["localhost", "localhost:4242", "127.0.0.1:4242", "[::1]:4242", "LOCALHOST:4242"] {
            assert!(local.allows(ok), "{ok}");
        }
        for bad in ["evil.com", "evil.com:4242", "localhost:80", "192.168.1.5:4242", "", "pi.local:4242"] {
            assert!(!local.allows(bad), "{bad}");
        }

        let lan = Guard::new(4242, Ipv4Addr::LOCALHOST.into(), Net::Sharing, Vec::new());
        lan.names.set(vec!["pi".into(), "pi.local".into()]).unwrap();
        for ok in ["localhost:4242", "192.168.1.5:4242", "[fe80::1]:4242", "pi.local:4242", "pi:4242", "PI.LOCAL."] {
            assert!(lan.allows(ok), "{ok}");
        }
        for bad in ["evil.com:4242", "pi.evil.com:4242", "192.168.1.5:80"] {
            assert!(!lan.allows(bad), "{bad}");
        }

        lan.set(Net::Private);
        assert!(!lan.allows("192.168.1.5:4242"));
        assert_eq!(lan.address(), IpAddr::from(Ipv4Addr::LOCALHOST));

        let proxied = Guard::new(4242, Ipv4Addr::LOCALHOST.into(), Net::Private, vec!["Board.example.ts.net.".into()]);
        for ok in ["board.example.ts.net", "BOARD.example.ts.net.", "board.example.ts.net:443", "localhost:4242"] {
            assert!(proxied.allows(ok), "{ok}");
        }
        for bad in ["example.ts.net", "board.example.ts.net.evil.com", "evil.board.example.ts.net", "", ":4242"] {
            assert!(!proxied.allows(bad), "{bad}");
        }
        assert!(proxied.listed("board.example.ts.net:443") && !proxied.listed("localhost:4242"));
    }
}