kanade-backend 0.61.1

axum + SQLite projection backend for the kanade endpoint-management system. Hosts /api/* and the embedded SPA dashboard, projects JetStream streams into SQLite, drives the cron scheduler
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
//! `GET /api/agents/installer` — generate an agent installer archive on the
//! fly, for Windows (ZIP), Linux or macOS (tar.gz). Sibling endpoints
//! `GET /api/agents/installer.ps1` / `GET /api/agents/installer.sh` return
//! generated one-liner scripts that download + extract + run that archive
//! in a single pasted command (each embeds the caller's own Bearer token
//! so the inner download is authenticated). `installer.sh` serves both
//! Linux and macOS, picking the archive by `uname -s` (plus `uname -m` on
//! Linux; macOS is Apple Silicon only, probed via `sysctl`).
//!
//! Self-service: the route sits in the viewer+ base router, gated by the
//! `agent-install` page feature, so a restricted "download user" account
//! (viewer + ONLY that feature) can kit a fresh machine: extract, run the
//! bootstrap as admin/root, done. There is no request body and no version
//! parameter — the caller picks only the platform
//! (`?os=windows|linux|macos`, default `windows`; `?arch=x86_64|aarch64`,
//! default `x86_64`, except macOS where the only — and default — arch is
//! `aarch64`: Intel Macs are unsupported and `?os=macos&arch=x86_64` is a
//! 400). The archive always bundles the latest release FOR
//! THAT PLATFORM (by Object Store `modified`, over the platform's keys —
//! bare keys for Windows, `<version>-linux-<arch>` for Linux,
//! `<version>-macos-aarch64` for macOS; see kanade_shared::bin_platform),
//! and the NATS url/token it bakes in come from the `agent_install`
//! section of the server-settings document (falling back to this
//! backend's own `[nats] url`, no token).
//!
//! Windows ZIP contents:
//!
//!   * `kanade-agent.exe` — the bytes of the latest release from the
//!     `agent_releases` Object Store.
//!   * `agent.toml` — the repo's `configs/agent.toml` with the single
//!     `nats_url` line rewritten to the settings (or backend) NATS URL.
//!   * `deploy-agent.ps1` — the canonical `scripts/deploy/agent.ps1`,
//!     verbatim. All install logic lives there; this module only wraps it.
//!   * `install-agent.ps1` — a generated wrapper that invokes
//!     `deploy-agent.ps1` with the configured `-NatsToken` and, when this
//!     backend signs commands, a `-CommandKeys` ring holding the backend's
//!     own PUBLIC key (never a break-glass key — those are distributed
//!     separately, by hand).
//!   * `install.cmd` — a generated CRLF bootstrap for double-click
//!     installs (PowerShell with a bypass policy, pause-on-failure).
//!   * `README.txt` — the two-step instructions.
//!
//! Linux tar.gz contents (the `deploy/linux/bundle-agent.sh` layout,
//! relative to the extraction root):
//!
//!   * `bin/kanade-agent` (0755) — the latest `<version>-linux-<arch>`
//!     release.
//!   * `etc/agent.toml` — same rewritten config as the Windows ZIP.
//!   * `systemd/kanade-agent.service` — the repo unit, verbatim.
//!   * `setup-agent.sh` (0755) — the canonical Linux installer, verbatim.
//!     It resolves the token from `KANADE_NATS_TOKEN` → co-located
//!     `nats.env` → existing `agent.env` → hard fail, and overrides
//!     `nats_url` only when `KANADE_NATS_URL` is set.
//!   * `install.sh` (0755) — a generated wrapper: exports
//!     `KANADE_NATS_TOKEN` when (and only when) the settings carry one,
//!     `KANADE_COMMAND_KEYS` when this backend signs commands and
//!     `KANADE_REQUIRE_SIGNED_COMMANDS=1` when the require-signed-commands
//!     setting is on and there is a key to back it, then
//!     `exec ./setup-agent.sh`. `KANADE_NATS_URL` is deliberately NOT
//!     exported — the baked agent.toml already carries it.
//!   * `README.txt` — extract + `sudo ./install.sh` instructions, with
//!     the same command-signing / enforcement note the Windows ZIP carries.
//!
//! macOS tar.gz contents (same shape, launchd instead of systemd):
//!
//!   * `bin/kanade-agent` (0755) — the latest `<version>-macos-aarch64`
//!     release (a thin Apple Silicon Mach-O).
//!   * `etc/agent.toml` — same rewritten config as the Windows ZIP.
//!   * `launchd/com.kanade.agent.plist` — the repo LaunchDaemon, verbatim.
//!   * `setup-agent-macos.sh` (0755) — the canonical macOS installer
//!     (`deploy/macos/setup-agent.sh`), verbatim. Token from
//!     `KANADE_NATS_TOKEN` → existing `agent.env` → hard fail; `nats_url`
//!     overridden only when `KANADE_NATS_URL` is set.
//!   * `install.sh` (0755) — the same generated wrapper as Linux, handing
//!     over to `setup-agent-macos.sh`.
//!   * `README.txt` — extract + `sudo ./install.sh`, the Gatekeeper note,
//!     and the same command-signing / enforcement note.

use axum::body::Body;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use kanade_shared::bin_platform::{
    LINUX_SUFFIX_AARCH64, LINUX_SUFFIX_X86_64, MACOS_SUFFIX_AARCH64, platform_of_key,
};
use kanade_shared::kv::OBJECT_AGENT_RELEASES;
use kanade_shared::wire::ServerSettings;
use serde::Deserialize;
use tokio::io::AsyncReadExt;
use tracing::{info, warn};

use super::AppState;
use crate::audit;
use crate::audit::Caller;

// The installer ships six files verbatim: the stock agent config, the
// three canonical install scripts, and the systemd unit + launchd plist.
// They are `include_str!`d from `crates/kanade-backend/assets/`, which is
// a COPY of the canonical originals at the workspace root.
//
// The copy exists for one reason: `cargo package` only puts the crate
// directory into the tarball, so an `include_str!` reaching outside it
// compiles everywhere EXCEPT the verification build `cargo publish` runs on
// the packaged copy. That failed every release from v0.45.5 to v0.45.9 — and
// only crates.io, never CI or a local build, because both of those compile in
// the workspace where the originals are right there (#1364). The publish job
// runs the members in topological order and stops on the first failure, so
// one unpackageable crate also held back `kanade` (the CLI, which
// `cargo install` and `self-update` read) at 0.45.4 for five releases.
//
// Duplication is the cost, and it is guarded rather than trusted:
// `assets_match_the_workspace_originals` below fails if a copy drifts. The
// test compiles only in the workspace (`cargo package` builds lib and bins,
// not tests — which is why kanade-shared's test-only `include_str!`s of the
// same kind have always published fine), so it runs exactly where drift can
// be introduced.

/// The stock agent config every fresh install starts from. The single
/// `nats_url` line ([`NATS_URL_LINE`]) is rewritten per request.
const AGENT_TOML_TEMPLATE: &str = include_str!("../../assets/agent.toml");

/// The canonical deploy script, shipped unmodified so the installer can
/// never drift from what `scripts/deploy/agent.ps1` documents.
const DEPLOY_AGENT_PS1: &str = include_str!("../../assets/deploy-agent.ps1");

/// The canonical Linux install script + systemd unit, shipped verbatim for
/// the same reason — all Linux install logic lives in `setup-agent.sh`.
const SETUP_AGENT_SH: &str = include_str!("../../assets/setup-agent.sh");
const AGENT_SERVICE: &str = include_str!("../../assets/kanade-agent.service");

/// The canonical macOS install script + LaunchDaemon plist, verbatim —
/// all macOS install logic lives in `deploy/macos/setup-agent.sh`.
const SETUP_AGENT_MACOS_SH: &str = include_str!("../../assets/setup-agent-macos.sh");
const AGENT_PLIST: &str = include_str!("../../assets/com.kanade.agent.plist");

/// The exact `[agent]` line in `configs/agent.toml` that carries the
/// loopback default. Matched verbatim (and replaced exactly once) so a
/// template edit that moves or rewords the line fails loudly at request
/// time instead of silently shipping an unrewritten loopback config.
const NATS_URL_LINE: &str = "nats_url = 'nats://127.0.0.1:4222'";

/// Which OS the generated installer targets. Default Windows (the
/// pre-Linux behavior, so existing links keep working).
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
enum InstallerOs {
    #[default]
    Windows,
    Linux,
    Macos,
}

impl InstallerOs {
    fn as_str(&self) -> &'static str {
        match self {
            InstallerOs::Windows => "windows",
            InstallerOs::Linux => "linux",
            InstallerOs::Macos => "macos",
        }
    }
}

/// Which CPU architecture a Linux/macOS installer targets. Default x86_64
/// (aarch64 on macOS, its only supported arch).
/// (Windows releases sit at the bare `<version>` key regardless of arch —
/// the key scheme's backward-compat decision — so this only filters Linux
/// and macOS.)
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
enum InstallerArch {
    #[default]
    X86_64,
    Aarch64,
}

impl InstallerArch {
    fn as_str(&self) -> &'static str {
        match self {
            InstallerArch::X86_64 => "x86_64",
            InstallerArch::Aarch64 => "aarch64",
        }
    }

    /// The Object Store key suffix for this arch's Linux releases.
    fn linux_suffix(&self) -> &'static str {
        match self {
            InstallerArch::X86_64 => LINUX_SUFFIX_X86_64,
            InstallerArch::Aarch64 => LINUX_SUFFIX_AARCH64,
        }
    }
}

/// `?os=windows|linux|macos&arch=x86_64|aarch64` — both optional, unknown
/// values rejected 400 by the Query extractor's serde failure.
#[derive(Deserialize, Debug, Default)]
pub struct InstallerParams {
    #[serde(default)]
    os: InstallerOs,
    #[serde(default)]
    arch: Option<InstallerArch>,
}

impl InstallerParams {
    /// The effective arch for this request: the explicit `?arch=`, else
    /// the OS default (x86_64; aarch64 on macOS). Intel Macs are
    /// unsupported — `?os=macos&arch=x86_64` is a 400, decided here before
    /// any store lookup.
    fn resolve_arch(&self) -> Result<InstallerArch, (StatusCode, String)> {
        match (self.os, self.arch) {
            (InstallerOs::Macos, Some(InstallerArch::X86_64)) => Err((
                StatusCode::BAD_REQUEST,
                "Intel (x86_64) Macs are not supported — kanade supports Apple Silicon (arm64) \
                 Macs only; use arch=aarch64"
                    .to_string(),
            )),
            (InstallerOs::Macos, None) => Ok(InstallerArch::Aarch64),
            (_, arch) => Ok(arch.unwrap_or_default()),
        }
    }
}

pub async fn installer(
    State(state): State<AppState>,
    caller: Caller,
    Query(params): Query<InstallerParams>,
) -> Result<Response, (StatusCode, String)> {
    let arch = params.resolve_arch()?;
    let store = state
        .jetstream
        .get_object_store(OBJECT_AGENT_RELEASES)
        .await
        .map_err(|e| {
            warn!(error = %e, "get_object_store agent_releases");
            (
                StatusCode::SERVICE_UNAVAILABLE,
                format!(
                    "Object Store '{OBJECT_AGENT_RELEASES}' not found — the backend creates it at startup, so it was removed since or this broker is not the one expected; check `GET /api/jetstream/status` (restarting the backend recreates it)"
                ),
            )
        })?;

    // Always the latest release FOR THE REQUESTED PLATFORM by `modified`
    // (mirrors `agent_releases::list_releases` ordering) — a self-service
    // download offers no version choice, only os/arch.
    let key = {
        let metas = crate::projector::object_meta::list_bucket(&state.pool, OBJECT_AGENT_RELEASES)
            .await
            .map_err(|e| {
                warn!(error = %e, "object_store_meta list agent_releases");
                (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
            })?;
        let rows: Vec<(String, Option<String>)> =
            metas.into_iter().map(|m| (m.key, m.modified)).collect();
        match latest_key_for_platform(&rows, params.os, arch) {
            Some(k) => k,
            None => {
                let label = match params.os {
                    InstallerOs::Windows => "windows".to_string(),
                    InstallerOs::Linux => format!("linux-{}", arch.as_str()),
                    InstallerOs::Macos => format!("macos-{}", arch.as_str()),
                };
                return Err((
                    StatusCode::NOT_FOUND,
                    format!(
                        "no {label} agent releases in {OBJECT_AGENT_RELEASES} — publish one first \
                         (`kanade agent publish`)"
                    ),
                ));
            }
        }
    };
    check_version(&key)?;

    // The NATS coordinates baked into the archive come from the
    // server-settings document, NOT from the caller — a self-service
    // download user must never choose (or see) them.
    let settings = super::server_settings::load(&state).await.map_err(|e| {
        warn!(error = %format!("{e:#}"), "read server_settings for installer");
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("read server_settings: {e:#}"),
        )
    })?;
    let (nats_url, nats_token) = resolve_nats(&settings, &state.nats_url)?;
    let agent_toml = render_agent_toml(&nats_url)?;

    // Read the release binary. ~20 MB in memory is acceptable — the
    // publish path already buffers 64 MB multipart bodies.
    let mut obj = store.get(&key).await.map_err(|e| {
        let msg = e.to_string();
        if msg.contains("not found") || msg.contains("no objects") {
            return (
                StatusCode::NOT_FOUND,
                format!("release '{key}' not in Object Store"),
            );
        }
        warn!(error = %e, %key, "object_store.get");
        (StatusCode::INTERNAL_SERVER_ERROR, msg)
    })?;
    let mut exe = Vec::with_capacity(obj.info().size);
    obj.read_to_end(&mut exe).await.map_err(|e| {
        warn!(error = %e, %key, "read agent binary");
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("read agent binary '{key}': {e}"),
        )
    })?;

    // Archive assembly is CPU-bound (deflate/gzip over ~20 MB) — built in
    // a spawn_blocking closure below.
    //
    // When this backend signs commands, provision the fresh agent's ring with
    // THIS backend's own public key — nothing else — on every OS. Break-glass
    // keys are never bundled; an operator distributes those separately.
    let keyring = state.commands.keyring_entry();
    let command_keys = match &keyring {
        Some(entry) => Some(serde_json::to_string(&vec![entry]).map_err(|e| {
            warn!(error = %e, "serialize command keyring");
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
        })?),
        None => None,
    };
    let enforcement_requested = settings
        .agent_install
        .as_ref()
        .and_then(|ai| ai.require_signed_commands)
        .unwrap_or(false);
    let enforcement = resolve_enforcement(enforcement_requested, keyring.is_some());
    if enforcement == EnforcementPlan::RequestedButNoKey {
        warn!(
            %key,
            "installer: require_signed_commands is set but this backend has no command-signing \
             key — the generated installer will not enable enforcement"
        );
    }
    let (content_type, filename, payload, command_keys_embedded) = match params.os {
        InstallerOs::Windows => {
            let install_ps1 = render_install_ps1(
                &key,
                nats_token.as_deref(),
                command_keys.as_deref(),
                enforcement == EnforcementPlan::Embedded,
            );
            let install_cmd = render_install_cmd(&key);
            let readme = render_readme(&key, command_keys.is_some(), enforcement);
            let entries: Vec<(&str, Vec<u8>)> = vec![
                ("kanade-agent.exe", exe),
                ("agent.toml", agent_toml.into_bytes()),
                ("deploy-agent.ps1", DEPLOY_AGENT_PS1.as_bytes().to_vec()),
                ("install-agent.ps1", install_ps1.into_bytes()),
                ("install.cmd", install_cmd.into_bytes()),
                ("README.txt", readme.into_bytes()),
            ];
            let zip_bytes = tokio::task::spawn_blocking(move || build_zip(entries))
                .await
                .map_err(|e| {
                    warn!(error = %e, "installer zip task join");
                    (StatusCode::INTERNAL_SERVER_ERROR, format!("zip task: {e}"))
                })?
                .map_err(|e| {
                    warn!(error = %e, "build installer zip");
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("build installer zip: {e}"),
                    )
                })?;
            (
                "application/zip",
                format!("kanade-agent-installer-{key}.zip"),
                zip_bytes,
                command_keys.is_some(),
            )
        }
        InstallerOs::Linux | InstallerOs::Macos => {
            let entries = unix_tar_entries(
                params.os,
                &key,
                exe,
                agent_toml,
                nats_token.as_deref(),
                command_keys.as_deref(),
                enforcement,
            );
            let tgz_bytes = tokio::task::spawn_blocking(move || build_tar_gz(entries))
                .await
                .map_err(|e| {
                    warn!(error = %e, "installer tar task join");
                    (StatusCode::INTERNAL_SERVER_ERROR, format!("tar task: {e}"))
                })?
                .map_err(|e| {
                    warn!(error = %e, "build installer tarball");
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("build installer tarball: {e}"),
                    )
                })?;
            info!(%key, arch = arch.as_str(), "installer: tar.gz generated");
            (
                "application/gzip",
                format!("kanade-agent-installer-{key}.tar.gz"),
                tgz_bytes,
                command_keys.is_some(),
            )
        }
    };

    info!(%key, os = params.os.as_str(), nats_url = %nats_url, "installer: archive generated");

    audit::record(
        &state.nats,
        "operator",
        "agent_installer_download",
        Some(&key),
        Some(&caller),
        // NEVER the token itself — only that one was embedded.
        serde_json::json!({
            "version": key,
            "os": params.os.as_str(),
            "arch": arch.as_str(),
            "nats_url": nats_url,
            "token_embedded": nats_token.is_some(),
            "command_keys_embedded": command_keys_embedded,
        }),
    )
    .await;

    Ok((
        [
            (header::CONTENT_TYPE, content_type.to_string()),
            (
                header::CONTENT_DISPOSITION,
                format!("attachment; filename=\"{filename}\""),
            ),
        ],
        Body::from(payload),
    )
        .into_response())
}

// ─── GET /api/agents/installer.ps1 + installer.sh — one-liner scripts ───

/// `GET /api/agents/installer.ps1` — a generated PowerShell one-liner
/// installer: download the Windows ZIP (authenticated as the caller) into
/// a temp dir, extract, run `install-agent.ps1` — elevated via UAC for
/// just the install step when the caller isn't already admin. On failure
/// the temp dir is kept (only success deletes it) and the error names
/// `install.log` inside it: the elevated UAC console closes the instant
/// `install-agent.ps1` exits, so that transcript is the only place a
/// failure's real error text survives to be read.
pub async fn installer_ps1(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> Result<Response, (StatusCode, String)> {
    let (base, token) = script_context(&state, &headers)?;
    Ok((
        [(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
        render_installer_ps1(&base, &token),
    )
        .into_response())
}

/// `GET /api/agents/installer.sh` — a generated POSIX sh one-liner
/// installer for Linux AND macOS: map `uname -s` to a release OS and the
/// CPU to a release arch (`uname -m` on Linux; `sysctl hw.optional.arm64`
/// on macOS, Apple Silicon only), download that tar.gz (authenticated as
/// the caller), extract, run `install.sh`. Meant to be piped through sudo
/// (`curl … | sudo bash`).
pub async fn installer_sh(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> Result<Response, (StatusCode, String)> {
    let (base, token) = script_context(&state, &headers)?;
    Ok((
        [(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
        render_installer_sh(&base, &token),
    )
        .into_response())
}

/// The two values baked into a one-liner script: this backend's absolute
/// base URL and the caller's own Bearer token (so the script's inner
/// archive download authenticates as the same account that generated it —
/// the token expires with that session, which the script header says).
///
/// The base URL rule is exactly the account-email one
/// (`password_setup::link_base`): configured `[server] public_url` when
/// set, else derived from the request `Host` (+ `X-Forwarded-Proto`)
/// header. The `Host` fallback is acceptable here for the same reason it
/// is there: the caller is authenticated, so a spoofed Host only poisons
/// their own script.
fn script_context(
    state: &AppState,
    headers: &HeaderMap,
) -> Result<(String, String), (StatusCode, String)> {
    let base = super::password_setup::link_base(state.public_url.as_deref(), headers).ok_or((
        StatusCode::INTERNAL_SERVER_ERROR,
        "cannot derive the backend's base URL (no [server] public_url configured and no Host \
         header on the request) — set public_url in backend.toml"
            .to_string(),
    ))?;
    let token = bearer_token(headers).ok_or((
        StatusCode::BAD_REQUEST,
        "script generation requires a Bearer Authorization header".to_string(),
    ))?;
    Ok((base, token.to_string()))
}

/// The raw token out of an `Authorization: Bearer <token>` header, or
/// `None` when the header is missing, malformed, or empty. (The header
/// always exists on authenticated calls — `auth::verify` required it —
/// but a service-token or auth-disabled caller may present something
/// else, hence the graceful 400 path.)
fn bearer_token(headers: &HeaderMap) -> Option<&str> {
    headers
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .filter(|t| !t.is_empty())
}

/// The generated `installer.ps1` one-liner (CRLF line endings). `base`
/// and `token` are embedded as PowerShell single-quoted literals
/// ([`ps_quote`]), so a `'` in either can't break out.
fn render_installer_ps1(base: &str, token: &str) -> String {
    let zip_url = ps_quote(&format!("{base}/api/agents/installer"));
    let auth = ps_quote(&format!("Bearer {token}"));
    let mut s = String::new();
    s.push_str(
        "# kanade-agent one-liner installer (generated by kanade-backend — do not edit)\r\n",
    );
    s.push_str("# Installs the latest agent as a Windows service. The embedded token expires\r\n");
    s.push_str("# with the issuer's session.\r\n");
    s.push_str("$ErrorActionPreference = 'Stop'\r\n");
    s.push_str("$tmp = Join-Path $env:TEMP ('kanade-agent-install-' + [guid]::NewGuid())\r\n");
    s.push_str("New-Item -ItemType Directory -Path $tmp | Out-Null\r\n");
    s.push_str("$zip = Join-Path $tmp 'installer.zip'\r\n");
    s.push_str("try {\r\n");
    s.push_str(&format!(
        "    Invoke-WebRequest -Uri {zip_url} -Headers @{{ Authorization = {auth} }} -OutFile $zip\r\n"
    ));
    s.push_str("    Expand-Archive -Path $zip -DestinationPath $tmp\r\n");
    s.push_str("    $installScript = Join-Path $tmp 'install-agent.ps1'\r\n");
    s.push_str("    $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)\r\n");
    s.push_str("    if ($isAdmin) {\r\n");
    s.push_str("        & $installScript\r\n");
    s.push_str("        $code = $LASTEXITCODE\r\n");
    s.push_str("    } else {\r\n");
    s.push_str("        # Elevate ONLY the install step (UAC prompt); the download above\r\n");
    s.push_str(
        "        # already ran unelevated, so the token never reaches an admin process.\r\n",
    );
    s.push_str("        $proc = Start-Process powershell -Verb RunAs -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File',\"`\"$installScript`\"\" -Wait -PassThru\r\n");
    s.push_str("        $code = $proc.ExitCode\r\n");
    s.push_str("    }\r\n");
    s.push_str("    if ($code -ne 0) { throw \"install failed (exit $code)\" }\r\n");
    s.push_str("    Write-Host \"kanade-agent installed.\"\r\n");
    s.push_str("    Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue\r\n");
    s.push_str("} catch {\r\n");
    s.push_str("    # Covers every failure path (download, extract, admin-direct throw,\r\n");
    s.push_str("    # and the exit-code check above): $tmp survives so there's something\r\n");
    s.push_str("    # to inspect, and install.log is named only once it actually exists.\r\n");
    s.push_str("    $log = Join-Path $tmp 'install.log'\r\n");
    s.push_str(
        "    $hint = if (Test-Path $log) { \" See $log for details.\" } else { \" Installer files kept at $tmp.\" }\r\n",
    );
    s.push_str("    throw \"$($_.Exception.Message)$hint\"\r\n");
    s.push_str("}\r\n");
    s
}

/// The generated `installer.sh` one-liner (LF line endings). `base` and
/// `token` are embedded as POSIX single-quoted literals ([`sh_quote`]).
/// One script for both unix platforms: `uname -s` picks the archive
/// (Linux → `os=linux`, Darwin → `os=macos`). On Linux `uname -m` picks
/// the arch. On macOS only Apple Silicon is supported, and `uname -m` is
/// NOT trusted there — a Rosetta-translated shell reports `x86_64` on an
/// Apple Silicon Mac — so the script asks `sysctl -n hw.optional.arm64`
/// (`1` on Apple Silicon even under Rosetta, absent/`0` on Intel) and
/// refuses Intel Macs outright. Everything it runs exists on a stock
/// macOS too (`mktemp -d`, `sysctl`, bsdtar's `tar xzf`, curl).
fn render_installer_sh(base: &str, token: &str) -> String {
    let url_os = sh_quote(&format!("{base}/api/agents/installer?os="));
    let url_arch = sh_quote("&arch=");
    // The token rides a curl config heredoc (`-K -`), NOT a `-H` flag: a
    // process's argv is readable by every local user (/proc/<pid>/cmdline
    // on Linux, `ps` on macOS), so a header on the command line would
    // expose the session token to all of them. Escape the two bytes that
    // could break out of the double-quoted config value.
    let token_cfg = token.replace('\\', "\\\\").replace('"', "\\\"");
    let mut s = String::new();
    s.push_str("#!/bin/sh\n");
    s.push_str("# kanade-agent one-liner installer (generated by kanade-backend — do not edit)\n");
    s.push_str("# Meant to be run via the one-liner on the Agent Install page\n");
    s.push_str(&format!(
        "#   ({base}/agent-install — piped through `sudo bash`).\n"
    ));
    s.push_str("# Linux (systemd) and macOS (launchd) alike.\n");
    s.push_str("# install.sh needs root; without the sudo pipe it fails there by design.\n");
    s.push_str("# The embedded token expires with the issuer's session.\n");
    s.push_str("set -eu\n");
    s.push_str("case \"$(uname -s)\" in\n");
    s.push_str("    Linux)\n");
    s.push_str("        OS=linux\n");
    s.push_str("        case \"$(uname -m)\" in\n");
    s.push_str("            x86_64) ARCH=x86_64 ;;\n");
    s.push_str("            aarch64|arm64) ARCH=aarch64 ;;\n");
    s.push_str("            *) echo \"unsupported architecture: $(uname -m)\" >&2; exit 1 ;;\n");
    s.push_str("        esac\n");
    s.push_str("        ;;\n");
    s.push_str("    Darwin)\n");
    s.push_str("        OS=macos\n");
    // `uname -m` lies under Rosetta (x86_64 on Apple Silicon); the sysctl
    // reports the hardware.
    s.push_str(
        "        if [ \"$(sysctl -n hw.optional.arm64 2>/dev/null || true)\" = \"1\" ]; then\n",
    );
    s.push_str("            ARCH=aarch64\n");
    s.push_str("        else\n");
    s.push_str("            echo \"Intel Macs are not supported — kanade supports Apple Silicon Macs only\" >&2\n");
    s.push_str("            exit 1\n");
    s.push_str("        fi\n");
    s.push_str("        ;;\n");
    s.push_str("    *) echo \"unsupported OS: $(uname -s)\" >&2; exit 1 ;;\n");
    s.push_str("esac\n");
    s.push_str("TMP=\"$(mktemp -d)\"\n");
    s.push_str("trap 'rm -rf \"$TMP\"' EXIT\n");
    // The os/arch vars sit OUTSIDE the single-quoted URL pieces so the
    // shell expands them; the base half stays literal-safe.
    s.push_str(&format!(
        "curl -fsSL -K - -o \"$TMP/installer.tar.gz\" {url_os}\"$OS\"{url_arch}\"$ARCH\" <<'KANADE_CURL_CONFIG'\n"
    ));
    s.push_str(&format!("header = \"Authorization: Bearer {token_cfg}\"\n"));
    s.push_str("KANADE_CURL_CONFIG\n");
    s.push_str("tar xzf \"$TMP/installer.tar.gz\" -C \"$TMP\"\n");
    s.push_str("sh \"$TMP/install.sh\"\n");
    s.push_str("echo \"kanade-agent installed.\"\n");
    s
}

/// The latest key (by `modified`, desc) belonging to the requested
/// platform. `rows` are `(key, modified)` pairs from the object_meta
/// index. Pure so the per-platform filtering is testable without a DB.
fn latest_key_for_platform(
    rows: &[(String, Option<String>)],
    os: InstallerOs,
    arch: InstallerArch,
) -> Option<String> {
    let mut matches: Vec<&(String, Option<String>)> = rows
        .iter()
        .filter(|(key, _)| key_matches_platform(key, os, arch))
        .collect();
    matches.sort_by(|a, b| b.1.cmp(&a.1));
    matches.first().map(|(k, _)| k.clone())
}

/// Whether a store key belongs to the requested platform, by SUFFIX only
/// (semver prerelease dashes mid-version are never parsed — see
/// kanade_shared::bin_platform). macOS keys exist for aarch64 only, so
/// macOS + x86_64 matches nothing (the handler rejects it earlier anyway).
fn key_matches_platform(key: &str, os: InstallerOs, arch: InstallerArch) -> bool {
    match os {
        InstallerOs::Windows => platform_of_key(key) == "windows",
        InstallerOs::Linux => key.ends_with(arch.linux_suffix()),
        InstallerOs::Macos => arch == InstallerArch::Aarch64 && key.ends_with(MACOS_SUFFIX_AARCH64),
    }
}

/// What the ZIP bakes in for NATS: the `agent_install` section of the
/// server-settings document where set, else this backend's own `[nats] url`
/// and no token. Split out pure so the fallback/validation rules are
/// testable without a broker.
///
/// A stored `nats_url` that fails the TOML literal-string rules (validated
/// at PUT, but a hand-written KV value can bypass that) is a 500 naming the
/// Settings page — NOT a silent fallback, which would ship installers that
/// dial a different broker than the operator configured.
fn resolve_nats(
    settings: &ServerSettings,
    backend_url: &str,
) -> Result<(String, Option<String>), (StatusCode, String)> {
    let Some(ai) = settings.agent_install.as_ref() else {
        return Ok((backend_url.to_string(), None));
    };
    let url = match ai.nats_url.as_deref() {
        Some(u) if u.is_empty() || u.contains('\'') || u.contains('\n') || u.contains('\r') => {
            return Err((
                StatusCode::INTERNAL_SERVER_ERROR,
                "server_settings agent_install.nats_url is invalid (must be non-empty, with no \
                 single quote or newline) — fix it on the Settings page"
                    .into(),
            ));
        }
        Some(u) => u.to_string(),
        None => backend_url.to_string(),
    };
    // An empty stored token (a hand-written KV value bypassing PUT
    // validation) is no token: embedding `-NatsToken ''` would hand
    // deploy-agent.ps1 an empty-string argument, and the audit record
    // would claim a token was embedded when none was.
    let token = ai.nats_token.clone().filter(|t| !t.is_empty());
    Ok((url, token))
}

/// The store key reaches several sinks that tolerate no hostile bytes: a
/// quoted `Content-Disposition` filename, a PowerShell `#` comment, batch
/// `REM`/`echo` lines, and shell scripts. Keys can also be written
/// directly over NATS, while the PE VERSIONINFO extraction only trims
/// whitespace — so the charset is restricted (semver-ish) rather than
/// escaping four different formats. The rule itself lives in
/// kanade_shared::bin_platform, shared with the publish endpoints.
fn check_version(version: &str) -> Result<(), (StatusCode, String)> {
    kanade_shared::bin_platform::check_release_key(version)
        .map_err(|e| (StatusCode::BAD_REQUEST, e))
}

/// `agent.toml` with the loopback `nats_url` line rewritten to `nats_url`.
///
/// The value goes into a TOML literal string (single quotes, no escape
/// sequences), so a `'` or newline in the URL would either corrupt the
/// document or inject extra config lines — reject both (400) rather than
/// trying to escape a format that has no escapes.
fn render_agent_toml(nats_url: &str) -> Result<String, (StatusCode, String)> {
    if nats_url.is_empty() {
        return Err((StatusCode::BAD_REQUEST, "nats_url must not be empty".into()));
    }
    if nats_url.contains('\'') || nats_url.contains('\n') || nats_url.contains('\r') {
        return Err((
            StatusCode::BAD_REQUEST,
            "nats_url must not contain a single quote or newline (TOML literal-string safety)"
                .into(),
        ));
    }
    if !AGENT_TOML_TEMPLATE.contains(NATS_URL_LINE) {
        warn!("configs/agent.toml no longer contains the expected nats_url line");
        return Err((
            StatusCode::INTERNAL_SERVER_ERROR,
            format!(
                "configs/agent.toml template changed — expected line `{NATS_URL_LINE}` not found; \
                 update the installer rewrite to match"
            ),
        ));
    }
    Ok(AGENT_TOML_TEMPLATE.replacen(NATS_URL_LINE, &format!("nats_url = '{nats_url}'"), 1))
}

/// A PowerShell single-quoted literal: escape `'` by doubling it.
fn ps_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "''"))
}

/// What the installer should do about `-RequireSignedCommands`, decided
/// from the two inputs that matter and nothing else — kept pure and
/// separate from the request handler for the same reason `resolve_kid` in
/// `kanade-backend`'s `main.rs` is: a decision worth getting right deserves
/// a test that doesn't need a running server.
///
/// `RequestedButNoKey` is its own outcome, not folded into `Off`, because
/// those two cases must be told apart downstream. Settings asking for
/// enforcement while this backend has no signing key configured is a
/// misconfiguration, not a "nothing to do" — silently generating an
/// installer that behaves like `Off` would let an operator believe a fresh
/// fleet is protected when not one machine actually is. The empty-keyring
/// fallback in `command_verify.rs` (an enforcing agent with no keys
/// declines to enforce, rather than refusing everything) protects hosts
/// that already got such an installer; it is not a reason to keep handing
/// out more of them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EnforcementPlan {
    /// Not requested — `-RequireSignedCommands` is omitted, same as today.
    Off,
    /// Requested, and this backend has a signing key to back it: embed
    /// `-RequireSignedCommands` alongside the `-CommandKeys` ring.
    Embedded,
    /// Requested, but this backend has no signing key — embedding the
    /// switch here would ask a fresh agent to enforce against an empty
    /// ring, which the agent declines to do (see `command_verify.rs`), so
    /// the request would be silently inert. Surfaced in README.txt instead
    /// of being dropped without a trace.
    RequestedButNoKey,
}

fn resolve_enforcement(requested: bool, key_present: bool) -> EnforcementPlan {
    match (requested, key_present) {
        (false, _) => EnforcementPlan::Off,
        (true, true) => EnforcementPlan::Embedded,
        (true, false) => EnforcementPlan::RequestedButNoKey,
    }
}

/// The generated `install-agent.ps1` wrapper. All real work stays in
/// `deploy-agent.ps1`; this only pins the version banner, the provisioned
/// knobs (`-NatsToken`, `-CommandKeys`, `-RequireSignedCommands`, each
/// omitted from the invocation entirely when not provided/requested), and a
/// transcript to `install.log` next to the script. The transcript exists
/// because the one-liner's UAC-elevated console (see
/// [`render_installer_ps1`]) closes the instant this script exits, taking
/// any on-screen error with it — `install.log` is what's left to read
/// afterward. CRLF line endings like every other Windows-facing file in the
/// ZIP.
fn render_install_ps1(
    version: &str,
    nats_token: Option<&str>,
    command_keys: Option<&str>,
    require_signed_commands: bool,
) -> String {
    let mut args = String::new();
    if let Some(token) = nats_token {
        args.push_str(&format!(" -NatsToken {}", ps_quote(token)));
    }
    if let Some(keys) = command_keys {
        args.push_str(&format!(" -CommandKeys {}", ps_quote(keys)));
    }
    if require_signed_commands {
        args.push_str(" -RequireSignedCommands");
    }
    format!(
        "# Generated by kanade-backend — do not edit.\r\n\
         # Installs kanade-agent {version} as a Windows service. Run as Administrator.\r\n\
         $ErrorActionPreference = 'Stop'\r\n\
         Start-Transcript -Path (Join-Path $PSScriptRoot 'install.log') -Force | Out-Null\r\n\
         try {{\r\n\
         \x20   & (Join-Path $PSScriptRoot 'deploy-agent.ps1'){args}\r\n\
         \x20   exit $LASTEXITCODE\r\n\
         }} finally {{\r\n\
         \x20   Stop-Transcript | Out-Null\r\n\
         }}\r\n"
    )
}

/// The generated `install.cmd` double-click bootstrap. MUST be CRLF
/// throughout — cmd.exe's parser misparses LF-only batch files inside
/// parenthesized blocks. Echo lines deliberately avoid `&` (a command
/// separator even inside most quoting) and parentheses outside the
/// `if errorlevel` block.
fn render_install_cmd(version: &str) -> String {
    let mut s = String::new();
    s.push_str("@echo off\r\n");
    s.push_str(&format!(
        "REM kanade-agent installer (generated by kanade-backend). Installs kanade-agent {version}.\r\n"
    ));
    s.push_str(
        "powershell -NoProfile -ExecutionPolicy Bypass -File \"%~dp0install-agent.ps1\"\r\n",
    );
    s.push_str("if errorlevel 1 (\r\n");
    s.push_str("  echo.\r\n");
    s.push_str("  echo INSTALL FAILED - see the output above.\r\n");
    s.push_str("  pause\r\n");
    s.push_str("  exit /b 1\r\n");
    s.push_str(")\r\n");
    s.push_str("echo.\r\n");
    s.push_str(&format!("echo kanade-agent {version} installed.\r\n"));
    s.push_str("pause\r\n");
    s
}

/// `README.txt` — the contents list plus the two-step install. Mentions
/// the embedded command-signing PUBLIC key when the backend signs, so the
/// operator knows what the ZIP carries (and what it deliberately does
/// not: break-glass keys). `enforcement` additionally calls out
/// `-RequireSignedCommands` when embedded, and — when settings asked for it
/// but no signing key exists — surfaces that loudly rather than shipping an
/// installer that silently omits the protection the operator thinks they
/// turned on.
fn render_readme(version: &str, signing: bool, enforcement: EnforcementPlan) -> String {
    let signing_note = if signing {
        "This ZIP embeds the backend's command-signing PUBLIC key (provisioned\r\n\
         into the agent's keyring by the installer, so signed commands verify\r\n\
         from first boot). Public keys are not secrets. Break-glass keys are\r\n\
         NEVER included in this ZIP — distribute those separately.\r\n"
    } else {
        "The backend that generated this ZIP is not signing commands, so no\r\n\
         command-signing keyring is provisioned by the installer.\r\n"
    };
    let enforcement_note = match enforcement {
        EnforcementPlan::Off => "",
        EnforcementPlan::Embedded => {
            "\r\nThis installer passes -RequireSignedCommands: the agent will REFUSE any\r\n\
             command it cannot verify against the embedded keyring, starting from\r\n\
             first boot.\r\n"
        }
        EnforcementPlan::RequestedButNoKey => {
            "\r\n*** WARNING: RequireSignedCommands was requested in server settings, but\r\n\
             *** this backend has no command-signing key configured, so this installer\r\n\
             *** does NOT enable enforcement — an agent enforcing against an empty\r\n\
             *** keyring would just decline to enforce, which is not what was asked for.\r\n\
             *** Run `kanade-backend command-key-generate` on the backend host, then\r\n\
             *** re-download this installer.\r\n"
        }
    };
    let mut s = String::new();
    s.push_str(&format!("kanade-agent installer (version {version})\r\n"));
    s.push_str("==========================================\r\n");
    s.push_str("\r\n");
    s.push_str("Contents:\r\n");
    s.push_str("\r\n");
    s.push_str(&format!(
        "  kanade-agent.exe   the agent binary (release {version})\r\n"
    ));
    s.push_str("  agent.toml         agent configuration (NATS URL baked in)\r\n");
    s.push_str("  deploy-agent.ps1   the canonical install/update script\r\n");
    s.push_str("  install-agent.ps1  generated wrapper (tokens and keys baked in)\r\n");
    s.push_str("  install.cmd        double-click bootstrap\r\n");
    s.push_str("  README.txt         this file\r\n");
    s.push_str("\r\n");
    s.push_str("Install:\r\n");
    s.push_str("\r\n");
    s.push_str("  1. Extract this ZIP to a folder on the target PC.\r\n");
    s.push_str("  2. Right-click install.cmd and choose \"Run as administrator\".\r\n");
    s.push_str("\r\n");
    s.push_str("Re-running the installer upgrades the agent in place.\r\n");
    s.push_str("\r\n");
    s.push_str(signing_note);
    s.push_str(enforcement_note);
    s
}

/// Assemble the installer ZIP in memory. Pure/blocking — the handler runs
/// it under `spawn_blocking` (deflate over ~20 MB of exe is CPU-bound).
fn build_zip(entries: Vec<(&str, Vec<u8>)>) -> Result<Vec<u8>, zip::result::ZipError> {
    use std::io::Write as _;
    use zip::write::SimpleFileOptions;

    let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::<u8>::new()));
    let opts = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
    for (name, data) in entries {
        zw.start_file(name, opts)?;
        zw.write_all(&data)?;
    }
    Ok(zw.finish()?.into_inner())
}

/// One entry of a Linux/macOS installer tarball: path (relative to the
/// extraction root, matching the layout the setup script expects around
/// itself), permission bits, and bytes.
struct TarEntry {
    name: &'static str,
    mode: u32,
    data: Vec<u8>,
}

impl TarEntry {
    fn new(name: &'static str, mode: u32, data: Vec<u8>) -> Self {
        Self { name, mode, data }
    }
}

/// The Linux/macOS tarball's entries. Same shape on both — the binary +
/// config, the OS's service definition, its canonical setup script, and
/// the generated `install.sh` that hands over to it — only the service
/// definition, the setup script's name, and the README differ. `os` is
/// Linux or macOS; the handler never calls this for Windows (and a
/// Windows value falls through to the Linux shape).
fn unix_tar_entries(
    os: InstallerOs,
    key: &str,
    exe: Vec<u8>,
    agent_toml: String,
    nats_token: Option<&str>,
    command_keys: Option<&str>,
    enforcement: EnforcementPlan,
) -> Vec<TarEntry> {
    let (service_entry, setup_name, setup_script, service_kind, readme) =
        if os == InstallerOs::Macos {
            (
                TarEntry::new(
                    "launchd/com.kanade.agent.plist",
                    0o644,
                    AGENT_PLIST.as_bytes().to_vec(),
                ),
                "setup-agent-macos.sh",
                SETUP_AGENT_MACOS_SH,
                "a launchd daemon",
                render_readme_macos(key, command_keys.is_some(), enforcement),
            )
        } else {
            (
                TarEntry::new(
                    "systemd/kanade-agent.service",
                    0o644,
                    AGENT_SERVICE.as_bytes().to_vec(),
                ),
                "setup-agent.sh",
                SETUP_AGENT_SH,
                "a systemd service",
                render_readme_linux(key, command_keys.is_some(), enforcement),
            )
        };
    let install_sh = render_install_sh(
        nats_token,
        command_keys,
        enforcement == EnforcementPlan::Embedded,
        setup_name,
        service_kind,
    );
    vec![
        TarEntry::new("bin/kanade-agent", 0o755, exe),
        TarEntry::new("etc/agent.toml", 0o644, agent_toml.into_bytes()),
        service_entry,
        TarEntry::new(setup_name, 0o755, setup_script.as_bytes().to_vec()),
        TarEntry::new("install.sh", 0o755, install_sh.into_bytes()),
        TarEntry::new("README.txt", 0o644, readme.into_bytes()),
    ]
}

/// Assemble a Linux/macOS installer tar.gz in memory. Pure/blocking — the
/// handler runs it under `spawn_blocking` (gzip over ~20 MB of binary is
/// CPU-bound). Modes are set explicitly per entry: the exec bit on
/// `bin/kanade-agent`, `setup-agent.sh` and `install.sh` is what lets the
/// README say `sudo ./install.sh` instead of `sudo bash install.sh` (a
/// Windows-built tar without it is exactly why setup-agent.sh documents
/// `bash ./setup-agent.sh`).
fn build_tar_gz(entries: Vec<TarEntry>) -> std::io::Result<Vec<u8>> {
    let enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
    let mut builder = tar::Builder::new(enc);
    for entry in &entries {
        let mut header = tar::Header::new_gnu();
        header.set_size(entry.data.len() as u64);
        header.set_mode(entry.mode);
        // Reproducible output: no build-machine mtime baked in.
        header.set_mtime(0);
        header.set_cksum();
        builder.append_data(&mut header, entry.name, entry.data.as_slice())?;
    }
    let enc = builder.into_inner()?;
    enc.finish()
}

/// A POSIX shell single-quoted literal: `'` → `'\''` (close, escaped
/// quote, reopen). Newlines never reach here — the settings PUT rejects
/// them in `nats_token`.
fn sh_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

/// The generated `install.sh` wrapper (LF endings, 0755). All real work
/// stays in the canonical setup script (`setup_script`: `setup-agent.sh`
/// on Linux, `setup-agent-macos.sh` on macOS; `service` names what it
/// installs, for the header comment); this only provisions the token from
/// the backend's settings — plus, when this backend signs commands, its
/// command-signing public key as `KANADE_COMMAND_KEYS` and (when the
/// require-signed-commands setting is on) `KANADE_REQUIRE_SIGNED_COMMANDS=1`,
/// each omitted entirely when not provided/requested — and hands over.
/// `KANADE_NATS_URL` is
/// deliberately NOT exported: the baked `etc/agent.toml` already carries
/// it, and both setup scripts only rewrite the url when the env var is
/// set — leaving it unset keeps the "preserve an existing deployment's
/// broker on redeploy" logic intact.
fn render_install_sh(
    nats_token: Option<&str>,
    command_keys: Option<&str>,
    require_signed_commands: bool,
    setup_script: &str,
    service: &str,
) -> String {
    let mut s = String::new();
    s.push_str("#!/bin/sh\n");
    s.push_str("# Generated by kanade-backend — do not edit.\n");
    s.push_str(&format!(
        "# Installs kanade-agent as {service}. Run as root (sudo).\n"
    ));
    s.push_str("set -eu\n");
    s.push_str("cd \"$(dirname \"$0\")\"\n");
    if let Some(token) = nats_token {
        s.push_str(&format!("export KANADE_NATS_TOKEN={}\n", sh_quote(token)));
    }
    if let Some(keys) = command_keys {
        s.push_str(&format!("export KANADE_COMMAND_KEYS={}\n", sh_quote(keys)));
    }
    if require_signed_commands {
        s.push_str("export KANADE_REQUIRE_SIGNED_COMMANDS=1\n");
    }
    s.push_str(&format!("exec ./{setup_script}\n"));
    s
}

/// The command-signing / enforcement paragraph of the Linux and macOS
/// READMEs, the LF counterpart of the notes in [`render_readme`]. `keyring` is
fn unix_signing_note(signing: bool, enforcement: EnforcementPlan) -> String {
    let mut s = String::new();
    if signing {
        s.push_str(
            "This tarball embeds the backend's command-signing PUBLIC key (provisioned\n\
             into the agent's keyring by the installer, so signed commands verify\n\
             from first boot). Public keys are not secrets. Break-glass keys are\n\
             NEVER included in this tarball — distribute those separately.\n",
        );
    } else {
        s.push_str(
            "The backend that generated this tarball is not signing commands, so no\n\
             command-signing keyring is provisioned by the installer.\n",
        );
    }
    match enforcement {
        EnforcementPlan::Off => {}
        EnforcementPlan::Embedded => s.push_str(
            "\nThis installer sets KANADE_REQUIRE_SIGNED_COMMANDS=1: the agent will REFUSE\n\
             any command it cannot verify against the embedded keyring, starting from\n\
             first boot.\n",
        ),
        EnforcementPlan::RequestedButNoKey => s.push_str(
            "\n*** WARNING: RequireSignedCommands was requested in server settings, but\n\
             *** this backend has no command-signing key configured, so this installer\n\
             *** does NOT enable enforcement — an agent enforcing against an empty\n\
             *** keyring would just decline to enforce, which is not what was asked for.\n\
             *** Run `kanade-backend command-key-generate` on the backend host, then\n\
             *** re-download this installer.\n",
        ),
    }
    s
}

/// Linux `README.txt` — the contents list plus extract/install steps and the
/// command-signing state (see [`unix_signing_note`]).
fn render_readme_linux(key: &str, signing: bool, enforcement: EnforcementPlan) -> String {
    let mut s = String::new();
    s.push_str(&format!("kanade-agent installer (release {key})\n"));
    s.push_str("=================================================\n");
    s.push('\n');
    s.push_str("Contents:\n");
    s.push('\n');
    s.push_str("  bin/kanade-agent              the agent binary\n");
    s.push_str("  etc/agent.toml                agent configuration (NATS URL baked in)\n");
    s.push_str("  systemd/kanade-agent.service  the systemd unit\n");
    s.push_str("  setup-agent.sh                the canonical install/update script\n");
    s.push_str("  install.sh                    generated wrapper (token baked in, if any)\n");
    s.push_str("  README.txt                    this file\n");
    s.push('\n');
    s.push_str("Install:\n");
    s.push('\n');
    s.push_str("  1. Extract this tarball on the target machine and enter the\n");
    s.push_str("     directory, e.g.:\n");
    s.push_str("       mkdir kanade-agent-installer && cd kanade-agent-installer\n");
    s.push_str(&format!(
        "       tar xzf ../kanade-agent-installer-{key}.tar.gz\n"
    ));
    s.push_str("  2. Run the installer as root:\n");
    s.push_str("       sudo ./install.sh\n");
    s.push('\n');
    s.push_str("Re-running the installer upgrades the agent in place (an existing\n");
    s.push_str("/etc/kanade/agent.env token and broker URL are preserved).\n");
    s.push('\n');
    s.push_str(&unix_signing_note(signing, enforcement));
    s
}

/// macOS `README.txt` — the Linux README's shape, plus the Gatekeeper /
/// code-signing facts an operator hits on a Mac.
fn render_readme_macos(key: &str, signing: bool, enforcement: EnforcementPlan) -> String {
    let mut s = String::new();
    s.push_str(&format!("kanade-agent installer (release {key})\n"));
    s.push_str("=================================================\n");
    s.push('\n');
    s.push_str("Contents:\n");
    s.push('\n');
    s.push_str("  bin/kanade-agent                the agent binary\n");
    s.push_str("  etc/agent.toml                  agent configuration (NATS URL baked in)\n");
    s.push_str("  launchd/com.kanade.agent.plist  the LaunchDaemon definition\n");
    s.push_str("  setup-agent-macos.sh            the canonical install/update script\n");
    s.push_str("  install.sh                      generated wrapper (token baked in, if any)\n");
    s.push_str("  README.txt                      this file\n");
    s.push('\n');
    s.push_str("Install:\n");
    s.push('\n');
    s.push_str("  1. Extract this tarball on the target Mac and enter the directory,\n");
    s.push_str("     e.g. in Terminal:\n");
    s.push_str("       mkdir kanade-agent-installer && cd kanade-agent-installer\n");
    s.push_str(&format!(
        "       tar xzf ../kanade-agent-installer-{key}.tar.gz\n"
    ));
    s.push_str("  2. Run the installer as root:\n");
    s.push_str("       sudo ./install.sh\n");
    s.push('\n');
    s.push_str("The agent runs as the LaunchDaemon com.kanade.agent\n");
    s.push_str("(/Library/LaunchDaemons/com.kanade.agent.plist), binary at\n");
    s.push_str("/usr/local/bin/kanade-agent, config + token under /etc/kanade, logs\n");
    s.push_str("under /var/log/kanade. Check it with:\n");
    s.push_str("       sudo launchctl print system/com.kanade.agent\n");
    s.push('\n');
    s.push_str("Re-running the installer upgrades the agent in place (an existing\n");
    s.push_str("/etc/kanade/agent.env token and broker URL are preserved).\n");
    s.push('\n');
    s.push_str("Gatekeeper: the agent binary is not notarized. A tarball downloaded\n");
    s.push_str("with a browser carries the com.apple.quarantine attribute; the\n");
    s.push_str("installer clears it from the installed binary, and launchd runs the\n");
    s.push_str("unsigned command-line binary without a Gatekeeper prompt. Apple\n");
    s.push_str("Silicon still requires at least an ad-hoc code signature, which the\n");
    s.push_str("Rust toolchain's linker applies; a binary modified after the build\n");
    s.push_str("must be re-signed (codesign --force --sign - <binary>).\n");
    s.push('\n');
    s.push_str(&unix_signing_note(signing, enforcement));
    s
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The six `assets/` files are copies; this is what keeps them honest.
    ///
    /// Editing `configs/agent.toml` or one of the install scripts and not the
    /// copy would ship an installer that disagrees with the script an
    /// operator runs by hand — the exact drift the old out-of-crate
    /// `include_str!` made impossible, and the only thing it bought. Pairing
    /// them here restores that guarantee at the cost of a failing test
    /// instead of a silent divergence.
    ///
    /// This compiles only in the workspace. `cargo package` builds the lib
    /// and bins, not tests, so the originals being absent from the published
    /// tarball cannot break the verification build (#1364) — kanade-shared
    /// has carried test-only `include_str!`s of workspace files for as long
    /// and has always published cleanly.
    #[test]
    fn assets_match_the_workspace_originals() {
        for (copy, original, path) in [
            (
                AGENT_TOML_TEMPLATE,
                include_str!("../../../../configs/agent.toml"),
                "configs/agent.toml",
            ),
            (
                DEPLOY_AGENT_PS1,
                include_str!("../../../../scripts/deploy/agent.ps1"),
                "scripts/deploy/agent.ps1",
            ),
            (
                SETUP_AGENT_SH,
                include_str!("../../../../deploy/linux/setup-agent.sh"),
                "deploy/linux/setup-agent.sh",
            ),
            (
                AGENT_SERVICE,
                include_str!("../../../../deploy/linux/systemd/kanade-agent.service"),
                "deploy/linux/systemd/kanade-agent.service",
            ),
            (
                SETUP_AGENT_MACOS_SH,
                include_str!("../../../../deploy/macos/setup-agent.sh"),
                "deploy/macos/setup-agent.sh",
            ),
            (
                AGENT_PLIST,
                include_str!("../../../../deploy/macos/launchd/com.kanade.agent.plist"),
                "deploy/macos/launchd/com.kanade.agent.plist",
            ),
        ] {
            assert_eq!(
                copy, original,
                "crates/kanade-backend/assets/ has drifted from {path} — copy it across",
            );
        }
    }

    #[test]
    fn agent_toml_url_line_is_rewritten() {
        let out = render_agent_toml("nats://broker.corp:4222").unwrap();
        assert!(out.contains("nats_url = 'nats://broker.corp:4222'"));
        assert!(!out.contains(NATS_URL_LINE));
        // Everything else is byte-identical to the template: one line
        // differs, nothing more.
        let template_lines: Vec<&str> = AGENT_TOML_TEMPLATE.lines().collect();
        let out_lines: Vec<&str> = out.lines().collect();
        assert_eq!(template_lines.len(), out_lines.len());
        let differing = template_lines
            .iter()
            .zip(&out_lines)
            .filter(|(a, b)| a != b)
            .count();
        assert_eq!(differing, 1);
    }

    #[test]
    fn version_charset_is_restricted() {
        // Mirrors agent_toml_rejects_literal_string_injection: the version
        // is spliced into a ps1 `#` comment, batch REM/echo lines, and a
        // quoted Content-Disposition filename — a newline or quote in an
        // Object Store key must be a 400, not code execution on install.
        for bad in [
            "",
            "0.43.99\n evil",
            "0.43.99\revil",
            "0.43.99\"x",
            "0.43.99'x",
            "0.43.99&del",
            "0.43.99%PATH%",
        ] {
            let (code, _) = check_version(bad).unwrap_err();
            assert_eq!(code, StatusCode::BAD_REQUEST, "{bad:?}");
        }
        for good in ["0.43.99", "0.43.99-rc.1+build.5", "1.0.0_alpha"] {
            check_version(good).unwrap();
        }
    }

    #[test]
    fn agent_toml_rejects_literal_string_injection() {
        // A quote would terminate the TOML literal string early and let the
        // rest of the value rewrite the document; a newline would inject
        // whole extra lines. Both are 400s, not escapes — TOML literal
        // strings have no escape sequences.
        for bad in [
            "nats://evil'\n[agent]\nid='x'",
            "nats://a\nb",
            "nats://a\rb",
        ] {
            let (code, _) = render_agent_toml(bad).unwrap_err();
            assert_eq!(code, StatusCode::BAD_REQUEST, "{bad:?}");
        }
        let (code, _) = render_agent_toml("").unwrap_err();
        assert_eq!(code, StatusCode::BAD_REQUEST);
    }

    #[test]
    fn installer_ps1_embeds_base_and_token_crlf_only() {
        let out = render_installer_ps1("https://kanade.example.com", "tok-123");
        assert!(
            out.contains(
                "Invoke-WebRequest -Uri 'https://kanade.example.com/api/agents/installer'"
            )
        );
        assert!(out.contains("-Headers @{ Authorization = 'Bearer tok-123' }"));
        assert!(out.contains("Expand-Archive"));
        assert!(out.contains("-Verb RunAs"));
        assert!(out.contains("$LASTEXITCODE"));
        assert!(out.contains("token expires"));
        // CRLF throughout — no bare LF (PowerShell tolerates LF, but the
        // file is Windows-facing like every other ps1 we generate).
        for (i, b) in out.bytes().enumerate() {
            if b == b'\n' {
                assert!(
                    i > 0 && out.as_bytes()[i - 1] == b'\r',
                    "bare LF at byte {i}"
                );
            }
        }
    }

    #[test]
    fn installer_ps1_doubles_single_quotes_in_embeds() {
        // An unescaped quote in the token would terminate the literal and
        // let the rest run as script.
        let out = render_installer_ps1("https://k", "it's");
        assert!(out.contains("Authorization = 'Bearer it''s'"));
    }

    #[test]
    fn installer_ps1_keeps_tmp_and_points_at_log_on_failure() {
        // The elevated UAC console closes the instant install-agent.ps1
        // exits, so on failure nothing on-screen survives -- the error
        // must name install.log, and cleanup must be skipped so it's
        // still there to read (only the success path removes $tmp).
        let out = render_installer_ps1("https://kanade.example.com", "tok-123");
        assert!(out.contains("install.log"));
        assert!(out.contains("throw \"install failed (exit $code)"));
        assert!(out.contains("} catch {"));
        assert!(out.contains("Installer files kept at $tmp"));
        // Remove-Item only appears once, in the success path (no `finally`
        // wiping $tmp unconditionally like the old behavior did).
        assert_eq!(out.matches("Remove-Item").count(), 1);
    }

    #[test]
    fn installer_sh_embeds_base_token_and_os_arch_map_lf_only() {
        let out = render_installer_sh("https://kanade.example.com", "tok-123");
        assert!(out.starts_with("#!/bin/sh\n"));
        assert!(out.contains("set -eu\n"));
        // The token rides a stdin curl config (-K -), never a -H flag or
        // anywhere else on a command line — argv is readable by every local
        // user (/proc/<pid>/cmdline on Linux, `ps` on macOS).
        assert!(!out.contains("-H 'Authorization:"));
        let curl_line = out.lines().find(|l| l.starts_with("curl ")).unwrap();
        assert!(!curl_line.contains("tok-123"), "{curl_line}");
        assert!(out.contains("curl -fsSL -K - -o \"$TMP/installer.tar.gz\""));
        assert!(out.contains("header = \"Authorization: Bearer tok-123\""));
        assert!(out.contains("<<'KANADE_CURL_CONFIG'"));
        // os and arch are shell vars, outside the quoted literals.
        assert!(out.contains(
            "'https://kanade.example.com/api/agents/installer?os='\"$OS\"'&arch='\"$ARCH\""
        ));
        assert!(out.contains("case \"$(uname -s)\" in"));
        assert!(out.contains("unsupported OS"));
        // Linux: arch from `uname -m`.
        assert!(out.contains("OS=linux\n"));
        assert!(out.contains("case \"$(uname -m)\" in"));
        assert!(out.contains("x86_64) ARCH=x86_64 ;;"));
        assert!(out.contains("aarch64|arm64) ARCH=aarch64 ;;"));
        assert!(out.contains("unsupported architecture"));
        // macOS: Apple Silicon only, detected via sysctl (uname -m lies
        // under Rosetta), Intel refused with a clear error.
        let darwin = &out[out.find("    Darwin)\n").expect("Darwin branch")..];
        let darwin = &darwin[..darwin.find(";;").unwrap()];
        assert!(darwin.contains("OS=macos\n"), "{darwin}");
        assert!(
            darwin.contains("\"$(sysctl -n hw.optional.arm64 2>/dev/null || true)\" = \"1\""),
            "{darwin}"
        );
        assert!(darwin.contains("ARCH=aarch64\n"), "{darwin}");
        assert!(!darwin.contains("uname -m"), "{darwin}");
        assert!(!darwin.contains("ARCH=x86_64"), "{darwin}");
        assert!(
            darwin.contains(
                "echo \"Intel Macs are not supported — kanade supports Apple Silicon Macs only\" >&2\n            exit 1\n"
            ),
            "{darwin}"
        );
        assert!(out.contains("tar xzf \"$TMP/installer.tar.gz\" -C \"$TMP\""));
        assert!(out.contains("sh \"$TMP/install.sh\""));
        assert!(out.contains("sudo bash"));
        // LF only.
        assert!(!out.contains('\r'));
    }

    #[test]
    fn installer_sh_escapes_the_token_for_the_curl_config() {
        // A `"` or `\` in the token would break out of the double-quoted
        // config value.
        let out = render_installer_sh("https://k", "we\"ird\\tok");
        assert!(out.contains("header = \"Authorization: Bearer we\\\"ird\\\\tok\""));
    }

    #[test]
    fn bearer_token_parsing() {
        let mut h = HeaderMap::new();
        assert_eq!(bearer_token(&h), None);
        h.insert(header::AUTHORIZATION, "Bearer tok-123".parse().unwrap());
        assert_eq!(bearer_token(&h), Some("tok-123"));
        // Wrong scheme / empty token → None (the handler 400s).
        h.insert(header::AUTHORIZATION, "Basic dXNlcg==".parse().unwrap());
        assert_eq!(bearer_token(&h), None);
        h.insert(header::AUTHORIZATION, "Bearer ".parse().unwrap());
        assert_eq!(bearer_token(&h), None);
    }

    #[test]
    fn install_ps1_embeds_token_and_keys_when_given() {
        let out = render_install_ps1(
            "0.43.99",
            Some("s3cret"),
            Some(r#"[{"kid":"backend-1","public_key":"AAAA","label":"backend"}]"#),
            false,
        );
        assert!(out.contains("# Installs kanade-agent 0.43.99 as a Windows service."));
        assert!(out.contains("-NatsToken 's3cret'"));
        assert!(out.contains(
            "-CommandKeys '[{\"kid\":\"backend-1\",\"public_key\":\"AAAA\",\"label\":\"backend\"}]'"
        ));
        assert!(!out.contains("-RequireSignedCommands"));
        assert!(out.contains("exit $LASTEXITCODE"));
        assert!(out.contains("Start-Transcript -Path (Join-Path $PSScriptRoot 'install.log')"));
        assert!(out.contains("Stop-Transcript"));
    }

    #[test]
    fn install_ps1_embeds_require_signed_commands_when_enforcement_is_embedded() {
        let out = render_install_ps1(
            "0.43.99",
            Some("s3cret"),
            Some(r#"[{"kid":"backend-1","public_key":"AAAA"}]"#),
            true,
        );
        assert!(out.contains("-CommandKeys"));
        assert!(out.contains("-RequireSignedCommands"));
        // Comes after the other args, on the same invocation line.
        let line = out
            .lines()
            .find(|l| l.contains("deploy-agent.ps1"))
            .unwrap();
        assert!(line.trim_end().ends_with("-RequireSignedCommands"));
    }

    #[test]
    fn resolve_enforcement_off_when_not_requested() {
        assert_eq!(resolve_enforcement(false, true), EnforcementPlan::Off);
        assert_eq!(resolve_enforcement(false, false), EnforcementPlan::Off);
    }

    #[test]
    fn resolve_enforcement_embeds_only_when_a_key_is_present() {
        assert_eq!(resolve_enforcement(true, true), EnforcementPlan::Embedded);
    }

    #[test]
    fn resolve_enforcement_flags_a_request_with_no_key_rather_than_silently_dropping_it() {
        assert_eq!(
            resolve_enforcement(true, false),
            EnforcementPlan::RequestedButNoKey
        );
    }

    #[test]
    fn install_ps1_is_crlf_throughout() {
        // Windows-facing like every other ps1 we generate — a bare LF
        // inside the try/finally block would still run under PowerShell,
        // but stay consistent with the rest of the ZIP.
        let out = render_install_ps1("0.43.99", Some("tok"), None, false);
        for (i, b) in out.bytes().enumerate() {
            if b == b'\n' {
                assert!(
                    i > 0 && out.as_bytes()[i - 1] == b'\r',
                    "bare LF at byte {i}"
                );
            }
        }
    }

    #[test]
    #[cfg(target_os = "windows")]
    fn install_agent_ps1_writes_install_log_when_deploy_agent_throws() {
        // Runtime regression for the diagnosability fix: actually spawn the
        // generated install-agent.ps1 (per CodeRabbit review on #1428)
        // against a stub deploy-agent.ps1 that throws, and confirm the
        // real error text lands in install.log -- the only thing that
        // survives once the one-liner's elevated UAC console closes.
        use std::process::Command;

        let dir = std::env::temp_dir().join(format!(
            "kanade-install-agent-test-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("install-agent.ps1"),
            render_install_ps1("9.9.9", None, None, false),
        )
        .unwrap();
        std::fs::write(
            dir.join("deploy-agent.ps1"),
            "throw \"simulated deploy failure: file in use\"\r\n",
        )
        .unwrap();

        let status = Command::new("powershell.exe")
            .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"])
            .arg(dir.join("install-agent.ps1"))
            .status()
            .expect("failed to spawn powershell.exe");
        assert!(
            !status.success(),
            "the stub throw should propagate as a nonzero exit"
        );

        let log = std::fs::read_to_string(dir.join("install.log"))
            .expect("install.log should exist even though the script failed");
        assert!(
            log.contains("simulated deploy failure: file in use"),
            "install.log is missing the real error text: {log}"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn install_ps1_omits_args_entirely_when_not_given() {
        let out = render_install_ps1("0.43.99", None, None, false);
        assert!(!out.contains("-NatsToken"));
        assert!(!out.contains("-CommandKeys"));
        assert!(!out.contains("-RequireSignedCommands"));
        // Nothing trailing the script path but the newline.
        assert!(out.contains("& (Join-Path $PSScriptRoot 'deploy-agent.ps1')\r\n"));
    }

    #[test]
    fn install_ps1_doubles_single_quotes() {
        // PowerShell single-quoted literal escaping: `'` becomes `''`. An
        // unescaped quote would terminate the literal and let the rest of
        // the token run as script.
        let out = render_install_ps1("0.43.99", Some("it's"), None, false);
        assert!(out.contains("-NatsToken 'it''s'"));
    }

    #[test]
    fn install_cmd_is_crlf_throughout() {
        let out = render_install_cmd("0.43.99");
        assert!(!out.is_empty());
        // No bare LF anywhere: every line ends CRLF. cmd.exe's batch
        // parser misparses LF-only files inside parenthesized blocks.
        for (i, b) in out.bytes().enumerate() {
            if b == b'\n' {
                assert!(
                    i > 0 && out.as_bytes()[i - 1] == b'\r',
                    "bare LF at byte {i}"
                );
            }
        }
        assert!(out.contains("%~dp0install-agent.ps1"));
        assert!(out.contains("REM kanade-agent installer (generated by kanade-backend). Installs kanade-agent 0.43.99."));
        // Echo lines must not carry cmd metacharacters that break out of
        // the echo (`&` separates commands even where quoting is fuzzy).
        for line in out.lines().filter(|l| l.trim_start().starts_with("echo ")) {
            assert!(!line.contains('&'), "echo line with '&': {line}");
        }
    }

    #[test]
    fn zip_round_trips_all_entries() {
        let agent_toml = render_agent_toml("nats://broker.corp:4222").unwrap();
        let install_ps1 =
            render_install_ps1("0.43.99", Some("tok"), Some("[{\"kid\":\"k\"}]"), true);
        let entries: Vec<(&str, Vec<u8>)> = vec![
            ("kanade-agent.exe", b"MZ-fake-exe".to_vec()),
            ("agent.toml", agent_toml.clone().into_bytes()),
            ("deploy-agent.ps1", DEPLOY_AGENT_PS1.as_bytes().to_vec()),
            ("install-agent.ps1", install_ps1.clone().into_bytes()),
            ("install.cmd", render_install_cmd("0.43.99").into_bytes()),
            (
                "README.txt",
                render_readme("0.43.99", true, EnforcementPlan::Embedded).into_bytes(),
            ),
        ];
        let bytes = build_zip(entries).unwrap();

        let mut archive =
            zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("zip reads back");
        let names: std::collections::HashSet<String> =
            archive.file_names().map(str::to_owned).collect();
        for expected in [
            "kanade-agent.exe",
            "agent.toml",
            "deploy-agent.ps1",
            "install-agent.ps1",
            "install.cmd",
            "README.txt",
        ] {
            assert!(names.contains(expected), "missing {expected}");
        }
        assert_eq!(names.len(), 6);

        // The generated files round-trip byte-for-byte, and the deploy
        // script ships unmodified.
        use std::io::Read as _;
        let mut buf = String::new();
        archive
            .by_name("agent.toml")
            .unwrap()
            .read_to_string(&mut buf)
            .unwrap();
        assert_eq!(buf, agent_toml);
        buf.clear();
        archive
            .by_name("install-agent.ps1")
            .unwrap()
            .read_to_string(&mut buf)
            .unwrap();
        assert_eq!(buf, install_ps1);
        buf.clear();
        archive
            .by_name("deploy-agent.ps1")
            .unwrap()
            .read_to_string(&mut buf)
            .unwrap();
        assert_eq!(buf, DEPLOY_AGENT_PS1);
    }

    #[test]
    fn readme_names_the_signing_state() {
        let signed = render_readme("0.43.99", true, EnforcementPlan::Off);
        assert!(signed.contains("command-signing PUBLIC key"));
        assert!(signed.contains("Break-glass keys are\r\nNEVER included"));
        let unsigned = render_readme("0.43.99", false, EnforcementPlan::Off);
        assert!(unsigned.contains("not signing commands"));
        assert!(!unsigned.contains("PUBLIC key (provisioned"));
    }

    #[test]
    fn readme_names_embedded_enforcement() {
        let out = render_readme("0.43.99", true, EnforcementPlan::Embedded);
        assert!(out.contains("-RequireSignedCommands"));
        assert!(out.contains("REFUSE"));
    }

    #[test]
    fn readme_warns_loudly_when_enforcement_was_requested_but_no_key_exists() {
        let out = render_readme("0.43.99", false, EnforcementPlan::RequestedButNoKey);
        assert!(out.contains("WARNING"));
        assert!(out.contains("command-key-generate"));
        assert!(out.contains("does NOT enable enforcement"));
    }

    #[test]
    fn resolve_nats_falls_back_to_the_backend_url() {
        // No section at all, and a section without a url, both mean "dial
        // the same broker this backend does"; neither embeds a token.
        for settings in [
            ServerSettings::default(),
            ServerSettings {
                agent_install: Some(kanade_shared::wire::AgentInstallSection {
                    nats_token: Some("tok".into()),
                    ..Default::default()
                }),
                ..Default::default()
            },
        ] {
            let (url, _) = resolve_nats(&settings, "nats://backend:4222").unwrap();
            assert_eq!(url, "nats://backend:4222");
        }
        let (_, token) = resolve_nats(&ServerSettings::default(), "nats://backend:4222").unwrap();
        assert_eq!(token, None);
    }

    #[test]
    fn resolve_nats_prefers_the_settings_values() {
        let settings = ServerSettings {
            agent_install: Some(kanade_shared::wire::AgentInstallSection {
                nats_url: Some("nats://broker.corp:4222".into()),
                nats_token: Some("s3cret".into()),
                nats_token_set: false,
                require_signed_commands: None,
            }),
            ..Default::default()
        };
        let (url, token) = resolve_nats(&settings, "nats://backend:4222").unwrap();
        assert_eq!(url, "nats://broker.corp:4222");
        assert_eq!(token.as_deref(), Some("s3cret"));
    }

    #[test]
    fn resolve_nats_treats_an_empty_token_as_no_token() {
        // A hand-written KV value with `nats_token = Some("")` bypasses PUT
        // validation — embedding `-NatsToken ''` would hand deploy-agent.ps1
        // an empty argument and the audit would claim a token was embedded.
        let settings = ServerSettings {
            agent_install: Some(kanade_shared::wire::AgentInstallSection {
                nats_token: Some(String::new()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let (_, token) = resolve_nats(&settings, "nats://backend:4222").unwrap();
        assert_eq!(token, None);
    }

    #[test]
    fn resolve_nats_rejects_a_hostile_stored_url() {
        // PUT validates, but a hand-written KV value can bypass it — a bad
        // stored url is a 500 naming the Settings page, never a ZIP with
        // injected agent.toml lines.
        for bad in ["", "nats://evil'\nx='y'", "nats://a\nb", "nats://a\rb"] {
            let settings = ServerSettings {
                agent_install: Some(kanade_shared::wire::AgentInstallSection {
                    nats_url: Some(bad.into()),
                    ..Default::default()
                }),
                ..Default::default()
            };
            let (code, msg) = resolve_nats(&settings, "nats://backend:4222").unwrap_err();
            assert_eq!(code, StatusCode::INTERNAL_SERVER_ERROR, "{bad:?}");
            assert!(msg.contains("Settings"), "{msg}");
        }
    }

    #[test]
    fn params_default_to_windows_x86_64_and_reject_unknowns() {
        let p: InstallerParams = serde_urlencoded_defaults();
        assert_eq!(p.os, InstallerOs::Windows);
        assert_eq!(p.resolve_arch().unwrap(), InstallerArch::X86_64);
        // Unknown values are a deserialize error — axum's Query extractor
        // turns that into a 400 before the handler runs.
        assert!(serde_json::from_str::<InstallerOs>(r#""freebsd""#).is_err());
        assert!(serde_json::from_str::<InstallerArch>(r#""armv7""#).is_err());
        assert_eq!(
            serde_json::from_str::<InstallerOs>(r#""linux""#).unwrap(),
            InstallerOs::Linux
        );
        assert_eq!(
            serde_json::from_str::<InstallerOs>(r#""macos""#).unwrap(),
            InstallerOs::Macos
        );
        assert_eq!(
            serde_json::from_str::<InstallerArch>(r#""aarch64""#).unwrap(),
            InstallerArch::Aarch64
        );
    }

    fn serde_urlencoded_defaults() -> InstallerParams {
        InstallerParams::default()
    }

    fn params_from(query: &str) -> InstallerParams {
        let uri: axum::http::Uri = format!("/api/agents/installer?{query}").parse().unwrap();
        Query::<InstallerParams>::try_from_uri(&uri).unwrap().0
    }

    #[test]
    fn macos_is_apple_silicon_only() {
        // Intel Macs are unsupported: an explicit x86_64 macOS request is a
        // 400 with a clear message (decided before any store lookup).
        let (code, msg) = params_from("os=macos&arch=x86_64")
            .resolve_arch()
            .unwrap_err();
        assert_eq!(code, StatusCode::BAD_REQUEST);
        assert!(
            msg.contains("Intel (x86_64) Macs are not supported"),
            "{msg}"
        );
        assert!(msg.contains("Apple Silicon"), "{msg}");
        // aarch64 is macOS's only — and default — arch.
        for q in ["os=macos&arch=aarch64", "os=macos"] {
            assert_eq!(
                params_from(q).resolve_arch().unwrap(),
                InstallerArch::Aarch64,
                "{q}"
            );
        }
        // Linux keeps both arches, defaulting to x86_64.
        assert_eq!(
            params_from("os=linux").resolve_arch().unwrap(),
            InstallerArch::X86_64
        );
        assert_eq!(
            params_from("os=linux&arch=aarch64").resolve_arch().unwrap(),
            InstallerArch::Aarch64
        );
        // Even if a stray x86_64 macOS key were in the store, macOS never
        // matches it.
        let rows: Vec<(String, Option<String>)> = vec![(
            "0.45.3-macos-x86_64".into(),
            Some("2026-07-04T00:00:00Z".into()),
        )];
        assert_eq!(
            latest_key_for_platform(&rows, InstallerOs::Macos, InstallerArch::Aarch64),
            None
        );
    }

    #[test]
    fn latest_key_filters_by_platform() {
        let rows: Vec<(String, Option<String>)> = vec![
            ("0.44.0".into(), Some("2026-07-01T00:00:00Z".into())),
            ("0.45.4".into(), Some("2026-07-03T00:00:00Z".into())),
            (
                "0.45.4-linux-x86_64".into(),
                Some("2026-07-02T00:00:00Z".into()),
            ),
            (
                "0.45.3-linux-x86_64".into(),
                Some("2026-07-04T00:00:00Z".into()),
            ),
            (
                "0.45.4-linux-aarch64".into(),
                Some("2026-07-05T00:00:00Z".into()),
            ),
        ];
        // Windows sees only bare keys, newest by modified — never a
        // linux-suffixed key, even when that's newer overall.
        assert_eq!(
            latest_key_for_platform(&rows, InstallerOs::Windows, InstallerArch::X86_64),
            Some("0.45.4".into())
        );
        // Linux x86_64 sees only its own suffix: 0.45.3-linux-x86_64 is
        // newer than 0.45.4-linux-x86_64 (timestamps, not semver, order).
        assert_eq!(
            latest_key_for_platform(&rows, InstallerOs::Linux, InstallerArch::X86_64),
            Some("0.45.3-linux-x86_64".into())
        );
        assert_eq!(
            latest_key_for_platform(&rows, InstallerOs::Linux, InstallerArch::Aarch64),
            Some("0.45.4-linux-aarch64".into())
        );
        // arch is ignored for Windows (bare keys carry no arch).
        assert_eq!(
            latest_key_for_platform(&rows, InstallerOs::Windows, InstallerArch::Aarch64),
            Some("0.45.4".into())
        );
        // No key for the platform → None (the handler 404s).
        let bare_only: Vec<(String, Option<String>)> =
            vec![("0.44.0".into(), Some("2026-07-01T00:00:00Z".into()))];
        assert_eq!(
            latest_key_for_platform(&bare_only, InstallerOs::Linux, InstallerArch::X86_64),
            None
        );
        // Semver prerelease dashes are never misparsed: the prerelease
        // WINDOWS key must not look like a linux key, and the linux
        // prerelease key still matches its suffix.
        let rc: Vec<(String, Option<String>)> = vec![
            (
                "0.46.0-rc-linux".into(),
                Some("2026-07-01T00:00:00Z".into()),
            ),
            (
                "0.46.0-rc.1-linux-x86_64".into(),
                Some("2026-07-02T00:00:00Z".into()),
            ),
        ];
        assert_eq!(
            latest_key_for_platform(&rc, InstallerOs::Windows, InstallerArch::X86_64),
            Some("0.46.0-rc-linux".into())
        );
        assert_eq!(
            latest_key_for_platform(&rc, InstallerOs::Linux, InstallerArch::X86_64),
            Some("0.46.0-rc.1-linux-x86_64".into())
        );
    }

    #[test]
    fn latest_key_keeps_macos_and_linux_apart() {
        let rows: Vec<(String, Option<String>)> = vec![
            ("0.45.4".into(), Some("2026-07-01T00:00:00Z".into())),
            (
                "0.45.4-linux-aarch64".into(),
                Some("2026-07-02T00:00:00Z".into()),
            ),
            (
                "0.45.4-macos-aarch64".into(),
                Some("2026-07-03T00:00:00Z".into()),
            ),
            (
                "0.46.0-rc.1-macos-aarch64".into(),
                Some("2026-07-05T00:00:00Z".into()),
            ),
        ];
        // macOS sees only its own arch's suffix, newest by modified
        // (a prerelease dash mid-version doesn't confuse the suffix match).
        assert_eq!(
            latest_key_for_platform(&rows, InstallerOs::Macos, InstallerArch::Aarch64),
            Some("0.46.0-rc.1-macos-aarch64".into())
        );
        // Newer macOS keys never leak into Linux or Windows.
        assert_eq!(
            latest_key_for_platform(&rows, InstallerOs::Linux, InstallerArch::Aarch64),
            Some("0.45.4-linux-aarch64".into())
        );
        assert_eq!(
            latest_key_for_platform(&rows, InstallerOs::Windows, InstallerArch::X86_64),
            Some("0.45.4".into())
        );
        // Linux-only store → no macOS release (the handler 404s).
        let linux_only: Vec<(String, Option<String>)> = vec![(
            "0.45.4-linux-x86_64".into(),
            Some("2026-07-01T00:00:00Z".into()),
        )];
        assert_eq!(
            latest_key_for_platform(&linux_only, InstallerOs::Macos, InstallerArch::Aarch64),
            None
        );
    }

    #[test]
    fn install_sh_exports_the_token_only_when_given() {
        let with = render_install_sh(
            Some("s3cret"),
            None,
            false,
            "setup-agent.sh",
            "a systemd service",
        );
        assert!(with.starts_with("#!/bin/sh\n"));
        assert!(with.contains("set -eu\n"));
        assert!(with.contains("export KANADE_NATS_TOKEN='s3cret'\n"));
        assert!(with.ends_with("exec ./setup-agent.sh\n"));
        // No url export — the baked agent.toml carries it (setup-agent.sh
        // only overrides when KANADE_NATS_URL is set).
        assert!(!with.contains("KANADE_NATS_URL"));
        // LF only.
        assert!(!with.contains('\r'));

        let without = render_install_sh(None, None, false, "setup-agent.sh", "a systemd service");
        assert!(!without.contains("KANADE_NATS_TOKEN"));
        assert!(without.ends_with("exec ./setup-agent.sh\n"));
    }

    #[test]
    fn install_sh_shell_escapes_single_quotes() {
        // POSIX single-quote escaping: `'` → `'\''`. An unescaped quote
        // would terminate the literal and let the rest of the token run
        // as shell.
        let out = render_install_sh(
            Some("it's"),
            None,
            false,
            "setup-agent.sh",
            "a systemd service",
        );
        assert!(out.contains("export KANADE_NATS_TOKEN='it'\\''s'\n"));
    }

    /// Build the tarball and read it back as `name → (mode, bytes)`.
    fn tar_round_trip(entries: Vec<TarEntry>) -> std::collections::HashMap<String, (u32, Vec<u8>)> {
        let bytes = build_tar_gz(entries).unwrap();
        let dec = flate2::read::GzDecoder::new(bytes.as_slice());
        let mut archive = tar::Archive::new(dec);
        let mut seen = std::collections::HashMap::new();
        for entry in archive.entries().unwrap() {
            let mut entry = entry.unwrap();
            let name = entry.path().unwrap().to_string_lossy().into_owned();
            let mode = entry.header().mode().unwrap();
            let mut data = Vec::new();
            use std::io::Read as _;
            entry.read_to_end(&mut data).unwrap();
            seen.insert(name, (mode, data));
        }
        seen
    }

    #[test]
    fn linux_tar_gz_round_trips_all_entries_with_modes() {
        let agent_toml = render_agent_toml("nats://broker.corp:4222").unwrap();
        let seen = tar_round_trip(unix_tar_entries(
            InstallerOs::Linux,
            "0.45.4-linux-x86_64",
            b"\x7fELF-fake".to_vec(),
            agent_toml.clone(),
            Some("tok"),
            None,
            EnforcementPlan::Off,
        ));
        for expected in [
            "bin/kanade-agent",
            "etc/agent.toml",
            "systemd/kanade-agent.service",
            "setup-agent.sh",
            "install.sh",
            "README.txt",
        ] {
            assert!(seen.contains_key(expected), "missing {expected}");
        }
        assert_eq!(seen.len(), 6);
        // Executables carry the exec bit; data files don't.
        for exe_name in ["bin/kanade-agent", "setup-agent.sh", "install.sh"] {
            assert_eq!(seen[exe_name].0, 0o755, "{exe_name} mode");
        }
        for data_name in [
            "etc/agent.toml",
            "systemd/kanade-agent.service",
            "README.txt",
        ] {
            assert_eq!(seen[data_name].0, 0o644, "{data_name} mode");
        }
        // The generated files round-trip byte-for-byte, and the canonical
        // scripts ship unmodified.
        assert_eq!(seen["bin/kanade-agent"].1, b"\x7fELF-fake");
        assert_eq!(seen["etc/agent.toml"].1, agent_toml.as_bytes());
        assert_eq!(
            seen["install.sh"].1,
            render_install_sh(
                Some("tok"),
                None,
                false,
                "setup-agent.sh",
                "a systemd service"
            )
            .as_bytes()
        );
        assert_eq!(seen["setup-agent.sh"].1, SETUP_AGENT_SH.as_bytes());
        assert_eq!(
            seen["systemd/kanade-agent.service"].1,
            AGENT_SERVICE.as_bytes()
        );
    }

    #[test]
    fn macos_tar_gz_carries_the_launchd_layout() {
        let agent_toml = render_agent_toml("nats://broker.corp:4222").unwrap();
        let seen = tar_round_trip(unix_tar_entries(
            InstallerOs::Macos,
            "0.45.4-macos-aarch64",
            b"\xcf\xfa\xed\xfe-fake".to_vec(),
            agent_toml.clone(),
            Some("tok"),
            None,
            EnforcementPlan::Off,
        ));
        let mut names: Vec<&str> = seen.keys().map(String::as_str).collect();
        names.sort_unstable();
        assert_eq!(
            names,
            [
                "README.txt",
                "bin/kanade-agent",
                "etc/agent.toml",
                "install.sh",
                "launchd/com.kanade.agent.plist",
                "setup-agent-macos.sh",
            ]
        );
        for exe_name in ["bin/kanade-agent", "setup-agent-macos.sh", "install.sh"] {
            assert_eq!(seen[exe_name].0, 0o755, "{exe_name} mode");
        }
        for data_name in [
            "etc/agent.toml",
            "launchd/com.kanade.agent.plist",
            "README.txt",
        ] {
            assert_eq!(seen[data_name].0, 0o644, "{data_name} mode");
        }
        assert_eq!(seen["etc/agent.toml"].1, agent_toml.as_bytes());
        assert_eq!(
            seen["setup-agent-macos.sh"].1,
            SETUP_AGENT_MACOS_SH.as_bytes()
        );
        assert_eq!(
            seen["launchd/com.kanade.agent.plist"].1,
            AGENT_PLIST.as_bytes()
        );
        // The wrapper hands over to the macOS script, not the Linux one.
        let install_sh = String::from_utf8(seen["install.sh"].1.clone()).unwrap();
        assert!(install_sh.contains("# Installs kanade-agent as a launchd daemon."));
        assert!(install_sh.contains("export KANADE_NATS_TOKEN='tok'\n"));
        assert!(install_sh.ends_with("exec ./setup-agent-macos.sh\n"));
        assert!(!install_sh.contains("KANADE_NATS_URL"));
        let readme = String::from_utf8(seen["README.txt"].1.clone()).unwrap();
        assert!(readme.contains("release 0.45.4-macos-aarch64"));
    }

    #[test]
    fn readme_linux_documents_the_flow_and_the_signing_state() {
        let out = render_readme_linux("0.45.4-linux-x86_64", true, EnforcementPlan::Off);
        assert!(out.contains("release 0.45.4-linux-x86_64"));
        assert!(out.contains("tar xzf"));
        assert!(out.contains("sudo ./install.sh"));
        assert!(!out.contains("Windows-only"));
        assert!(!out.contains("INACTIVE"));
        assert!(out.contains("command-signing PUBLIC key"));
        assert!(out.contains("Break-glass keys are"));
        // LF only.
        assert!(!out.contains('\r'));
    }

    #[test]
    fn readme_macos_documents_the_flow_gatekeeper_and_the_signing_state() {
        let out = render_readme_macos("0.45.4-macos-aarch64", false, EnforcementPlan::Off);
        assert!(out.contains("release 0.45.4-macos-aarch64"));
        assert!(out.contains("tar xzf ../kanade-agent-installer-0.45.4-macos-aarch64.tar.gz"));
        assert!(out.contains("sudo ./install.sh"));
        assert!(out.contains("launchctl print system/com.kanade.agent"));
        assert!(out.contains("com.apple.quarantine"));
        assert!(!out.contains("Windows-only"));
        assert!(out.contains("is not signing commands"));
        assert!(!out.contains('\r'));
    }

    const KEYS_JSON: &str = r#"[{"kid":"backend-1","public_key":"AAAA","label":"it's"}]"#;

    fn install_sh_of(os: InstallerOs, keys: Option<&str>, enforcement: EnforcementPlan) -> String {
        let seen = tar_round_trip(unix_tar_entries(
            os,
            "0.45.4-x",
            b"bin".to_vec(),
            "toml".into(),
            Some("tok"),
            keys,
            enforcement,
        ));
        String::from_utf8(seen["install.sh"].1.clone()).unwrap()
    }

    #[test]
    fn unix_install_sh_embeds_the_backend_key_and_enforcement() {
        for os in [InstallerOs::Linux, InstallerOs::Macos] {
            let sh = install_sh_of(os, Some(KEYS_JSON), EnforcementPlan::Embedded);
            // Quoted as data: the embedded quote must not end the literal.
            assert!(sh.contains(&format!(
                "export KANADE_COMMAND_KEYS={}\n",
                sh_quote(KEYS_JSON)
            )));
            assert!(sh.contains("export KANADE_REQUIRE_SIGNED_COMMANDS=1\n"));
            assert!(sh.find("export KANADE_COMMAND_KEYS").unwrap() < sh.find("exec ./").unwrap());
            assert!(!sh.contains('\r'));

            let keys_only = install_sh_of(os, Some(KEYS_JSON), EnforcementPlan::Off);
            assert!(keys_only.contains("KANADE_COMMAND_KEYS="));
            assert!(!keys_only.contains("KANADE_REQUIRE_SIGNED_COMMANDS"));

            // Requested but no key: never export the switch without a ring.
            let none = install_sh_of(os, None, EnforcementPlan::RequestedButNoKey);
            assert!(!none.contains("KANADE_COMMAND_KEYS"));
            assert!(!none.contains("KANADE_REQUIRE_SIGNED_COMMANDS"));
        }
    }

    #[test]
    fn unix_readmes_name_the_signing_and_enforcement_state() {
        let embedded = render_readme_linux("k", true, EnforcementPlan::Embedded);
        assert!(embedded.contains("KANADE_REQUIRE_SIGNED_COMMANDS=1"));
        let warned = render_readme_macos("k", false, EnforcementPlan::RequestedButNoKey);
        assert!(warned.contains("*** WARNING"));
        assert!(warned.contains("does NOT enable enforcement"));
        assert!(!warned.contains('\r'));
    }
}