arks-server 1.3.3

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
//! In-process SSH listener for `arks serve` (durable accept + live rebind).
//!
//! Evidence: B1/B2 OpenSSH ChaCha wire + `git clone ssh://`
//! ([[evidence:root/20261110235116-claimed-ssh]]) and B7 SSH dual-bind rebind
//! ([[evidence:root/20261111092000-claimed-rebind-ssh]]); with both, the IW-SSH-LABEL
//! drop condition holds and the listener carries no Partial readiness label (queue Q21).
//!
//! Max honest wire today (structured stages):
//! 1. resolve host-key + `authorized_keys` paths (env / options / defaults)
//! 2. prove TCP bind on the requested listen address
//! 3. optional RFC 4253 identification exchange
//! 4. optional SSH_MSG_KEXINIT exchange + peer name-list parse
//! 5. local curve25519-sha256 ECDH (+ peer ECDH INIT when offered)
//! 6. host-key **sign** Partial (OpenSSH ed25519 unencrypted) + NEWKEYS when key loads
//! 7. OpenSSH `chacha20-poly1305@openssh.com` packet protection after NEWKEYS
//! 8. wire publickey auth verify against `authorized_keys` (Partial; when peer continues)
//! 9. session channel + `exec` → `git-upload-pack`|`git-receive-pack` dispatch into
//!    `upload_pack_stream` / `receive_pack_stream` (Partial; when channel opens)
//!
//! SoT §17(c)/(d): durable accept + same-process live rebind; bind failure stays
//! fail-closed and silent degrade is forbidden. Ops SSHD + `arks upload-pack` /
//! `receive-pack` remains valid. Cite: [[sot:root/arks-self-host-server]]

use crate::error::ServerError;
use crate::push_policy::Pusher;
use crate::serve::ListenRebindSlot;
use crate::ssh_openssh_chacha::OpenSshChaCha;
use crate::stdio::{receive_pack_stream_as, upload_pack_stream};
use crate::web_ui::store::ForgeStore;
use arks_repo::Repository;
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use sha2::{Digest, Sha256};
use std::collections::VecDeque;
use std::io::{Cursor, Read, Write};
use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::{Duration, Instant};
use x25519_dalek::{PublicKey, StaticSecret};

/// RFC 4254 advertised local receive window (2 MiB).
const SSH_LOCAL_INITIAL_WINDOW: u32 = 2 * 1024 * 1024;
/// Replenish local receive window via `SSH_MSG_CHANNEL_WINDOW_ADJUST` once consumed >= 512 KiB.
const SSH_LOCAL_WINDOW_REFILL_THRESHOLD: u32 = 512 * 1024;
/// RFC 4254 advertised maximum packet size.
const SSH_LOCAL_MAX_PACKET: u32 = 32_768;

/// Stop flag + join handle of a background listener thread.
type ListenerThread = thread::JoinHandle<Result<(), ServerError>>;

/// Named fail-closed stages for in-process SSH Partial (not Claimed).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)] // IdExchange retained for stage vocabulary / future accept-path notes.
enum SshStage {
    IdExchange,
    KexInit,
    AlgoSelect,
    Ecdh,
    HostKeySign,
    NewKeys,
    EncryptedTransport,
    AuthPublickey,
    ChannelSession,
}

impl SshStage {
    fn as_str(self) -> &'static str {
        match self {
            Self::IdExchange => "id_exchange",
            Self::KexInit => "kexinit",
            Self::AlgoSelect => "algo_select",
            Self::Ecdh => "ecdh_curve25519",
            Self::HostKeySign => "host_key_sign",
            Self::NewKeys => "newkeys",
            Self::EncryptedTransport => "encrypted_transport",
            Self::AuthPublickey => "auth_publickey",
            Self::ChannelSession => "channel_session",
        }
    }
}

/// Options for the in-process SSH git listener.
#[derive(Debug, Clone)]
pub struct ServeSshOptions {
    pub listen: SocketAddr,
    /// Repository or base path the listener would serve.
    pub path: PathBuf,
    /// Host key path (OpenSSH-format expected when Claimed). Default / env override.
    pub host_key: PathBuf,
    /// `authorized_keys` path for public-key auth (when Claimed).
    pub authorized_keys: PathBuf,
    /// Optional same-process live rebind target (§17(c); B7 SSH dual-bind drain).
    pub rebind_desired: Option<ListenRebindSlot>,
}

impl ServeSshOptions {
    /// Build options with default key paths under `~/.config/arks/ssh/` (or env).
    pub fn with_defaults(listen: SocketAddr, path: PathBuf) -> Self {
        Self {
            listen,
            path,
            host_key: default_host_key_path(),
            authorized_keys: default_authorized_keys_path(),
            rebind_desired: None,
        }
    }
}

/// Default host key: `ARKS_SERVE_SSH_HOST_KEY` or `~/.config/arks/ssh/host_key`.
pub fn default_host_key_path() -> PathBuf {
    if let Ok(p) = std::env::var("ARKS_SERVE_SSH_HOST_KEY") {
        if !p.is_empty() {
            return PathBuf::from(p);
        }
    }
    arks_config_dir().join("ssh").join("host_key")
}

/// Default authorized_keys: `ARKS_SERVE_SSH_AUTHORIZED_KEYS` or
/// `~/.config/arks/ssh/authorized_keys`.
pub fn default_authorized_keys_path() -> PathBuf {
    if let Ok(p) = std::env::var("ARKS_SERVE_SSH_AUTHORIZED_KEYS") {
        if !p.is_empty() {
            return PathBuf::from(p);
        }
    }
    arks_config_dir().join("ssh").join("authorized_keys")
}

fn arks_config_dir() -> PathBuf {
    let home = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."));
    home.join(".config").join("arks")
}

fn path_status(p: &Path) -> &'static str {
    if p.is_file() {
        "present"
    } else if p.exists() {
        "exists-not-file"
    } else {
        "missing"
    }
}

/// Probe host-key bytes for known OpenSSH / PEM markers (auth scaffolding; no load Claimed).
fn probe_host_key_format(path: &Path) -> String {
    if !path.is_file() {
        return "absent".into();
    }
    let mut f = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(e) => return format!("unreadable ({e})"),
    };
    let mut buf = [0u8; 96];
    let n = f.read(&mut buf).unwrap_or(0);
    let head = String::from_utf8_lossy(&buf[..n]);
    if head.starts_with("openssh-key-v1") || head.contains("BEGIN OPENSSH PRIVATE KEY") {
        "openssh-private-key-marker".into()
    } else if head.contains("BEGIN RSA PRIVATE KEY")
        || head.contains("BEGIN EC PRIVATE KEY")
        || head.contains("BEGIN PRIVATE KEY")
    {
        "pem-private-key-marker".into()
    } else if head.starts_with("ssh-") || head.starts_with("ecdsa-") || head.starts_with("sk-") {
        "public-key-line-like".into()
    } else if n == 0 {
        "empty-file".into()
    } else {
        "unknown-bytes".into()
    }
}

/// Count non-empty, non-comment lines in authorized_keys (auth scaffolding; no verify Claimed).
fn probe_authorized_keys(path: &Path) -> String {
    if !path.is_file() {
        return "absent".into();
    }
    let raw = match std::fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) => return format!("unreadable ({e})"),
    };
    let mut ed25519 = 0usize;
    let mut rsa = 0usize;
    let mut ecdsa = 0usize;
    let mut total = 0usize;
    for line in raw
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty() && !l.starts_with('#'))
    {
        total += 1;
        let algo = line.split_whitespace().next().unwrap_or("");
        if algo.contains("ed25519") {
            ed25519 += 1;
        } else if algo.starts_with("ssh-rsa") || algo.starts_with("rsa-sha2-") {
            rsa += 1;
        } else if algo.starts_with("ecdsa-sha2-") {
            ecdsa += 1;
        }
    }
    if rsa > 0 || ecdsa > 0 {
        format!(
            "lines={total} (ed25519={ed25519}, rsa={rsa}, ecdsa={ecdsa}; note: in-process SSH authenticates ed25519 keys)"
        )
    } else {
        format!("lines={total} (ed25519={ed25519})")
    }
}

fn ssh_string(data: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(4 + data.len());
    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
    out.extend_from_slice(data);
    out
}

fn ssh_name_list(names: &[&str]) -> Vec<u8> {
    let joined = names.join(",");
    ssh_string(joined.as_bytes())
}

fn read_ssh_name_list(buf: &[u8], off: &mut usize) -> Option<Vec<String>> {
    if *off + 4 > buf.len() {
        return None;
    }
    let len = u32::from_be_bytes(buf[*off..*off + 4].try_into().ok()?) as usize;
    *off += 4;
    if *off + len > buf.len() {
        return None;
    }
    let s = std::str::from_utf8(&buf[*off..*off + len]).ok()?;
    *off += len;
    if s.is_empty() {
        return Some(Vec::new());
    }
    Some(s.split(',').map(|x| x.to_string()).collect())
}

fn read_ssh_bytes(buf: &[u8], off: &mut usize) -> Option<Vec<u8>> {
    if *off + 4 > buf.len() {
        return None;
    }
    let len = u32::from_be_bytes(buf[*off..*off + 4].try_into().ok()?) as usize;
    *off += 4;
    if *off + len > buf.len() {
        return None;
    }
    let out = buf[*off..*off + len].to_vec();
    *off += len;
    Some(out)
}

/// Host-key material for Partial sign (OpenSSH ed25519 unencrypted only).
#[derive(Clone)]
struct HostEd25519 {
    signing: SigningKey,
    /// SSH wire blob: string("ssh-ed25519") || string(32-byte pub).
    public_blob: Vec<u8>,
}

fn load_host_ed25519(path: &Path) -> Result<HostEd25519, String> {
    if !path.is_file() {
        return Err("host_key absent".into());
    }
    let raw = std::fs::read(path).map_err(|e| e.to_string())?;
    let text = String::from_utf8_lossy(&raw);
    let b64: String = if text.contains("BEGIN OPENSSH PRIVATE KEY") {
        text.lines()
            .filter(|l| !l.starts_with("-----") && !l.trim().is_empty())
            .collect::<String>()
    } else if raw.starts_with(b"openssh-key-v1\0") {
        return parse_openssh_ed25519_bin(&raw);
    } else {
        return Err("not OpenSSH PEM / openssh-key-v1".into());
    };
    let bin = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, b64.trim())
        .map_err(|e| format!("base64: {e}"))?;
    parse_openssh_ed25519_bin(&bin)
}

fn parse_openssh_ed25519_bin(bin: &[u8]) -> Result<HostEd25519, String> {
    const MAGIC: &[u8] = b"openssh-key-v1\0";
    if !bin.starts_with(MAGIC) {
        return Err("missing openssh-key-v1 magic".into());
    }
    let mut off = MAGIC.len();
    let cipher = read_ssh_bytes(bin, &mut off).ok_or("ciphername")?;
    let kdf = read_ssh_bytes(bin, &mut off).ok_or("kdfname")?;
    let _kdfopts = read_ssh_bytes(bin, &mut off).ok_or("kdfoptions")?;
    if cipher.as_slice() != b"none" || kdf.as_slice() != b"none" {
        return Err("encrypted OpenSSH host key not Partial-wired (none/none only)".into());
    }
    let nkeys = read_u32(bin, &mut off).map_err(|_| "num_keys short".to_string())?;
    if nkeys != 1 {
        return Err(format!("num_keys={nkeys} (Partial expects 1)"));
    }
    let pub_blob = read_ssh_bytes(bin, &mut off).ok_or("public key blob")?;
    let priv_block = read_ssh_bytes(bin, &mut off).ok_or("private block")?;
    let mut poff = 0usize;
    let _c1 = read_u32(&priv_block, &mut poff)?;
    let _c2 = read_u32(&priv_block, &mut poff)?;
    let keytype = read_ssh_bytes(&priv_block, &mut poff).ok_or("keytype")?;
    if keytype.as_slice() != b"ssh-ed25519" {
        return Err(format!(
            "host key type {} (Partial ed25519 only)",
            String::from_utf8_lossy(&keytype)
        ));
    }
    let _pub_in_priv = read_ssh_bytes(&priv_block, &mut poff).ok_or("pubkey in priv")?;
    let secret = read_ssh_bytes(&priv_block, &mut poff).ok_or("secret")?;
    // OpenSSH stores 64-byte ed25519 private as seed(32)||public(32).
    if secret.len() < 32 {
        return Err(format!("ed25519 secret len {}", secret.len()));
    }
    let mut seed = [0u8; 32];
    seed.copy_from_slice(&secret[..32]);
    let signing = SigningKey::from_bytes(&seed);
    // Prefer the public blob from the file header (SSH wire).
    let public_blob = if pub_blob.starts_with(&[0, 0, 0, 11]) || pub_blob.len() > 4 {
        pub_blob
    } else {
        build_ssh_ed25519_public_blob(signing.verifying_key().as_bytes())
    };
    Ok(HostEd25519 {
        signing,
        public_blob,
    })
}

fn read_u32(buf: &[u8], off: &mut usize) -> Result<u32, String> {
    let slice = buf
        .get(*off..off.saturating_add(4))
        .ok_or_else(|| "u32 short".to_string())?;
    let bytes: [u8; 4] = slice.try_into().map_err(|_| "u32 short".to_string())?;
    *off += 4;
    Ok(u32::from_be_bytes(bytes))
}

fn build_ssh_ed25519_public_blob(pub32: &[u8; 32]) -> Vec<u8> {
    let mut out = Vec::new();
    out.extend(ssh_string(b"ssh-ed25519"));
    out.extend(ssh_string(pub32));
    out
}

fn sign_ssh_ed25519(host: &HostEd25519, data: &[u8]) -> Vec<u8> {
    let sig = host.signing.sign(data);
    let mut out = Vec::new();
    out.extend(ssh_string(b"ssh-ed25519"));
    out.extend(ssh_string(&sig.to_bytes()));
    out
}

/// RFC 4253 SSH_MSG_KEXINIT — advertise curve25519; hostkey ssh-ed25519 when Partial load ok.
fn build_kexinit_payload(advertise_ed25519: bool) -> Vec<u8> {
    let mut p = Vec::with_capacity(256);
    p.push(20); // SSH_MSG_KEXINIT
    let cookie = StaticSecret::random().to_bytes();
    p.extend_from_slice(&cookie[..16]);
    p.extend(ssh_name_list(&[
        "curve25519-sha256",
        "curve25519-sha256@libssh.org",
        "kex-strict-s-v00@openssh.com",
    ]));
    if advertise_ed25519 {
        p.extend(ssh_name_list(&["ssh-ed25519"]));
    } else {
        // Honest Missing hostkey name when key unloadable.
        p.extend(ssh_name_list(&["arks-partial-missing-hostkey-sign"]));
    }
    // Only advertise the cipher implemented by this listener. OpenSSH still
    // negotiates a MAC name for AEAD ciphers, but the selected MAC is implicit
    // and no separate MAC is placed on the wire.
    p.extend(ssh_name_list(&["chacha20-poly1305@openssh.com"]));
    p.extend(ssh_name_list(&["chacha20-poly1305@openssh.com"]));
    p.extend(ssh_name_list(&["hmac-sha2-256"]));
    p.extend(ssh_name_list(&["hmac-sha2-256"]));
    p.extend(ssh_name_list(&["none"]));
    p.extend(ssh_name_list(&["none"]));
    p.extend(ssh_name_list(&[]));
    p.extend(ssh_name_list(&[]));
    p.push(0); // first_kex_packet_follows = false
    p.extend_from_slice(&0u32.to_be_bytes());
    p
}

/// Write one unencrypted SSH binary packet (no MAC — pre-NEWKEYS / cleartext Partial).
fn write_ssh_packet(stream: &mut TcpStream, payload: &[u8]) -> std::io::Result<()> {
    let mut padding_len = 4usize;
    while (4 + 1 + payload.len() + padding_len) % 8 != 0 {
        padding_len += 1;
    }
    let packet_length = (1 + payload.len() + padding_len) as u32;
    stream.write_all(&packet_length.to_be_bytes())?;
    stream.write_all(&[padding_len as u8])?;
    stream.write_all(payload)?;
    stream.write_all(&vec![0u8; padding_len])?;
    Ok(())
}

fn read_ssh_packet(stream: &mut TcpStream, max_payload: usize) -> std::io::Result<Vec<u8>> {
    let mut lenbuf = [0u8; 4];
    stream.read_exact(&mut lenbuf)?;
    let packet_length = u32::from_be_bytes(lenbuf) as usize;
    if packet_length < 5 || packet_length > max_payload + 256 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("ssh packet_length out of range ({packet_length})"),
        ));
    }
    let mut rest = vec![0u8; packet_length];
    stream.read_exact(&mut rest)?;
    let padding_len = rest[0] as usize;
    if padding_len + 1 > rest.len() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "ssh padding_length invalid",
        ));
    }
    let payload_end = rest.len() - padding_len;
    Ok(rest[1..payload_end].to_vec())
}

/// Read identification lines without reading past LF into the first binary
/// packet. RFC 4253 permits pre-identification banner lines.
fn read_ssh_identification(stream: &mut TcpStream) -> std::io::Result<String> {
    for _ in 0..50 {
        let mut line = Vec::with_capacity(64);
        loop {
            let mut byte = [0u8; 1];
            stream.read_exact(&mut byte)?;
            line.push(byte[0]);
            if byte[0] == b'\n' {
                break;
            }
            if line.len() >= 255 {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "SSH identification line exceeds 255 bytes",
                ));
            }
        }
        let line = String::from_utf8_lossy(&line)
            .trim_end_matches(['\r', '\n'])
            .to_string();
        if line.starts_with("SSH-") {
            return Ok(line);
        }
    }
    Err(std::io::Error::new(
        std::io::ErrorKind::InvalidData,
        "SSH identification not found",
    ))
}

/// Local curve25519 ECDH self-check (Partial crypto evidence; not peer handshake Claimed).
fn curve25519_ecdh_selfcheck() -> Result<String, String> {
    let a_secret = StaticSecret::random();
    let a_public = PublicKey::from(&a_secret);
    let b_secret = StaticSecret::random();
    let b_public = PublicKey::from(&b_secret);
    let shared_a = a_secret.diffie_hellman(&b_public);
    let shared_b = b_secret.diffie_hellman(&a_public);
    if shared_a.as_bytes() != shared_b.as_bytes() {
        return Err("shared secret mismatch".into());
    }
    let mut h = Sha256::new();
    h.update(b"arks-ssh-partial-ecdh");
    h.update(shared_a.as_bytes());
    let digest = h.finalize();
    Ok(format!(
        "ecdh_selfcheck=ok shared_sha256={:02x}{:02x}…",
        digest[0], digest[1]
    ))
}

/// One authorized `ssh-ed25519` key entry parsed from `authorized_keys`.
struct AuthorizedEd25519Key {
    verifying: VerifyingKey,
    blob: Vec<u8>,
    /// Username extracted from an immediately preceding `# <user> (<title>)` comment line, if any.
    comment_user: Option<String>,
}

/// Authenticated SSH identity captured from `SSH_MSG_USERAUTH_REQUEST` + verified Ed25519 key.
#[derive(Debug, Clone, PartialEq, Eq)]
struct SshAuthIdentity {
    /// Raw username sent in `SSH_MSG_USERAUTH_REQUEST`.
    request_user: String,
    /// Username extracted from `# <user> (<title>)` in `authorized_keys`, if present.
    key_comment_user: Option<String>,
    /// Verified SSH wire public key blob (`string "ssh-ed25519" || string pub32`).
    public_blob: Vec<u8>,
}

/// Extract `<user>` from a `sync_authorized_keys` comment line of the form `# <user> (<title>)`.
fn parse_authorized_keys_comment_user(comment_line: &str) -> Option<String> {
    let rest = comment_line.trim().strip_prefix('#')?.trim();
    let (user_part, title_part) = rest.split_once('(')?;
    if !title_part.ends_with(')') {
        return None;
    }
    let user = user_part.trim();
    if user.is_empty()
        || user.len() > 80
        || user.starts_with('.')
        || !user
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
    {
        return None;
    }
    Some(user.to_string())
}

/// Parse one OpenSSH `ssh-ed25519` public key line into `(VerifyingKey, wire_blob)`.
fn parse_authorized_ed25519_line(line: &str) -> Option<(VerifyingKey, Vec<u8>)> {
    let parts: Vec<&str> = line.split_whitespace().collect();
    if parts.len() < 2 {
        return None;
    }
    let (alg, b64) = if parts[0].starts_with("ssh-") || parts[0].starts_with("ecdsa-") {
        (parts[0], parts[1])
    } else if parts.len() >= 3 && (parts[1].starts_with("ssh-") || parts[1].starts_with("ecdsa-")) {
        (parts[1], parts[2])
    } else {
        return None;
    };
    if alg != "ssh-ed25519" {
        return None;
    }
    let blob = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, b64).ok()?;
    let vk = parse_ssh_ed25519_verifying(&blob)?;
    Some((vk, blob))
}

/// Load ssh-ed25519 verifying keys from an OpenSSH `authorized_keys` file, capturing
/// optional `# <user> (<title>)` comment ownership annotations (`SEC-02`).
fn load_authorized_ed25519_keys(authorized_keys: &Path) -> Vec<AuthorizedEd25519Key> {
    let mut out = Vec::new();
    let Ok(raw) = std::fs::read_to_string(authorized_keys) else {
        return out;
    };
    let mut pending_comment_user: Option<String> = None;
    for line in raw.lines() {
        let line = line.trim();
        if line.is_empty() {
            pending_comment_user = None;
            continue;
        }
        if line.starts_with('#') {
            pending_comment_user = parse_authorized_keys_comment_user(line);
            continue;
        }
        let comment_user = pending_comment_user.take();
        if let Some((verifying, blob)) = parse_authorized_ed25519_line(line) {
            out.push(AuthorizedEd25519Key {
                verifying,
                blob,
                comment_user,
            });
        }
    }
    out
}

/// Verify an ed25519 publickey signature against `authorized_keys`.
/// Returns `Ok(comment_user)` when authorized and signature verifies.
fn verify_publickey_against_authorized(
    authorized_keys: &Path,
    public_blob: &[u8],
    challenge: &[u8],
    signature_blob: &[u8],
) -> Result<Option<String>, String> {
    let keys = load_authorized_ed25519_keys(authorized_keys);
    if keys.is_empty() {
        return Err("authorized_keys has no ssh-ed25519 lines".into());
    }
    let Some(vk) = parse_ssh_ed25519_verifying(public_blob) else {
        return Err("public blob not ssh-ed25519".into());
    };
    let Some(matched) = keys.iter().find(|entry| {
        entry.verifying.as_bytes() == vk.as_bytes() || entry.blob.as_slice() == public_blob
    }) else {
        return Err("public key not in authorized_keys".into());
    };
    let mut off = 0usize;
    let alg = read_ssh_bytes(signature_blob, &mut off).ok_or("sig alg")?;
    if alg.as_slice() != b"ssh-ed25519" {
        return Err("signature alg not ssh-ed25519".into());
    }
    let sig_bytes = read_ssh_bytes(signature_blob, &mut off).ok_or("sig bytes")?;
    if sig_bytes.len() != 64 {
        return Err(format!("sig len {}", sig_bytes.len()));
    }
    let mut arr = [0u8; 64];
    arr.copy_from_slice(&sig_bytes);
    let sig = Signature::from_bytes(&arr);
    vk.verify(challenge, &sig)
        .map_err(|e| format!("ed25519 verify fail: {e}"))?;
    Ok(matched.comment_user.clone())
}

/// Resolve the effective authenticated username for an SSH session against `ForgeStore` (`SEC-02`).
///
/// Trust precedence prevents login-name spoofing:
/// 1. Cryptographic match of the verified Ed25519 key against `store.users[*].ssh_keys`.
/// 2. Key-matched `# <user> (<title>)` annotation from `authorized_keys` (cross-checked against
///    `store.users` when users are configured).
/// 3. `SSH_MSG_USERAUTH_REQUEST` username ONLY in single-user mode (`store.users.is_empty()`);
///    when `ForgeStore` users exist, never fall back to an untrusted `request_user` even for
///    keyless accounts.
fn resolve_ssh_identity(store: &ForgeStore, auth: &SshAuthIdentity) -> Option<String> {
    if store.corrupt {
        return None;
    }
    let presented_vk = parse_ssh_ed25519_verifying(&auth.public_blob);

    // 1. Direct cryptographic key match inside ForgeStore user records.
    if let Some(ref vk) = presented_vk {
        for acct in &store.users {
            for rec in &acct.ssh_keys {
                if let Some((stored_vk, stored_blob)) =
                    parse_authorized_ed25519_line(rec.public_key.trim())
                {
                    if stored_vk.as_bytes() == vk.as_bytes()
                        || stored_blob.as_slice() == auth.public_blob.as_slice()
                    {
                        return Some(acct.username.clone());
                    }
                }
            }
        }
    }

    // 2. `# <user> (<title>)` ownership annotation from `authorized_keys`.
    if let Some(ref comment_user) = auth.key_comment_user {
        let cu = comment_user.trim();
        if !cu.is_empty() {
            if store.users.is_empty() {
                return Some(cu.to_string());
            }
            if let Some(acct) = store.users.iter().find(|u| u.username == cu) {
                return Some(acct.username.clone());
            }
            // Key explicitly belongs to an unknown user; never fall back to request_user.
            return None;
        }
    }

    // 3. Fallback to SSH `USERAUTH_REQUEST` username ONLY in single-user mode
    // (`store.users.is_empty()`). When `ForgeStore` accounts exist, fail closed
    // so an unannotated key cannot impersonate keyless accounts via `request_user`.
    if !store.users.is_empty() {
        return None;
    }
    let req_user = auth.request_user.trim();
    if req_user.is_empty() {
        return None;
    }
    Some(req_user.to_string())
}

/// Enforce `ForgeStore` repository RBAC on SSH `git-upload-pack` / `git-receive-pack` (`SEC-02`).
///
/// Mirrors `web_ui::auth_api`:
/// - Corrupted `ForgeStore` always fails closed for both reads and writes.
/// - Archived repositories always reject writes (`git-receive-pack`).
/// - Single-user mode (`store.users.is_empty()`) stays open.
/// - Public repositories allow reads (`git-upload-pack`) for any authenticated SSH key.
/// - Private repository reads require an `admin`, `maintainer`, or explicit `store.collaborators`
///   account; writes always require an `admin` or `maintainer` (matching HTTP parity).
fn check_ssh_repo_rbac(
    store: &ForgeStore,
    effective_user: Option<&str>,
    is_write: bool,
) -> Result<(), String> {
    if store.corrupt {
        return Err("forge store is corrupted (fail-closed)".into());
    }
    if is_write && store.archived {
        return Err("repository is archived (read-only)".into());
    }
    if store.users.is_empty() {
        return Ok(());
    }
    let is_private = store.visibility == "private";
    if !is_write && !is_private {
        return Ok(());
    }
    let Some(username) = effective_user else {
        return Err(if is_write {
            "permission denied: SSH key is not bound to a repository write account".into()
        } else {
            "permission denied: private repository requires an authorized SSH user".into()
        });
    };
    let Some(acct) = store.users.iter().find(|u| u.username == username) else {
        return Err(format!(
            "permission denied: SSH user '{username}' is not registered"
        ));
    };
    let is_collaborator = store.collaborators.iter().any(|c| c == username);
    let is_privileged = acct.role == "admin" || acct.role == "maintainer";
    if is_privileged || (!is_write && is_collaborator) {
        Ok(())
    } else if is_write {
        Err(format!(
            "permission denied: role '{}' cannot push to this repository",
            acct.role
        ))
    } else {
        Err(format!(
            "permission denied: role '{}' cannot read private repository",
            acct.role
        ))
    }
}

/// Offline publickey verify Partial: parse authorized_keys + ed25519 verify path.
fn publickey_verify_scaffold(authorized_keys: &Path, host: Option<&HostEd25519>) -> String {
    let mut notes = Vec::new();
    let auth_probe = probe_authorized_keys(authorized_keys);
    notes.push(format!("authorized_keys_probe={auth_probe}"));
    let keys = load_authorized_ed25519_keys(authorized_keys);
    notes.push(format!("auth_ed25519_lines={}", keys.len()));
    if !keys.is_empty() {
        notes.push("auth_pubkey_line=ssh-ed25519_parse_ok".into());
    }
    if let Some(h) = host {
        let challenge = Sha256::digest(b"arks-ssh-partial-auth-verify-challenge");
        let sig = h.signing.sign(&challenge);
        match h.signing.verifying_key().verify(&challenge, &sig) {
            Ok(()) => notes.push("auth_verify_selfcheck=ok (host key; offline Partial)".into()),
            Err(e) => notes.push(format!("auth_verify_selfcheck=fail ({e})")),
        }
        // If host pubkey is also listed in authorized_keys, prove authorized verify path.
        let sig_blob = sign_ssh_ed25519(h, &challenge);
        match verify_publickey_against_authorized(
            authorized_keys,
            &h.public_blob,
            &challenge,
            &sig_blob,
        ) {
            Ok(_) => notes.push("auth_authorized_keys_verify=ok (host key listed; Partial)".into()),
            Err(e) => notes.push(format!("auth_authorized_keys_verify=skip ({e})")),
        }
    } else {
        notes.push("auth_verify_selfcheck=skipped (no host key)".into());
    }
    notes.join("; ")
}

fn parse_ssh_ed25519_verifying(blob: &[u8]) -> Option<VerifyingKey> {
    let mut off = 0usize;
    let alg = read_ssh_bytes(blob, &mut off)?;
    if alg.as_slice() != b"ssh-ed25519" {
        return None;
    }
    let pub32 = read_ssh_bytes(blob, &mut off)?;
    if pub32.len() != 32 {
        return None;
    }
    let mut a = [0u8; 32];
    a.copy_from_slice(&pub32);
    VerifyingKey::from_bytes(&a).ok()
}

/// Parse `git-upload-pack '|git-receive-pack` from an SSH `exec` command string (Partial).
fn parse_git_exec_service(cmd: &str) -> Option<&'static str> {
    if cmd.contains('\0') {
        return None;
    }
    let c = cmd.trim().trim_matches('\'').trim_matches('"');
    let first = c.split_whitespace().next().unwrap_or("");
    let base = first.rsplit('/').next().unwrap_or(first);
    match base {
        "git-upload-pack" | "upload-pack" => Some("git-upload-pack"),
        "git-receive-pack" | "receive-pack" => Some("git-receive-pack"),
        _ => None,
    }
}

fn extract_ssh_exec_path_arg(exec_cmd: &str) -> Result<String, String> {
    if exec_cmd.contains('\0') {
        return Err("invalid ssh exec command: NUL byte rejected".into());
    }
    let trimmed = exec_cmd.trim();
    let mut parts = trimmed.splitn(2, char::is_whitespace);
    let _svc = parts.next().unwrap_or("");
    let raw = parts.next().unwrap_or("").trim();
    let unquoted = if (raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2)
        || (raw.starts_with('"') && raw.ends_with('"') && raw.len() >= 2)
    {
        &raw[1..raw.len() - 1]
    } else {
        raw
    };
    if unquoted.contains('\0') {
        return Err("invalid multi-repo ssh path: NUL byte rejected".into());
    }
    Ok(unquoted.to_string())
}

/// Resolve a single repository or multi-repo child under `base_path` from an SSH `exec` command.
///
/// Multi-repo roots (`INT-S04`) accept `<root>/<repo>.git`, `<root>/<repo>`, or
/// `<root>/<repo>/.git`, strictly rejecting `..`, NUL, backslashes, hidden segments,
/// and canonical path escapes (including symlinks outside `base_path`).
fn open_ssh_repo(base_path: &Path, exec_cmd: &str) -> Result<Repository, String> {
    if exec_cmd.contains('\0') {
        return Err("invalid ssh exec command: NUL byte rejected".into());
    }
    // Single-repo mode: `base_path` (or `base_path/.git`) is itself a repository.
    if base_path.join("HEAD").is_file() {
        return Repository::open(base_path)
            .map_err(|e| format!("open repo {}: {e}", base_path.display()));
    }
    let dot_git = base_path.join(".git");
    if dot_git.join("HEAD").is_file() {
        return Repository::open(&dot_git)
            .map_err(|e| format!("open repo {}: {e}", dot_git.display()));
    }

    // Multi-repo root mode: extract and strictly validate target repo under `base_path`.
    let arg = extract_ssh_exec_path_arg(exec_cmd)?;
    if arg.is_empty() || arg.contains("..") || arg.contains('\\') || arg.contains('\0') {
        return Err(format!("invalid multi-repo ssh path: {arg}"));
    }
    let rel = arg.trim_start_matches('/').trim_end_matches('/');
    if rel.is_empty() || rel.contains("//") {
        return Err(format!("invalid multi-repo ssh path: {arg}"));
    }
    let mut seg_count = 0usize;
    for comp in Path::new(rel).components() {
        match comp {
            Component::Normal(os) => {
                let Some(seg) = os.to_str() else {
                    return Err(format!("invalid multi-repo ssh path: {arg}"));
                };
                if seg.is_empty()
                    || seg.starts_with('.')
                    || seg.contains("..")
                    || seg.contains('\\')
                    || seg.contains('\0')
                {
                    return Err(format!("invalid multi-repo ssh path: {arg}"));
                }
                seg_count += 1;
            }
            _ => return Err(format!("invalid multi-repo ssh path: {arg}")),
        }
    }
    if seg_count == 0 {
        return Err(format!("invalid multi-repo ssh path: {arg}"));
    }
    let clean = rel.trim_end_matches(".git");
    if clean.is_empty() || clean.ends_with('/') {
        return Err(format!("invalid multi-repo ssh path: {arg}"));
    }
    if Path::new(clean)
        .file_name()
        .and_then(|n| n.to_str())
        .is_none_or(|n| n.is_empty() || n.starts_with('.'))
    {
        return Err(format!("invalid multi-repo ssh path: {arg}"));
    }

    let canon_base = std::fs::canonicalize(base_path)
        .map_err(|e| format!("open repo root {}: {e}", base_path.display()))?;
    let candidates = [
        base_path.join(format!("{clean}.git")),
        base_path.join(clean),
        base_path.join(clean).join(".git"),
    ];
    for candidate in candidates {
        if !candidate.join("HEAD").is_file() {
            continue;
        }
        let canon_cand = std::fs::canonicalize(&candidate)
            .map_err(|e| format!("open repo {}: {e}", candidate.display()))?;
        if !canon_cand.starts_with(&canon_base) || canon_cand == canon_base {
            return Err(format!("invalid multi-repo ssh path (escapes root): {arg}"));
        }
        return Repository::open(&canon_cand)
            .map_err(|e| format!("open repo {}: {e}", canon_cand.display()));
    }
    Err(format!(
        "open repo {}: not found under {}",
        arg,
        base_path.display()
    ))
}

/// Dispatch session `exec` into existing pack stdio paths (Partial; not Claimed SSH channel e2e).
fn dispatch_git_exec_to_pack(repo_path: &Path, exec_cmd: &str) -> Result<String, String> {
    let Some(svc) = parse_git_exec_service(exec_cmd) else {
        return Err(format!("exec not git-upload-pack|receive-pack: {exec_cmd}"));
    };
    let mut repo = open_ssh_repo(repo_path, exec_cmd)?;
    // Empty duplex: proves dispatch wiring into pack entrypoints; real SSH channel IO Partial.
    let mut buf = Cursor::new(Vec::<u8>::new());
    match svc {
        "git-upload-pack" => match upload_pack_stream(&repo, &mut buf) {
            Ok(()) => Ok(
                "channel_exec=git-upload-pack dispatched upload_pack_stream ok \
                 (Partial empty-peer; Claimed SSH channel e2e Missing)"
                    .to_string(),
            ),
            Err(e) => Ok(format!(
                "channel_exec=git-upload-pack dispatch reached upload_pack_stream err={e} \
                 (Partial; empty peer expected; not Claimed)"
            )),
        },
        "git-receive-pack" => {
            let store = ForgeStore::load_shared(repo.common_dir());
            if store.corrupt {
                return Err("forge store is corrupted (fail-closed)".into());
            }
            if store.archived {
                return Err("repository is archived (read-only)".into());
            }
            match receive_pack_stream_as(&mut repo, &mut buf, &Pusher::ssh()) {
                Ok(()) => Ok(
                    "channel_exec=git-receive-pack dispatched receive_pack_stream ok \
                     (Partial empty-peer; Claimed SSH channel e2e Missing)"
                        .to_string(),
                ),
                Err(e) => Ok(format!(
                    "channel_exec=git-receive-pack dispatch reached receive_pack_stream err={e} \
                     (Partial; empty peer expected; not Claimed)"
                )),
            }
        }
        _ => Err(format!("unknown service {svc}")),
    }
}

fn channel_git_hookup_scaffold(repo_path: &Path) -> String {
    let st = path_status(repo_path);
    let up = dispatch_git_exec_to_pack(repo_path, "git-upload-pack '.'");
    let rp = dispatch_git_exec_to_pack(repo_path, "git-receive-pack '.'");
    format!(
        "channel_session=partial_dispatch; repo_path={} ({st}); upload={:?}; receive={:?}; \
         design ≠ Claimed SSH git subsystem e2e",
        repo_path.display(),
        up,
        rp
    )
}

/// Encode the X25519 output string as the positive SSH `mpint K`.
///
/// RFC 8731 §3.1 deliberately reinterprets the returned octets directly as
/// an unsigned fixed-length integer in network byte order; it does not first
/// reverse X25519's little-endian field-element representation.
fn x25519_shared_as_mpint(shared_wire: &[u8; 32]) -> Vec<u8> {
    let magnitude = shared_wire.to_vec();
    let first_nonzero = magnitude
        .iter()
        .position(|b| *b != 0)
        .unwrap_or(magnitude.len());
    let mut value = magnitude[first_nonzero..].to_vec();
    if value.first().is_some_and(|b| b & 0x80 != 0) {
        value.insert(0, 0);
    }
    ssh_string(&value)
}

/// RFC 4253 §7.2 KDF. `encoded_k` includes the SSH mpint length prefix.
fn ssh_kdf_bytes(encoded_k: &[u8], exchange_hash: &[u8], letter: u8, n: usize) -> Vec<u8> {
    let mut out = Vec::with_capacity(n);
    while out.len() < n {
        let mut h = Sha256::new();
        h.update(encoded_k);
        h.update(exchange_hash);
        if out.is_empty() {
            h.update([letter]);
            h.update(exchange_hash); // session_id is H for the first key exchange.
        } else {
            h.update(&out);
        }
        out.extend_from_slice(&h.finalize());
    }
    out.truncate(n);
    out
}

fn openssh_chacha(
    encoded_k: &[u8],
    exchange_hash: &[u8],
    client_to_server: bool,
    sequence: u32,
) -> Result<OpenSshChaCha, String> {
    let letter = if client_to_server { b'C' } else { b'D' };
    let key = ssh_kdf_bytes(encoded_k, exchange_hash, letter, 64);
    OpenSshChaCha::new(&key, sequence)
}

fn encrypted_transport_selfcheck(encoded_k: &[u8], exchange_hash: &[u8]) -> String {
    let mut c2s = match openssh_chacha(encoded_k, exchange_hash, true, 0) {
        Ok(c) => c,
        Err(e) => return format!("encrypted_transport=selfcheck_fail ({e})"),
    };
    let sample = b"arks-ssh-partial-post-newkeys";
    match c2s.seal_packet(sample).and_then(|packet| {
        let mut peer = openssh_chacha(encoded_k, exchange_hash, true, 0)?;
        let encrypted_length = packet[..4].try_into().map_err(|_| "length")?;
        // The selfcheck knows the deterministic packet body length.
        let body_len = packet.len() - 4 - 16;
        let body = packet[4..4 + body_len].to_vec();
        let tag = packet[4 + body_len..].try_into().map_err(|_| "tag")?;
        peer.open_packet(encrypted_length, body, tag, 65_536)
    }) {
        Ok(pt) if pt == sample => "encrypted_transport=OpenSSH-ChaCha packet selfcheck=ok \
             (live stock-client receipt still required for Claimed)"
            .into(),
        Ok(_) => "encrypted_transport=selfcheck_mismatch".into(),
        Err(e) => format!("encrypted_transport=selfcheck_fail ({e})"),
    }
}

fn write_encrypted_packet(
    stream: &mut TcpStream,
    cipher: &mut OpenSshChaCha,
    payload: &[u8],
) -> Result<(), String> {
    cipher.write_packet(stream, payload)
}

fn read_encrypted_packet(
    stream: &mut TcpStream,
    cipher: &mut OpenSshChaCha,
    max: usize,
) -> Result<Vec<u8>, String> {
    cipher.read_packet(stream, max)
}

/// After NEWKEYS: AEAD + USERAUTH loop + session channel → pack duplex.
fn continue_after_newkeys(
    stream: &mut TcpStream,
    encoded_k: &[u8],
    exchange_hash: &[u8],
    initial_sequence: u32,
    authorized_keys: &Path,
    repo_path: &Path,
    host: Option<&HostEd25519>,
) -> (SshStage, String) {
    let mut notes = vec![encrypted_transport_selfcheck(encoded_k, exchange_hash)];
    let mut c2s = match openssh_chacha(encoded_k, exchange_hash, true, initial_sequence) {
        Ok(c) => c,
        Err(e) => return (SshStage::EncryptedTransport, format!("c2s key error: {e}")),
    };
    let mut s2c = match openssh_chacha(encoded_k, exchange_hash, false, initial_sequence) {
        Ok(c) => c,
        Err(e) => return (SshStage::EncryptedTransport, format!("s2c key error: {e}")),
    };

    // Stock OpenSSH: SERVICE_REQUEST ssh-userauth → SERVICE_ACCEPT, then one or
    // more USERAUTH_REQUEST (none → publickey query → signed publickey).
    let _ = stream.set_nodelay(true);
    // Pack negotiation + tiny clone can exceed the accept-time 2s probe budget.
    let _ = stream.set_read_timeout(Some(Duration::from_secs(30)));
    let _ = stream.set_write_timeout(Some(Duration::from_secs(30)));
    let mut next = read_encrypted_packet(stream, &mut c2s, 65_536);
    if let Ok(payload) = &next
        && payload.first() == Some(&5)
    {
        let mut off = 1usize;
        if let Some(service) = read_ssh_bytes(payload, &mut off) {
            let mut accept = vec![6]; // SSH_MSG_SERVICE_ACCEPT
            accept.extend(ssh_string(&service));
            match write_encrypted_packet(stream, &mut s2c, &accept) {
                Ok(()) => notes.push(format!(
                    "wire_SERVICE_ACCEPT={} (OpenSSH ChaCha decrypt+encrypt ok)",
                    String::from_utf8_lossy(&service)
                )),
                Err(e) => notes.push(format!("wire_SERVICE_ACCEPT=write_err ({e})")),
            }
            next = read_encrypted_packet(stream, &mut c2s, 65_536);
        }
    }

    let mut authed_identity: Option<SshAuthIdentity> = None;
    for round in 0..8 {
        let payload = match next {
            Ok(p) => p,
            Err(e) => {
                notes.push(format!("wire_auth=timeout_or_err round={round} ({e})"));
                break;
            }
        };
        if payload.first() != Some(&50) {
            notes.push(format!(
                "wire_post_newkeys_msg={} (expected USERAUTH=50)",
                payload.first().copied().unwrap_or(0)
            ));
            break;
        }
        notes.push(format!("wire_USERAUTH_REQUEST=seen round={round}"));
        let (identity, auth_note) = handle_userauth_request_partial(
            &payload,
            exchange_hash,
            authorized_keys,
            host,
            stream,
            &mut s2c,
        );
        notes.push(auth_note);
        if let Some(id) = identity {
            authed_identity = Some(id);
            break;
        }
        next = read_encrypted_packet(stream, &mut c2s, 65_536);
    }

    let Some(auth_id) = authed_identity else {
        notes.push(publickey_verify_scaffold(authorized_keys, host));
        notes.push(channel_git_hookup_scaffold(repo_path));
        return (SshStage::AuthPublickey, notes.join("; "));
    };

    match run_session_channel_pack(stream, &mut c2s, &mut s2c, repo_path, &auth_id, &mut notes) {
        Ok(()) => (SshStage::ChannelSession, notes.join("; ")),
        Err(e) => {
            notes.push(e);
            notes.push(channel_git_hookup_scaffold(repo_path));
            (SshStage::ChannelSession, notes.join("; "))
        }
    }
}

/// SSH session channel + `exec` → live `upload_pack_stream` / `receive_pack_stream`.
fn run_session_channel_pack(
    stream: &mut TcpStream,
    c2s: &mut OpenSshChaCha,
    s2c: &mut OpenSshChaCha,
    repo_path: &Path,
    auth_id: &SshAuthIdentity,
    notes: &mut Vec<String>,
) -> Result<(), String> {
    let mut peer_chan: Option<u32> = None;
    let mut peer_initial_window: u32 = 0;
    let mut peer_max_packet: u32 = SSH_LOCAL_MAX_PACKET;
    let our_chan: u32 = 0;
    let mut exec_cmd: Option<String> = None;

    for _ in 0..32 {
        let msg = read_encrypted_packet(stream, c2s, 65_536)
            .map_err(|e| format!("wire_channel=timeout_or_err ({e})"))?;
        match msg.first().copied() {
            Some(90) => {
                // SSH_MSG_CHANNEL_OPEN
                let mut off = 1usize;
                let chan_type = read_ssh_bytes(&msg, &mut off).unwrap_or_default();
                let sender = read_u32(&msg, &mut off).unwrap_or(0);
                peer_initial_window = read_u32(&msg, &mut off).unwrap_or(0);
                peer_max_packet = read_u32(&msg, &mut off)
                    .unwrap_or(SSH_LOCAL_MAX_PACKET)
                    .max(1024);
                notes.push(format!(
                    "wire_CHANNEL_OPEN={} sender={sender} peer_window={peer_initial_window}",
                    String::from_utf8_lossy(&chan_type)
                ));
                if chan_type.as_slice() != b"session" {
                    let mut fail = vec![92]; // CHANNEL_OPEN_FAILURE
                    fail.extend_from_slice(&sender.to_be_bytes());
                    fail.extend_from_slice(&2u32.to_be_bytes()); // SSH_OPEN_ADMINISTRATIVELY_PROHIBITED
                    fail.extend(ssh_string(b"only session"));
                    fail.extend(ssh_string(b""));
                    let _ = write_encrypted_packet(stream, s2c, &fail);
                    return Err("channel_open=non_session".into());
                }
                peer_chan = Some(sender);
                let mut conf = vec![91]; // CHANNEL_OPEN_CONFIRMATION
                conf.extend_from_slice(&sender.to_be_bytes());
                conf.extend_from_slice(&our_chan.to_be_bytes());
                conf.extend_from_slice(&SSH_LOCAL_INITIAL_WINDOW.to_be_bytes());
                conf.extend_from_slice(&SSH_LOCAL_MAX_PACKET.to_be_bytes());
                write_encrypted_packet(stream, s2c, &conf)
                    .map_err(|e| format!("channel_open_confirm=write_err ({e})"))?;
            }
            Some(93) => {
                // RFC 4254 SSH_MSG_CHANNEL_WINDOW_ADJUST received prior to exec.
                let mut off = 1usize;
                let _recip = read_u32(&msg, &mut off).unwrap_or(0);
                let bytes_to_add = read_u32(&msg, &mut off).unwrap_or(0);
                peer_initial_window = peer_initial_window.saturating_add(bytes_to_add);
            }
            Some(98) => {
                // CHANNEL_REQUEST
                let mut off = 1usize;
                let recip = read_u32(&msg, &mut off).unwrap_or(0);
                let req = read_ssh_bytes(&msg, &mut off).unwrap_or_default();
                let want_reply = msg.get(off).copied().unwrap_or(0) != 0;
                if off < msg.len() {
                    off += 1;
                }
                if recip != our_chan {
                    notes.push(format!("wire_CHANNEL_REQUEST=wrong_recip={recip}"));
                }
                if req.as_slice() == b"exec" {
                    let cmd = read_ssh_bytes(&msg, &mut off).unwrap_or_default();
                    let cmd_s = String::from_utf8_lossy(&cmd).into_owned();
                    notes.push(format!("wire_CHANNEL_REQUEST_exec={cmd_s}"));
                    if want_reply {
                        let mut ok = vec![99]; // CHANNEL_SUCCESS
                        ok.extend_from_slice(&peer_chan.unwrap_or(0).to_be_bytes());
                        write_encrypted_packet(stream, s2c, &ok)
                            .map_err(|e| format!("channel_success=write_err ({e})"))?;
                    }
                    exec_cmd = Some(cmd_s);
                    break;
                }
                if req.as_slice() == b"subsystem" {
                    // git uses exec, not subsystem; refuse cleanly.
                    notes.push("wire_CHANNEL_REQUEST_subsystem=refused".into());
                    if want_reply {
                        let mut fail = vec![100];
                        fail.extend_from_slice(&peer_chan.unwrap_or(0).to_be_bytes());
                        let _ = write_encrypted_packet(stream, s2c, &fail);
                    }
                    continue;
                }
                // OpenSSH git often sends `env` (e.g. GIT_PROTOCOL) before exec.
                // Reply SUCCESS so the client continues; we do not apply env vars.
                notes.push(format!(
                    "wire_CHANNEL_REQUEST_ack={}",
                    String::from_utf8_lossy(&req)
                ));
                if want_reply {
                    let mut ok = vec![99]; // CHANNEL_SUCCESS
                    ok.extend_from_slice(&peer_chan.unwrap_or(0).to_be_bytes());
                    let _ = write_encrypted_packet(stream, s2c, &ok);
                }
            }
            Some(96) | Some(97) => {
                notes.push(format!(
                    "wire_channel_early_eof_or_close={}",
                    msg.first().copied().unwrap_or(0)
                ));
                break;
            }
            Some(2) | Some(4) => {
                // ignore / debug
            }
            other => {
                notes.push(format!("wire_channel_msg={}", other.unwrap_or(0)));
            }
        }
    }

    let Some(peer) = peer_chan else {
        return Err("channel_open=missing".into());
    };
    let Some(cmd) = exec_cmd else {
        return Err("channel_exec=missing".into());
    };

    let exit_code: u32 = if parse_git_exec_service(&cmd).is_some() {
        let mut pipe = SshChannelPipe {
            stream,
            c2s,
            s2c,
            peer_channel: peer,
            max_data: peer_max_packet.min(16_384) as usize,
            local_window_remaining: SSH_LOCAL_INITIAL_WINDOW,
            local_window_consumed: 0,
            peer_window_remaining: peer_initial_window,
            inbox: VecDeque::new(),
            eof: false,
            closed: false,
        };
        match dispatch_git_exec_live(repo_path, &cmd, auth_id, &mut pipe) {
            Ok(pack_note) => {
                notes.push(pack_note);
                0
            }
            Err(e) => {
                notes.push(e);
                1
            }
        }
    } else if cmd.trim() == "true" || cmd.trim().is_empty() {
        // B1 OpenSSH probe uses `ssh … true`; succeed with empty body.
        notes.push("channel_exec=true_ok".into());
        0
    } else {
        notes.push(format!("channel_exec=unsupported ({cmd})"));
        127
    };

    // Stock OpenSSH/git require exit-status before EOF/CLOSE or the client
    // treats the remote command as failed (clone_rc=128) even after a good pack.
    send_channel_exit_status(stream, s2c, peer, exit_code)?;
    let mut eof_pkt = vec![96]; // CHANNEL_EOF
    eof_pkt.extend_from_slice(&peer.to_be_bytes());
    write_encrypted_packet(stream, s2c, &eof_pkt)
        .map_err(|e| format!("channel_eof=write_err ({e})"))?;
    let mut close_pkt = vec![97]; // CHANNEL_CLOSE
    close_pkt.extend_from_slice(&peer.to_be_bytes());
    write_encrypted_packet(stream, s2c, &close_pkt)
        .map_err(|e| format!("channel_close=write_err ({e})"))?;
    // Ensure CHANNEL_DATA / exit-status reached the peer before TCP teardown.
    let _ = stream.flush();
    // Drain a short window for the client's CHANNEL_CLOSE so git does not
    // report "Connection closed by remote host" after a successful pack.
    let _ = stream.set_read_timeout(Some(Duration::from_millis(500)));
    for _ in 0..8 {
        match read_encrypted_packet(stream, c2s, 65_536) {
            Ok(msg) if msg.first() == Some(&97) || msg.first() == Some(&96) => break,
            Ok(_) => continue,
            Err(_) => break,
        }
    }
    if exit_code == 0 {
        Ok(())
    } else {
        Err(format!("channel_exec=exit_status={exit_code}"))
    }
}

fn send_channel_exit_status(
    stream: &mut TcpStream,
    s2c: &mut OpenSshChaCha,
    peer_channel: u32,
    code: u32,
) -> Result<(), String> {
    let mut pkt = vec![98]; // SSH_MSG_CHANNEL_REQUEST
    pkt.extend_from_slice(&peer_channel.to_be_bytes());
    pkt.extend(ssh_string(b"exit-status"));
    pkt.push(0); // want_reply = false
    pkt.extend_from_slice(&code.to_be_bytes());
    write_encrypted_packet(stream, s2c, &pkt).map_err(|e| format!("exit_status=write_err ({e})"))
}

fn send_channel_window_adjust(
    stream: &mut TcpStream,
    s2c: &mut OpenSshChaCha,
    peer_channel: u32,
    bytes_to_add: u32,
) -> Result<(), String> {
    let mut pkt = Vec::with_capacity(9);
    pkt.push(93); // SSH_MSG_CHANNEL_WINDOW_ADJUST (RFC 4254 §5.2)
    pkt.extend_from_slice(&peer_channel.to_be_bytes());
    pkt.extend_from_slice(&bytes_to_add.to_be_bytes());
    write_encrypted_packet(stream, s2c, &pkt).map_err(|e| format!("window_adjust=write_err ({e})"))
}

/// Duplex adapter: SSH CHANNEL_DATA ↔ Read+Write for pack sessions, enforcing
/// bidirectional RFC 4254 `SSH_MSG_CHANNEL_WINDOW_ADJUST` flow control (`NET-02`).
struct SshChannelPipe<'a> {
    stream: &'a mut TcpStream,
    c2s: &'a mut OpenSshChaCha,
    s2c: &'a mut OpenSshChaCha,
    peer_channel: u32,
    max_data: usize,
    local_window_remaining: u32,
    local_window_consumed: u32,
    peer_window_remaining: u32,
    inbox: VecDeque<u8>,
    eof: bool,
    closed: bool,
}

impl SshChannelPipe<'_> {
    fn consume_local_window(&mut self, bytes: usize) -> std::io::Result<()> {
        let delta = u32::try_from(bytes).unwrap_or(u32::MAX);
        self.local_window_remaining = self.local_window_remaining.saturating_sub(delta);
        self.local_window_consumed = self.local_window_consumed.saturating_add(delta);
        if self.local_window_consumed >= SSH_LOCAL_WINDOW_REFILL_THRESHOLD
            || (self.local_window_remaining < SSH_LOCAL_WINDOW_REFILL_THRESHOLD
                && self.local_window_consumed > 0)
        {
            let add = self.local_window_consumed;
            send_channel_window_adjust(self.stream, self.s2c, self.peer_channel, add)
                .map_err(std::io::Error::other)?;
            self.local_window_remaining = self.local_window_remaining.saturating_add(add);
            self.local_window_consumed = 0;
        }
        Ok(())
    }

    /// Read and dispatch one incoming encrypted SSH packet, updating inbox,
    /// local/peer flow-control windows, and EOF/CLOSE flags.
    fn pump_one_packet(&mut self) -> std::io::Result<()> {
        let msg =
            read_encrypted_packet(self.stream, self.c2s, 65_536).map_err(std::io::Error::other)?;
        match msg.first().copied() {
            Some(94) => {
                // SSH_MSG_CHANNEL_DATA
                let mut off = 1usize;
                let _recip = read_u32(&msg, &mut off).unwrap_or(0);
                if let Some(data) = read_ssh_bytes(&msg, &mut off) {
                    let n = data.len();
                    self.inbox.extend(data);
                    self.consume_local_window(n)?;
                }
            }
            Some(95) => {
                // SSH_MSG_CHANNEL_EXTENDED_DATA also consumes local window per RFC 4254 §5.2.
                let mut off = 1usize;
                let _recip = read_u32(&msg, &mut off).unwrap_or(0);
                let _data_type = read_u32(&msg, &mut off).unwrap_or(0);
                if let Some(data) = read_ssh_bytes(&msg, &mut off) {
                    self.consume_local_window(data.len())?;
                }
            }
            Some(93) => {
                // SSH_MSG_CHANNEL_WINDOW_ADJUST from peer increases our send budget.
                let mut off = 1usize;
                let _recip = read_u32(&msg, &mut off).unwrap_or(0);
                let bytes_to_add = read_u32(&msg, &mut off).unwrap_or(0);
                self.peer_window_remaining =
                    self.peer_window_remaining.saturating_add(bytes_to_add);
            }
            Some(96) => {
                // SSH_MSG_CHANNEL_EOF closes peer->server data; peer may still send WINDOW_ADJUST.
                self.eof = true;
            }
            Some(97) => {
                // SSH_MSG_CHANNEL_CLOSE terminates both directions.
                self.eof = true;
                self.closed = true;
            }
            Some(98) => {
                // Unexpected late request — fail if want_reply.
                let mut off = 1usize;
                let _ = read_u32(&msg, &mut off);
                let _ = read_ssh_bytes(&msg, &mut off);
                let want_reply = msg.get(off).copied().unwrap_or(0) != 0;
                if want_reply {
                    let mut fail = vec![100];
                    fail.extend_from_slice(&self.peer_channel.to_be_bytes());
                    let _ = write_encrypted_packet(self.stream, self.s2c, &fail);
                }
            }
            Some(2) | Some(4) => {}
            _ => {}
        }
        Ok(())
    }

    /// Best-effort stderr diagnostic over `SSH_MSG_CHANNEL_EXTENDED_DATA` (stderr=1).
    fn send_stderr_notice(&mut self, msg: &str) {
        if msg.is_empty() || self.closed {
            return;
        }
        let data = msg.as_bytes();
        let allowed = usize::try_from(self.peer_window_remaining).unwrap_or(usize::MAX);
        let chunk = data.len().min(self.max_data.max(1)).min(allowed);
        if chunk == 0 {
            return;
        }
        let mut pkt = vec![95]; // SSH_MSG_CHANNEL_EXTENDED_DATA
        pkt.extend_from_slice(&self.peer_channel.to_be_bytes());
        pkt.extend_from_slice(&1u32.to_be_bytes()); // SSH_EXTENDED_DATA_STDERR
        pkt.extend(ssh_string(&data[..chunk]));
        if write_encrypted_packet(self.stream, self.s2c, &pkt).is_ok() {
            self.peer_window_remaining = self
                .peer_window_remaining
                .saturating_sub(u32::try_from(chunk).unwrap_or(u32::MAX));
        }
    }
}

impl Read for SshChannelPipe<'_> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        while self.inbox.is_empty() && !self.eof {
            self.pump_one_packet()?;
        }
        if self.inbox.is_empty() {
            return Ok(0);
        }
        self.inbox.read(buf)
    }
}

impl Write for SshChannelPipe<'_> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        while self.peer_window_remaining == 0 {
            if self.closed {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "SSH peer closed channel with zero send window",
                ));
            }
            self.pump_one_packet()?;
        }
        let allowed = usize::try_from(self.peer_window_remaining).unwrap_or(usize::MAX);
        let chunk = buf.len().min(self.max_data.max(1)).min(allowed);
        let mut pkt = vec![94]; // CHANNEL_DATA
        pkt.extend_from_slice(&self.peer_channel.to_be_bytes());
        pkt.extend(ssh_string(&buf[..chunk]));
        write_encrypted_packet(self.stream, self.s2c, &pkt).map_err(std::io::Error::other)?;
        self.peer_window_remaining = self
            .peer_window_remaining
            .saturating_sub(u32::try_from(chunk).unwrap_or(u32::MAX));
        Ok(chunk)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.stream.flush()
    }
}

fn dispatch_git_exec_live(
    repo_path: &Path,
    exec_cmd: &str,
    auth_id: &SshAuthIdentity,
    pipe: &mut SshChannelPipe<'_>,
) -> Result<String, String> {
    let Some(svc) = parse_git_exec_service(exec_cmd) else {
        return Err(format!("exec not git-upload-pack|receive-pack: {exec_cmd}"));
    };
    let mut repo = open_ssh_repo(repo_path, exec_cmd)?;
    let is_single_repo =
        repo_path.join("HEAD").is_file() || repo_path.join(".git").join("HEAD").is_file();
    if !is_single_repo
        && repo.common_dir() != repo_path
        && repo_path.join(".arks-global-auth").exists()
    {
        let global_store = ForgeStore::load_shared(&repo_path.join(".arks-global-auth"));
        if global_store.corrupt {
            let reason = "global forge store is corrupted (fail-closed)".to_string();
            pipe.send_stderr_notice(&format!("remote: {reason}\n"));
            return Err(reason);
        }
        crate::web_ui::sync_global_auth_into_repo(repo_path, repo.common_dir());
    }
    let store = ForgeStore::load_shared(repo.common_dir());
    let effective_user = resolve_ssh_identity(&store, auth_id);
    match svc {
        "git-upload-pack" => {
            if let Err(reason) = check_ssh_repo_rbac(&store, effective_user.as_deref(), false) {
                pipe.send_stderr_notice(&format!("remote: {reason}\n"));
                return Err(reason);
            }
            match upload_pack_stream(&repo, pipe) {
                Ok(()) => Ok(
                    "channel_exec=git-upload-pack live upload_pack_stream ok (OpenSSH channel)"
                        .into(),
                ),
                Err(e) => Err(format!("channel_exec=git-upload-pack live err={e}")),
            }
        }
        "git-receive-pack" => {
            if let Err(reason) = check_ssh_repo_rbac(&store, effective_user.as_deref(), true) {
                pipe.send_stderr_notice(&format!("remote: {reason}\n"));
                return Err(reason);
            }
            let pusher = match effective_user {
                Some(ref user) => Pusher::ssh_user(user.as_str()),
                None => Pusher::ssh(),
            };
            match receive_pack_stream_as(&mut repo, pipe, &pusher) {
                Ok(()) => Ok(
                    "channel_exec=git-receive-pack live receive_pack_stream ok (OpenSSH channel)"
                        .into(),
                ),
                Err(e) => Err(format!("channel_exec=git-receive-pack live err={e}")),
            }
        }
        _ => Err(format!("unknown service {svc}")),
    }
}

/// Handle one USERAUTH_REQUEST. Returns `(authenticated_identity, notes)`.
fn handle_userauth_request_partial(
    payload: &[u8],
    session_id: &[u8],
    authorized_keys: &Path,
    host: Option<&HostEd25519>,
    stream: &mut TcpStream,
    s2c: &mut OpenSshChaCha,
) -> (Option<SshAuthIdentity>, String) {
    // SSH_MSG_USERAUTH_REQUEST: 50 || string user || string service || string method || …
    let mut off = 1usize;
    let user = read_ssh_bytes(payload, &mut off).unwrap_or_default();
    let service = read_ssh_bytes(payload, &mut off).unwrap_or_default();
    let method = read_ssh_bytes(payload, &mut off).unwrap_or_default();
    let request_user = String::from_utf8_lossy(&user).trim().to_string();
    let mut notes = format!(
        "auth_user={} service={} method={}",
        request_user,
        String::from_utf8_lossy(&service),
        String::from_utf8_lossy(&method)
    );
    if method.as_slice() != b"publickey" {
        notes.push_str("; auth=refuse_non_publickey Partial");
        let mut failure = vec![51]; // SSH_MSG_USERAUTH_FAILURE
        failure.extend(ssh_name_list(&["publickey"]));
        failure.push(0); // partial success = false
        let _ = write_encrypted_packet(stream, s2c, &failure);
        return (None, notes);
    }
    if off >= payload.len() {
        notes.push_str("; auth=publickey_short");
        let mut failure = vec![51];
        failure.extend(ssh_name_list(&["publickey"]));
        failure.push(0);
        let _ = write_encrypted_packet(stream, s2c, &failure);
        return (None, notes);
    }
    let has_sig = payload[off] != 0;
    off += 1;
    let alg = read_ssh_bytes(payload, &mut off).unwrap_or_default();
    let pubkey = read_ssh_bytes(payload, &mut off).unwrap_or_default();
    notes.push_str(&format!(
        "; alg={} has_sig={has_sig}",
        String::from_utf8_lossy(&alg)
    ));
    if !has_sig {
        let keys = load_authorized_ed25519_keys(authorized_keys);
        let ok = keys
            .iter()
            .any(|entry| entry.blob.as_slice() == pubkey.as_slice());
        notes.push_str(&format!("; auth_pubkey_query_authorized={ok}"));
        if ok {
            let mut pk_ok = vec![60]; // SSH_MSG_USERAUTH_PK_OK
            pk_ok.extend(ssh_string(&alg));
            pk_ok.extend(ssh_string(&pubkey));
            let _ = write_encrypted_packet(stream, s2c, &pk_ok);
        } else {
            let mut failure = vec![51];
            failure.extend(ssh_name_list(&["publickey"]));
            failure.push(0);
            let _ = write_encrypted_packet(stream, s2c, &failure);
        }
        return (None, notes);
    }
    let signed_request_end = off;
    let sig = read_ssh_bytes(payload, &mut off).unwrap_or_default();
    let mut challenge = ssh_string(session_id);
    challenge.extend_from_slice(&payload[..signed_request_end]);
    match verify_publickey_against_authorized(authorized_keys, &pubkey, &challenge, &sig) {
        Ok(key_comment_user) => {
            notes.push_str("; auth_publickey_verify=ok against authorized_keys");
            let _ = write_encrypted_packet(stream, s2c, &[52]); // USERAUTH_SUCCESS
            let id = SshAuthIdentity {
                request_user,
                key_comment_user,
                public_blob: pubkey,
            };
            (Some(id), notes)
        }
        Err(e) => {
            // Offline scaffold note only — must not invent wire auth success.
            if let Some(h) = host {
                let ch = Sha256::digest(b"arks-ssh-partial-wire-auth-fallback");
                let sig_blob = sign_ssh_ed25519(h, &ch);
                match verify_publickey_against_authorized(
                    authorized_keys,
                    &h.public_blob,
                    &ch,
                    &sig_blob,
                ) {
                    Ok(_) => notes.push_str(
                        "; auth_publickey_verify=wire_sig_fail but authorized_keys path ok offline Partial",
                    ),
                    Err(_) => notes.push_str(&format!("; auth_publickey_verify=fail ({e})")),
                }
            } else {
                notes.push_str(&format!("; auth_publickey_verify=fail ({e})"));
            }
            let mut failure = vec![51];
            failure.extend(ssh_name_list(&["publickey"]));
            failure.push(0);
            let _ = write_encrypted_packet(stream, s2c, &failure);
            (None, notes)
        }
    }
}

/// Attempt peer ECDH + optional host-key sign + NEWKEYS (Partial).
#[allow(clippy::too_many_arguments)]
fn try_peer_ecdh_and_sign(
    stream: &mut TcpStream,
    peer_kex: &[String],
    host: Option<&HostEd25519>,
    our_id: &str,
    peer_id: &str,
    our_kexinit: &[u8],
    peer_kexinit: &[u8],
    authorized_keys: &Path,
    repo_path: &Path,
) -> (SshStage, String) {
    let want = peer_kex
        .iter()
        .any(|n| n == "curve25519-sha256" || n == "curve25519-sha256@libssh.org");
    if !want {
        return (
            SshStage::AlgoSelect,
            "ecdh_peer=skipped (no common curve25519-sha256)".into(),
        );
    }
    let payload = match read_ssh_packet(stream, 4096) {
        Ok(p) => p,
        Err(e)
            if e.kind() == std::io::ErrorKind::WouldBlock
                || e.kind() == std::io::ErrorKind::TimedOut =>
        {
            return (SshStage::Ecdh, "ecdh_peer=timeout (no ECDH_INIT)".into());
        }
        Err(e) => return (SshStage::Ecdh, format!("ecdh_peer=err ({e})")),
    };
    if payload.is_empty() || payload[0] != 30 {
        let mt = payload.first().copied().unwrap_or(0);
        return (SshStage::Ecdh, format!("ecdh_peer=unexpected_msg={mt}"));
    }
    if payload.len() < 5 {
        return (SshStage::Ecdh, "ecdh_peer=init_short".into());
    }
    let qlen = u32::from_be_bytes(payload[1..5].try_into().unwrap_or([0; 4])) as usize;
    if qlen != 32 || payload.len() < 5 + qlen {
        return (SshStage::Ecdh, format!("ecdh_peer=bad_q_c_len ({qlen})"));
    }
    let mut q_c = [0u8; 32];
    q_c.copy_from_slice(&payload[5..5 + 32]);
    let peer_pk = PublicKey::from(q_c);
    let secret = StaticSecret::random();
    let q_s = PublicKey::from(&secret);
    let shared = secret.diffie_hellman(&peer_pk);
    if shared.as_bytes().iter().all(|byte| *byte == 0) {
        return (
            SshStage::Ecdh,
            "ecdh_peer=all_zero_shared_secret (RFC 8731 reject)".into(),
        );
    }
    let mut h = Sha256::new();
    h.update(b"arks-ssh-partial-peer-ecdh");
    h.update(shared.as_bytes());
    h.update(q_s.as_bytes());
    let digest = h.finalize();
    let mut notes = vec![format!(
        "ecdh_peer=shared_ok q_s_ready=1 shared_sha256={:02x}{:02x}…",
        digest[0], digest[1]
    )];

    let Some(host) = host else {
        notes.push(
            "stop=host_key_sign Missing (no loadable ed25519 host key; KEX_ECDH_REPLY withheld)"
                .into(),
        );
        return (SshStage::HostKeySign, notes.join("; "));
    };

    // RFC 8731 exchange hash:
    // string V_C || string V_S || string I_C || string I_S ||
    // string K_S || string Q_C || string Q_S || mpint K.
    let encoded_k = x25519_shared_as_mpint(shared.as_bytes());
    let mut exchange = Vec::new();
    exchange.extend(ssh_string(
        peer_id.trim_end_matches(['\r', '\n']).as_bytes(),
    ));
    exchange.extend(ssh_string(our_id.trim_end_matches(['\r', '\n']).as_bytes()));
    exchange.extend(ssh_string(peer_kexinit));
    exchange.extend(ssh_string(our_kexinit));
    exchange.extend(ssh_string(&host.public_blob));
    exchange.extend(ssh_string(&q_c));
    exchange.extend(ssh_string(q_s.as_bytes()));
    exchange.extend_from_slice(&encoded_k);
    let exchange_hash = Sha256::digest(&exchange);
    let signature = sign_ssh_ed25519(host, &exchange_hash);

    let mut reply = Vec::new();
    reply.push(31); // SSH_MSG_KEX_ECDH_REPLY
    reply.extend(ssh_string(&host.public_blob));
    reply.extend(ssh_string(q_s.as_bytes()));
    reply.extend(ssh_string(&signature));
    if let Err(e) = write_ssh_packet(stream, &reply) {
        notes.push(format!("host_key_sign=reply_write_err ({e})"));
        return (SshStage::HostKeySign, notes.join("; "));
    }
    notes.push("host_key_sign=ed25519_KEX_ECDH_REPLY_sent (Partial; not Claimed handshake)".into());

    // SSH_MSG_NEWKEYS (cleartext), then switch to OpenSSH ChaCha packets.
    if let Err(e) = write_ssh_packet(stream, &[21]) {
        notes.push(format!("newkeys=write_err ({e})"));
        return (SshStage::NewKeys, notes.join("; "));
    }
    notes.push("newkeys=sent".into());
    match read_ssh_packet(stream, 256) {
        Ok(p) if p.first() == Some(&21) => notes.push("newkeys=peer_ok".into()),
        Ok(p) => notes.push(format!(
            "newkeys=peer_msg={}",
            p.first().copied().unwrap_or(0)
        )),
        Err(e)
            if e.kind() == std::io::ErrorKind::WouldBlock
                || e.kind() == std::io::ErrorKind::TimedOut =>
        {
            notes.push("newkeys=peer_timeout".into());
        }
        Err(e) => notes.push(format!("newkeys=peer_err ({e})")),
    }

    let strict_kex = peer_kex
        .iter()
        .any(|name| name == "kex-strict-c-v00@openssh.com");
    let initial_sequence = if strict_kex { 0 } else { 3 };
    notes.push(format!(
        "strict_kex={strict_kex} encrypted_initial_sequence={initial_sequence}"
    ));
    let (stage, post) = continue_after_newkeys(
        stream,
        &encoded_k,
        &exchange_hash,
        initial_sequence,
        authorized_keys,
        repo_path,
        Some(host),
    );
    notes.push(post);
    (stage, notes.join("; "))
}

struct PeerKexInit {
    kex: Vec<String>,
    hostkey: Vec<String>,
    enc_c2s: Vec<String>,
    enc_s2c: Vec<String>,
    mac_c2s: Vec<String>,
    mac_s2c: Vec<String>,
}

fn parse_peer_kexinit(payload: &[u8]) -> Option<PeerKexInit> {
    if payload.first().copied()? != 20 {
        return None;
    }
    let mut off = 1 + 16; // type + cookie
    let kex = read_ssh_name_list(payload, &mut off)?;
    let hostkey = read_ssh_name_list(payload, &mut off)?;
    let enc_c2s = read_ssh_name_list(payload, &mut off)?;
    let enc_s2c = read_ssh_name_list(payload, &mut off)?;
    let mac_c2s = read_ssh_name_list(payload, &mut off)?;
    let mac_s2c = read_ssh_name_list(payload, &mut off)?;
    let _compression_c2s = read_ssh_name_list(payload, &mut off)?;
    let _compression_s2c = read_ssh_name_list(payload, &mut off)?;
    let _languages_c2s = read_ssh_name_list(payload, &mut off)?;
    let _languages_s2c = read_ssh_name_list(payload, &mut off)?;
    if off + 5 > payload.len() {
        return None;
    }
    Some(PeerKexInit {
        kex,
        hostkey,
        enc_c2s,
        enc_s2c,
        mac_c2s,
        mac_s2c,
    })
}

fn run_kex_stages(
    stream: &mut TcpStream,
    host: Option<&HostEd25519>,
    our_id: &str,
    peer_id: &str,
    authorized_keys: &Path,
    repo_path: &Path,
) -> (SshStage, String) {
    let mut notes = Vec::new();
    let advertise = host.is_some();
    let our_kexinit = build_kexinit_payload(advertise);

    if let Err(e) = write_ssh_packet(stream, &our_kexinit) {
        return (SshStage::KexInit, format!("kexinit=write_err ({e})"));
    }
    let peer_payload = match read_ssh_packet(stream, 16_384) {
        Ok(p) => p,
        Err(e)
            if e.kind() == std::io::ErrorKind::WouldBlock
                || e.kind() == std::io::ErrorKind::TimedOut =>
        {
            notes.push("kexinit=sent peer=(timeout)".into());
            match curve25519_ecdh_selfcheck() {
                Ok(s) => notes.push(s),
                Err(e) => notes.push(format!("ecdh_selfcheck=fail ({e})")),
            }
            notes.push("stop=host_key_sign Missing (no peer KEXINIT)".into());
            return (SshStage::HostKeySign, notes.join("; "));
        }
        Err(e) => {
            return (SshStage::KexInit, format!("kexinit=sent peer_err ({e})"));
        }
    };
    notes.push(format!(
        "kexinit=sent advertise_ed25519={advertise} peer_payload_len={}",
        peer_payload.len()
    ));

    let peer = match parse_peer_kexinit(&peer_payload) {
        Some(v) => v,
        None => {
            notes.push("algo_select=peer_kexinit_parse_fail".into());
            match curve25519_ecdh_selfcheck() {
                Ok(s) => notes.push(s),
                Err(e) => notes.push(format!("ecdh_selfcheck=fail ({e})")),
            }
            notes.push("stop=host_key_sign Missing".into());
            return (SshStage::HostKeySign, notes.join("; "));
        }
    };
    let kex_ok = peer
        .kex
        .iter()
        .any(|n| n == "curve25519-sha256" || n == "curve25519-sha256@libssh.org");
    let hostkey_ok = if advertise {
        peer.hostkey.iter().any(|n| n == "ssh-ed25519")
    } else {
        peer.hostkey
            .iter()
            .any(|n| n == "arks-partial-missing-hostkey-sign")
    };
    let cipher_ok = peer
        .enc_c2s
        .iter()
        .any(|n| n == "chacha20-poly1305@openssh.com")
        && peer
            .enc_s2c
            .iter()
            .any(|n| n == "chacha20-poly1305@openssh.com");
    let mac_ok = peer.mac_c2s.iter().any(|n| n == "hmac-sha2-256")
        && peer.mac_s2c.iter().any(|n| n == "hmac-sha2-256");
    notes.push(format!(
        "algo_select=kex_curve25519={kex_ok} hostkey_common={hostkey_ok} \
         openssh_chacha={cipher_ok} mac_name_common={mac_ok} peer_kex_n={} peer_hostkey_n={}",
        peer.kex.len(),
        peer.hostkey.len()
    ));
    if !kex_ok || !cipher_ok || !mac_ok {
        notes.push("stop=algo_select (no complete supported algorithm set)".into());
        return (SshStage::AlgoSelect, notes.join("; "));
    }
    if advertise && !hostkey_ok {
        notes.push(
            "note: peer did not offer ssh-ed25519 — still attempt ECDH; sign may be unused".into(),
        );
    }

    match curve25519_ecdh_selfcheck() {
        Ok(s) => notes.push(s),
        Err(e) => {
            notes.push(format!("ecdh_selfcheck=fail ({e})"));
            return (SshStage::Ecdh, notes.join("; "));
        }
    }

    let (stage, ecdh_notes) = try_peer_ecdh_and_sign(
        stream,
        &peer.kex,
        host,
        our_id,
        peer_id,
        &our_kexinit,
        &peer_payload,
        authorized_keys,
        repo_path,
    );
    notes.push(ecdh_notes);

    // If ECDH stopped before NEWKEYS, still record offline auth + pack dispatch Partial.
    if !matches!(
        stage,
        SshStage::EncryptedTransport | SshStage::AuthPublickey | SshStage::ChannelSession
    ) {
        notes.push(publickey_verify_scaffold(authorized_keys, host));
        notes.push(channel_git_hookup_scaffold(repo_path));
    }
    notes.push(format!("reached_stage={}", stage.as_str()));
    (stage, notes.join("; "))
}

/// Run an in-process SSH listener (durable accept per SoT §17(c)).
///
/// Advances structured KEX / sign / NEWKEYS / auth / channel stages per
/// connection. Stays up until `stop` is set. Bind failure fail-closed.
///
/// Callers MUST NOT silent-degrade to HTTP-only when SSH was left enabled.
pub fn serve_ssh_listener(opts: ServeSshOptions, stop: Arc<AtomicBool>) -> Result<(), ServerError> {
    let listener = TcpListener::bind(opts.listen)?;
    listener.set_nonblocking(true)?;
    serve_ssh_on_listener(listener, opts, stop)
}

fn serve_ssh_on_listener(
    mut listener: TcpListener,
    opts: ServeSshOptions,
    stop: Arc<AtomicBool>,
) -> Result<(), ServerError> {
    let host_st = path_status(&opts.host_key);
    let auth_st = path_status(&opts.authorized_keys);
    let host_fmt = probe_host_key_format(&opts.host_key);
    let auth_probe = probe_authorized_keys(&opts.authorized_keys);
    let repo_st = if opts.path.exists() {
        "present"
    } else {
        "missing"
    };
    let host_key = match load_host_ed25519(&opts.host_key) {
        Ok(h) => Some(h),
        Err(e) => {
            // Keep going — Partial without sign when key missing/unloadable.
            let _ = e;
            None
        }
    };
    let host_load = if host_key.is_some() {
        "ed25519_unencrypted_ok"
    } else {
        "unloadable_or_absent"
    };

    let mut current = listener.local_addr().unwrap_or(opts.listen);
    let our_id = "SSH-2.0-arks";
    eprintln!(
        "arks serve SSH durable listen on {current}; \
         host_key={hk} ({host_st}; format={host_fmt}; load={host_load}); \
         authorized_keys={ak} ({auth_st}; {auth_probe}); path={path} ({repo_st})",
        hk = opts.host_key.display(),
        ak = opts.authorized_keys.display(),
        path = opts.path.display(),
    );

    let host_key = Arc::new(host_key);
    let auth_keys = opts.authorized_keys.clone();
    let repo_path = opts.path.clone();
    let host_load = Arc::new(host_load.to_string());
    let session_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
    // Bounded dual-bind drain (mirror HTTP B7 Claimed; research:root/20261111090827).
    let mut draining: Vec<(TcpListener, SocketAddr, Instant)> = Vec::new();
    while !stop.load(Ordering::SeqCst) {
        if let Some(slot) = &opts.rebind_desired {
            if let Ok(mut g) = slot.lock() {
                if let Some(new_addr) = g.take() {
                    if new_addr != current {
                        match TcpListener::bind(new_addr) {
                            Ok(l) => {
                                if let Err(e) = l.set_nonblocking(true) {
                                    eprintln!(
                                        "arks serve SSH: live rebind bind ok but \
                                         nonblocking fail ({e}); keeping {current}"
                                    );
                                    *g = Some(new_addr);
                                } else {
                                    eprintln!(
                                        "arks serve SSH: live rebind dual-bind {current} → {new_addr}; \
                                         prior listener draining for 5s"
                                    );
                                    let old = std::mem::replace(&mut listener, l);
                                    draining.push((
                                        old,
                                        current,
                                        Instant::now() + Duration::from_secs(5),
                                    ));
                                    current = new_addr;
                                }
                            }
                            Err(e) => {
                                eprintln!(
                                    "arks serve SSH: live rebind fail {current} → \
                                     {new_addr} ({e}); keeping prior listen"
                                );
                            }
                        }
                    }
                }
            }
        }
        draining.retain(|(_, old_addr, deadline)| {
            if Instant::now() < *deadline {
                true
            } else {
                eprintln!("arks serve SSH: rebind drain complete; closing {old_addr}");
                false
            }
        });

        let spawn_session = |stream: TcpStream, peer: SocketAddr| {
            let n = session_counter.fetch_add(1, Ordering::SeqCst) + 1;
            let host_key = Arc::clone(&host_key);
            let auth_keys = auth_keys.clone();
            let repo_path = repo_path.clone();
            let host_load = Arc::clone(&host_load);
            let our_id = our_id.to_string();
            thread::spawn(move || {
                handle_ssh_session(
                    stream,
                    peer,
                    n,
                    &our_id,
                    host_key.as_ref().as_ref(),
                    &auth_keys,
                    &repo_path,
                    host_load.as_str(),
                );
            });
        };

        match listener.accept() {
            Ok((stream, peer)) => spawn_session(stream, peer),
            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                thread::sleep(Duration::from_millis(20));
            }
            Err(e) => {
                return Err(ServerError::Msg(format!(
                    "arks serve SSH durable accept err on {current}: {e}"
                )));
            }
        }
        for (old_listener, _, _) in &draining {
            match old_listener.accept() {
                Ok((stream, peer)) => spawn_session(stream, peer),
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
                Err(e) => eprintln!("arks serve SSH: draining listener accept error: {e}"),
            }
        }
    }

    eprintln!(
        "arks serve SSH durable listen stopped on {current} \
         (sessions={}; ops SSHD + upload-pack/receive-pack still valid)",
        session_counter.load(Ordering::SeqCst)
    );
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn handle_ssh_session(
    mut stream: TcpStream,
    peer: SocketAddr,
    sessions: u64,
    our_id: &str,
    host_key: Option<&HostEd25519>,
    authorized_keys: &Path,
    path: &Path,
    host_load: &str,
) {
    let _ = stream.set_nonblocking(false);
    let _ = stream.set_nodelay(true);
    // Longer read window so held peers can overlap a dual-bind drain (IW-B7-SSH).
    let _ = stream.set_read_timeout(Some(Duration::from_secs(8)));
    let _ = stream.set_write_timeout(Some(Duration::from_secs(8)));
    let ours = format!("{our_id}\r\n");
    let _ = stream.write_all(ours.as_bytes());
    let _ = stream.flush();
    let peer_id = read_ssh_identification(&mut stream)
        .unwrap_or_default()
        .chars()
        .take(255)
        .collect::<String>();
    let id_part = if peer_id.is_empty() {
        format!("id_exchange=no_peer_id peer={peer} peer_id=(empty/timeout)")
    } else {
        format!("id_exchange=ok peer={peer} peer_id={peer_id}")
    };
    let (stage, kex_part) = if peer_id.is_empty() {
        match curve25519_ecdh_selfcheck() {
            Ok(s) => {
                let auth = publickey_verify_scaffold(authorized_keys, host_key);
                let chan = channel_git_hookup_scaffold(path);
                (
                    SshStage::HostKeySign,
                    format!(
                        "kex=skipped_no_peer_id; {s}; host_load={host_load}; {auth}; {chan}; \
                         stop=host_key_sign/wire Missing without peer"
                    ),
                )
            }
            Err(e) => (
                SshStage::Ecdh,
                format!("kex=skipped_no_peer_id; ecdh_selfcheck=fail ({e})"),
            ),
        }
    } else {
        run_kex_stages(
            &mut stream,
            host_key,
            our_id,
            &peer_id,
            authorized_keys,
            path,
        )
    };
    // Flush then half-close write so in-flight CHANNEL_DATA is not RST'd.
    let _ = stream.flush();
    let _ = stream.shutdown(Shutdown::Write);
    eprintln!(
        "arks serve SSH session#{sessions} reached_stage={} \
         ({id_part}; {kex_part})",
        stage.as_str()
    );
}

type LoopbackSsh = (
    SocketAddr,
    Arc<AtomicBool>,
    thread::JoinHandle<Result<(), ServerError>>,
);

/// Spawn durable SSH listener on a background thread (cohost with HTTP/forge).
///
/// Binds the socket synchronously before spawning so bind failures surface
/// immediately and the kernel listen queue is ready before returning.
pub fn spawn_ssh_listener(
    opts: ServeSshOptions,
) -> Result<(Arc<AtomicBool>, ListenerThread), ServerError> {
    let listener = TcpListener::bind(opts.listen)?;
    listener.set_nonblocking(true)?;
    let stop = Arc::new(AtomicBool::new(false));
    let stop2 = stop.clone();
    let handle = thread::spawn(move || serve_ssh_on_listener(listener, opts, stop2));
    Ok((stop, handle))
}

/// Ephemeral loopback SSH listener for `arks serve ssh-smoke --git-pack` and tests.
///
/// Keeps the bound `TcpListener` alive and passes it directly into the serving
/// thread (no port-drop TOCTOU window or blind sleep).
pub fn spawn_loopback_ssh(opts: ServeSshOptions) -> Result<LoopbackSsh, ServerError> {
    let listener = TcpListener::bind("127.0.0.1:0")?;
    let addr = listener.local_addr()?;
    listener.set_nonblocking(true)?;
    let mut opts = opts;
    opts.listen = addr;
    let stop = Arc::new(AtomicBool::new(false));
    let stop2 = stop.clone();
    let handle = thread::spawn(move || serve_ssh_on_listener(listener, opts, stop2));
    Ok((addr, stop, handle))
}

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

    #[test]
    fn parse_git_exec_services() {
        assert_eq!(
            parse_git_exec_service("git-upload-pack '/tmp/r.git'"),
            Some("git-upload-pack")
        );
        assert_eq!(
            parse_git_exec_service("git-receive-pack '/tmp/r.git'"),
            Some("git-receive-pack")
        );
        assert_eq!(parse_git_exec_service("bash"), None);
    }

    #[test]
    fn chacha_aead_roundtrip_partial() {
        let shared = x25519_shared_as_mpint(&[7u8; 32]);
        let h = Sha256::digest(b"exchange-hash-partial");
        let note = encrypted_transport_selfcheck(&shared, &h);
        assert!(note.contains("selfcheck=ok"), "{note}");
    }

    #[test]
    fn rfc8731_shared_secret_mpint_encoding() {
        let mut high_bit = [0u8; 32];
        high_bit[0] = 0x80;
        let encoded = x25519_shared_as_mpint(&high_bit);
        assert_eq!(&encoded[..4], &33u32.to_be_bytes());
        assert_eq!(encoded[4], 0);
        assert_eq!(encoded[5], 0x80);

        let mut leading_zero = [0u8; 32];
        leading_zero[1] = 1;
        let encoded = x25519_shared_as_mpint(&leading_zero);
        assert_eq!(&encoded[..4], &31u32.to_be_bytes());
        assert_eq!(encoded[4], 1);
    }

    #[test]
    fn authorized_keys_verify_partial() {
        let dir = tempfile::tempdir().unwrap();
        let seed = [9u8; 32];
        let signing = SigningKey::from_bytes(&seed);
        let vk = signing.verifying_key();
        let blob = build_ssh_ed25519_public_blob(vk.as_bytes());
        let b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &blob);
        let ak = dir.path().join("authorized_keys");
        std::fs::write(&ak, format!("ssh-ed25519 {b64} test@arks\n")).unwrap();
        let challenge = b"challenge-partial";
        let sig = signing.sign(challenge);
        let mut sig_blob = Vec::new();
        sig_blob.extend(ssh_string(b"ssh-ed25519"));
        sig_blob.extend(ssh_string(&sig.to_bytes()));
        verify_publickey_against_authorized(&ak, &blob, challenge, &sig_blob).unwrap();
    }

    #[test]
    fn ssh_receive_pack_rejects_archived_repo() {
        let dir = tempfile::tempdir().unwrap();
        let repo_path = dir.path().join("arch.git");
        std::fs::create_dir_all(repo_path.join("objects")).unwrap();
        std::fs::create_dir_all(repo_path.join("refs").join("heads")).unwrap();
        std::fs::write(repo_path.join("HEAD"), "ref: refs/heads/main\n").unwrap();
        std::fs::write(
            repo_path.join("config"),
            "[core]\n\trepositoryformatversion = 0\n\tbare = true\n",
        )
        .unwrap();
        let mut store = crate::web_ui::store::ForgeStore::load(&repo_path);
        store.archived = true;
        store.save(&repo_path).unwrap();
        let err = dispatch_git_exec_to_pack(&repo_path, "git-receive-pack '.'").unwrap_err();
        assert!(
            err.contains("archived"),
            "SSH receive-pack must reject archived repo: {err}"
        );
    }

    #[test]
    fn ssh_identity_resolution_and_rbac_with_pusher_ssh_user() {
        let dir = tempfile::tempdir().unwrap();
        let alice_sk = SigningKey::from_bytes(&[1u8; 32]);
        let bob_sk = SigningKey::from_bytes(&[2u8; 32]);
        let carol_sk = SigningKey::from_bytes(&[3u8; 32]);

        let alice_blob = build_ssh_ed25519_public_blob(alice_sk.verifying_key().as_bytes());
        let bob_blob = build_ssh_ed25519_public_blob(bob_sk.verifying_key().as_bytes());
        let carol_blob = build_ssh_ed25519_public_blob(carol_sk.verifying_key().as_bytes());

        let alice_b64 =
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &alice_blob);
        let bob_b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &bob_blob);
        let carol_b64 =
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &carol_blob);

        let ak = dir.path().join("authorized_keys");
        std::fs::write(
            &ak,
            format!(
                "# alice (laptop)\nssh-ed25519 {alice_b64} alice@example.invalid\n\
                 # bob (reader-key)\nssh-ed25519 {bob_b64} bob@example.invalid\n\
                 # carol (collab-key)\nssh-ed25519 {carol_b64} carol@example.invalid\n"
            ),
        )
        .unwrap();

        let challenge = b"ssh-userauth-challenge";
        let alice_sig = sign_ssh_ed25519(
            &HostEd25519 {
                signing: alice_sk,
                public_blob: alice_blob.clone(),
            },
            challenge,
        );
        let comment_user =
            verify_publickey_against_authorized(&ak, &alice_blob, challenge, &alice_sig).unwrap();
        assert_eq!(comment_user.as_deref(), Some("alice"));

        let mut store = ForgeStore {
            visibility: "private".into(),
            ..Default::default()
        };
        store.users.push(crate::web_ui::store::UserAccount {
            username: "alice".into(),
            password_hash: "x".into(),
            role: "admin".into(),
            ssh_keys: vec![crate::web_ui::store::SshKeyRecord {
                title: "laptop".into(),
                public_key: format!("ssh-ed25519 {alice_b64} alice@example.invalid"),
                added_at: 1,
                fingerprint: String::new(),
            }],
            created_at: 1,
            totp_secret_b32: None,
            recovery_codes: Vec::new(),
            external_ids: Vec::new(),
        });
        store.users.push(crate::web_ui::store::UserAccount {
            username: "bob".into(),
            password_hash: "x".into(),
            role: "reader".into(),
            ssh_keys: vec![crate::web_ui::store::SshKeyRecord {
                title: "reader-key".into(),
                public_key: format!("ssh-ed25519 {bob_b64} bob@example.invalid"),
                added_at: 1,
                fingerprint: String::new(),
            }],
            created_at: 1,
            totp_secret_b32: None,
            recovery_codes: Vec::new(),
            external_ids: Vec::new(),
        });
        store.users.push(crate::web_ui::store::UserAccount {
            username: "carol".into(),
            password_hash: "x".into(),
            role: "reader".into(),
            ssh_keys: vec![crate::web_ui::store::SshKeyRecord {
                title: "collab-key".into(),
                public_key: format!("ssh-ed25519 {carol_b64} carol@example.invalid"),
                added_at: 1,
                fingerprint: String::new(),
            }],
            created_at: 1,
            totp_secret_b32: None,
            recovery_codes: Vec::new(),
            external_ids: Vec::new(),
        });
        store.collaborators.push("carol".into());

        // Connecting as `git@host` with alice's key resolves to `alice` and binds Pusher::ssh_user.
        let alice_id = SshAuthIdentity {
            request_user: "git".into(),
            key_comment_user: Some("alice".into()),
            public_blob: alice_blob,
        };
        let resolved_alice = resolve_ssh_identity(&store, &alice_id);
        assert_eq!(resolved_alice.as_deref(), Some("alice"));
        let pusher = Pusher::ssh_user(resolved_alice.as_deref().unwrap());
        assert_eq!(pusher.transport, "ssh");
        assert_eq!(pusher.verified_user.as_deref(), Some("alice"));
        assert!(check_ssh_repo_rbac(&store, resolved_alice.as_deref(), false).is_ok());
        assert!(check_ssh_repo_rbac(&store, resolved_alice.as_deref(), true).is_ok());

        // Spoofing `alice@host` with bob's key MUST resolve to `bob` (never `alice`) and fail RBAC.
        let spoof_id = SshAuthIdentity {
            request_user: "alice".into(),
            key_comment_user: Some("bob".into()),
            public_blob: bob_blob,
        };
        let resolved_bob = resolve_ssh_identity(&store, &spoof_id);
        assert_eq!(resolved_bob.as_deref(), Some("bob"));
        assert!(check_ssh_repo_rbac(&store, resolved_bob.as_deref(), false).is_err());
        assert!(check_ssh_repo_rbac(&store, resolved_bob.as_deref(), true).is_err());

        // Explicit `"reader"` collaborator (`carol`) passes private read (`upload-pack`)
        // but is denied push (`receive-pack`) to match HTTP parity.
        let carol_id = SshAuthIdentity {
            request_user: "git".into(),
            key_comment_user: Some("carol".into()),
            public_blob: carol_blob,
        };
        let resolved_carol = resolve_ssh_identity(&store, &carol_id);
        assert_eq!(resolved_carol.as_deref(), Some("carol"));
        assert!(check_ssh_repo_rbac(&store, resolved_carol.as_deref(), false).is_ok());
        assert!(check_ssh_repo_rbac(&store, resolved_carol.as_deref(), true).is_err());
    }

    #[test]
    fn ssh_channel_pipe_bidirectional_window_adjust_over_2mib() {
        let key_c2s = [0x11u8; 64];
        let key_s2c = [0x22u8; 64];
        let payload_len = (2 * 1024 * 1024) + (512 * 1024); // 2.5 MiB (> 2 MiB window)

        // Part 1: >2 MiB peer -> server transfer (push) must trigger WINDOW_ADJUST back to peer.
        {
            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
            let addr = listener.local_addr().unwrap();
            let expected: Vec<u8> = (0..payload_len).map(|i| (i % 251) as u8).collect();
            let client_data = expected.clone();

            let client = thread::spawn(move || -> u64 {
                let mut sock = TcpStream::connect(addr).unwrap();
                sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
                sock.set_write_timeout(Some(Duration::from_secs(5)))
                    .unwrap();
                let mut c2s = OpenSshChaCha::new(&key_c2s, 0).unwrap();
                let mut s2c = OpenSshChaCha::new(&key_s2c, 0).unwrap();
                let mut remote_window: u32 = SSH_LOCAL_INITIAL_WINDOW;
                let mut total_adjust_received: u64 = 0;

                for chunk in client_data.chunks(16_384) {
                    while (remote_window as usize) < chunk.len() {
                        let msg = read_encrypted_packet(&mut sock, &mut s2c, 65_536).unwrap();
                        assert_eq!(msg.first().copied(), Some(93), "expected WINDOW_ADJUST");
                        let mut off = 1usize;
                        let _chan = read_u32(&msg, &mut off).unwrap();
                        let add = read_u32(&msg, &mut off).unwrap();
                        remote_window = remote_window.saturating_add(add);
                        total_adjust_received += u64::from(add);
                    }
                    let mut pkt = vec![94]; // CHANNEL_DATA
                    pkt.extend_from_slice(&0u32.to_be_bytes());
                    pkt.extend(ssh_string(chunk));
                    write_encrypted_packet(&mut sock, &mut c2s, &pkt).unwrap();
                    remote_window -= chunk.len() as u32;
                }
                let mut eof = vec![96];
                eof.extend_from_slice(&0u32.to_be_bytes());
                write_encrypted_packet(&mut sock, &mut c2s, &eof).unwrap();
                let _ = sock.shutdown(std::net::Shutdown::Write);
                while let Ok(msg) = read_encrypted_packet(&mut sock, &mut s2c, 65_536) {
                    if msg.first().copied() == Some(93) {
                        let mut off = 1usize;
                        let _chan = read_u32(&msg, &mut off).unwrap();
                        let add = read_u32(&msg, &mut off).unwrap();
                        total_adjust_received += u64::from(add);
                    }
                }
                total_adjust_received
            });

            let (mut srv_sock, _) = listener.accept().unwrap();
            srv_sock
                .set_read_timeout(Some(Duration::from_secs(5)))
                .unwrap();
            srv_sock
                .set_write_timeout(Some(Duration::from_secs(5)))
                .unwrap();
            let mut c2s = OpenSshChaCha::new(&key_c2s, 0).unwrap();
            let mut s2c = OpenSshChaCha::new(&key_s2c, 0).unwrap();
            let mut pipe = SshChannelPipe {
                stream: &mut srv_sock,
                c2s: &mut c2s,
                s2c: &mut s2c,
                peer_channel: 7,
                max_data: 16_384,
                local_window_remaining: SSH_LOCAL_INITIAL_WINDOW,
                local_window_consumed: 0,
                peer_window_remaining: 65_536,
                inbox: VecDeque::new(),
                eof: false,
                closed: false,
            };
            let mut received = Vec::with_capacity(payload_len);
            pipe.read_to_end(&mut received).unwrap();
            assert_eq!(received.len(), expected.len());
            assert_eq!(received, expected);
            let total_adjust = client.join().unwrap();
            assert!(
                total_adjust >= 512 * 1024,
                "server must send WINDOW_ADJUST during >2 MiB push (got {total_adjust})"
            );
        }

        // Part 2: >2 MiB server -> peer transfer (clone/fetch) with small 128 KiB peer initial
        // window must wait for peer WINDOW_ADJUST and preserve interleaved CHANNEL_DATA in inbox.
        {
            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
            let addr = listener.local_addr().unwrap();
            let expected: Vec<u8> = (0..payload_len).map(|i| ((i * 7) % 251) as u8).collect();
            let initial_peer_window: u32 = 128 * 1024;

            let client = thread::spawn(move || -> Vec<u8> {
                let mut sock = TcpStream::connect(addr).unwrap();
                sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
                sock.set_write_timeout(Some(Duration::from_secs(5)))
                    .unwrap();
                let mut c2s = OpenSshChaCha::new(&key_c2s, 0).unwrap();
                let mut s2c = OpenSshChaCha::new(&key_s2c, 0).unwrap();
                let mut got = Vec::with_capacity(payload_len);
                let mut remaining_window: u32 = initial_peer_window;
                let mut sent_interleaved_data = false;

                while got.len() < payload_len {
                    let msg = read_encrypted_packet(&mut sock, &mut s2c, 65_536).unwrap();
                    assert_eq!(msg.first().copied(), Some(94), "expected CHANNEL_DATA");
                    let mut off = 1usize;
                    let _chan = read_u32(&msg, &mut off).unwrap();
                    let data = read_ssh_bytes(&msg, &mut off).unwrap();
                    assert!(
                        (data.len() as u32) <= remaining_window,
                        "server violated peer RFC 4254 window: sent {} with {} remaining",
                        data.len(),
                        remaining_window
                    );
                    remaining_window -= data.len() as u32;
                    got.extend_from_slice(&data);

                    if remaining_window == 0 && got.len() < payload_len {
                        if !sent_interleaved_data {
                            let mut inter = vec![94]; // interleaved CHANNEL_DATA while server blocks
                            inter.extend_from_slice(&0u32.to_be_bytes());
                            inter.extend(ssh_string(b"interleaved-ping"));
                            write_encrypted_packet(&mut sock, &mut c2s, &inter).unwrap();
                            sent_interleaved_data = true;
                        }
                        let refill: u32 = 256 * 1024;
                        let mut adj = vec![93]; // WINDOW_ADJUST
                        adj.extend_from_slice(&0u32.to_be_bytes());
                        adj.extend_from_slice(&refill.to_be_bytes());
                        write_encrypted_packet(&mut sock, &mut c2s, &adj).unwrap();
                        remaining_window += refill;
                    }
                }
                got
            });

            let (mut srv_sock, _) = listener.accept().unwrap();
            srv_sock
                .set_read_timeout(Some(Duration::from_secs(5)))
                .unwrap();
            srv_sock
                .set_write_timeout(Some(Duration::from_secs(5)))
                .unwrap();
            let mut c2s = OpenSshChaCha::new(&key_c2s, 0).unwrap();
            let mut s2c = OpenSshChaCha::new(&key_s2c, 0).unwrap();
            let mut pipe = SshChannelPipe {
                stream: &mut srv_sock,
                c2s: &mut c2s,
                s2c: &mut s2c,
                peer_channel: 7,
                max_data: 16_384,
                local_window_remaining: SSH_LOCAL_INITIAL_WINDOW,
                local_window_consumed: 0,
                peer_window_remaining: initial_peer_window,
                inbox: VecDeque::new(),
                eof: false,
                closed: false,
            };
            pipe.write_all(&expected).unwrap();
            pipe.flush().unwrap();

            let mut buffered = [0u8; 32];
            let n = pipe.read(&mut buffered).unwrap();
            assert_eq!(&buffered[..n], b"interleaved-ping");

            let client_got = client.join().unwrap();
            assert_eq!(client_got.len(), expected.len());
            assert_eq!(client_got, expected);
        }
    }

    #[test]
    fn open_ssh_repo_multi_repo_hardening() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("repos");
        let outside = dir.path().join("secret.git");
        std::fs::create_dir_all(&root).unwrap();

        for repo_dir in [
            root.join("alpha.git"),
            root.join("beta"),
            root.join("gamma").join(".git"),
            outside.clone(),
        ] {
            std::fs::create_dir_all(repo_dir.join("objects")).unwrap();
            std::fs::create_dir_all(repo_dir.join("refs/heads")).unwrap();
            std::fs::write(repo_dir.join("HEAD"), "ref: refs/heads/main\n").unwrap();
        }

        assert!(open_ssh_repo(&root, "git-upload-pack '/alpha.git'").is_ok());
        assert!(open_ssh_repo(&root, "git-upload-pack '/alpha'").is_ok());
        assert!(open_ssh_repo(&root, "git-upload-pack '/beta'").is_ok());
        assert!(open_ssh_repo(&root, "git-upload-pack '/gamma'").is_ok());

        for bad in [
            "git-upload-pack '/../secret.git'",
            "git-upload-pack '/alpha/../../secret.git'",
            "git-upload-pack '/alpha\0.git'",
            "git-upload-pack '/.arks-global-auth'",
            "git-upload-pack '/.git'",
            "git-upload-pack '/..\\secret.git'",
            "git-upload-pack '.'",
        ] {
            assert!(
                open_ssh_repo(&root, bad).is_err(),
                "must reject traversal/invalid ssh path: {bad}"
            );
        }

        #[cfg(unix)]
        {
            let link = root.join("escape.git");
            std::os::unix::fs::symlink(&outside, &link).unwrap();
            assert!(
                open_ssh_repo(&root, "git-upload-pack '/escape.git'").is_err(),
                "must reject symlink escaping multi-repo root"
            );
        }
    }

    #[test]
    fn ssh_rbac_corrupt_store_fails_closed() {
        let corrupt_store = ForgeStore {
            corrupt: true,
            ..Default::default()
        };
        let auth = SshAuthIdentity {
            request_user: "alice".into(),
            key_comment_user: Some("alice".into()),
            public_blob: Vec::new(),
        };
        assert_eq!(resolve_ssh_identity(&corrupt_store, &auth), None);
        let read_err = check_ssh_repo_rbac(&corrupt_store, Some("alice"), false).unwrap_err();
        assert!(read_err.contains("corrupted"), "{read_err}");
        let write_err = check_ssh_repo_rbac(&corrupt_store, Some("alice"), true).unwrap_err();
        assert!(write_err.contains("corrupted"), "{write_err}");
    }

    #[test]
    fn ssh_identity_rejects_keyless_admin_request_user_spoofing() {
        let attacker_sk = SigningKey::from_bytes(&[42u8; 32]);
        let attacker_blob = build_ssh_ed25519_public_blob(attacker_sk.verifying_key().as_bytes());

        let mut store = ForgeStore {
            visibility: "private".into(),
            ..Default::default()
        };
        // Keyless admin account (`ssh_keys` is empty).
        store.users.push(crate::web_ui::store::UserAccount {
            username: "admin".into(),
            password_hash: "x".into(),
            role: "admin".into(),
            ssh_keys: Vec::new(),
            created_at: 1,
            totp_secret_b32: None,
            recovery_codes: Vec::new(),
            external_ids: Vec::new(),
        });

        // Unannotated key claiming `request_user: "admin"` MUST NOT bind to keyless admin.
        let spoof = SshAuthIdentity {
            request_user: "admin".into(),
            key_comment_user: None,
            public_blob: attacker_blob.clone(),
        };
        assert_eq!(resolve_ssh_identity(&store, &spoof), None);
        assert!(check_ssh_repo_rbac(&store, None, false).is_err());
        assert!(check_ssh_repo_rbac(&store, None, true).is_err());

        // Explicit `# admin (ops)` annotation in `authorized_keys` remains trusted.
        let annotated = SshAuthIdentity {
            request_user: "git".into(),
            key_comment_user: Some("admin".into()),
            public_blob: attacker_blob,
        };
        assert_eq!(
            resolve_ssh_identity(&store, &annotated).as_deref(),
            Some("admin")
        );
        assert!(check_ssh_repo_rbac(&store, Some("admin"), true).is_ok());
    }

    #[test]
    fn ssh_reader_collaborator_upload_allowed_receive_denied_and_multi_repo_global_auth_syncs() {
        let mut store = ForgeStore {
            visibility: "private".into(),
            ..Default::default()
        };
        store.users.push(crate::web_ui::store::UserAccount {
            username: "reader_collab".into(),
            password_hash: "x".into(),
            role: "reader".into(),
            ssh_keys: Vec::new(),
            created_at: 1,
            totp_secret_b32: None,
            recovery_codes: Vec::new(),
            external_ids: Vec::new(),
        });
        store.users.push(crate::web_ui::store::UserAccount {
            username: "maint1".into(),
            password_hash: "x".into(),
            role: "maintainer".into(),
            ssh_keys: Vec::new(),
            created_at: 1,
            totp_secret_b32: None,
            recovery_codes: Vec::new(),
            external_ids: Vec::new(),
        });
        store.collaborators.push("reader_collab".into());

        // Reader collaborator can upload-pack (read) but is denied receive-pack (push).
        assert!(check_ssh_repo_rbac(&store, Some("reader_collab"), false).is_ok());
        let err = check_ssh_repo_rbac(&store, Some("reader_collab"), true).unwrap_err();
        assert!(err.contains("cannot push"), "{err}");

        // Maintainer passes both upload-pack and receive-pack.
        assert!(check_ssh_repo_rbac(&store, Some("maint1"), false).is_ok());
        assert!(check_ssh_repo_rbac(&store, Some("maint1"), true).is_ok());

        // Multi-repo root global auth sync populates child repo ForgeStore before RBAC.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("multi");
        let child = root.join("demo.git");
        let global = root.join(".arks-global-auth");
        std::fs::create_dir_all(child.join("objects")).unwrap();
        std::fs::create_dir_all(child.join("refs/heads")).unwrap();
        std::fs::write(child.join("HEAD"), "ref: refs/heads/main\n").unwrap();
        std::fs::create_dir_all(&global).unwrap();

        let admin_sk = SigningKey::from_bytes(&[77u8; 32]);
        let admin_blob = build_ssh_ed25519_public_blob(admin_sk.verifying_key().as_bytes());
        let admin_b64 =
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &admin_blob);
        let mut gstore = ForgeStore::load(&global);
        gstore.users.push(crate::web_ui::store::UserAccount {
            username: "global_admin".into(),
            password_hash: "x".into(),
            role: "admin".into(),
            ssh_keys: vec![crate::web_ui::store::SshKeyRecord {
                title: "deploy".into(),
                public_key: format!("ssh-ed25519 {admin_b64} global-admin@example.invalid"),
                added_at: 1,
                fingerprint: String::new(),
            }],
            created_at: 1,
            totp_secret_b32: None,
            recovery_codes: Vec::new(),
            external_ids: Vec::new(),
        });
        gstore.save(&global).unwrap();

        let repo = open_ssh_repo(&root, "git-receive-pack '/demo.git'").unwrap();
        assert_ne!(repo.common_dir(), root.as_path());
        crate::web_ui::sync_global_auth_into_repo(&root, repo.common_dir());
        let synced = ForgeStore::load_shared(repo.common_dir());
        let id = SshAuthIdentity {
            request_user: "git".into(),
            key_comment_user: None,
            public_blob: admin_blob,
        };
        let resolved = resolve_ssh_identity(&synced, &id);
        assert_eq!(resolved.as_deref(), Some("global_admin"));
        assert!(check_ssh_repo_rbac(&synced, resolved.as_deref(), true).is_ok());
    }

    #[test]
    fn parse_openssh_ed25519_bin_rejects_truncated_inputs_without_panic() {
        assert!(parse_openssh_ed25519_bin(b"").is_err());
        assert!(parse_openssh_ed25519_bin(b"openssh-key-v1\0").is_err());

        let mut short_nkeys = b"openssh-key-v1\0".to_vec();
        short_nkeys.extend(ssh_string(b"none"));
        short_nkeys.extend(ssh_string(b"none"));
        short_nkeys.extend(ssh_string(b""));
        short_nkeys.extend_from_slice(&[0u8, 1u8]);
        assert!(parse_openssh_ed25519_bin(&short_nkeys).is_err());

        let mut short_priv = b"openssh-key-v1\0".to_vec();
        short_priv.extend(ssh_string(b"none"));
        short_priv.extend(ssh_string(b"none"));
        short_priv.extend(ssh_string(b""));
        short_priv.extend_from_slice(&1u32.to_be_bytes());
        short_priv.extend(ssh_string(b"pub"));
        short_priv.extend(ssh_string(b"abc"));
        assert!(parse_openssh_ed25519_bin(&short_priv).is_err());

        let mut off = 2usize;
        assert!(read_u32(&[1, 2, 3], &mut off).is_err());
        let mut max_off = usize::MAX;
        assert!(read_u32(&[1, 2, 3, 4], &mut max_off).is_err());
    }
}