feather-reader 0.4.5

A minimalist, atproto-native RSS/Atom reader in Rust — your feed subscriptions live in your own PDS.
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
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
//! The axum web layer — server-rendered HTML + a dash of htmx, **no SPA**.
//!
//! This module owns the HTTP surface: [`router`] builds an `axum::Router` over
//! the shared [`AppState`], wiring the store, feed, atproto, and config seams into
//! a small set of typography-first, dark-mode-ready views rendered with
//! `askama` templates (under `templates/`). Progressive enhancement is a single
//! vendored `htmx` script plus a tiny keyboard handler (`static/keyboard.js`);
//! every interaction also works as a plain HTML form POST, so the reader is fully
//! usable with JavaScript disabled.
//!
//! ## HTTP surface
//!
//! * `GET  /health` — liveness + version, as `text/plain`.
//! * `GET  /about`, `/standard-site`, `/stats`, `/privacy`, `/terms` — static
//!   and status pages.
//! * `GET  /manage` — feed and folder management.
//! * `GET  /` — the reader: a folders/feeds sidebar (from the PDS records layer)
//!   plus the main article list. Query params pick the scope (`?feed=…` /
//!   `?folder=…` / all) and the view (`?view=unread|all|starred`).
//! * `GET  /entries/{id}` — the clean, distraction-free reader for one entry,
//!   with prev/next within the current list.
//! * `POST /entries/{id}/read` — mark an entry read/unread (htmx row swap).
//! * `POST /entries/{id}/star` — star/unstar; writes a
//!   `community.lexicon.rss.saved` record to the user's PDS.
//! * `POST /saved/{rkey}/delete` — unsave a `saved` record.
//! * `POST /read-all` — mark-all-read (per feed via `?feed=…`, else everything).
//! * `POST /subscriptions` — subscribe by URL (autodiscover → PDS record).
//! * `POST /subscriptions/{rkey}/delete` — unsubscribe (delete the PDS record).
//! * `POST /subscriptions/{rkey}/rename` — retitle / move a feed to a folder.
//! * `POST /folders` — create a folder record.
//! * `POST /folders/{rkey}/rename` — rename a folder record.
//! * `POST /folders/{rkey}/delete` — delete a folder record.
//! * `POST /opml` — OPML import (multipart upload *or* pasted textarea) → bulk
//!   subscription records in the PDS.
//! * `GET  /opml/export` — OPML export (records → a downloadable document).
//! * `GET /login` + `POST /login` + `/oauth/callback` + `/logout` — the atproto
//!   OAuth sign-in flow, on whichever backend `FEATHERREADER_REPO_BACKEND`
//!   selects. `GET /oauth/client-metadata.json` and `/oauth/jwks.json` publish
//!   the Rust client's identity.
//! * `POST /account/delete` — revoke the session and drop this DID's local state.
//! * `GET|POST /beta/redeem` — closed-beta invite redemption.
//! * `GET /claim?t=<token>` — the follow→invite bot's claim link: an opaque token
//!   reserving a pre-minted invite code; behaves like a successful `/beta/redeem`
//!   (sets the reserving cookie → `/login`).
//! * `POST /bot/claims` — headless, shared-secret (`X-Bot-Secret`) mint of a claim
//!   code + token/url for the bot to post. Cap-aware (409 when full).
//! * `POST /admin/invites`, `GET /admin/metrics` — admin-only invite minting and
//!   the backend metrics view.
//!
//! ## Identity — a cookie-resolved atproto session
//!
//! Per-request identity comes from a **signed session cookie** (`fr_session`)
//! keyed by the logged-in DID, set by `oauth_callback` and read by
//! `current_session` / `current_did`. For local runs without the sidecar,
//! [`Config::dev_did`] (env `FEATHERREADER_DEV_DID`) supplies a fallback identity.
//! All PDS reads and writes route through [`AppState::repo`], which dispatches to
//! the sidecar or the Rust OAuth client by `FEATHERREADER_REPO_BACKEND`.

use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use askama::Template;
use axum::{
    extract::{ConnectInfo, DefaultBodyLimit, Multipart, Path, Query, State},
    http::{header, HeaderMap, StatusCode},
    middleware::{self, Next},
    response::{Html, IntoResponse, Redirect, Response},
    routing::{get, post},
    Form, Router,
};
use serde::Deserialize;
use std::net::SocketAddr;
use tower_http::services::{ServeDir, ServeFile};
use tower_http::set_header::SetResponseHeaderLayer;
use tower_http::trace::TraceLayer;
use tracing::{info, warn};

use crate::config::Config;
use crate::lexicon::{self, Folder, Saved, Subscription};
use crate::safe_link::SafeLink;
use crate::{feed, store, AppState, Session, VERSION};

// The OPML import/export module lives at `src/opml.rs` but isn't declared in the
// crate root (`lib.rs`), which is outside this phase's edit surface. Wire it in
// here via an explicit path so the reader's OPML routes can use the canonical
// `parse_opml` / `to_opml` without duplicating that logic.
#[path = "opml.rs"]
mod opml;

/// The name of the signed session cookie.
const SESSION_COOKIE: &str = "fr_session";

/// The name of the short-lived signed **invite** cookie.
///
/// Set by `POST /beta/redeem` on a valid, capacity-ok code and consumed by the
/// OAuth callback. It reserves *intent* to redeem a specific code before the
/// visitor ever starts the OAuth handshake, so a non-invited visitor can't burn
/// a sidecar handshake (pre-handshake gate). It carries the invite code, HMAC-
/// signed with the same key as the session cookie.
const INVITE_COOKIE: &str = "fr_invite";

/// Browser-binding cookie for an in-flight OAuth login (Rust backend only).
///
/// `state` alone cannot stop a login CSRF: it lives in a server-global table, so
/// a stolen `state` replayed from ANOTHER browser matches just as well as from
/// the one that started the flow. This cookie is what makes the callback
/// browser-specific — the pending row stores only its hash, and a callback that
/// cannot present it is refused.
const OAUTH_BINDING_COOKIE: &str = "fr_oauth";

/// How long an in-flight login may sit, matching the pending row's own TTL.
const OAUTH_BINDING_MAX_AGE_SECS: i64 = 600;

/// TTL (seconds) for a minted invite code and for the reserving invite cookie.
/// Short enough that a reserved-but-unclaimed seat frees quickly.
const INVITE_TTL_SECS: i64 = 1800;

/// The canonical AGPL-3.0 source repository — surfaced in the footer, the
/// sign-in pitch, and `/about`.
const REPO_URL: &str = "https://github.com/justin-stanley/feather-reader";

/// The tip / support link (cloud plan public-experiment UI).
const KOFI_URL: &str = "https://ko-fi.com/justinstanley";

/// The published crate on crates.io — surfaced on the signed-out landing page.
const CRATES_URL: &str = "https://crates.io/crates/feather-reader";

/// The Content-Security-Policy applied to every response.
///
/// Tuned to keep the app fully working while neutralising injected script:
/// * `default-src 'self'` — same-origin baseline.
/// * `script-src 'self'` — only our vendored `htmx.min.js` + `keyboard.js` from
///   `/static`; **no** `'unsafe-inline'`, so an injected `<script>` or a
///   `javascript:` href (F4) cannot execute. (The design's templates carry no
///   inline event handlers — every control is wired in `keyboard.js`.)
/// * `style-src 'self' 'unsafe-inline'` — the linked stylesheet plus the small
///   inline styles htmx toggles for its request indicators.
/// * `img-src 'self' https: data:` — feed content routinely embeds remote
///   images; allow https + data URIs but not other schemes.
/// * `form-action 'self'`, `base-uri 'self'`, `frame-ancestors 'none'` — lock
///   down form posts, `<base>` hijacking, and clickjacking.
/// * `object-src 'none'` — no plugins.
const CONTENT_SECURITY_POLICY: &str = "default-src 'self'; \
     script-src 'self'; \
     style-src 'self' 'unsafe-inline'; \
     img-src 'self' https: data:; \
     font-src 'self'; \
     connect-src 'self'; \
     form-action 'self'; \
     base-uri 'self'; \
     frame-ancestors 'none'; \
     object-src 'none'";

/// The resolved identity for the current request.
///
/// `did` is the primary key for all per-user local state; `handle` is display
/// only; `sid` is the opaque server-side session id the cookie carried (needed
/// so logout can revoke exactly this session). Sourced from the signed cookie
/// (real login) or, if none, the configured dev DID fallback.
#[derive(Clone, Debug)]
struct CurrentUser {
    did: String,
    handle: Option<String>,
    /// The opaque session id, if this identity came from a real cookie session
    /// (absent for the dev-DID fallback, which has no server-side session row).
    sid: Option<String>,
}

/// Resolve the current request's session from the signed cookie, falling back to
/// the configured dev DID (env `FEATHERREADER_DEV_DID`) for local runs.
///
/// The cookie carries an opaque server-minted session id (not the DID). We
/// verify its HMAC, look the id up in the registry, and — crucially —
/// **re-check the DID against the closed-beta gate on every request**
/// ([`store::has_beta_access`]), not just at the OAuth callback, so revoking a
/// DID's beta seat takes effect immediately for already-issued cookies. (The
/// gate replaced the old static `ALLOWED_DIDS` check; `ALLOWED_DIDS` remains the
/// admin-bootstrap seed, granted a seat at startup via `ensure_seed`.)
async fn current_session(state: &AppState, headers: &HeaderMap) -> Option<CurrentUser> {
    if let Some(sid) = cookie::verify_session(headers, &state.config.cookie_secret) {
        if let Some(session) = state.sessions.get(&sid) {
            if store::has_beta_access(&state.db, &session.did)
                .await
                .unwrap_or(false)
            {
                return Some(CurrentUser {
                    did: session.did,
                    handle: session.handle,
                    sid: Some(sid),
                });
            }
            // DID no longer holds a beta seat: treat as logged out (and drop the
            // stale server-side session so the dead cookie can't linger).
            state.sessions.remove(&sid);
        }
    }
    // No valid cookie: dev fallback only if explicitly configured *and* still
    // inside the beta gate (seeded via ensure_seed / a redeemed code).
    if let Some(did) = state.config.dev_did.clone() {
        if store::has_beta_access(&state.db, &did)
            .await
            .unwrap_or(false)
        {
            return Some(CurrentUser {
                did,
                handle: None,
                sid: None,
            });
        }
    }
    None
}

/// The current request's DID, or `None` when logged out (no cookie, no dev DID).
async fn current_did(state: &AppState, headers: &HeaderMap) -> Option<String> {
    current_session(state, headers).await.map(|u| u.did)
}

/// Build the application router over shared [`AppState`].
///
/// Wires the reader routes, the health check, and the `/static` asset mount
/// (the stylesheet, vendored htmx, and the keyboard handler, served from
/// `static/` via `ServeDir`). A `TraceLayer` gives per-request tracing.
pub fn router(state: AppState) -> Router {
    // The shared per-IP rate limiter for the abuse-prone paths (login, redeem,
    // and the write endpoints). One instance is cloned into the state closure of
    // the `rate_limit` middleware.
    let limiter = RateLimiter::shared();
    // The trusted client-IP source for the limiter (a proxy header the operator
    // controls, or the socket peer when unset). Bundled with the limiter so the
    // middleware derives a spoof-resistant IP.
    let rl_state = RateLimitState {
        limiter,
        trusted_header: state.config.trusted_ip_header.clone(),
    };

    Router::new()
        .route("/health", get(health))
        .route("/about", get(about))
        .route("/standard-site", get(standard_site))
        .route("/stats", get(stats))
        .route("/privacy", get(privacy))
        .route("/terms", get(terms))
        .route("/manage", get(manage))
        .route("/", get(index))
        .route("/entries/{id}", get(entry_view))
        .route("/entries/{id}/read", post(mark_read))
        .route("/entries/{id}/star", post(toggle_star))
        .route("/saved/{rkey}/delete", post(unsave_record))
        .route("/read-all", post(mark_all_read))
        .route("/subscriptions", post(add_subscription))
        .route("/subscriptions/{rkey}/delete", post(delete_subscription))
        .route("/subscriptions/{rkey}/rename", post(rename_subscription))
        .route("/folders", post(create_folder))
        .route("/folders/{rkey}/rename", post(rename_folder))
        .route("/folders/{rkey}/delete", post(delete_folder))
        // OPML import takes untrusted uploads: cap the body so a huge upload
        // can't OOM (residual body-cap), on top of the streamed feed-fetch cap.
        .route(
            "/opml",
            post(import_opml).layer(DefaultBodyLimit::max(OPML_BODY_LIMIT)),
        )
        .route("/opml/export", get(export_opml))
        .route("/login", get(login_form).post(login_submit))
        .route(
            "/beta/redeem",
            get(beta_redeem_form).post(beta_redeem_submit),
        )
        // The follow→invite bot's claim link: a public skeet points a new
        // follower here with an opaque token that reserves a pre-minted code.
        .route("/claim", get(claim))
        // Headless bot mint endpoint (shared-secret, not OAuth). Mints a claim
        // code + returns its token/url for the bot to post.
        .route("/bot/claims", post(bot_mint_claim))
        .route("/admin/invites", post(admin_mint_invites))
        .route("/admin/metrics", get(admin_metrics))
        .route("/oauth/client-metadata.json", get(oauth_client_metadata))
        .route("/oauth/jwks.json", get(oauth_jwks))
        .route("/account/delete", post(account_delete))
        .route("/oauth/callback", get(oauth_callback))
        .route("/logout", post(logout))
        .nest_service("/static", ServeDir::new("static"))
        // Browsers (and some feed clients) request /favicon.ico at the root
        // regardless of the <link rel="icon"> tags; serve the same icon that
        // lives under /static so the bare path stops 404-ing.
        .route_service("/favicon.ico", ServeFile::new("static/favicon.ico"))
        // Cache-Control (viral/CDN plan): `public, max-age=300` on the cacheable
        // logged-out landing + static assets, `no-store` on anything that
        // rendered a session's private view. Runs *inside* the security layers so
        // the CSP/nosniff/frame headers are untouched.
        .layer(middleware::from_fn(cache_control))
        // Per-IP rate limit on the abuse-prone paths (429 over the limit). Runs
        // as a middleware so it sees the matched path + the peer IP.
        .layer(middleware::from_fn_with_state(rl_state, rate_limit))
        .layer(TraceLayer::new_for_http())
        // Baseline security headers on *every* response (F4). The CSP is the
        // backstop that neutralises any XSS that slips past sanitization; the
        // others harden sniffing, framing, and referrer leakage.
        .layer(static_header_layer(
            "content-security-policy",
            CONTENT_SECURITY_POLICY,
        ))
        .layer(static_header_layer("x-content-type-options", "nosniff"))
        .layer(static_header_layer(
            "referrer-policy",
            "strict-origin-when-cross-origin",
        ))
        .layer(static_header_layer("x-frame-options", "DENY"))
        .with_state(state)
}

/// Body-size ceiling for the OPML import upload: **1 MiB, deliberately below
/// axum's 2 MiB default.**
///
/// The value used to BE the framework default, which made the route's own
/// `DefaultBodyLimit` layer a no-op: removing the layer changed nothing, so
/// nothing could test it, and the ceiling this route wanted was whatever the
/// framework happened to pick. Sized to this route instead — one outline is
/// ~92 bytes, so 1 MiB carries ~11 000 of them against a per-DID cap
/// (`max_subs_per_did`, default 500) the import trims to anyway. Anything
/// larger is not a subscription list.
///
/// Being strictly tighter than the default is what makes the layer both real
/// and pinnable: `opml_import_over_the_route_cap_is_refused_below_the_framework_default`
/// uploads a payload that only this limit refuses.
const OPML_BODY_LIMIT: usize = 1024 * 1024;

/// axum's own `DefaultBodyLimit` (2 MiB as of axum 0.8), for the test that
/// uploads a payload between the two ceilings.
///
/// **What matters is only that it EXCEEDS [`OPML_BODY_LIMIT`]**, not that this
/// number is exact — axum does not export it, so it cannot be imported. The
/// exceeding is what the test's mutation demonstrates: with the route's layer
/// removed, a payload of this size is accepted. If axum ever lowers its
/// default below ours, that mutation stops failing and the compile-time
/// assertion below is the thing to revisit.
#[cfg(test)]
const AXUM_DEFAULT_BODY_LIMIT: usize = 2 * 1024 * 1024;

/// The route's cap must stay strictly tighter than the framework's, or its
/// layer is a no-op again. A compile error, not a test failure: this is a
/// property of the two constants, and nothing should be able to build a binary
/// where it is false.
#[cfg(test)]
const _: () = assert!(
    OPML_BODY_LIMIT < AXUM_DEFAULT_BODY_LIMIT,
    "OPML_BODY_LIMIT must be tighter than axum's default, or the route's layer does nothing"
);

/// A response-header layer that sets `name: value` on every response, overriding
/// any existing header of that name. `name`/`value` must be valid static header
/// tokens (they are, for our fixed security headers).
fn static_header_layer(
    name: &'static str,
    value: &'static str,
) -> SetResponseHeaderLayer<header::HeaderValue> {
    SetResponseHeaderLayer::overriding(
        header::HeaderName::from_static(name),
        header::HeaderValue::from_static(value),
    )
}

// ---------------------------------------------------------------------------
// Per-IP rate limiting (token bucket, self-contained — no extra crate)
// ---------------------------------------------------------------------------

/// The abuse-prone paths the rate limiter guards (429 over the limit): the OAuth
/// kick-off and callback, the invite redeem, logout, the mutating write
/// endpoints, and mark-read/star/mark-all. Plain read-only navigation is
/// intentionally *not* limited.
///
/// The criterion is **does this path make an outbound request**, not "does it
/// mutate" — the two diverge, and every miss so far has been on the outbound
/// side. This is an allowlist a new route has to be added to by hand, which is
/// exactly why it has now been missed three times: `/saved/` (fixed), then
/// `/oauth/callback` and `/logout`. The callback was the bad one — it is the
/// only path here reachable with no session at all.
///
/// Known and deliberate gaps: `GET /`, `GET /manage` and `GET /opml/export` each
/// make PDS calls but are ordinary authenticated navigation, and throttling them
/// would degrade normal reading. They are bounded by needing a valid session.
fn is_rate_limited_path(path: &str, method: &axum::http::Method) -> bool {
    use axum::http::Method;
    // `/claim` is a GET (a link the bot posts), but it consumes a reservation and
    // a claim token in a public URL is grabbable, so it MUST be per-IP limited
    // like the other abuse-prone entry points — not just `/login`.
    // `/oauth/callback` is a GET, is UNAUTHENTICATED, and every hit performs a
    // real outbound round-trip — a sidecar `resolve_session` or a full token
    // exchange against a PDS. Anyone could spend one outbound request per hit.
    // It is the only entry point here that needs no session at all.
    if method != Method::POST
        && !(method == Method::GET
            && (path == "/login" || path == "/claim" || path == "/oauth/callback"))
    {
        return false;
    }
    match path {
        // `/logout` and `/oauth/callback` are here because they make outbound
        // calls, not because they mutate: logout revokes at the PDS (up to two
        // round-trips) and the callback exchanges a code. The list is by
        // *network cost*, which is what the limiter is actually for.
        "/login" | "/claim" | "/oauth/callback" | "/logout" | "/beta/redeem" | "/subscriptions"
        | "/opml" | "/read-all" | "/admin/invites" | "/bot/claims" | "/account/delete"
        | "/folders" => true,
        // Every per-record subscription/folder mutation (delete/rename) and the
        // star/mark-read taps make a sidecar/PDS round-trip, so limit them too.
        p => {
            (p.starts_with("/entries/") && (p.ends_with("/read") || p.ends_with("/star")))
                // Unsaving makes a DPoP-signed deleteRecord round-trip to the
                // PDS, which is exactly the reason the neighbours above are
                // limited. It was added as a new route and not added here.
                || p.starts_with("/saved/")
                || p.starts_with("/subscriptions/")
                || p.starts_with("/folders/")
        }
    }
}

/// Middleware state for [`rate_limit`]: the shared limiter plus the trusted
/// client-IP header (if any). Cloned into every request; both fields are cheap.
#[derive(Clone)]
struct RateLimitState {
    limiter: RateLimiter,
    /// The lowercased proxy header the operator trusts for the client IP, or
    /// `None` to trust only the socket peer. See [`client_ip`].
    trusted_header: Option<String>,
}

/// A tiny per-IP token-bucket rate limiter. Each IP gets [`RATE_BURST`] tokens
/// that refill at [`RATE_REFILL_PER_SEC`]/sec; a request costs one token and is
/// rejected (429) when the bucket is empty. Self-contained (no `tower_governor`
/// dependency → no network fetch at build, deterministic offline CI).
#[derive(Clone)]
struct RateLimiter {
    inner: std::sync::Arc<Mutex<RateLimiterState>>,
}

/// The limiter's shared state: the buckets plus when they were last swept.
struct RateLimiterState {
    buckets: HashMap<IpAddr, Bucket>,
    last_sweep: Instant,
}

/// One IP's token bucket: a fractional token count + the last-refill instant.
struct Bucket {
    tokens: f64,
    last: Instant,
}

/// Burst capacity per IP — how many requests can arrive back-to-back.
const RATE_BURST: f64 = 20.0;
/// Steady-state refill rate (tokens/sec) once the burst is spent.
const RATE_REFILL_PER_SEC: f64 = 1.0;
/// Evict idle buckets older than this so the map can't grow unbounded.
const RATE_IDLE_EVICT: Duration = Duration::from_secs(3600);

/// How often the idle sweep may actually run.
///
/// The sweep used to run on EVERY guarded request — an O(n) scan of the whole
/// map to find entries that, by construction, can only age out on an hour
/// boundary. `GET /login` and `GET /claim` are guarded and unauthenticated, so
/// under any volume of distinct source IPs the server spent its single shared
/// core re-walking a map whose contents had not changed. Once a minute is
/// plenty: it bounds bucket lifetime at `RATE_IDLE_EVICT + RATE_SWEEP_EVERY`.
const RATE_SWEEP_EVERY: Duration = Duration::from_secs(60);

/// Most buckets kept. At roughly 100 bytes each this is ~1 MB — a bound, not a
/// target, sized so ordinary traffic never reaches it.
///
/// The idle eviction above was the only bound, and it is a TIME bound, which
/// says nothing about how many distinct IPs can arrive inside one hour.
/// `net.rs` bounds the equivalent structure by count (`MAX_PINNED_CLIENTS`);
/// this one did not.
const MAX_RATE_BUCKETS: usize = 10_000;

/// When the cap is hit, evict down to this fraction of it rather than removing
/// a single entry — so the O(n) eviction happens once per `cap/8` requests
/// instead of once per request while the map sits full.
const RATE_EVICT_DOWN_TO: usize = MAX_RATE_BUCKETS * 7 / 8;

impl RateLimiter {
    /// A fresh, shared limiter (cloned into the middleware state).
    fn shared() -> Self {
        Self {
            inner: std::sync::Arc::new(Mutex::new(RateLimiterState {
                buckets: HashMap::new(),
                last_sweep: Instant::now(),
            })),
        }
    }

    /// Charge one token for `ip`; returns `true` if allowed, `false` if the
    /// bucket is empty (→ 429).
    fn check(&self, ip: IpAddr) -> bool {
        self.check_at(ip, Instant::now())
    }

    /// [`check`](Self::check) with the clock injected, so the sweep and eviction
    /// paths below are reachable in a test without sleeping through an hour.
    fn check_at(&self, ip: IpAddr, now: Instant) -> bool {
        let mut state = match self.inner.lock() {
            Ok(m) => m,
            // A poisoned lock shouldn't take the site down — fail open.
            Err(p) => p.into_inner(),
        };

        // Idle sweep, at most once per `RATE_SWEEP_EVERY`.
        if now.duration_since(state.last_sweep) >= RATE_SWEEP_EVERY {
            state
                .buckets
                .retain(|_, b| now.duration_since(b.last) < RATE_IDLE_EVICT);
            state.last_sweep = now;
        }

        // Hard size bound, independent of the time bound above.
        //
        // Evicting LEAST-RECENTLY-USED is what makes this safe to do at all. An
        // attacker cannot use eviction to clear their OWN throttled bucket: that
        // bucket is by definition the most recently touched, so it is the last
        // thing this removes. Going quiet long enough to become the oldest entry
        // is exactly what the refill already grants for free.
        if state.buckets.len() >= MAX_RATE_BUCKETS && !state.buckets.contains_key(&ip) {
            let mut by_age: Vec<(IpAddr, Instant)> =
                state.buckets.iter().map(|(k, b)| (*k, b.last)).collect();
            by_age.sort_unstable_by_key(|(_, last)| *last);
            for (victim, _) in by_age
                .into_iter()
                .take(state.buckets.len().saturating_sub(RATE_EVICT_DOWN_TO))
            {
                state.buckets.remove(&victim);
            }
            warn!(
                buckets = state.buckets.len(),
                "rate-limit bucket cap reached; evicted the least recently seen clients"
            );
        }

        let bucket = state.buckets.entry(ip).or_insert(Bucket {
            tokens: RATE_BURST,
            last: now,
        });
        let elapsed = now.duration_since(bucket.last).as_secs_f64();
        bucket.tokens = (bucket.tokens + elapsed * RATE_REFILL_PER_SEC).min(RATE_BURST);
        bucket.last = now;
        if bucket.tokens >= 1.0 {
            bucket.tokens -= 1.0;
            true
        } else {
            false
        }
    }
}

/// The **trusted** client IP for a request.
///
/// Security: a naive limiter that trusts the *left-most* `X-Forwarded-For` hop
/// is fully bypassable — the left-most value is attacker-supplied (any client
/// can send `X-Forwarded-For: <random>`), so each forged value lands in a fresh
/// bucket and the per-IP limit never bites. We therefore derive the IP only from
/// a source the operator controls:
///
/// * If `trusted_header` is configured (e.g. `Fly-Client-IP`,
///   `CF-Connecting-IP`), we read the client IP from THAT header only — it is
///   set by the proxy we run in front and overwrites any client-supplied copy.
///   We take the LAST value if the header happens to be a comma list (the hop
///   the trusted proxy appended), which is also the correct read for a
///   right-most-`X-Forwarded-For` deployment where the operator points
///   `trusted_header` at `x-forwarded-for`.
/// * Otherwise we ignore all forwarding headers and use the socket peer
///   (`ConnectInfo`) — correct for a direct bind with no proxy.
///
/// Returns `None` only when neither source yields a parseable IP (the limiter
/// then fails open for that one request).
fn client_ip(
    headers: &HeaderMap,
    conn: Option<&SocketAddr>,
    trusted_header: Option<&str>,
) -> Option<IpAddr> {
    if let Some(name) = trusted_header {
        if let Some(raw) = headers.get(name).and_then(|v| v.to_str().ok()) {
            // Right-most hop is the one the trusted proxy appended; earlier
            // entries may be client-forged, so never trust the left-most.
            if let Some(last) = raw.split(',').next_back() {
                if let Ok(ip) = last.trim().parse::<IpAddr>() {
                    return Some(ip);
                }
            }
        }
        // Trusted header absent/unparseable → fall through to the socket peer.
    }
    conn.map(|s| s.ip())
}

/// Rate-limit middleware: 429 on the abuse-prone paths once an IP's bucket is
/// empty; every other request (and every non-guarded path) passes through. The
/// peer `SocketAddr` is read from the request extension `ConnectInfo` sets (via
/// `into_make_service_with_connect_info`), preferring `X-Forwarded-For`.
async fn rate_limit(
    State(rl): State<RateLimitState>,
    req: axum::extract::Request,
    next: Next,
) -> Response {
    let path = req.uri().path().to_string();
    let method = req.method().clone();
    if is_rate_limited_path(&path, &method) {
        let conn = req
            .extensions()
            .get::<ConnectInfo<SocketAddr>>()
            .map(|c| c.0);
        let ip = client_ip(req.headers(), conn.as_ref(), rl.trusted_header.as_deref());
        // Deliberately fail OPEN when no client IP is derivable (no trusted
        // header / no socket peer): there is no per-IP key to enforce, and a
        // blanket 429 would self-DoS every guarded path (incl. /login). This is
        // safe precisely because we never key on an attacker-forged XFF — see
        // `rate_limit_ignores_spoofed_xff_rotation`.
        if let Some(ip) = ip {
            if !rl.limiter.check(ip) {
                warn!(%ip, %path, "rate limit exceeded");
                return (
                    StatusCode::TOO_MANY_REQUESTS,
                    [(header::RETRY_AFTER, "1")],
                    "rate limit exceeded\n",
                )
                    .into_response();
            }
        }
    }
    next.run(req).await
}

// ---------------------------------------------------------------------------
// Cache-Control (viral / CDN vs. private authenticated views)
// ---------------------------------------------------------------------------

/// Cache-Control middleware. Emits `public, max-age=300` on the cacheable
/// logged-out surfaces (the `/login` landing without a handle, `/about`,
/// `/standard-site`, `/privacy`, `/terms`, and the `/static/*` assets) and `no-store` on the
/// authenticated app pages, so a CDN /
/// browser can hold the viral landing while never caching a signed-in user's
/// private view. Never overrides a handler that already set Cache-Control.
async fn cache_control(req: axum::extract::Request, next: Next) -> Response {
    let path = req.uri().path().to_string();
    // The logged-out landing is only cacheable when it's the bare form — a
    // `?handle=` GET kicks off OAuth (a redirect), which must not be cached.
    let is_login_landing = path == "/login"
        && req.method() == axum::http::Method::GET
        && !req.uri().query().unwrap_or("").contains("handle=");
    let public = is_login_landing
        || path == "/about"
        || path == "/standard-site"
        || path == "/privacy"
        || path == "/terms"
        || path.starts_with("/static/");

    let mut resp = next.run(req).await;
    if resp.headers().contains_key(header::CACHE_CONTROL) {
        return resp;
    }
    let value = if public {
        "public, max-age=300"
    } else {
        "no-store"
    };
    if let Ok(hv) = header::HeaderValue::from_str(value) {
        resp.headers_mut().insert(header::CACHE_CONTROL, hv);
    }
    resp
}

// ---------------------------------------------------------------------------
// Health
// ---------------------------------------------------------------------------

/// Run `/health`'s database probe. **The single path, so a test cannot assert
/// on a string the handler is free to ignore** — a named constant alone was not
/// enough: the test read the constant while the handler passed `query_scalar`
/// whatever it liked, so degrading the real call to `SELECT 1` shipped green.
async fn health_db_probe(pool: &store::Pool) -> Result<Option<i64>, sqlx::Error> {
    sqlx::query_scalar::<_, i64>(HEALTH_DB_PROBE_SQL)
        .fetch_optional(pool)
        .await
}

/// The statement `/health` uses to prove the database is readable.
///
/// **A named constant so the test can assert on the query that actually runs.**
/// `the_health_probe_opens_a_real_table` used to `EXPLAIN` a hand-typed copy of
/// this string, so degrading the real probe to `SELECT 1` — which opens no page
/// and therefore cannot detect a broken database — left the suite green.
const HEALTH_DB_PROBE_SQL: &str = "SELECT 1 FROM feeds LIMIT 1";

/// How long `/health` will wait for its database ping before calling it broken.
///
/// Under `fly.toml`'s 3 s check timeout, so a hung pool produces a 503 this
/// handler chose rather than a timeout Fly inferred — the difference between a
/// log line that says why and one that says nothing.
const HEALTH_DB_TIMEOUT: Duration = Duration::from_secs(2);

/// Floor for the poll-heartbeat staleness threshold. **Reported, never fatal** —
/// see the handler for why.
///
/// The threshold itself is derived from the configured tick
/// ([`health_tick_stale_secs`]): hardcoding 15 minutes meant an operator who
/// raised `FEATHERREADER_POLL_TICK_SECS` above 900 got a permanent `poller:
/// stale` in the body the deployment docs now tell them to alert on.
const HEALTH_TICK_STALE_FLOOR_SECS: i64 = 15 * 60;

/// How long without a completed tick before the poller reads as stale: several
/// tick intervals, floored, so a normally-paced loop never trips it and a
/// genuinely wedged one always does.
fn health_tick_stale_secs(tick: Duration) -> i64 {
    let tick = i64::try_from(tick.as_secs()).unwrap_or(i64::MAX);
    tick.saturating_mul(5).max(HEALTH_TICK_STALE_FLOOR_SECS)
}

/// The poll tick this instance is configured for. Read from the same env var
/// `scheduler.rs` reads, because the scheduler lives in the binary crate and the
/// handler cannot see its constants.
fn configured_poll_tick() -> Duration {
    std::env::var("FEATHERREADER_POLL_TICK_SECS")
        .ok()
        .and_then(|v| v.trim().parse::<u64>().ok())
        .filter(|s| *s > 0)
        .map_or(DEFAULT_POLL_TICK_SECS, Duration::from_secs)
}

/// Mirrors `scheduler::DEFAULT_POLL_TICK`, which lives in the BINARY crate and
/// so cannot be imported here. Duplicated deliberately and named, rather than
/// left as a bare `60` inside the parse chain, so the drift is at least visible
/// if the scheduler's value ever moves.
const DEFAULT_POLL_TICK_SECS: Duration = Duration::from_secs(60);

/// Grace period after boot before a poller that has never ticked is called
/// `stale` rather than `not-yet-ticked`.
///
/// Without this the two are indistinguishable forever, which matters precisely
/// in the case the startup delays were added for: in a crash loop with 30 s+ boot
/// cycles the poller never reaches its first tick, so `/health` reported the
/// benign `not-yet-ticked` on every single probe and the heartbeat could not
/// detect the failure mode it exists for. `run_poller` returning early — a failed
/// HTTP client build — has the same shape and was equally invisible.
///
/// Sized off the poller's own startup delay plus its tick, with slack.
const HEALTH_FIRST_TICK_GRACE_SECS: i64 = 5 * 60;

/// `GET /health` — does this process still work, and what are its loops doing?
///
/// This used to return a constant string, touching no database, no pool and no
/// scheduler state — while being the ONLY automated signal in `fly.toml`, whose
/// sole other failure detector is a child process exiting. It proved the HTTP
/// listener was up and nothing else.
///
/// **What can fail the check: the database, and only the database.** A process
/// that cannot reach its store serves nothing, so a restart is the right
/// response and this returns 503. The probe is a read (`SELECT 1`), which in WAL
/// mode is not blocked by any writer — so the retention sweep, the poller and a
/// login burst cannot make this flap. That property is the reason it is a read
/// and not, say, a write canary.
///
/// **What is reported but never fails the check: everything else.** A stale poll
/// heartbeat, a watermark pause, a missing OAuth runtime — all real problems,
/// and none of them a reason to stop serving.
///
/// That last clause is the whole justification, and it is NOT the one this
/// comment used to give. It said "Fly restarts on a failed check", which is
/// false — verified against Fly's own docs, which state it three times: *"your
/// Machines won't automatically restart or stop due to failing their health
/// checks"*. A failing `[[http_service.checks]]` check makes Fly Proxy stop
/// ROUTING to the Machine. Nothing restarts it. That capability existed on Apps
/// V1 (`restart_limit`) and has no successor on Machines.
///
/// The corrected model makes the conclusion stronger, not weaker. With one
/// Machine there is no healthy peer to shift traffic to, so a 503 here is not a
/// failover — it is a total outage that lasts exactly as long as the condition,
/// and it also fails a `fly deploy` (rolling strategy, no auto-rollback). So the
/// question the status code answers is not "would a restart fix this" but **"can
/// this process still serve a useful request at all"**. A stale poller can. A
/// database it cannot read cannot.
///
/// Re-registration is automatic: the proxy keeps probing and routes again the
/// moment the check passes. That is what makes a 503 recoverable without
/// intervention — not a restart, which never comes.
///
/// The body is machine facts only — no user counts, no DIDs, no feed URLs — so
/// it is publishable on the same terms as `/stats`. It is also the non-session
/// diagnostic for an OAuth outage: when nobody can log in, `/admin/metrics`
/// (which needs a live admin session) is exactly as unreachable as the thing it
/// would diagnose, while this is reachable with `curl`.
async fn health(State(state): State<AppState>) -> Response {
    let now = chrono::Utc::now().timestamp();
    let rh = &state.runtime_health;

    use crate::runtime_health::DbProbe;
    let db = match rh.begin_db_probe() {
        // A probe is already in flight; report its predecessor rather than
        // starting a second one. See `RuntimeHealth::begin_db_probe`.
        Err(borrowed) => borrowed,
        Ok(probe) => {
            // **Spawned, so the probe cannot be cancelled by the caller.**
            //
            // Axum drops the handler future when a client disconnects. With the
            // probe inline, that dropped it mid-flight and released the claim
            // WITHOUT recording a verdict — which let an unauthenticated caller
            // manufacture the no-verdict state on demand and freeze what every
            // other caller, Fly's check included, reads. Running it detached
            // means the verdict is always recorded and the claim is always
            // released after it.
            let pool = state.db.clone();
            let task = tokio::spawn(async move {
                // **`SELECT 1` was not a database probe.** It compiles to
                // `Init/Integer/ResultRow/Halt` — there is no `OpenRead`, so it
                // never touches a b-tree, never reads a page, and never consults
                // the file. Against a corrupted database it returns success
                // while every real query returns SQLITE_CORRUPT. Reading one row
                // from a real table costs the same and actually proves what the
                // check claims. `LIMIT 1` keeps it to a single page; an empty
                // table still opens the b-tree root, which is the part that
                // matters.
                let verdict =
                    match tokio::time::timeout(HEALTH_DB_TIMEOUT, health_db_probe(&pool)).await {
                        Ok(Ok(_)) => DbProbe::Ok,
                        // Coarse, not the raw error. An unauthenticated caller
                        // learning exactly which failure it hit is an
                        // attack-progress oracle; the detail belongs in the log,
                        // which gets it here.
                        Ok(Err(err)) => {
                            warn!(%err, "health: database probe failed");
                            DbProbe::Failed("unavailable".to_string())
                        }
                        Err(_) => {
                            warn!(
                                timeout_s = HEALTH_DB_TIMEOUT.as_secs(),
                                "health: database probe timed out (pool exhausted?)"
                            );
                            DbProbe::Failed("timeout".to_string())
                        }
                    };
                probe.record(verdict.clone());
                verdict
            });
            // A panicking task drops the guard, which releases the claim without
            // a verdict — the only remaining path to that state, and not one a
            // caller can drive.
            task.await.unwrap_or(DbProbe::Unknown)
        }
    };

    let uptime = rh.uptime_secs(now);
    let poller = if !rh.schedulers_enabled() {
        // Not a fault. Dev runs and the seam tests disable the loops on purpose,
        // and reporting that as "stale" would be a false alarm on every one.
        "disabled".to_string()
    } else {
        match rh.secs_since_poll_tick(now) {
            // "Never ticked" is benign right after boot and alarming well after
            // it — so it is read against UPTIME, not left permanently benign.
            None => match uptime {
                Some(up) if up > HEALTH_FIRST_TICK_GRACE_SECS => {
                    format!("stale never-ticked {up}s")
                }
                _ => "not-yet-ticked".to_string(),
            },
            Some(secs) if secs > health_tick_stale_secs(configured_poll_tick()) => {
                format!("stale {secs}s")
            }
            Some(secs) => format!("ok {secs}s"),
        }
    };

    // **Only a MEASURED failure fails the check.**
    //
    // `Unknown` means no probe has completed — a concurrent request arrived
    // before the first one finished, or a previous owner was cancelled before
    // recording. It is reported and returns 200, because an unmeasured database
    // is not evidence of a broken one, and this endpoint is reachable by
    // unauthenticated callers who can manufacture that state. Treating it as a
    // failure handed them a lever on the only signal the platform acts on.
    let mut body = String::new();
    let status = match &db {
        DbProbe::Ok => {
            body.push_str(&format!("ok featherreader/{VERSION}\n"));
            body.push_str("db: ok\n");
            StatusCode::OK
        }
        // **Not `ok`.** The first token is the state, and this one is neither
        // healthy nor failed. It used to print a line byte-identical to the
        // healthy branch, which mattered because `fly.toml` tells operators to
        // alert on the BODY for everything the status code deliberately ignores
        // — so a monitor keying on `^ok` read green in exactly the state this
        // enum exists to make visible.
        DbProbe::Unknown => {
            body.push_str(&format!("unknown featherreader/{VERSION}\n"));
            body.push_str("db: unknown (no probe has completed yet)\n");
            StatusCode::OK
        }
        DbProbe::Failed(why) => {
            body.push_str(&format!("FAIL featherreader/{VERSION}\n"));
            body.push_str(&format!("db: {why}\n"));
            StatusCode::SERVICE_UNAVAILABLE
        }
    };
    // Uptime answers the first question anyone asks about a container under a
    // supervisor that tears the machine down whenever a child exits: is this
    // thing restarting? Nothing else on any surface could tell you.
    body.push_str(&format!(
        "uptime: {}\n",
        match uptime {
            Some(secs) => format!("{secs}s"),
            None => "unknown".to_string(),
        }
    ));
    body.push_str(&format!("poller: {poller}\n"));
    body.push_str(&format!(
        "polling-paused: {}\n",
        if rh.watermark_paused() { "yes" } else { "no" }
    ));
    // Deliberately NOT the measured database size. `/health` is the one path
    // exempted from the Caddy origin lock, so it answers direct hits to the Fly
    // IP that never passed Cloudflare — which caps what belongs here at the
    // class of facts `/stats` already publishes to anyone. "Polling is paused"
    // is that; the exact byte count is a precise internal number that adds
    // nothing an operator cannot get from `/stats` or the logs.
    body.push_str(&format!(
        "backend: {}\n",
        state.config.repo_backend.as_str()
    ));
    body.push_str(&format!(
        "oauth-runtime: {}\n",
        if state.oauth.is_some() {
            "built"
        } else {
            "absent"
        }
    ));

    // Never cached: a stale health response is worse than none, and Cloudflare
    // sits in front of this.
    let mut resp = (status, body).into_response();
    if let Ok(hv) = header::HeaderValue::from_str("no-store") {
        resp.headers_mut().insert(header::CACHE_CONTROL, hv);
    }
    resp
}

/// `GET /about` — the public-experiment page: the full disclaimer (experimental,
/// no SLA, may pause anytime), the OSS / self-host pitch, and the tip link.
/// Readable whether or not a session exists.
///
/// Optionally carries one quiet line about network adoption
/// (`design/NETWORK-SPEC.md` §4.4). With `FEATHERREADER_SHOW_ADOPTION` off — the
/// default — the handler issues **zero** queries and the page is byte-identical
/// to what it was before the probe existed.
async fn about(State(state): State<AppState>) -> Response {
    let adoption = if state.config.show_adoption {
        adoption_line(&state).await
    } else {
        None
    };
    render(&AboutTemplate {
        card: Card::public(
            &state.config,
            "/about",
            "About — FeatherReader",
            "What FeatherReader is and isn't: an open-source, atproto-native reader for \
             RSS feeds and standard.site publications, run as an experiment, free to \
             self-host under the AGPL.",
        ),
        version: VERSION,
        repo_url: REPO_URL,
        kofi_url: KOFI_URL,
        adoption,
        standard_site: state.config.standard_site,
    })
}

/// `GET /standard-site` — the public feature page for standard.site
/// publications: what a publication is, what FeatherReader shows from one, how
/// to subscribe, the limits, and the latest releases. Readable whether or not
/// a session exists, like `/about`. Every how-to-subscribe line is conditional
/// on `Config::standard_site`, as on the other public pages.
async fn standard_site(State(state): State<AppState>) -> Response {
    render(&StandardSiteTemplate {
        card: Card::public(
            &state.config,
            "/standard-site",
            "standard.site — FeatherReader",
            "Read standard.site publications beside your RSS feeds: articles \
             published as atproto records, followed with the same portable \
             subscription record.",
        ),
        version: VERSION,
        repo_url: REPO_URL,
        kofi_url: KOFI_URL,
        standard_site: state.config.standard_site,
        releases: RELEASES,
    })
}

/// `POST /saved/:rkey/delete` — remove a saved record that has no local entry.
///
/// The normal star toggle is keyed on an entry id, which a PDS-only saved row
/// does not have. This deletes the record straight from the repo by its rkey,
/// and then clears any LOCAL star for the same article.
///
/// That second step is not belt-and-braces. "Has no local entry" is how the
/// starred view classifies a record, and it decides that through `sub_ref` — so
/// an article that really is cached, and really is starred, lands here whenever
/// the reader has unsubscribed from its feed. Deleting only the record left
/// `entry_state.starred = 1` behind: invisible, because the starred list is
/// `sub_ref`-scoped too, until a resubscribe brought the star back with nothing
/// in the PDS backing it. A reader who clicks "remove" gets it removed from both
/// places it lives.
async fn unsave_record(
    State(state): State<AppState>,
    headers: HeaderMap,
    Path(rkey): Path<String>,
) -> Response {
    let Some(did) = current_did(&state, &headers).await else {
        return (StatusCode::UNAUTHORIZED, "sign in first\n").into_response();
    };

    // Read the record's identity BEFORE deleting it — afterwards there is
    // nothing left to learn it from. Best-effort: a failure here must not block
    // the deletion the reader actually asked for, so it degrades to the old
    // behaviour (record gone, local star possibly stale) and says so.
    let identity = match state.repo().list_saved(&did).await {
        Ok(records) => records
            .into_iter()
            .find(|(k, _)| *k == rkey)
            .map(|(_, rec)| (rec.url, rec.entry_id)),
        Err(err) => {
            warn!(%err, %did, %rkey, "could not read the saved record before deleting it; \
                                      a local star for the same article may survive");
            None
        }
    };

    match state.repo().remove_saved(&did, &rkey).await {
        Ok(()) => info!(%did, %rkey, "removed a saved record with no cached entry"),
        Err(err) => {
            warn!(%err, %did, %rkey, "could not remove the saved record");
            return (StatusCode::BAD_GATEWAY, "could not remove that item\n").into_response();
        }
    }

    // Deliberately AFTER the delete: the PDS is the source of truth for what was
    // saved, so clearing the local star before knowing the record is gone would
    // be the desync in the other direction.
    if let Some((url, guid)) = identity {
        match store::clear_star_by_identity(&state.db, &did, Some(&url), guid.as_deref()).await {
            Ok(0) => {}
            Ok(n) => {
                info!(%did, %rkey, cleared = n, "cleared the local star for an unsaved record")
            }
            Err(err) => warn!(%err, %did, %rkey, "could not clear the local star after unsaving"),
        }
    }
    // htmx swaps the row out; a plain form post goes back to the starred list.
    if is_htmx(&headers) {
        return (StatusCode::OK, "").into_response();
    }
    Redirect::to("/?view=starred").into_response()
}

/// What the poller is doing, as one word for `/stats`.
///
/// **Parity with `/health` is the point.** `polling_paused` alone reported
/// "running" for three different states including the two where nothing polls,
/// on the page added to answer exactly that. The first attempt at fixing it
/// added `off` and `starting` and claimed parity — but left out `stale`, so a
/// poll loop that ticked once at boot and then WEDGED still read as running.
/// That is the wedged-loop case `/health`'s heartbeat exists for, and the
/// original finding's exact shape surviving its own fix.
///
/// Shares the staleness threshold with `/health` rather than picking its own, so
/// the two pages cannot disagree about what "stale" means.
fn fetching_state(rh: &crate::runtime_health::RuntimeHealth, now_unix: i64) -> &'static str {
    if !rh.schedulers_enabled() {
        return "off";
    }
    // Checked before the pause: a wedged poller cannot clear a pause either, so
    // reporting "paused" would name the symptom and hide the cause.
    match rh.secs_since_poll_tick(now_unix) {
        None => {
            // Never ticked. Benign at boot, a dead loop long after — read
            // against uptime, exactly as `/health` does.
            match rh.uptime_secs(now_unix) {
                Some(up) if up > HEALTH_FIRST_TICK_GRACE_SECS => "stale",
                _ => "starting",
            }
        }
        Some(secs) if secs > health_tick_stale_secs(configured_poll_tick()) => "stale",
        _ if rh.watermark_paused() => "paused",
        _ => "running",
    }
}

/// `GET /stats` — public poll health.
async fn stats(State(state): State<AppState>) -> Response {
    let now = chrono::Utc::now();
    let health = match store::poll_health(
        &state.db,
        &now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
        &(now - chrono::Duration::hours(1)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
    )
    .await
    {
        Ok(health) => health,
        Err(err) => {
            warn!(%err, "could not compute poll health");
            return (StatusCode::INTERNAL_SERVER_ERROR, "stats unavailable\n").into_response();
        }
    };

    // Percentage of a zero-feed instance is 100, not a divide-by-zero: a fresh
    // instance is not behind on anything.
    let polled_pct = if health.feeds_tracked == 0 {
        100
    } else {
        health.polled_last_hour * 100 / health.feeds_tracked
    };

    render(&StatsTemplate {
        card: Card::public(
            &state.config,
            "/stats",
            "Stats — FeatherReader",
            "Is this instance's poller keeping up? Aggregate feed-polling health — \
             counts only; no feed and no reader is named.",
        ),
        version: VERSION,
        repo_url: REPO_URL,
        kofi_url: KOFI_URL,
        feeds_tracked: health.feeds_tracked,
        polled_last_hour: health.polled_last_hour,
        polled_pct,
        overdue: health.overdue,
        last_poll: humanise_ago(health.last_poll_secs_ago),
        oldest_poll: if health.never_polled > 0 {
            "never".to_string()
        } else {
            humanise_ago(health.oldest_poll_secs_ago)
        },
        never_polled: health.never_polled,
        poll_interval_mins: state.config.poll_interval.as_secs() as i64 / 60,
        // **The two states that actually stop feeds updating.**
        //
        // Neither was visible anywhere. `overdue` and `polled_last_hour` move in
        // both and distinguish neither — and `overdue` moves the WRONG WAY for
        // backoff, since backoff is applied by pushing `next_poll` forward, so a
        // feed failing every fetch drops out of the backlog and makes the page
        // read healthier. Both of these are machine facts with no per-feed
        // detail, so they sit inside the page's stated contract.
        in_backoff: health.in_backoff,
        badly_broken: health.badly_broken,
        failure_kinds: health.failure_kinds,
        fetching: fetching_state(&state.runtime_health, now.timestamp()),
    })
}

/// "3h 11m ago", or "never" when there has been no poll at all.
///
/// `None` must not render as `0` — on a fresh instance that would read as
/// "polled just now", which is the opposite of the truth.
fn humanise_ago(secs: Option<i64>) -> String {
    let Some(secs) = secs else {
        return "never".to_string();
    };
    match secs {
        s if s < 60 => format!("{s}s ago"),
        s if s < 3600 => format!("{}m ago", s / 60),
        s => format!("{}h {}m ago", s / 3600, (s % 3600) / 60),
    }
}

/// The `/about` adoption line's data, or `None` (no successful probe yet, an
/// observation of zero, or a store failure).
///
/// A read failure degrades to `None` plus a `warn!` rather than propagating: the
/// probe is never allowed to affect the reader, and that rule applies at the
/// display end too — a locked or corrupt DB costs the About page one log line,
/// not a 500.
async fn adoption_line(state: &AppState) -> Option<AdoptionLine> {
    match store::latest_network_stat(&state.db, store::ADOPTION_STAT_KEY).await {
        // A legitimate zero renders nothing rather than a sad "0 accounts".
        Ok(Some(stat)) if stat.value > 0 => Some(AdoptionLine {
            repos: stat.value,
            truncated: stat.truncated,
            observed_on: stat
                .observed_at
                .split('T')
                .next()
                .unwrap_or_default()
                .to_string(),
        }),
        Ok(_) => None,
        Err(err) => {
            warn!(%err, "about: adoption stat read failed; omitting the line");
            None
        }
    }
}

/// `GET /privacy` — the plain-language privacy page: no account/tracking, data
/// lives in the user's PDS, what the server caches, and the session-token
/// handling. A static render; readable whether or not a session exists.
async fn privacy(State(state): State<AppState>) -> Response {
    render(&PrivacyTemplate {
        card: Card::public(
            &state.config,
            "/privacy",
            "Privacy — FeatherReader",
            "No account and no tracking: your subscriptions and reading state live in \
             your own PDS. What this server caches, for how long, and how the session \
             token is handled.",
        ),
        version: VERSION,
        repo_url: REPO_URL,
        kofi_url: KOFI_URL,
    })
}

/// `GET /terms` — the terms of use: the experimental / as-is disclaimer,
/// acceptable use, the AGPL/self-host note, and the liability limitation. A
/// static render; readable whether or not a session exists.
async fn terms(State(state): State<AppState>) -> Response {
    render(&TermsTemplate {
        card: Card::public(
            &state.config,
            "/terms",
            "Terms — FeatherReader",
            "The terms of use: an experimental service offered as-is with no warranty, \
             what acceptable use means here, and the AGPL self-host note.",
        ),
        version: VERSION,
        repo_url: REPO_URL,
        kofi_url: KOFI_URL,
    })
}

// ---------------------------------------------------------------------------
// View models
// ---------------------------------------------------------------------------

/// A feed as shown in the sidebar (title + its unread count + a stable scope key
/// and the PDS subscription rkey for management actions).
struct FeedView {
    /// PDS subscription rkey — addresses the record for rename/unsubscribe.
    rkey: String,
    /// Canonical feed URL — the sidebar filter key (`?feed=<url>`).
    url: String,
    title: String,
    unread: i64,
    /// Whether this feed is the currently-selected scope.
    selected: bool,
    /// The feed's current folder `at://` URI (from its subscription record), or
    /// `None` if un-foldered. Drives the pre-selected `<option>` in the manage
    /// rename row so an untouched folder dropdown does not silently un-folder the
    /// feed on save.
    folder: Option<String>,
}

/// A folder grouping in the sidebar, sourced from the PDS `folder` records.
struct FolderView {
    /// PDS folder rkey — addresses the record for rename/delete.
    rkey: String,
    /// The folder's `at://` URI — the sidebar filter key (`?folder=<uri>`).
    uri: String,
    name: String,
    feeds: Vec<FeedView>,
    /// Whether this folder is the currently-selected scope.
    selected: bool,
}

/// One entry as shown in the article list / after an htmx swap.
struct EntryRow {
    id: i64,
    title: String,
    feed_title: String,
    published: String,
    read: bool,
    starred: bool,
    /// The reader link href, already carrying the scope/view query so opening an
    /// entry and paging back stays within the list it came from.
    link: SafeLink,
    /// Whether the article itself is in this instance's cache.
    ///
    /// `false` for a saved record that exists in the reader's PDS but whose
    /// entry was never cached here — starred in another atproto reader, or
    /// starred here and since evicted. There is no local row, so the row has no
    /// usable `id`: it links straight out to the article and carries no
    /// mark-read control, because there is nothing local to mark.
    cached: bool,
    /// The PDS record key, for un-saving a row that has no local entry.
    rkey: String,
}

/// A folder as an option in the "move feed to folder" select.
struct FolderOption {
    uri: String,
    name: String,
}

/// The shared navigation "rail" model: the same DOM element is the
/// mobile drawer and the desktop sidebar, so every chrome page (list / reader /
/// manage) renders it from this one struct. Feed management lives on `/manage`,
/// not here — the rail is navigation only.
struct Nav {
    /// `@handle` for the identity chip (falls back to the DID's tail).
    handle: String,
    /// Two-letter avatar initials for the identity chip.
    avatar: String,
    /// The active filter: `"unread" | "all" | "starred"` (drives `aria-current`).
    view: String,
    /// The scope query suffix (`feed=…` / `folder=…`) carried onto filter links,
    /// empty for the unscoped "everything" views.
    scope_qs: String,
    /// Folders (each with its feeds) then un-foldered feeds, for the rail lists.
    /// Per-feed `selected` flags drive the rail's feed `aria-current`.
    folders: Vec<FolderView>,
    loose_feeds: Vec<FeedView>,
    /// Whether the "Manage feeds" rail tool is the current page.
    manage_active: bool,
}

/// The subscribe input's `pattern` when standard.site is on, and the input is
/// `type="text"` (see `templates/manage.html`). It keeps the browser asking for
/// a scheme, as `type="url"` did, while admitting `at://`. Matched in any case,
/// because the handler canonicalises the scheme. Browsers compile `pattern`
/// with the `v` flag and anchor it at both ends. Unlike `type="url"`, a text
/// input does not strip surrounding whitespace before checking, so the pattern
/// allows it: a URL pasted with a leading space is common, and the handler
/// trims it.
pub(crate) const FEED_URL_PATTERN: &str = "\\s*(?:[Hh][Tt][Tt][Pp][Ss]?|[Aa][Tt])://.+";

// ---------------------------------------------------------------------------
// Link cards (Open Graph / Twitter / Bluesky)
// ---------------------------------------------------------------------------

/// The site's own title: the landing page's, and the one every private view
/// shows instead of its own.
const SITE_TITLE: &str = "FeatherReader — read, quietly";

/// The site's one-paragraph description: the landing page's, and the one every
/// private view shows instead of its own.
const SITE_DESCRIPTION: &str = "A minimalist, atproto-native reader for RSS feeds and \
standard.site publications. Your subscriptions live in your own PDS — no signup, no \
password, no tracking.";

/// Where the share image is served, relative to the public origin. The file is
/// `static/social-card.png`, rendered from `static/social-card.svg` by
/// `scripts/social-card.sh`; `base.html` advertises its dimensions, and a test
/// checks the PNG's own header agrees.
const SHARE_IMAGE_PATH: &str = "/static/social-card.png";

/// What a link to a page unfurls as when it is posted — on Bluesky, in a chat,
/// anywhere that reads Open Graph tags. `base.html` renders it into `<head>`.
///
/// Measured before this existed: Bluesky's card service
/// (`cardyb.bsky.app/v1/extract?url=https://feather-reader.com/`) returned
/// `{"title":"FeatherReader — read, quietly","description":"","image":""}`,
/// because `<title>` was the only tag it could find. Card fetchers read the
/// initial HTML server-side, run no JS, and resolve nothing relative, so every
/// URL here is absolute on [`Config::public_url`] — `https://feather-reader.com`
/// in production, whatever `FEATHERREADER_PUBLIC_URL` says elsewhere.
#[derive(Debug, Clone)]
pub(crate) struct Card {
    /// `og:title`. On a public page, the same text as its `<title>`.
    pub title: String,
    /// `og:description` and `<meta name="description">`: one or two plain
    /// sentences about THIS page, not the site.
    pub description: String,
    /// `og:url` and `<link rel="canonical">`: absolute, on the public origin.
    pub url: String,
    /// `og:image`: absolute, on the public origin.
    pub image: String,
    /// Set on a page that renders a session's private view. The card is then
    /// the site's generic one — nothing from the view reaches `<head>` — and
    /// the page is `noindex`.
    pub private: bool,
}

impl Card {
    /// The card of the public page at `path` (leading slash) on this instance.
    fn public(
        config: &Config,
        path: &str,
        title: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        let origin = config.public_url.trim_end_matches('/');
        Card {
            title: title.into(),
            description: description.into(),
            url: format!("{origin}{path}"),
            image: format!("{origin}{SHARE_IMAGE_PATH}"),
            private: false,
        }
    }

    /// The landing page's card: the site's own title and description.
    fn site(config: &Config) -> Self {
        Card::public(config, "/", SITE_TITLE, SITE_DESCRIPTION)
    }

    /// The card of a page that renders a session's private view: the site's
    /// generic card pointing at the front door, plus `noindex`. The view's
    /// heading, feed names and handle stay out of `<head>`.
    fn private(config: &Config) -> Self {
        Card {
            private: true,
            ..Card::site(config)
        }
    }
}

/// The reader index (`GET /`).
#[derive(Template)]
#[template(path = "index.html")]
struct IndexTemplate {
    /// The link card. A private view: the site's generic card, `noindex`.
    card: Card,
    version: &'static str,
    repo_url: &'static str,
    kofi_url: &'static str,
    flash: String,
    /// Shown as `role="alert"` when the subscription list is the cached one
    /// because the PDS listing failed; empty otherwise.
    alert: String,
    /// The shared rail (drawer + desktop sidebar) navigation model.
    nav: Nav,
    /// The article list for the selected scope + view.
    entries: Vec<EntryRow>,
    /// The list heading (the selected view/feed/folder name).
    heading: String,
    /// Whether a feed scope is active (enables per-feed mark-all-read).
    feed_scope: Option<String>,
    /// Total CACHED entries in this scope + view across ALL pages. The count used
    /// to be `entries.len()`, which was the same number only because the list was
    /// unpaged — the thing this change exists to stop.
    ///
    /// The pager is derived from this, so it must not include the uncached PDS
    /// rows below: they are appended to the last page rather than paged, and
    /// counting them here advertised a page the clamp could never reach.
    total: i64,
    /// How many of `total` are PDS saved records the cache cannot show.
    ///
    /// A subset of `total`, not an addition to it — the heading says "N entries
    /// (M saved elsewhere)". An earlier version rendered "N entries, plus M",
    /// which double counted once `total` started including them, against an M
    /// that had become page-local in the same commit while the template stayed
    /// put.
    uncached_total: i64,
    /// 1-based current page.
    page: i64,
    /// Total pages, at least 1 (an empty list is page 1 of 1).
    page_count: i64,
    /// Link to the previous (newer) page, or `None` on the first.
    prev_href: Option<String>,
    /// Link to the next (older) page, or `None` on the last.
    next_href: Option<String>,
}

/// The feed-management page (`GET /manage`) — subscribe / your-feeds / OPML.
#[derive(Template)]
#[template(path = "manage.html")]
struct ManageTemplate {
    /// The link card. A private view: the site's generic card, `noindex`.
    card: Card,
    version: &'static str,
    repo_url: &'static str,
    kofi_url: &'static str,
    flash: String,
    /// See [`IndexTemplate::alert`].
    alert: String,
    nav: Nav,
    /// All folders as move-targets for the subscribe folder select.
    folder_options: Vec<FolderOption>,
    /// Folders (each with feeds) + loose feeds, for the "Your feeds" list.
    folders: Vec<FolderView>,
    loose_feeds: Vec<FeedView>,
    /// `Config::standard_site`. With it on, the subscribe form says a
    /// `site.standard.publication` URI is accepted and its input drops
    /// `type="url"`, whose browser validation rejects the DID form. With it off
    /// `add_subscription` refuses every `at://` paste, so the form must not
    /// advertise one.
    standard_site: bool,
}

/// The optional one-line adoption fact at the bottom of `/about`
/// (`design/NETWORK-SPEC.md` §4.4). `None` whenever the display flag is off, no
/// probe has succeeded yet, or the read failed — the line then simply does not
/// render.
struct AdoptionLine {
    /// Repos a relay has indexed as holding the subscription collection.
    repos: i64,
    /// The probe hit its page cap, so the copy must say "at least".
    truncated: bool,
    /// Observation date, `YYYY-MM-DD` (UTC), sliced from the stored RFC3339 stamp.
    observed_on: String,
}

/// The public-experiment `/about` page — disclaimer + OSS pitch + tip link, plus
/// the optional adoption line.
#[derive(Template)]
#[template(path = "about.html")]
struct AboutTemplate {
    /// The link card: this page's own title and description.
    card: Card,
    version: &'static str,
    repo_url: &'static str,
    kofi_url: &'static str,
    adoption: Option<AdoptionLine>,
    /// `Config::standard_site`: whether the publications section may tell the
    /// reader how to subscribe to one here. See [`ManageTemplate::standard_site`].
    standard_site: bool,
}

/// The public `/standard-site` feature page. Carries the same footer fields
/// as the other public pages, the standard.site flag, and the release list for
/// the "latest releases" call-out.
#[derive(Template)]
#[template(path = "standard_site.html")]
struct StandardSiteTemplate {
    /// The link card: this page's own title and description.
    card: Card,
    version: &'static str,
    repo_url: &'static str,
    kofi_url: &'static str,
    /// `Config::standard_site`: whether the page may tell a visitor how to
    /// subscribe to a publication here. See [`ManageTemplate::standard_site`].
    standard_site: bool,
    /// [`RELEASES`], newest first, for `templates/releases.html`.
    releases: &'static [Release],
}

/// One tagged release, as the "latest releases" call-out
/// (`templates/releases.html`) shows it on `/standard-site` and the landing
/// page. The links are derived from `version` and `date`, so a release is
/// described in exactly one place: an entry in [`RELEASES`].
pub(crate) struct Release {
    /// The crate version, without the `v` (`"0.4.1"`). The tag is `v{version}`.
    pub(crate) version: &'static str,
    /// The release date, `YYYY-MM-DD`, as the CHANGELOG heading has it.
    pub(crate) date: &'static str,
    /// One or two plain sentences for a visitor. No markup: the template escapes it.
    pub(crate) summary: &'static str,
}

impl Release {
    /// The GitHub release page: `{REPO_URL}/releases/tag/v{version}`.
    pub(crate) fn url(&self) -> String {
        format!("{REPO_URL}/releases/tag/v{}", self.version)
    }

    /// The release's section of `CHANGELOG.md` on `main`. GitHub derives the
    /// anchor for a heading `## 0.4.1 — 2026-10-04` as `041--2026-10-04`: the
    /// dots dropped, the em dash dropped, each space a hyphen.
    pub(crate) fn changelog_url(&self) -> String {
        format!(
            "{REPO_URL}/blob/main/CHANGELOG.md#{}--{}",
            self.version.replace('.', ""),
            self.date
        )
    }
}

/// **The one place a release is described for the website.** Newest first.
/// To announce the next release, add one entry at the top; the call-out on
/// `/standard-site` and the landing page, and both links, follow from it.
/// `releases_are_newest_first_and_link_the_tag_and_changelog` pins the shape.
pub(crate) const RELEASES: &[Release] = &[
    Release {
        version: "0.4.5",
        date: "2026-10-06",
        summary: "An operator teardown now signs every user out at their own \
                  server before deleting anything, and the session-writing \
                  code is hardened against the races that work exposed.",
    },
    Release {
        version: "0.4.4",
        date: "2026-10-05",
        summary: "The feed parser moves to feed-rs 3.0 with entry ids and \
                  links unchanged and real RSS bylines, and the address guard \
                  refuses the reserved ranges it missed.",
    },
    Release {
        version: "0.4.3",
        date: "2026-10-05",
        summary: "Two write-path fixes for any PDS: large OPML imports and \
                  read-state syncs are sent in calls the PDS accepts, and a \
                  read-state sync that disagreed with the PDS recovers instead \
                  of failing every round.",
    },
    Release {
        version: "0.4.2",
        date: "2026-10-04",
        summary: "A public standard.site feature page with this list of recent \
                  releases, and link cards: a posted feather-reader.com link \
                  now unfurls with a description and an image.",
    },
    Release {
        version: "0.4.1",
        date: "2026-10-04",
        summary: "The public pages explain standard.site publications, and the \
                  subscribe form can submit the DID form of a publication URI, \
                  which browsers refused in 0.4.0.",
    },
    Release {
        version: "0.4.0",
        date: "2026-10-03",
        summary: "standard.site support: publications are read from their \
                  authors' atproto repos as subscriptions, beside RSS, on their \
                  own polling loop. Every stored field from a feed or a \
                  publication now has a size bound.",
    },
];

/// The public `/stats` page — is the poller keeping up?
///
/// Aggregate only, deliberately. It is published to anyone, so it carries no
/// user counts and no per-feed detail: a reader does not need to know how many
/// people use an instance or which feeds are failing. What it does answer is the
/// question that decides whether an instance can take more readers — whether the
/// poller is servicing the feeds it already has.
///
/// The counts below are aggregate machine facts, which is why they fit that
/// contract: "12 feeds are in backoff" names no feed and no reader, while
/// answering the question the page was previously unable to answer at all.
#[derive(Template)]
#[template(path = "stats.html")]
struct StatsTemplate {
    /// The link card: this page's own title and description.
    card: Card,
    version: &'static str,
    repo_url: &'static str,
    kofi_url: &'static str,
    feeds_tracked: i64,
    polled_last_hour: i64,
    polled_pct: i64,
    overdue: i64,
    last_poll: String,
    oldest_poll: String,
    never_polled: i64,
    poll_interval_mins: i64,
    /// Feeds in error backoff. Invisible before, and excluded from `overdue`.
    in_backoff: i64,
    /// Of those, the ones retried hours apart rather than minutes. **Not
    /// "effectively dead"** — see `store::BADLY_BROKEN_ERRORS`; they recover on
    /// their next successful poll, and most of this instance's did.
    badly_broken: i64,
    /// Failing feeds by cause, descending — counts only, never which feed.
    failure_kinds: Vec<(String, i64)>,
    /// What the poller is actually doing: `running`, `paused` (at the size
    /// watermark), `starting` (no tick completed yet) or `off` (schedulers
    /// disabled). Three of those four used to render as "running".
    fetching: &'static str,
}

/// The public `/privacy` page — what the server holds vs. what lives in the
/// user's PDS. Carries the same `repo_url`/`kofi_url`/`version` the shared
/// footer include needs.
#[derive(Template)]
#[template(path = "privacy.html")]
struct PrivacyTemplate {
    /// The link card: this page's own title and description.
    card: Card,
    version: &'static str,
    repo_url: &'static str,
    kofi_url: &'static str,
}

/// The public `/terms` page — the as-is / no-warranty terms of use. Carries the
/// same fields the shared footer include needs.
#[derive(Template)]
#[template(path = "terms.html")]
struct TermsTemplate {
    /// The link card: this page's own title and description.
    card: Card,
    version: &'static str,
    repo_url: &'static str,
    kofi_url: &'static str,
}

/// The signed-out landing page (`GET /` with no session) — the public front
/// door at feather-reader.com. A static render, no session required.
#[derive(Template)]
#[template(path = "landing.html")]
struct LandingTemplate {
    /// The link card: the site's own title and description.
    card: Card,
    version: &'static str,
    repo_url: &'static str,
    crates_url: &'static str,
    kofi_url: &'static str,
    /// `Config::standard_site`: whether the publications point may tell a
    /// visitor how to subscribe to one here. See [`ManageTemplate::standard_site`].
    standard_site: bool,
    /// [`RELEASES`], newest first, for the quiet "latest releases" strip.
    releases: &'static [Release],
}

/// The single-entry reader view (`GET /entries/:id`).
#[derive(Template)]
#[template(path = "entry.html")]
struct EntryTemplate {
    /// The link card. A private view: the site's generic card, `noindex`.
    card: Card,
    version: &'static str,
    repo_url: &'static str,
    kofi_url: &'static str,
    nav: Nav,
    id: i64,
    title: String,
    feed_title: String,
    author: Option<String>,
    published: String,
    /// The entry's own link, for `entry.html`'s two `href`s.
    ///
    /// `Option<SafeLink>`, not `Option<String>`: the column it comes from holds
    /// a remote feed's `<link>`. Ingest scheme-checks it, but that guard is a
    /// long way from the `href` and holds only while every future writer to
    /// `entries.url` remembers to go through `feed.rs` — the same procedural
    /// defence that, on the saved-record row, turned out to be deletable with
    /// all 679 tests still green. `None` is the refusal: the template's
    /// no-URL branch already renders a disabled open-original button.
    url: Option<SafeLink>,
    content_html: Option<String>,
    read: bool,
    starred: bool,
    /// The query string to carry the reading context back to the list.
    back_qs: String,
    /// Prev/next entry ids within the current list, for keyboard/paging nav.
    prev_id: Option<i64>,
    next_id: Option<i64>,
    /// Rendered inline (not an out-of-band swap fragment): always `false` here.
    oob: bool,
}

/// The htmx swap fragment for a single entry row (`entry_row.html`).
#[derive(Template)]
#[template(path = "entry_row.html")]
struct EntryRowTemplate {
    e: EntryRow,
}

/// The reader's action-bar fragment (`entry_actionbar.html`) returned as an
/// out-of-band swap after a mark-read / star toggle FROM THE READER, so the
/// button's hidden value + `aria-pressed` update in place (the reader `<li>`
/// isn't in the DOM to swap, unlike the list view's `entry_row.html`).
#[derive(Template)]
#[template(path = "entry_actionbar.html")]
struct EntryActionBarTemplate {
    id: i64,
    read: bool,
    starred: bool,
    /// Emit the `hx-swap-oob` attribute: `true` for the handler's OOB response.
    oob: bool,
}

/// The login stub (`GET /login`).
#[derive(Template)]
#[template(path = "login.html")]
struct LoginTemplate {
    /// The link card: this page's own title and description.
    card: Card,
    repo_url: &'static str,
    error: String,
    /// A neutral/success banner (e.g. the post-delete "signed out" confirmation),
    /// distinct from `error`. Empty renders nothing.
    flash: String,
}

/// The closed-beta invite-redeem page (`GET /beta/redeem`).
#[derive(Template)]
#[template(path = "beta_redeem.html")]
struct BetaRedeemTemplate {
    /// The link card: this page's own title and description.
    card: Card,
    repo_url: &'static str,
    error: String,
    /// When true the seat cap is full: hide the form and show the "capacity
    /// full — try self-hosting" message instead.
    capacity_full: bool,
}

// ---------------------------------------------------------------------------
// Rendering + error helpers
// ---------------------------------------------------------------------------

/// Render an askama template into an HTML response, mapping a render failure to
/// a `500` rather than panicking (no `unwrap` in the request path).
fn render<T: Template>(tmpl: &T) -> Response {
    match tmpl.render() {
        Ok(body) => Html(body).into_response(),
        Err(err) => {
            warn!(%err, "template render failed");
            (StatusCode::INTERNAL_SERVER_ERROR, "template render error").into_response()
        }
    }
}

/// A minimal web error type so handlers can `?`-propagate `anyhow` failures and
/// still return an `impl IntoResponse`. Renders as a `500` with a short message
/// by default; a handler may override the status (e.g. `413` for an over-cap
/// upload) via [`WebError::with_status`].
struct WebError {
    err: anyhow::Error,
    status: StatusCode,
}

impl<E: Into<anyhow::Error>> From<E> for WebError {
    fn from(err: E) -> Self {
        WebError {
            err: err.into(),
            status: StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl WebError {
    /// Attach an explicit HTTP status to render instead of the default `500`.
    fn with_status(err: impl Into<anyhow::Error>, status: StatusCode) -> Self {
        WebError {
            err: err.into(),
            status,
        }
    }
}

impl IntoResponse for WebError {
    fn into_response(self) -> Response {
        warn!(error = %self.err, status = %self.status, "request failed");
        let body = if self.status == StatusCode::INTERNAL_SERVER_ERROR {
            "internal error"
        } else {
            self.status.canonical_reason().unwrap_or("error")
        };
        (self.status, body).into_response()
    }
}

/// Map an axum [`MultipartError`] to a [`WebError`] that preserves the error's
/// own HTTP status. When a request exceeds the route's `DefaultBodyLimit` the
/// multipart extractor reports `413 Payload Too Large`; a malformed body reports
/// `400`. Either way this avoids collapsing the failure into a generic `500`.
fn multipart_response(err: axum::extract::multipart::MultipartError) -> WebError {
    let status = err.status();
    WebError::with_status(err, status)
}

/// A short, human display of a feed/site title for the sidebar/list, falling
/// back to the host of a URL and finally to the raw string.
fn display_title(title: Option<&str>, url: &str) -> String {
    if let Some(t) = title {
        let t = t.trim();
        if !t.is_empty() {
            return t.to_string();
        }
    }
    url::Url::parse(url)
        .ok()
        .and_then(|u| u.host_str().map(str::to_string))
        .unwrap_or_else(|| url.to_string())
}

/// A display `@handle` for the identity chip: the stored handle if present,
/// else the tail of the DID so the chip is never empty.
fn display_handle(handle: Option<&str>, did: &str) -> String {
    match handle {
        Some(h) if !h.trim().is_empty() => format!("@{}", h.trim().trim_start_matches('@')),
        _ => did.rsplit(':').next().unwrap_or(did).to_string(),
    }
}

/// Two-letter, lowercase avatar initials from a handle/DID.
fn avatar_initials(handle: Option<&str>, did: &str) -> String {
    let source = handle
        .map(|h| h.trim().trim_start_matches('@'))
        .filter(|h| !h.is_empty())
        .unwrap_or_else(|| did.rsplit(':').next().unwrap_or(did));
    let letters: String = source
        .chars()
        .filter(|c| c.is_alphanumeric())
        .take(2)
        .collect::<String>()
        .to_lowercase();
    if letters.is_empty() {
        "fr".to_string()
    } else {
        letters
    }
}

/// Trim a stored RFC3339 timestamp down to the `YYYY-MM-DD` date for calm,
/// low-noise display. Falls back to the raw string if it doesn't look like one.
fn display_date(published: Option<&str>) -> String {
    // CHARACTERS, not bytes. `p[..10]` panics when byte 10 lands inside a
    // multi-byte character, and every caller used to pass a timestamp the feed
    // parser had produced. The saved-record path passes `createdAt` straight off
    // a PDS record, which the lexicon types as a bare string with no validation
    // — written by whatever atproto client the reader used. A `createdAt` of
    // "日本語日本語日本" took down the whole starred view, and there is no
    // catch-panic layer in the stack, so the page stayed down until the record
    // was removed from the very view that would not render.
    match published {
        Some(p) => p.chars().take(10).collect(),
        None => String::new(),
    }
}

/// Percent-encode a value for use in a query string (RFC 3986 unreserved kept).
/// Small and dependency-free — the `url` crate's form-encoding isn't exposed for
/// a bare value, and this keeps the scope-preserving links honest.
fn qenc(s: &str) -> String {
    let mut out = String::with_capacity(s.len() * 3);
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char)
            }
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

// ---------------------------------------------------------------------------
// Reader: index
// ---------------------------------------------------------------------------

/// Query for `GET /` — the scope + view selector.
#[derive(Debug, Deserialize, Default)]
struct IndexQuery {
    /// Filter to a single feed by its canonical URL.
    #[serde(default)]
    feed: Option<String>,
    /// Filter to a folder by its `at://` URI (shows every feed in the folder).
    #[serde(default)]
    folder: Option<String>,
    /// `unread` (default) | `all` | `starred`.
    #[serde(default)]
    view: Option<String>,
    /// 1-based page within the selected scope + view. Absent/0 means page 1.
    #[serde(default)]
    page: Option<u32>,
    /// Optional flash message (e.g. after an action redirect).
    #[serde(default)]
    flash: Option<String>,
}

/// Rows per page in the reader's list views.
///
/// The list projection no longer carries article bodies ([`store::EntryListRow`]),
/// so a page is on the order of tens of kilobytes rather than the tens or
/// hundreds of megabytes an unbounded list of full entries could reach. The page
/// bound is the second half of that fix: without it, a reader with a long
/// backlog still decides how much memory a single request allocates.
const ENTRIES_PER_PAGE: i64 = 100;

/// How many pages `total` entries occupy. An empty list is page 1 of 1, so the
/// pager reads "1 / 1" rather than "1 / 0".
fn page_count_for(total: i64) -> i64 {
    ((total + ENTRIES_PER_PAGE - 1) / ENTRIES_PER_PAGE).max(1)
}

/// Ceiling on the reader's prev/next id list.
///
/// Unlike the page above, this genuinely spans the whole list — prev/next is the
/// reader's position within it — so it is bounded by count rather than paged. At
/// 8 bytes per id this is ~40 KB at the cap. Past it the neighbour links stop
/// resolving; the article itself still opens, and the list view still pages.
const PREV_NEXT_MAX: i64 = 5_000;

/// Ceiling on the cached-starred identity set matched against PDS saved records.
///
/// Deliberately generous: under-reading this set makes a cached article look
/// uncached, and an uncached starred row's button deletes the PDS RECORD rather
/// than un-starring the entry. Truncating here would change what a click
/// destroys, so the cap exists only as a backstop against an absurd starred
/// count, not as a routine bound.
const STARRED_IDENTITY_MAX: i64 = 20_000;

/// Most uncached PDS saved records this handler will hold in memory for one
/// request.
///
/// **A memory bound, not a visibility bound.** These rows are PAGED alongside
/// the cached entries, so `ENTRIES_PER_PAGE` decides how many are rendered and
/// this only caps how many are collected before slicing. An earlier version used
/// it to cap what was SHOWN, which left everything past it invisible and —
/// because the un-save control lives on the row, and nothing else in the app
/// lists these — unremovable.
///
/// Well above the PDS list ceiling's practical reach for one reader, so a reader
/// meeting it has thousands of saved records and gets a logged, ordered prefix
/// rather than a failure.
const MAX_UNCACHED_SAVED_ROWS: usize = 5_000;

/// A subscription resolved against the local cache: the PDS record + its
/// (possibly-missing) cached feed row.
struct ResolvedSub {
    rkey: String,
    sub: Subscription,
    feed: Option<store::Feed>,
}

/// Pull the user's subscriptions (source of truth = PDS), ensure each has a
/// local cache row so unread counts work, and return them resolved. Best-effort
/// on the sidecar: a failure falls back to the local cache alone.
async fn resolve_subscriptions(state: &AppState, did: &str) -> Vec<ResolvedSub> {
    resolve_subscriptions_noting(state, did).await.0
}

/// What to tell a reader whose subscription list could not be read from their
/// PDS, so the last-known list being shown does not pass for a fresh one.
///
/// **A malformed record is named as such** (#177): the walk refuses rather than
/// drop that subscription, and "unreachable" would send the reader looking at
/// their network when the cause is a record some client wrote into their repo.
fn subscriptions_alert(err: &anyhow::Error) -> String {
    match err.downcast_ref::<crate::atproto::MalformedRecords>() {
        Some(m) => format!(
            "{} record(s) in your subscription list could not be read, so it was not \
             refreshed. Showing your last-known subscriptions; nothing was removed.",
            m.count
        ),
        None => "Your subscription list could not be read from your PDS just now. \
                 Showing your last-known subscriptions."
            .to_string(),
    }
}

/// [`resolve_subscriptions`], plus the alert to show when the list shown is the
/// cached one because the PDS listing failed.
async fn resolve_subscriptions_noting(
    state: &AppState,
    did: &str,
) -> (Vec<ResolvedSub>, Option<String>) {
    let pool = &state.db;
    let subs = match state.repo().list_subscriptions_sorted(did).await {
        Ok(s) => s,
        Err(err) => {
            let alert = subscriptions_alert(&err);
            warn!(%err, %did, "could not list PDS subscriptions; showing this DID's cached subscriptions only");
            // Fail CLOSED: the PDS is the source of truth for what this DID
            // follows. When it is unreachable we must NOT widen the caller's
            // authorization surface. Serve from the DID's OWN last-known
            // `sub_ref` projection (its own feeds, possibly stale) and leave
            // `sub_ref` untouched — never synthesize from every cached feed,
            // which would grant cross-tenant read+mutate during any outage.
            // A DB failure here is NOT the same as "this DID follows nothing",
            // but `unwrap_or_default` rendered it as exactly that: an empty
            // sidebar and an empty reader, which arrives as "all my feeds
            // vanished". It still degrades to empty — there is nothing better to
            // show — but it says so, so the support ticket and the log line can
            // be matched up.
            let feeds = store::feeds_for_did(pool, did).await.unwrap_or_else(|err| {
                warn!(%err, %did, "the PDS is unreachable AND the local subscription \
                                   projection could not be read; rendering an EMPTY \
                                   feed list, which is not the same as having none");
                Vec::new()
            });
            let cached = feeds
                .into_iter()
                .map(|f| ResolvedSub {
                    rkey: String::new(),
                    sub: Subscription::new(f.url.clone(), now_rfc3339()),
                    feed: Some(f),
                })
                .collect();
            return (cached, Some(alert));
        }
    };

    // **Deliberately NOT truncated to `max_subs_per_did`.**
    //
    // The PDS list is unbounded in practice — any client can write subscription
    // records, and only the 20,000-record list ceiling stops it — and the first
    // attempt at bounding it truncated the list right here. That was the wrong
    // place: `sync_sub_refs` below writes `sub_ref` from exactly this set, and
    // `sub_ref` is THE per-DID authorization hook, so dropping entries silently
    // removed the reader's ability to read OR mutate those feeds. A query-shape
    // problem would have become an access problem.
    //
    // The shape problem was the scope filter emitting one SQL placeholder per
    // feed; `store::list_query_sql` now passes the whole set as a single
    // `json_each` bind, so there is no size to defend against here and nothing
    // to truncate. `max_subs_per_did` stays what it is — a policy cap on ADDING
    // feeds — rather than becoming a silent read-time filter.
    let mut out = Vec::with_capacity(subs.len());
    for (rkey, sub) in subs {
        let feed = match store::get_feed_by_url(pool, &sub.url).await {
            Ok(Some(f)) => Some(f),
            Ok(None) => {
                // `sub.url` came out of an atproto record. The lexicon is open —
                // ANY client can write a subscription into a user's repo — so
                // this is untrusted input on the hot path of `GET /`, and it was
                // being stored with none of the three checks the add and import
                // paths apply. Two of those are capacity ceilings; this one is
                // the invariant in `FeedPrivacy`'s doc comment, which promises a
                // private feed URL is "never stored". Writing a
                // `…/feed/private/<token>` into the SHARED `feeds` table breaks
                // that promise even though `net::guarded_get` still refuses to
                // fetch it.
                if !feed::is_storable_feed_url(&sub.url, state.config.standard_site)
                    || feed::classify_feed_privacy(&sub.url).is_private()
                {
                    warn!(
                        %did,
                        "skipping cache row for a subscription URL that is private or not http(s)"
                    );
                    out.push(ResolvedSub {
                        rkey,
                        sub,
                        feed: None,
                    });
                    continue;
                }
                // Upsert a cache row so the sidebar reflects the real follow-list.
                //
                // A silent failure here is a support ticket with no evidence: no
                // `feeds` row means the poller never selects this subscription,
                // so the reader sees "I added a feed and it never updates" while
                // the PDS record looks perfect. Logged with the URL so the
                // failing subscription is identifiable.
                if let Err(err) = store::upsert_feed(
                    pool,
                    &store::NewFeed {
                        url: sub.url.clone(),
                        title: sub.title.clone(),
                        site_url: sub.site_url.clone(),
                        ..Default::default()
                    },
                )
                .await
                {
                    warn!(%err, url = %sub.url, %did, "could not cache a subscribed feed; \
                                                       it will not be polled");
                }
                store::get_feed_by_url(pool, &sub.url).await.ok().flatten()
            }
            Err(err) => {
                warn!(%err, url = %sub.url, "get_feed_by_url failed");
                None
            }
        };
        out.push(ResolvedSub { rkey, sub, feed });
    }
    // Mirror the caller's resolved subscription set into `sub_ref`, so every
    // scoped entry/feed read + read/star mutation authorizes against exactly
    // the feeds this DID follows right now. This is THE per-DID isolation hook.
    sync_sub_refs(pool, did, &out).await;
    (out, None)
}

/// Refresh the `sub_ref` projection for `did` to exactly the feed ids present
/// in `subs`. Best-effort: a failure here only degrades the scoped reads (they
/// fail closed / show fewer rows), never leaks another user's entries.
async fn sync_sub_refs(pool: &store::Pool, did: &str, subs: &[ResolvedSub]) {
    let feed_ids: Vec<i64> = subs
        .iter()
        .filter_map(|s| s.feed.as_ref().map(|f| f.id))
        .collect();
    if let Err(err) = store::replace_sub_refs(pool, did, &feed_ids).await {
        warn!(%err, %did, "failed to sync sub_ref projection");
    }
}

/// `GET /` — the reader. Renders the sidebar (folders + feeds from the PDS
/// records layer) and the article list for the selected scope + view.
async fn index(
    State(state): State<AppState>,
    headers: HeaderMap,
    Query(q): Query<IndexQuery>,
) -> Result<Response, WebError> {
    let user = match current_session(&state, &headers).await {
        Some(u) => u,
        // Signed out: serve the public landing page rather than bouncing to
        // /login. /login remains the entry point for the actual OAuth sign-in.
        None => {
            return Ok(render(&LandingTemplate {
                card: Card::site(&state.config),
                version: VERSION,
                repo_url: REPO_URL,
                crates_url: CRATES_URL,
                kofi_url: KOFI_URL,
                standard_site: state.config.standard_site,
                releases: RELEASES,
            }))
        }
    };
    let did = user.did.clone();
    let pool = &state.db;

    let (subs, alert) = resolve_subscriptions_noting(&state, &did).await;

    // View: unread (default) | all | starred.
    let view = match q.view.as_deref() {
        Some("all") => "all",
        Some("starred") => "starred",
        _ => "unread",
    }
    .to_string();
    let list_view = list_view_of(q.view.as_deref());

    // Which feed URLs are in scope?
    let scope_urls = scope_urls_for(&subs, q.feed.as_deref(), q.folder.as_deref());
    // …and the feed ids they resolve to. Scope is applied inside the query now,
    // so a page is a page of rows the reader will actually see. Filtering after
    // a `LIMIT` would have made pages arbitrarily short — sometimes empty — for
    // any scope narrower than the whole subscription list.
    let scope_ids = scoped_feed_ids(&subs, &scope_urls);

    let feed_title_by_id = |id: i64| -> String {
        subs.iter()
            .find(|s| s.feed.as_ref().map(|f| f.id) == Some(id))
            .map(|s| {
                display_title(
                    s.sub
                        .title
                        .as_deref()
                        .or(s.feed.as_ref().and_then(|f| f.title.as_deref())),
                    &s.sub.url,
                )
            })
            .unwrap_or_default()
    };

    // **One page of the chosen view, filtered, ordered and bounded in SQL.**
    //
    // All three views used to materialize every matching entry — `SELECT e.*`,
    // no `LIMIT`, article bodies included — and the "all" view additionally ran
    // one such query PER SUBSCRIBED FEED and merged the results in memory. None
    // of the row fields below read the body. See `store::EntryListRow`.
    // **Saved records the cache cannot show.**
    //
    // The starred view is built from local `entries`, so a saved record whose
    // article was never cached here is invisible — the case that matters is
    // starring in ANOTHER atproto reader, which is the portability the shared
    // lexicon exists for. Those rows are rendered from the PDS record alone.
    let mut uncached: Vec<EntryRow> = Vec::new();
    if view == "starred" {
        // **Match against every SUBSCRIBED cached starred entry, not `source`.**
        //
        // `source` has already been filtered by feed/folder. Matching against it
        // meant an entry that IS cached but sits outside the current filter
        // looked uncached — so it rendered as a "not cached" row whose star
        // button deletes the PDS RECORD instead of un-starring the entry. A
        // scope filter must not change what is destroyed. Paging is the same
        // hazard in a new form: matching against the visible PAGE would make
        // every cached article outside it look uncached. Hence a dedicated
        // identity query over the whole starred set — urls and guids only, no
        // bodies — rather than reusing `source`.
        //
        // One gap remains BY DESIGN, and is handled at the other end. This query
        // still carries the `sub_ref` predicate, so a starred, cached entry in a
        // feed the reader has UNSUBSCRIBED from is absent here and its record
        // renders as uncached. That is the right rendering — the article is no
        // longer part of any feed the reader follows, and the PDS record is what
        // still holds it — but it means the un-save button is the record-deleting
        // one. `unsave_record` therefore clears the local star too, so the two
        // stores agree however the row got classified. Dropping the predicate
        // here instead would have made the row link to `/entries/{id}`, which is
        // `sub_ref`-scoped and would 404.
        //
        // **Three ways this can be unusable, and all three fail CLOSED.** With an
        // incomplete identity set, a cached article looks uncached and renders an
        // un-save button that deletes the PDS RECORD. Showing no uncached rows
        // loses rows for one render; getting this wrong loses data permanently,
        // so every uncertain case suppresses them.
        let identities = match store::starred_identities(pool, &did, STARRED_IDENTITY_MAX).await {
            Ok(store::StarredIdentities::All(rows)) => Some(rows),
            // The cap is a memory backstop, and reaching it means the set is an
            // arbitrary subset. It used to return that subset with no way to
            // tell, so every starred article outside it got the destructive
            // button.
            Ok(store::StarredIdentities::Truncated) => {
                warn!(
                    %did,
                    cap = STARRED_IDENTITY_MAX,
                    "cached-starred set exceeded its cap; suppressing uncached saved rows \
                     rather than rendering record-deleting buttons for cached articles"
                );
                None
            }
            Err(err) => {
                warn!(%err, %did, "cached-starred identity lookup failed; \
                                    suppressing uncached saved rows this render");
                None
            }
        };
        // The escape hatch asks whether this DID has ANY cached starred entry —
        // not whether the current SCOPE does. `total` is narrowed by
        // `?feed=`/`?folder=` while the identity set spans every feed, so
        // comparing them waved the fail-closed condition through for any narrow
        // scope: a record whose `feedUrl` matched the filter while its cached
        // entry lived under another feed rendered as uncached.
        let identities_ok = identities.is_some();
        let identities = identities.unwrap_or_default();
        let cached_urls: std::collections::HashSet<&str> = identities
            .iter()
            .filter_map(|(url, _)| url.as_deref())
            .collect();
        let cached_guids: std::collections::HashSet<&str> =
            identities.iter().map(|(_, guid)| guid.as_str()).collect();

        // Collected in full here, sliced per page later. They sort after every
        // cached row, so the two lists form one sequence that the pager walks —
        // see the slice below. Collected BEFORE the page is chosen because the
        // page count depends on how many there are.
        // Bounded like everything else on this page. These come from the PDS
        // (up to the list ceiling — 20,000 on the sidecar backend, 5,000 on
        // `backend=rust`, whose caps are a quarter of the other's) and are
        // appended whole to the last page, so `ENTRIES_PER_PAGE` does not
        // constrain them at all. The
        // cap is generous — a reader with more saved-elsewhere records than this
        // is not the case being designed for — but a response has to have a size
        // an operator can reason about.
        let mut uncached_dropped = 0usize;
        match state.repo().list_saved_sorted(&did).await {
            Ok(saved) if identities_ok => {
                for (rkey, item) in saved {
                    let known = cached_urls.contains(item.url.as_str())
                        || item
                            .entry_id
                            .as_deref()
                            .is_some_and(|g| cached_guids.contains(g));
                    if known {
                        continue;
                    }
                    // And the scope filter applies to these rows too. Without
                    // it, `?feed=X` still listed saved records from every other
                    // feed — the filter silently did nothing for them.
                    if let Some(urls) = &scope_urls {
                        match item.feed_url.as_deref() {
                            Some(feed_url) if urls.iter().any(|u| u == feed_url) => {}
                            // A saved record with no `feedUrl` cannot be placed
                            // in any feed's scope, so it belongs only to the
                            // unfiltered view.
                            _ => continue,
                        }
                    }
                    // **`safe_link` FIRST, and a failure no longer drops the row.**
                    //
                    // `item.url` is attacker-controlled — a saved record written
                    // by any client — and it lands in an `href`. Askama escapes
                    // HTML metacharacters but not SCHEMES, so `javascript:`
                    // survives escaping intact. This project already built the
                    // helper for exactly that, and `feed.rs` uses it on the
                    // equivalent link; this path was simply not routed through it.
                    //
                    // The real defect was what a failure DID: it `continue`d, so
                    // the row vanished entirely — no badge, no count, nothing —
                    // and the only trace was a `debug!` below any realistic
                    // filter. That makes the record unremovable FROM HERE, because
                    // the un-save button lives on the row; the reader has to open
                    // a different atproto client to get rid of it. A bad URL is a
                    // reason to withhold the LINK, not the row.
                    //
                    // The check also moved ABOVE the poll nudge. That is ordering
                    // hygiene rather than a fix: the nudge keys on `feed_url`, not
                    // on the URL being rejected here, and is already gated on the
                    // reader actually subscribing to that feed — so it was never
                    // reachable by an unusable `item.url`. Deciding whether a
                    // record is renderable before doing anything outbound on its
                    // behalf is simply the order that stays correct if either of
                    // those two facts later stops being true.
                    let link = SafeLink::external(&item.url);
                    if link.is_empty() {
                        warn!(
                            %did, %rkey,
                            "a saved record has an unusable URL; rendering it without a link \
                             so it can still be removed"
                        );
                    }

                    // Opportunistic re-fetch: if the reader still subscribes to
                    // the feed, make it due now. If the article is still inside
                    // the feed's window the poller caches it normally and this
                    // row becomes a real entry on its own — no synthetic rows in
                    // the shared cache, which every subscriber would otherwise
                    // see as a content-less entry.
                    // **Bound the WORK, not just the response.** This check sat
                    // after the nudge and the `subs` scan below, so every render
                    // still walked all ≤20,000 PDS records, ran a subs-length
                    // string scan per record, and issued up to that many
                    // `mark_feed_due` round-trips on a 5-connection pool — then
                    // discarded everything past the cap. A cap that runs after
                    // the expensive part is a cap on the output only.
                    if uncached.len() >= MAX_UNCACHED_SAVED_ROWS {
                        uncached_dropped += 1;
                        continue;
                    }
                    if let Some(feed_url) = item.feed_url.as_deref() {
                        if subs.iter().any(|s| s.sub.url == feed_url) {
                            // Bounded to one nudge per feed per poll interval —
                            // see `mark_feed_due`. Unbounded, a reload loop here
                            // becomes outbound amplification.
                            let stale_before = (chrono::Utc::now()
                                - chrono::Duration::from_std(state.config.poll_interval)
                                    .unwrap_or_else(|_| chrono::Duration::hours(1)))
                            .to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
                            if let Err(err) =
                                store::mark_feed_due(pool, feed_url, &stale_before).await
                            {
                                tracing::debug!(%err, %feed_url, "could not nudge a feed for a saved article");
                            }
                        }
                    }
                    uncached.push(EntryRow {
                        id: 0,
                        title: item
                            .title
                            .clone()
                            .filter(|t| !t.trim().is_empty())
                            // Falling back to the URL is fine for a link we are
                            // willing to render, and wrong for one we are not:
                            // it would put the exact string `safe_link` just
                            // rejected into the page as the record's name. The
                            // rkey is what the un-save button acts on, so it is
                            // the honest identifier for a row that has nothing
                            // else trustworthy to show.
                            .unwrap_or_else(|| {
                                if link.is_empty() {
                                    format!("Saved item {rkey}")
                                } else {
                                    item.url.clone()
                                }
                            }),
                        feed_title: item.feed_url.clone().unwrap_or_default(),
                        published: display_date(Some(&item.created_at)),
                        read: false,
                        starred: true,
                        // Empty = "render this row without an anchor". The
                        // template branches on it, so the rejected URL never
                        // reaches an `href` even as an escaped string.
                        link,
                        cached: false,
                        rkey,
                    });
                }
            }
            // Identity lookup was unusable — see the fail-closed note above.
            Ok(_) => {}
            Err(err) => warn!(%err, %did, "could not list saved records from the PDS"),
        }
        if uncached_dropped > 0 {
            warn!(
                %did,
                dropped = uncached_dropped,
                cap = MAX_UNCACHED_SAVED_ROWS,
                "more saved records than this instance will hold in one response; the \
                 rest are not reachable from here"
            );
        }
    }

    // **One sequence, two sources.** The cached rows come from SQL, the uncached
    // PDS records follow them, and the pager walks the concatenation.
    //
    // The first version appended the uncached rows to the last page only and
    // kept them out of `total`, which left everything past a cap invisible AND
    // unremovable — the un-save button lives on the row, and there is no other
    // surface in the app that lists these. That is the same "unremovable FROM
    // HERE" hazard the `safe_link` fix above exists to prevent, reintroduced
    // forty lines later by a bound meant to protect memory.
    //
    // Paging the concatenation makes every record reachable and needs no cap on
    // what is RENDERED — one page is one page either way. The version before
    // that inflated `total` while clamping on the cached count, which advertised
    // a page the clamp could never reach; both numbers come from the same total
    // now, which is what makes that impossible rather than merely fixed.
    let total_cached =
        store::count_entries_for_view(pool, &did, list_view, scope_ids.as_deref()).await?;
    let uncached_len = uncached.len();
    let total = total_cached + uncached_len as i64;
    // Clamped to the range that exists. Past the end the list is empty, and the
    // empty state renders instead of the pager — which would strand a reader who
    // typed a page number, or who paged to the end and then marked entries read
    // out from under their own URL. Showing the last page is the answer to both.
    let page = i64::from(q.page.unwrap_or(1).max(1)).min(page_count_for(total));
    let offset = (page - 1) * ENTRIES_PER_PAGE;
    // Past the cached rows this returns nothing, which is exactly right: the
    // page is then made up entirely of uncached ones.
    let source = store::list_entries(
        pool,
        &did,
        list_view,
        scope_ids.as_deref(),
        ENTRIES_PER_PAGE,
        offset,
    )
    .await?;
    // **Both halves of the page are computed from the COUNT alone.**
    //
    // `total_cached` (a COUNT) and `source` (a SELECT) are separate unsynchronised
    // queries, so they can disagree about how many cached rows exist. Any part of
    // the page composition that reads `source.len()` inherits that disagreement.
    //
    // `cached_allotment` is this page's cached share according to the snapshot,
    // and it is what the uncached `skip`/`take` are derived from — so consecutive
    // pages tile the uncached list exactly, whichever way the count drifted.
    // `source` is then truncated to it only to avoid rendering rows the next page
    // will also claim.
    //
    // The previous version took `skip` from the count but `take` from
    // `source.len()`, which agreed only when the count UNDERSTATED. Overstating —
    // an un-star or a retention delete landing between the two queries — made
    // page N render `uncached[0..70]` while page N+1 rendered `uncached[50..80]`,
    // putting twenty rows, each carrying the record-DELETING un-save button, on
    // two pages at once. The comment claimed that shape was impossible; it was
    // merely rarer.
    let cached_allotment = (total_cached - offset).clamp(0, ENTRIES_PER_PAGE) as usize;
    let cached_here = cached_allotment.min(source.len());
    // Only compose when there is something to compose WITH. `uncached` is empty
    // on every view but `starred`, and truncating there just drops trailing rows
    // that no page then shows — the poller inserting between the COUNT and the
    // SELECT was enough to trigger it.
    let source = if uncached_len == 0 {
        &source[..]
    } else {
        &source[..cached_here]
    };
    let uncached_page: Vec<EntryRow> = {
        let skip = (offset - total_cached).max(0) as usize;
        let take = (ENTRIES_PER_PAGE as usize) - cached_allotment;
        uncached.into_iter().skip(skip).take(take).collect()
    };
    // This page's slice, used only to append below. The heading needs the
    // WHOLE-list figure, which is the set's size before slicing.
    let uncached_total = uncached_len as i64;

    // The scope/view suffix carried onto every entry link (built once).
    let entry_scope_qs = {
        let mut parts = Vec::new();
        if let Some(f) = q.feed.as_deref() {
            parts.push(format!("feed={}", qenc(f)));
        }
        if let Some(f) = q.folder.as_deref() {
            parts.push(format!("folder={}", qenc(f)));
        }
        if view != "unread" {
            parts.push(format!("view={}", qenc(&view)));
        }
        parts.join("&")
    };
    let entries: Vec<EntryRow> = source
        .iter()
        .map(|e| EntryRow {
            id: e.id,
            title: e
                .title
                .clone()
                .filter(|t| !t.trim().is_empty())
                .unwrap_or_else(|| "(untitled)".to_string()),
            feed_title: feed_title_by_id(e.feed_id),
            published: display_date(e.published.as_deref()),
            // Both bits ride along on the row's own `entry_state` join now. They
            // used to be membership tests against the full unread and starred
            // sets, which is why those two lists were fetched in their entirety
            // on every render even when the page showed a hundred rows.
            read: e.read,
            starred: e.starred,
            link: SafeLink::entry(e.id, &entry_scope_qs),
            cached: true,
            rkey: String::new(),
        })
        .collect();

    // The uncached slice for this page follows the cached rows.
    let mut entries = entries;
    entries.extend(uncached_page);
    let entries = entries;

    let selected_feed = q.feed.as_deref();
    let selected_folder = q.folder.as_deref();

    // Build the shared sidebar (folders + loose feeds, with unread counts).
    let (folder_views, loose_feeds, _folder_options) =
        build_sidebar(&state, &did, &subs, selected_feed, selected_folder).await;

    // Heading + scope query-string suffix.
    let (heading, scope_qs) = if let Some(feed_url) = selected_feed {
        let name = subs
            .iter()
            .find(|s| s.sub.url == feed_url)
            .map(|s| {
                display_title(
                    s.sub
                        .title
                        .as_deref()
                        .or(s.feed.as_ref().and_then(|f| f.title.as_deref())),
                    &s.sub.url,
                )
            })
            .unwrap_or_else(|| display_title(None, feed_url));
        (name, format!("feed={}", qenc(feed_url)))
    } else if let Some(folder_uri) = selected_folder {
        let name = folder_views
            .iter()
            .find(|f| f.uri == folder_uri)
            .map(|f| f.name.clone())
            .unwrap_or_else(|| "Folder".to_string());
        (name, format!("folder={}", qenc(folder_uri)))
    } else {
        let h = match view.as_str() {
            "all" => "All",
            "starred" => "Starred",
            _ => "Unread",
        };
        (h.to_string(), String::new())
    };

    let feed_scope = selected_feed.map(str::to_string);
    let nav = build_nav(&user, &view, scope_qs, folder_views, loose_feeds, false);

    // Pager links. `entry_scope_qs` already carries feed/folder/view, so the
    // page number is the only thing appended — which keeps a paged link
    // identical to an unpaged one in every other respect.
    let page_href = |n: i64| -> String {
        let mut parts = Vec::new();
        if !entry_scope_qs.is_empty() {
            parts.push(entry_scope_qs.clone());
        }
        if n > 1 {
            parts.push(format!("page={n}"));
        }
        if parts.is_empty() {
            "/".to_string()
        } else {
            format!("/?{}", parts.join("&"))
        }
    };
    let prev_href = (page > 1).then(|| page_href(page - 1));
    let next_href = (page * ENTRIES_PER_PAGE < total).then(|| page_href(page + 1));

    let tmpl = IndexTemplate {
        card: Card::private(&state.config),
        version: VERSION,
        repo_url: REPO_URL,
        kofi_url: KOFI_URL,
        flash: q.flash.unwrap_or_default(),
        alert: alert.unwrap_or_default(),
        nav,
        entries,
        heading,
        feed_scope,
        total,
        // Whole-list figure, so it sits beside `total` without double counting.
        // The per-page slice is composed above and is not a heading number.
        uncached_total,
        page,
        page_count: page_count_for(total),
        prev_href,
        next_href,
    };
    Ok(render(&tmpl))
}

/// Query for `GET /manage` — carries an optional flash after an action redirect.
#[derive(Debug, Deserialize, Default)]
struct ManageQuery {
    #[serde(default)]
    flash: Option<String>,
}

/// `GET /manage` — the feed-management page. Renders the rail plus the subscribe
/// / your-feeds / OPML surfaces; the forms POST to the existing routes
/// (`/subscriptions`, `/folders`, `/opml`, …). A read/render route only — no
/// mutation logic of its own.
async fn manage(
    State(state): State<AppState>,
    headers: HeaderMap,
    Query(q): Query<ManageQuery>,
) -> Result<Response, WebError> {
    let user = match current_session(&state, &headers).await {
        Some(u) => u,
        None => return Ok(Redirect::to("/login").into_response()),
    };
    let did = user.did.clone();

    let (subs, alert) = resolve_subscriptions_noting(&state, &did).await;
    let (folder_views, loose_feeds, folder_options) =
        build_sidebar(&state, &did, &subs, None, None).await;

    // Clone the sidebar for the rail; the page body reuses folders/loose feeds.
    let nav = build_nav(
        &user,
        "unread",
        String::new(),
        folder_views.iter().map(clone_folder_view).collect(),
        loose_feeds.iter().map(clone_feed_view).collect(),
        true,
    );

    let tmpl = ManageTemplate {
        card: Card::private(&state.config),
        version: VERSION,
        repo_url: REPO_URL,
        kofi_url: KOFI_URL,
        flash: q.flash.unwrap_or_default(),
        alert: alert.unwrap_or_default(),
        nav,
        folder_options,
        folders: folder_views,
        loose_feeds,
        standard_site: state.config.standard_site,
    };
    Ok(render(&tmpl))
}

/// Shallow clone helpers so `/manage` can hand the same sidebar to both the rail
/// (`Nav`) and the page body without an extra DB round-trip.
fn clone_feed_view(f: &FeedView) -> FeedView {
    FeedView {
        rkey: f.rkey.clone(),
        url: f.url.clone(),
        title: f.title.clone(),
        unread: f.unread,
        selected: f.selected,
        folder: f.folder.clone(),
    }
}

fn clone_folder_view(f: &FolderView) -> FolderView {
    FolderView {
        rkey: f.rkey.clone(),
        uri: f.uri.clone(),
        name: f.name.clone(),
        feeds: f.feeds.iter().map(clone_feed_view).collect(),
        selected: f.selected,
    }
}

/// The set of feed URLs a scope covers: `Some([one url])` for a single-feed
/// scope, `Some([urls…])` for a folder (its member feeds), or `None` for the
/// unscoped "everything" view. A folder scope takes the feed scope when both are
/// somehow present (feed wins, matching the query precedence elsewhere).
fn scope_urls_for(
    subs: &[ResolvedSub],
    feed: Option<&str>,
    folder: Option<&str>,
) -> Option<Vec<String>> {
    if let Some(feed_url) = feed {
        Some(vec![feed_url.to_string()])
    } else {
        folder.map(|folder_uri| {
            subs.iter()
                .filter(|s| s.sub.folder.as_deref() == Some(folder_uri))
                .map(|s| s.sub.url.clone())
                .collect()
        })
    }
}

/// The `at://` URI for a folder record given the owner DID + rkey.
fn folder_uri(did: &str, rkey: &str) -> String {
    format!("at://{did}/{}/{rkey}", lexicon::nsid::FOLDER)
}

/// Build the sidebar folder/loose-feed views (with per-feed unread counts) for a
/// DID — the shared source for both the reader index and the rail on every
/// chrome page. `selected_feed` / `selected_folder` drive `aria-current`.
async fn build_sidebar(
    state: &AppState,
    did: &str,
    subs: &[ResolvedSub],
    selected_feed: Option<&str>,
    selected_folder: Option<&str>,
) -> (Vec<FolderView>, Vec<FeedView>, Vec<FolderOption>) {
    let pool = &state.db;
    // Counted in SQL. This used to fetch every unread ENTRY — article bodies and
    // all — purely to `.filter().count()` them in Rust, on every page that
    // renders chrome, which made the sidebar the most frequently executed
    // instance of the unbounded-projection problem.
    let unread_counts = store::unread_counts_by_feed(pool, did)
        .await
        .unwrap_or_else(|err| {
            warn!(%err, %did, "sidebar unread counts failed; rendering zeroes");
            Default::default()
        });
    let folders = state
        .repo()
        .list_folders_sorted(did)
        .await
        .unwrap_or_default();

    let unread_count = |feed_id: Option<i64>| -> i64 {
        feed_id
            .and_then(|id| unread_counts.get(&id).copied())
            .unwrap_or(0)
    };
    let mk_feed_view = |s: &ResolvedSub| FeedView {
        rkey: s.rkey.clone(),
        url: s.sub.url.clone(),
        title: display_title(
            s.sub
                .title
                .as_deref()
                .or(s.feed.as_ref().and_then(|f| f.title.as_deref())),
            &s.sub.url,
        ),
        unread: unread_count(s.feed.as_ref().map(|f| f.id)),
        selected: selected_feed == Some(s.sub.url.as_str()),
        folder: s.sub.folder.clone(),
    };

    let mut folder_views = Vec::with_capacity(folders.len());
    for (rkey, folder) in &folders {
        let uri = folder_uri(did, rkey);
        let feeds: Vec<FeedView> = subs
            .iter()
            .filter(|s| s.sub.folder.as_deref() == Some(uri.as_str()))
            .map(mk_feed_view)
            .collect();
        folder_views.push(FolderView {
            rkey: rkey.clone(),
            uri: uri.clone(),
            name: folder.name.clone(),
            feeds,
            selected: selected_folder == Some(uri.as_str()),
        });
    }

    let known_uris: std::collections::HashSet<String> =
        folders.iter().map(|(r, _)| folder_uri(did, r)).collect();
    let loose_feeds: Vec<FeedView> = subs
        .iter()
        .filter(|s| {
            s.sub
                .folder
                .as_deref()
                .map(|f| !known_uris.contains(f))
                .unwrap_or(true)
        })
        .map(mk_feed_view)
        .collect();

    let folder_options: Vec<FolderOption> = folders
        .iter()
        .map(|(rkey, folder)| FolderOption {
            name: folder.name.clone(),
            uri: folder_uri(did, rkey),
        })
        .collect();

    (folder_views, loose_feeds, folder_options)
}

/// Assemble the shared rail [`Nav`] for a chrome page.
fn build_nav(
    user: &CurrentUser,
    view: &str,
    scope_qs: String,
    folders: Vec<FolderView>,
    loose_feeds: Vec<FeedView>,
    manage_active: bool,
) -> Nav {
    Nav {
        handle: display_handle(user.handle.as_deref(), &user.did),
        avatar: avatar_initials(user.handle.as_deref(), &user.did),
        view: view.to_string(),
        scope_qs,
        folders,
        loose_feeds,
        manage_active,
    }
}

// ---------------------------------------------------------------------------
// Reader: single entry
// ---------------------------------------------------------------------------

/// Query for `GET /entries/:id` — carries the reading context (scope + view) so
/// prev/next and "back" stay within the list the reader came from.
#[derive(Debug, Deserialize, Default)]
struct EntryQuery {
    #[serde(default)]
    feed: Option<String>,
    #[serde(default)]
    folder: Option<String>,
    #[serde(default)]
    view: Option<String>,
}

/// `GET /entries/:id` — the clean reader view for one entry, with prev/next
/// within the current reading list.
async fn entry_view(
    State(state): State<AppState>,
    headers: HeaderMap,
    Path(id): Path<i64>,
    Query(q): Query<EntryQuery>,
) -> Result<Response, WebError> {
    let user = match current_session(&state, &headers).await {
        Some(u) => u,
        None => return Ok(Redirect::to("/login").into_response()),
    };
    let did = user.did.clone();
    let pool = &state.db;

    // Resolve subscriptions FIRST: this refreshes the `sub_ref` projection so
    // the per-DID entry gate below authorizes against the caller's current PDS
    // subscription set (not another user's cached feeds).
    let subs = resolve_subscriptions(&state, &did).await;

    let entry = match get_entry_by_id(pool, &did, id).await? {
        Some(e) => e,
        None => return Ok((StatusCode::NOT_FOUND, "entry not found").into_response()),
    };

    let feed_title = feed_title_by_entry(pool, entry.feed_id).await;

    let read = entry_is_read(pool, &did, id).await?;
    let starred = entry_is_starred(pool, &did, id).await?;

    // Reconstruct the current list to compute prev/next, so paging in the reader
    // matches what the list showed.
    let (prev_id, next_id) = neighbors_in_scope(&state, &did, &q, id).await;

    let back_qs = scope_query(&q);

    let (folder_views, loose_feeds, _) =
        build_sidebar(&state, &did, &subs, q.feed.as_deref(), q.folder.as_deref()).await;
    let nav_view = match q.view.as_deref() {
        Some("all") => "all",
        Some("starred") => "starred",
        _ => "unread",
    };
    let nav = build_nav(
        &user,
        nav_view,
        back_qs.clone(),
        folder_views,
        loose_feeds,
        false,
    );

    let tmpl = EntryTemplate {
        card: Card::private(&state.config),
        version: VERSION,
        repo_url: REPO_URL,
        kofi_url: KOFI_URL,
        nav,
        id: entry.id,
        title: entry
            .title
            .clone()
            .filter(|t| !t.trim().is_empty())
            .unwrap_or_else(|| "(untitled)".to_string()),
        feed_title,
        author: entry.author.clone().filter(|a| !a.trim().is_empty()),
        published: display_date(entry.published.as_deref()),
        url: entry.url.as_deref().and_then(SafeLink::external_opt),
        content_html: entry.content_html.clone(),
        read,
        starred,
        back_qs,
        prev_id,
        next_id,
        oob: false,
    };
    Ok(render(&tmpl))
}

/// Compute the prev/next entry ids around `current` within the reader's current
/// scope + view, so the reader view can offer keyboard/paging navigation.
async fn neighbors_in_scope(
    state: &AppState,
    did: &str,
    q: &EntryQuery,
    current: i64,
) -> (Option<i64>, Option<i64>) {
    let idx_q = IndexQuery {
        feed: q.feed.clone(),
        folder: q.folder.clone(),
        view: q.view.clone(),
        // Neighbours span the whole list, not the page the reader arrived from.
        page: None,
        flash: None,
    };
    let ids = list_entry_ids(state, did, &idx_q).await;
    let pos = ids.iter().position(|&x| x == current);
    match pos {
        Some(p) => {
            let prev = if p > 0 { Some(ids[p - 1]) } else { None };
            let next = ids.get(p + 1).copied();
            (prev, next)
        }
        None => (None, None),
    }
}

/// The ordered entry ids for a scope + view — the same ordering `index` renders,
/// used for reader prev/next. Best-effort; PDS failures degrade to local cache.
async fn list_entry_ids(state: &AppState, did: &str, q: &IndexQuery) -> Vec<i64> {
    let pool = &state.db;
    let subs = resolve_subscriptions(state, did).await;

    let scope_urls = scope_urls_for(&subs, q.feed.as_deref(), q.folder.as_deref());

    // Ids only, and bounded. This used to fetch whole entries — bodies included
    // — for all three views and then throw everything but `id` away; the "all"
    // branch additionally ran one unbounded query PER FEED and sorted the union
    // in memory. Scope is now a feed-id restriction inside the query, so the
    // database does the filtering and the ordering exactly once.
    store::list_entry_ids(
        pool,
        did,
        list_view_of(q.view.as_deref()),
        scoped_feed_ids(&subs, &scope_urls).as_deref(),
        PREV_NEXT_MAX,
    )
    .await
    .unwrap_or_else(|err| {
        warn!(%err, %did, "prev/next id list failed; the reader loses its neighbour links");
        Vec::new()
    })
}

/// Map the `?view=` query value onto the store's list view. Anything
/// unrecognised is the unread default, matching `index`.
fn list_view_of(view: Option<&str>) -> store::ListView {
    match view {
        Some("all") => store::ListView::All,
        Some("starred") => store::ListView::Starred,
        _ => store::ListView::Unread,
    }
}

/// Translate a feed/folder scope into the feed ids to restrict a list query to.
///
/// `None` means unscoped (every subscribed feed). `Some(&[])` means the scope
/// matched no local feed, which must return nothing rather than everything — so
/// the empty vec is deliberately preserved, not collapsed back into `None`.
fn scoped_feed_ids(subs: &[ResolvedSub], scope_urls: &Option<Vec<String>>) -> Option<Vec<i64>> {
    let urls = scope_urls.as_ref()?;
    Some(
        subs.iter()
            .filter(|s| urls.contains(&s.sub.url))
            .filter_map(|s| s.feed.as_ref().map(|f| f.id))
            .collect(),
    )
}

/// Build a `?…` query string that preserves the reading scope + view for links.
fn scope_query(q: &EntryQuery) -> String {
    let mut parts = Vec::new();
    if let Some(f) = q.feed.as_deref() {
        parts.push(format!("feed={}", qenc(f)));
    }
    if let Some(f) = q.folder.as_deref() {
        parts.push(format!("folder={}", qenc(f)));
    }
    if let Some(v) = q.view.as_deref() {
        if v != "unread" {
            parts.push(format!("view={}", qenc(v)));
        }
    }
    parts.join("&")
}

// ---------------------------------------------------------------------------
// Mark read / unread
// ---------------------------------------------------------------------------

/// Form body for `POST /entries/:id/read`.
#[derive(Debug, Deserialize)]
struct ReadForm {
    #[serde(default)]
    read: Option<String>,
}

/// `POST /entries/:id/read` — toggle an entry's read-state for the current DID.
async fn mark_read(
    State(state): State<AppState>,
    Path(id): Path<i64>,
    headers: HeaderMap,
    Form(form): Form<ReadForm>,
) -> Result<Response, WebError> {
    let did = match current_did(&state, &headers).await {
        Some(d) => d,
        None => return Ok(Redirect::to("/login").into_response()),
    };
    let pool = &state.db;

    let read = matches!(
        form.read.as_deref(),
        Some("true") | Some("1") | Some("on") | None
    );

    // Refresh the caller's `sub_ref` projection, then apply the AUTHORIZED
    // mutation: `mark_read` only writes when `did` subscribes to the entry's
    // feed. A non-subscriber gets a 404, never a mutation of someone else's
    // (or the shared cache's) state.
    resolve_subscriptions(&state, &did).await;
    if !store::mark_read(pool, &did, id, read).await? {
        return Ok((StatusCode::NOT_FOUND, "entry not found").into_response());
    }

    if !is_htmx(&headers) {
        return Ok(Redirect::to("/").into_response());
    }

    // The reader view swaps an out-of-band action-bar fragment (its `<li>` isn't
    // in the DOM), so its button's hidden value + aria-pressed update in place
    // and a second keypress can reverse the toggle. The list view swaps the row.
    if is_reader_request(&headers) {
        let starred = entry_is_starred(pool, &did, id).await?;
        return Ok(render(&EntryActionBarTemplate {
            id,
            read,
            starred,
            oob: true,
        }));
    }

    let row = build_entry_row(pool, &did, id, Some(read)).await?;
    match row {
        Some(r) => Ok(render(&EntryRowTemplate { e: r })),
        None => Ok((StatusCode::NOT_FOUND, "entry not found").into_response()),
    }
}

// ---------------------------------------------------------------------------
// Star / save
// ---------------------------------------------------------------------------

/// Form body for `POST /entries/:id/star`.
#[derive(Debug, Deserialize)]
struct StarForm {
    #[serde(default)]
    starred: Option<String>,
}

/// `POST /entries/:id/star` — star/unstar an entry.
///
/// Sets the local `starred` bit (fast working copy) and writes/removes a
/// `community.lexicon.rss.saved` record in the user's PDS (stars are worth
/// owning). The PDS write is best-effort — the local star still lands.
async fn toggle_star(
    State(state): State<AppState>,
    Path(id): Path<i64>,
    headers: HeaderMap,
    Form(form): Form<StarForm>,
) -> Result<Response, WebError> {
    let did = match current_did(&state, &headers).await {
        Some(d) => d,
        None => return Ok(Redirect::to("/login").into_response()),
    };
    let pool = &state.db;

    let starred = matches!(
        form.starred.as_deref(),
        Some("true") | Some("1") | Some("on") | None
    );

    // Refresh the caller's `sub_ref` projection, then apply the AUTHORIZED
    // mutation: `mark_starred` only writes when `did` subscribes to the entry's
    // feed. A non-subscriber gets a 404, never a mutation.
    resolve_subscriptions(&state, &did).await;
    if !store::mark_starred(pool, &did, id, starred).await? {
        return Ok((StatusCode::NOT_FOUND, "entry not found").into_response());
    }

    // Reflect into the PDS saved-records collection. `get_entry_by_id` is scoped
    // to the caller's subscriptions, so this only ever acts on the caller's feed.
    if let Ok(Some(entry)) = get_entry_by_id(pool, &did, id).await {
        let entry_url = entry.url.clone().unwrap_or_default();
        if !entry_url.is_empty() {
            if starred {
                let mut saved = Saved::new(entry_url.clone(), now_rfc3339());
                saved.title = entry.title.clone();
                saved.feed_url = feed_url_for_id(pool, entry.feed_id).await;
                saved.entry_id = Some(entry.guid.clone());
                match state.repo().add_saved(&did, &saved).await {
                    Ok(rkey) => info!(%did, url = %entry_url, %rkey, "wrote saved record to PDS"),
                    Err(err) => warn!(%err, %did, "PDS saved write failed (starred locally)"),
                }
            } else {
                // Un-star: find and delete the matching saved record by URL.
                match state.repo().list_saved(&did).await {
                    Ok(records) => {
                        for (rkey, _rec) in records.iter().filter(|(_, r)| r.url == entry_url) {
                            if let Err(err) = state.repo().remove_saved(&did, rkey).await {
                                warn!(%err, %did, %rkey, "PDS saved delete failed");
                            }
                        }
                    }
                    Err(err) => warn!(%err, %did, "could not list saved records to un-star"),
                }
            }
        }
    }

    if !is_htmx(&headers) {
        return Ok(Redirect::to("/").into_response());
    }

    // Reader → out-of-band action-bar fragment; list → the row (see mark_read).
    if is_reader_request(&headers) {
        let read = entry_is_read(pool, &did, id).await?;
        return Ok(render(&EntryActionBarTemplate {
            id,
            read,
            starred,
            oob: true,
        }));
    }

    let row = build_entry_row(pool, &did, id, None).await?;
    match row {
        Some(r) => Ok(render(&EntryRowTemplate { e: r })),
        None => Ok((StatusCode::NOT_FOUND, "entry not found").into_response()),
    }
}

/// The feed URL for a cached feed id, if the row exists.
async fn feed_url_for_id(pool: &store::Pool, feed_id: i64) -> Option<String> {
    sqlx::query_scalar::<_, String>("SELECT url FROM feeds WHERE id = ?1")
        .bind(feed_id)
        .fetch_optional(pool)
        .await
        .ok()
        .flatten()
}

// ---------------------------------------------------------------------------
// Mark-all-read
// ---------------------------------------------------------------------------

/// Query for `POST /read-all` — an optional `?feed=<url>` scopes it to one feed;
/// absent means mark everything read.
#[derive(Debug, Deserialize, Default)]
struct ReadAllQuery {
    #[serde(default)]
    feed: Option<String>,
}

/// `POST /read-all` — mark every entry read for the current DID, optionally
/// scoped to one feed (mark-all-read per feed or globally).
async fn mark_all_read(
    State(state): State<AppState>,
    headers: HeaderMap,
    Query(q): Query<ReadAllQuery>,
) -> Result<Response, WebError> {
    let did = match current_did(&state, &headers).await {
        Some(d) => d,
        None => return Ok(Redirect::to("/login").into_response()),
    };
    let pool = &state.db;

    // Refresh the caller's `sub_ref` projection so the scoped mark-read writes
    // only ever touch feeds this DID actually subscribes to.
    resolve_subscriptions(&state, &did).await;

    if let Some(feed_url) = q.feed.as_deref() {
        if let Ok(Some(feed)) = store::get_feed_by_url(pool, feed_url).await {
            store::mark_feed_read(pool, &did, feed.id, true).await?;
        }
        return Ok(Redirect::to(&format!("/?feed={}", qenc(feed_url))).into_response());
    }

    // Global: mark every subscribed feed read. Fan out over the DID's feeds
    // (bounded by the per-DID subscription cap) using the batched per-feed path,
    // rather than one UPDATE round-trip per unread entry (unbounded) — same end
    // state, but O(feeds) statements instead of O(unread entries).
    for feed_id in store::subscribed_feed_ids(pool, &did).await? {
        store::mark_feed_read(pool, &did, feed_id, true).await?;
    }
    Ok(Redirect::to("/").into_response())
}

// ---------------------------------------------------------------------------
// Subscribe by URL
// ---------------------------------------------------------------------------

/// Flash for a URL this instance cannot store as a feed — not private, just
/// not a kind of feed it supports (an `at://` publication with
/// `FEATHERREADER_STANDARD_SITE` off, an unsupported scheme). Distinct from
/// [`PRIVATE_FEED_REFUSAL`], whose "not saved or sent anywhere" would be a
/// false promise for a record that may already exist in the user's PDS.
const UNSUPPORTED_FEED_URL_REFUSAL: &str =
    "That isn't a kind of feed this instance can subscribe to. Nothing was saved.";

/// Shown when an OPML export is refused because the subscription list could not
/// be read in full.
///
/// **An empty export is worse than no export.** This path used to
/// `unwrap_or_default()`, so a failed read produced a 200 carrying a zero-feed
/// file — a blank backup, handed over at the moment the reader reached for one.
const EXPORT_INCOMPLETE_REFUSAL: &str =
    "Could not read your subscriptions in full, so nothing was exported. Your \
     feeds are unchanged — try again, and if it keeps failing the list may be \
     larger than this reader can page through.";

/// Refusal message shown when a private/paid feed is submitted. FeatherReader
/// stores subscriptions in the user's PUBLIC PDS, so it supports public feeds
/// only for now — a private feed's secret URL is never saved, fetched, or sent
/// anywhere. Kept as a constant so the add and OPML paths share the exact wording
/// and the boot-smoke can assert on it.
const PRIVATE_FEED_REFUSAL: &str = "Private/paid feeds aren't supported yet. \
    FeatherReader stores your subscriptions in your public PDS, so it supports public \
    feeds for now — private-feed support arrives when atproto's private data \
    (permissioned records) ships. Your feed URL was not saved or sent anywhere.";

/// Form body for `POST /subscriptions`.
#[derive(Debug, Deserialize)]
struct SubscribeForm {
    url: String,
    /// Optional folder `at://` URI to file the new feed under.
    #[serde(default)]
    folder: Option<String>,
}

/// The DID-form URL to store for a pasted `at://` publication, or the flash
/// to refuse it with.
///
/// - The scheme is canonicalised: `At://` is the same publication, and
///   storing a second spelling makes a second row for it (#183).
/// - It must name a `site.standard.publication`; anything else is not a feed
///   this instance can read.
/// - A handle is resolved to its DID: a handle is a mutable name, and
///   `feeds.url` is keyed on identity, so only the DID form is stored.
async fn publication_url_from_paste(state: &AppState, input: &str) -> Result<String, String> {
    let unsupported = || UNSUPPORTED_FEED_URL_REFUSAL.to_string();
    let canonical = format!(
        "{}{}",
        crate::atproto::AT_URI_PREFIX,
        &input[crate::atproto::AT_URI_PREFIX.len()..]
    );
    let uri = crate::standard_site::AtUri::parse(&canonical).ok_or_else(unsupported)?;
    if uri.collection != lexicon::nsid::STANDARD_PUBLICATION {
        return Err(unsupported());
    }
    let did = if crate::oauth::identity::is_atproto_did(&uri.authority) {
        uri.authority.clone()
    } else {
        let handle =
            // Validated as a handle before it is sent anywhere: an authority
            // that is neither a DID nor a handle (`did:plc:TOOSHORT`, an
            // uppercase DID, a newline) is unsupported, not a lookup (found in
            // review).
            crate::oauth::identity::normalize_handle(&uri.authority).map_err(|_| unsupported())?;
        crate::atproto::resolve_handle(&state.http, &state.config.resolver_base, &handle)
            .await
            .map_err(|err| {
                warn!(%err, handle = %uri.authority, "could not resolve a pasted publication's handle");
                format!("Couldn't resolve the handle {} to an account.", uri.authority)
            })?
    };
    let url = format!(
        "{}{did}/{}/{}",
        crate::atproto::AT_URI_PREFIX,
        uri.collection,
        uri.rkey
    );
    if !feed::is_storable_feed_url(&url, true) {
        return Err(unsupported());
    }
    Ok(url)
}

/// `POST /subscriptions` — subscribe by URL.
async fn add_subscription(
    State(state): State<AppState>,
    headers: HeaderMap,
    Form(form): Form<SubscribeForm>,
) -> Result<Response, WebError> {
    let did = match current_did(&state, &headers).await {
        Some(d) => d,
        None => return Ok(Redirect::to("/login").into_response()),
    };
    let pool = &state.db;
    let input = form.url.trim().to_string();
    if input.is_empty() {
        return Ok(Redirect::to("/").into_response());
    }

    // Per-DID subscription cap: bound one account's storage/poller footprint on
    // the small box. Checked BEFORE any fetch/resolve so an over-cap account
    // can't even trigger an outbound request. `<= 0` disables the cap.
    let cap = state.config.max_subs_per_did;
    if cap > 0 {
        match store::count_subscriptions_for_did(pool, &did).await {
            Ok(n) if n >= cap => {
                info!(%did, current = n, cap, "refused subscribe: per-DID subscription cap reached");
                return Ok(Redirect::to(&format!(
                    "/?flash={}",
                    qenc(&format!(
                        "Subscription limit reached ({cap}). Remove a feed before adding another."
                    ))
                ))
                .into_response());
            }
            Ok(_) => {}
            Err(err) => warn!(%err, %did, "could not count subscriptions for cap check; allowing"),
        }
    }

    // **An at:// paste is a standard.site publication, read by the poller
    // since 0.4.0**: canonicalised and resolved to its DID form here, then it
    // joins the ordinary path below. With the flag off it is refused as it
    // always was — the flag gates what may be stored.
    let is_at_uri = input
        .get(..crate::atproto::AT_URI_PREFIX.len())
        .is_some_and(|p| p.eq_ignore_ascii_case(crate::atproto::AT_URI_PREFIX));
    let publication_url = if is_at_uri {
        if !state.config.standard_site {
            info!(url = %input, %did, "refused an at:// paste: standard.site is off (not stored)");
            return Ok(
                Redirect::to(&format!("/?flash={}", qenc(UNSUPPORTED_FEED_URL_REFUSAL)))
                    .into_response(),
            );
        }
        match publication_url_from_paste(&state, &input).await {
            Ok(url) => Some(url),
            Err(flash) => {
                info!(url = %input, %did, %flash, "refused an at:// paste (not stored)");
                return Ok(Redirect::to(&format!("/?flash={}", qenc(&flash))).into_response());
            }
        }
    } else {
        None
    };

    if let feed::FeedPrivacy::Private(reason) =
        feed::classify_feed_privacy(publication_url.as_deref().unwrap_or(&input))
    {
        info!(url = %input, %reason, %did, "refused private/paid feed at add (not fetched or stored)");
        return Ok(
            Redirect::to(&format!("/?flash={}", qenc(PRIVATE_FEED_REFUSAL))).into_response(),
        );
    }

    let resolved = match publication_url {
        Some(url) => Ok(url),
        None => resolve_feed_url(&state.config, &input).await,
    };
    let feed_url = match resolved {
        Ok(u) => u,
        Err(err) => {
            warn!(%err, url = %input, "could not resolve a feed from the given URL");
            return Ok(Redirect::to(&format!(
                "/?flash={}",
                qenc("Couldn't find a feed at that URL")
            ))
            .into_response());
        }
    };

    // Defensive: resolution may have discovered a feed URL that itself carries a
    // secret (e.g. a public site page linking a tokened feed). Re-check the
    // resolved URL and refuse before storing/writing anything.
    if let feed::FeedPrivacy::Private(reason) = feed::classify_feed_privacy(&feed_url) {
        info!(url = %feed_url, %reason, %did, "refused private/paid feed after resolution (not stored)");
        return Ok(
            Redirect::to(&format!("/?flash={}", qenc(PRIVATE_FEED_REFUSAL))).into_response(),
        );
    }

    // The URL about to be STORED is what must be storable — not the one the
    // user typed. Autodiscovery already yields only http(s), but this is the
    // path that writes the row and the PDS record, so the check lives here too:
    // the same gate the OPML and rename paths apply, on the same terms.
    if !feed::is_storable_feed_url(&feed_url, state.config.standard_site) {
        info!(url = %feed_url, %did, "refused unsupported feed URL after resolution (not stored)");
        return Ok(
            Redirect::to(&format!("/?flash={}", qenc(UNSUPPORTED_FEED_URL_REFUSAL)))
                .into_response(),
        );
    }

    // Global feeds ceiling: a brand-new distinct feed is refused once the shared
    // cache is full (an existing/duplicate feed URL is always fine — it adds no
    // row). Bounds total cache size across all users on the box. `<= 0` disables.
    let feeds_cap = state.config.max_feeds_global;
    if feeds_cap > 0 && store::get_feed_by_url(pool, &feed_url).await?.is_none() {
        match store::count_feeds(pool).await {
            Ok(n) if n >= feeds_cap => {
                warn!(%did, feeds = n, cap = feeds_cap, feed = %feed_url, "refused subscribe: global feeds ceiling reached");
                return Ok(Redirect::to(&format!(
                    "/?flash={}",
                    qenc(
                        "This instance is at its feed capacity right now. Please try again later."
                    )
                ))
                .into_response());
            }
            Ok(_) => {}
            Err(err) => warn!(%err, "could not count feeds for global-cap check; allowing"),
        }
    }

    store::upsert_feed(
        pool,
        &store::NewFeed {
            url: feed_url.clone(),
            ..Default::default()
        },
    )
    .await?;

    if let Ok(client) = feed::build_client() {
        if let Some(feed_row) = store::get_feed_by_url(pool, &feed_url).await? {
            match feed::poll_feed_by_kind(pool, &client, &state.config, &feed_row).await {
                Ok(outcome) => {
                    info!(feed = %feed_url, ?outcome, "polled new subscription");
                    // **This path is not the scheduler, so it must settle the
                    // error columns itself.** `poll_feed` writes validators and
                    // `last_polled` and nothing else.
                    feed::settle_poll(pool, &feed_url, &outcome, state.config.poll_interval).await;
                }
                Err(err) => warn!(%err, feed = %feed_url, "initial poll failed"),
            }
        }
    }

    let mut sub = Subscription::new(feed_url.clone(), now_rfc3339());
    if let Ok(Some(feed_row)) = store::get_feed_by_url(pool, &feed_url).await {
        sub.title = feed_row.title.clone();
        sub.site_url = feed_row.site_url.clone();
    }
    sub.folder = form
        .folder
        .map(|f| f.trim().to_string())
        .filter(|f| !f.is_empty());

    match state.repo().add_subscription(&did, &sub).await {
        Ok(rkey) => info!(feed = %feed_url, %rkey, %did, "wrote subscription record to PDS"),
        Err(err) => {
            warn!(%err, feed = %feed_url, %did, "PDS subscription write failed (cached locally)")
        }
    }

    Ok(Redirect::to("/").into_response())
}

/// `POST /subscriptions/:rkey/delete` — unsubscribe (delete the PDS record).
async fn delete_subscription(
    State(state): State<AppState>,
    headers: HeaderMap,
    Path(rkey): Path<String>,
) -> Result<Response, WebError> {
    let did = match current_did(&state, &headers).await {
        Some(d) => d,
        None => return Ok(Redirect::to("/login").into_response()),
    };
    match state.repo().remove_subscription(&did, &rkey).await {
        Ok(()) => info!(%did, %rkey, "unsubscribed (deleted PDS subscription record)"),
        Err(err) => warn!(%err, %did, %rkey, "PDS unsubscribe failed"),
    }
    Ok(Redirect::to("/").into_response())
}

/// Form body for `POST /subscriptions/:rkey/rename`.
#[derive(Debug, Deserialize)]
struct RenameSubForm {
    url: String,
    #[serde(default)]
    title: Option<String>,
    #[serde(default)]
    site_url: Option<String>,
    #[serde(default)]
    folder: Option<String>,
}

/// `POST /subscriptions/:rkey/rename` — retitle a feed and/or move it to a
/// folder, rewriting the whole subscription record via `putRecord`.
async fn rename_subscription(
    State(state): State<AppState>,
    headers: HeaderMap,
    Path(rkey): Path<String>,
    Form(form): Form<RenameSubForm>,
) -> Result<Response, WebError> {
    let did = match current_did(&state, &headers).await {
        Some(d) => d,
        None => return Ok(Redirect::to("/login").into_response()),
    };
    let feed_url = form.url.trim().to_string();

    // Reject an empty/blank resolved URL — a rename with no usable URL must not
    // write a junk row to the cache or a malformed subscription record to the
    // PDS (add_subscription refuses an empty input the same way).
    if feed_url.is_empty() {
        return Ok(Redirect::to("/").into_response());
    }

    // **Read before write — `update_subscription` is a `putRecord`, and a
    // putRecord replaces the WHOLE record** (see its doc on `atproto.rs`).
    //
    // This used to build a fresh `Subscription::new(feed_url, now_rfc3339())`
    // and hand that over, so every field the form does not carry was written
    // back as its default. `templates/manage_row.html` posts `url`, `title` and
    // `folder` — and nothing else — so a rename silently destroyed four fields:
    // `siteUrl`, `fetchHint`, `private`, and `createdAt`.
    //
    // `createdAt` is the one that matters most: it is the reader's subscribe
    // time, it is the sort key for "when did I subscribe", it lives in THEIR
    // repo rather than our cache, and once overwritten it is gone with nothing
    // in the UI to say so.
    //
    // There is no single-record read on `Repo` (no `getRecord`), so this lists
    // and filters. That is one extra round trip on an action that is already
    // doing a PDS write, and it is bounded; a `get_subscription` would be
    // strictly better if this ever measures badly.
    //
    // **A failed read refuses the rename.** Falling back to the old
    // rebuild-from-scratch here would reinstate the data loss on exactly the
    // flaky path, which is the worst place to have it. The write below already
    // takes this stance — "a failure here means nothing was renamed or moved" —
    // and the read gets the same one.
    let existing = match state.repo().list_subscriptions_sorted(&did).await {
        Ok(subs) => subs.into_iter().find(|(k, _)| *k == rkey).map(|(_, s)| s),
        Err(err) => {
            warn!(%err, %did, %rkey, "could not read the subscription before renaming it");
            return Ok(Redirect::to(&format!(
                "/?flash={}",
                qenc("Could not reach your PDS — nothing was renamed or moved.")
            ))
            .into_response());
        }
    };
    let Some(existing) = existing else {
        // The rkey is not in the reader's repo. Renaming a record that is not
        // there would CREATE one, which is not what "rename" means and would
        // give it a fresh `createdAt` — the bug this read exists to prevent.
        warn!(%did, %rkey, "refused rename: no such subscription in the repo");
        return Ok(Redirect::to(&format!(
            "/?flash={}",
            qenc("That subscription is no longer in your repo — nothing was renamed or moved.")
        ))
        .into_response());
    };

    // The subscription can be repointed at a different feed URL. **Every gate
    // on the URL applies to a repoint and only a repoint** — the three below
    // were each, at one time, run before this line on the URL as posted, and
    // each refused a pure retitle of a record that already existed:
    //
    // - privacy: the narrowed at:// arm fails closed as `Private` for an
    //   at-URI that is not a publication (a feed generator another client
    //   subscribed to), so the record became un-editable with a flash saying
    //   it "was not saved or sent anywhere";
    // - the global feeds ceiling keyed on "URL not in the cache", and an
    //   at:// record is never cached with the flag off, so at capacity a
    //   retitle was refused for a row the handler would not insert;
    // - storability, the same way.
    //
    // An unchanged URL is already in the reader's repo; refusing to retitle
    // it protects nothing and takes their own record away from them.
    // Like for like: the form value is trimmed, and a record another client
    // wrote may carry padding — compared raw, every retitle of it was a repoint.
    let url_changed = existing.url.trim() != feed_url;

    // **Storability, on the same terms as the add and OPML paths — for a
    // REPOINT, and FIRST.** A target this instance cannot store gets that
    // answer, not "private" (the at:// arm fails closed) or "at capacity"
    // (it would never be inserted) — the ordering the add path has. This handler writes `feeds` via `upsert_feed` and had only the
    // privacy check above, so `FEATHERREADER_STANDARD_SITE` was bypassable
    // here; a review found it by enumerating every writer of the table. The
    // first fix ran this check before the repo lookup, on the URL as posted —
    // which refused a pure retitle of a subscription that already IS an
    // at-URI, on every instance with the flag off. The flag gates what the
    // cache may store, not whether a reader may edit their own record: an
    // unchanged non-storable URL keeps its PDS write and simply gets no cache
    // row below.
    let storable = feed::is_storable_feed_url(&feed_url, state.config.standard_site);
    if url_changed && !storable {
        info!(url = %feed_url, %did, %rkey, "refused a repoint to a non-storable feed URL");
        return Ok(
            Redirect::to(&format!("/?flash={}", qenc(UNSUPPORTED_FEED_URL_REFUSAL)))
                .into_response(),
        );
    }

    // Block private/paid feeds on a repoint. `url` is attacker-controllable,
    // and rename both upserts it to the local cache AND rewrites the PDS
    // subscription record (a public `putRecord`), so without this guard a
    // crafted rename could land a secret-bearing URL in the public PDS — the
    // exact leak the add and OPML paths already prevent.
    if url_changed {
        if let feed::FeedPrivacy::Private(reason) = feed::classify_feed_privacy(&feed_url) {
            info!(url = %feed_url, %reason, %did, %rkey, "refused private/paid feed at rename (not stored or written)");
            return Ok(
                Redirect::to(&format!("/?flash={}", qenc(PRIVATE_FEED_REFUSAL))).into_response(),
            );
        }
    }

    // Global feeds ceiling parity with add_subscription: a repoint to a
    // brand-new feed URL would insert a NEW `feeds` row. Refuse that when the
    // shared cache is at capacity (an existing/duplicate URL adds no row and
    // is always fine). `<= 0` disables.
    let feeds_cap = state.config.max_feeds_global;
    if url_changed
        && feeds_cap > 0
        && store::get_feed_by_url(&state.db, &feed_url)
            .await?
            .is_none()
    {
        match store::count_feeds(&state.db).await {
            Ok(n) if n >= feeds_cap => {
                warn!(%did, %rkey, feeds = n, cap = feeds_cap, feed = %feed_url, "refused rename: global feeds ceiling reached");
                return Ok(Redirect::to(&format!(
                    "/?flash={}",
                    qenc(
                        "This instance is at its feed capacity right now. Please try again later."
                    )
                ))
                .into_response());
            }
            Ok(_) => {}
            Err(err) => warn!(%err, "could not count feeds for global-cap check; allowing"),
        }
    }

    let mut sub = existing;
    sub.url = feed_url;
    sub.title = form
        .title
        .map(|t| t.trim().to_string())
        .filter(|t| !t.is_empty());
    sub.folder = form
        .folder
        .map(|f| f.trim().to_string())
        .filter(|f| !f.is_empty());
    // `createdAt` and `private` carry over untouched — neither is a property of
    // which feed URL the subscription points at.
    //
    // `siteUrl` and `fetchHint` ARE properties of the specific feed, so a
    // repoint drops them rather than leaving a site link for the old feed
    // hanging off the new one. An explicit form value still wins if the form
    // ever starts carrying one.
    match form
        .site_url
        .map(|t| t.trim().to_string())
        .filter(|t| !t.is_empty())
    {
        Some(site) => sub.site_url = Some(site),
        None if url_changed => sub.site_url = None,
        None => {}
    }
    if url_changed {
        sub.fetch_hint = None;
    }

    // Keep the local cache title in step for the loose-feed fallback path —
    // for a row this instance would have. Two cases write nothing:
    //
    // - not storable (an existing at-URI with the flag off): the record is the
    //   reader's to edit, the cache row is not this instance's to create;
    // - an unchanged URL with no cache row: a retitle is never the write that
    //   CREATES a row. That covers two findings at once — the ceiling is
    //   checked on a repoint only, so a retitle must not insert past it; and
    //   a secret-bearing URL another client subscribed to has no row (the
    //   privacy gate above runs on a repoint only, and `resolve_subscriptions`
    //   refuses to cache it), so it cannot enter the shared table here, be
    //   polled, fail, and be printed on the admin page. A privacy re-check on
    //   this write was the first draft; mutation showed it dead — the row
    //   rule already refused every case it would have.
    let cache_write =
        storable && (url_changed || store::get_feed_by_url(&state.db, &sub.url).await?.is_some());
    if !cache_write {
        info!(%did, %rkey, url = %sub.url, "renamed a subscription without touching the cache");
    } else if let Err(err) = store::upsert_feed(
        &state.db,
        &store::NewFeed {
            url: sub.url.clone(),
            title: sub.title.clone(),
            site_url: sub.site_url.clone(),
            ..Default::default()
        },
    )
    .await
    {
        // Not fatal to the rename — the PDS record below is the source of truth
        // — but a missing `feeds` row means this subscription is never polled.
        warn!(%err, %did, url = %sub.url, "could not update the cached feed row on rename");
    }

    // **The PDS write decides what the reader is told.**
    //
    // This used to `warn!` on failure and then redirect exactly as it does on
    // success, so a rename that did not happen was indistinguishable from one
    // that did — the reader saw their old title come back and had no reason to
    // think anything had gone wrong. The PDS record IS the subscription; a
    // failure here means nothing was renamed or moved.
    match state.repo().update_subscription(&did, &rkey, &sub).await {
        Ok(res) => {
            info!(%did, %rkey, uri = %res.uri, "renamed/moved subscription");
            Ok(Redirect::to("/").into_response())
        }
        Err(err) => {
            warn!(%err, %did, %rkey, "PDS subscription update failed");
            Ok(Redirect::to(&format!(
                "/?flash={}",
                qenc("Could not save that change to your PDS — nothing was renamed or moved.")
            ))
            .into_response())
        }
    }
}

// ---------------------------------------------------------------------------
// Folders
// ---------------------------------------------------------------------------

/// Form body for `POST /folders`.
#[derive(Debug, Deserialize)]
struct FolderForm {
    name: String,
}

/// `POST /folders` — create a folder record.
async fn create_folder(
    State(state): State<AppState>,
    headers: HeaderMap,
    Form(form): Form<FolderForm>,
) -> Result<Response, WebError> {
    let did = match current_did(&state, &headers).await {
        Some(d) => d,
        None => return Ok(Redirect::to("/login").into_response()),
    };
    let name = form.name.trim();
    if name.is_empty() {
        return Ok(Redirect::to("/").into_response());
    }
    let folder = Folder::new(name.to_string(), now_rfc3339());
    match state.repo().add_folder(&did, &folder).await {
        Ok(rkey) => info!(%did, %rkey, name, "created folder record"),
        Err(err) => warn!(%err, %did, "PDS folder create failed"),
    }
    Ok(Redirect::to("/").into_response())
}

/// `POST /folders/:rkey/rename` — rename a folder record.
async fn rename_folder(
    State(state): State<AppState>,
    headers: HeaderMap,
    Path(rkey): Path<String>,
    Form(form): Form<FolderForm>,
) -> Result<Response, WebError> {
    let did = match current_did(&state, &headers).await {
        Some(d) => d,
        None => return Ok(Redirect::to("/login").into_response()),
    };
    let name = form.name.trim();
    if name.is_empty() {
        return Ok(Redirect::to("/").into_response());
    }
    let folder = Folder::new(name.to_string(), now_rfc3339());
    match state.repo().rename_folder(&did, &rkey, &folder).await {
        Ok(res) => info!(%did, %rkey, uri = %res.uri, "renamed folder"),
        Err(err) => warn!(%err, %did, %rkey, "PDS folder rename failed"),
    }
    Ok(Redirect::to("/").into_response())
}

/// `POST /folders/:rkey/delete` — delete a folder record (feeds referencing it
/// simply become un-foldered).
async fn delete_folder(
    State(state): State<AppState>,
    headers: HeaderMap,
    Path(rkey): Path<String>,
) -> Result<Response, WebError> {
    let did = match current_did(&state, &headers).await {
        Some(d) => d,
        None => return Ok(Redirect::to("/login").into_response()),
    };
    match state.repo().remove_folder(&did, &rkey).await {
        Ok(()) => info!(%did, %rkey, "deleted folder record"),
        Err(err) => warn!(%err, %did, %rkey, "PDS folder delete failed"),
    }
    Ok(Redirect::to("/").into_response())
}

/// Resolve a user-pasted URL to a canonical feed URL: if fetching it yields a
/// feed document we take it as-is; if it yields an HTML page we run
/// autodiscovery over its `<link rel="alternate">` tags.
async fn resolve_feed_url(_config: &Config, input: &str) -> anyhow::Result<String> {
    let parsed =
        url::Url::parse(input).map_err(|e| anyhow::anyhow!("not a valid URL {input:?}: {e}"))?;

    let client = feed::build_client()?;
    // Fetch through the SSRF guard: scheme + resolved-IP checks on the URL and
    // every redirect hop, so a user-pasted URL can't reach cloud metadata /
    // loopback / private hosts.
    let resp = crate::net::guarded_get(&client, parsed.as_str(), &[]).await?;
    let final_url = resp.url().clone();
    let content_type = resp
        .headers()
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .to_ascii_lowercase();
    // Cap the body (streamed, aborts over 8 MiB) — never trust Content-Length,
    // gzip strips it, and this response is reflected into the UI.
    let raw = crate::net::read_capped(resp).await?;
    let body = String::from_utf8_lossy(&raw).into_owned();

    let looks_like_feed = content_type.contains("xml")
        || content_type.contains("rss")
        || content_type.contains("atom")
        || content_type.contains("application/feed+json")
        || {
            let head = body.trim_start();
            head.starts_with("<?xml")
                || head.starts_with("<rss")
                || head.starts_with("<feed")
                || head.contains("<rss")
                || head.contains("<feed")
        };
    if looks_like_feed {
        return Ok(final_url.to_string());
    }

    match feed::discover_feed(&body, Some(&final_url)) {
        Some(u) => Ok(u.to_string()),
        None => anyhow::bail!("no feed found at {input} (no autodiscovery link)"),
    }
}

// ---------------------------------------------------------------------------
// Login (atproto OAuth via the sidecar)
// ---------------------------------------------------------------------------

/// Query for `GET /login`.
#[derive(Debug, Deserialize, Default)]
struct LoginQuery {
    #[serde(default)]
    handle: Option<String>,
    #[serde(default)]
    error: Option<String>,
    #[serde(default)]
    flash: Option<String>,
}

/// `GET /login` — start the atproto OAuth flow, or render the handle form.
///
/// **Pre-handshake gate:** starting OAuth (a `?handle=` GET) is refused unless
/// the visitor is allowed by [`may_start_oauth`] — an existing beta seat (via
/// session cookie *or* the submitted handle resolving to a seated DID) or a
/// valid reserving invite cookie. Refusal redirects to `/beta/redeem`. The bare
/// form (no handle) always renders.
async fn login_form(
    State(state): State<AppState>,
    headers: HeaderMap,
    Query(q): Query<LoginQuery>,
) -> Response {
    if let Some(handle) = q
        .handle
        .map(|h| h.trim().to_string())
        .filter(|h| !h.is_empty())
    {
        if !may_start_oauth(&state, &headers, &handle).await {
            return Redirect::to("/beta/redeem").into_response();
        }
        return start_oauth(&state, &handle).await;
    }
    render(&LoginTemplate {
        card: login_card(&state.config),
        repo_url: REPO_URL,
        error: q.error.unwrap_or_default(),
        flash: q.flash.unwrap_or_default(),
    })
}

/// `POST /login` — the handle-form submit: redirect into the sidecar OAuth flow.
/// Subject to the same pre-handshake invite gate as `GET /login?handle=`.
async fn login_submit(
    State(state): State<AppState>,
    headers: HeaderMap,
    Form(form): Form<LoginForm>,
) -> Response {
    let handle = form.handle.trim();
    if handle.is_empty() {
        return login_error(&state, "Enter your atproto handle.");
    }
    if !may_start_oauth(&state, &headers, handle).await {
        return Redirect::to("/beta/redeem").into_response();
    }
    start_oauth(&state, handle).await
}

/// Whether this visitor is allowed to *start* the OAuth handshake. The gate
/// admits, in order of cost:
///
/// 1. an existing beta member's cookie session whose DID already holds a seat;
/// 2. a fresh visitor carrying a valid reserving invite cookie;
/// 3. a cookie-less visitor whose submitted `handle` resolves to a DID that
///    already holds a seat — this honors the **seeded admin's first login** on a
///    fresh deploy (and any returning member who cleared cookies) without a
///    session cookie or an invite code.
///
/// The cookie/invite fast paths run FIRST and short-circuit, so the network
/// handle→DID resolution is only attempted when neither applies. It fails
/// CLOSED: a malformed/unresolvable handle, a resolution error/timeout, or a
/// resolved DID with no seat all leave the visitor bounced to `/beta/redeem`.
/// This keeps the anti-abuse intent — a rando now pays a cheap handle
/// resolution instead of a burned sidecar handshake (and `/login` is already in
/// the rate-limited path set).
async fn may_start_oauth(state: &AppState, headers: &HeaderMap, handle: &str) -> bool {
    // The production resolver is the app's existing atproto handle→DID path,
    // routed through the SSRF guard. Resolution is injected so tests can exercise
    // the gate without a live network call (the guard forbids loopback mocks).
    may_start_oauth_with(state, headers, handle, |h| async move {
        crate::atproto::resolve_handle(&state.http, &state.config.resolver_base, &h)
            .await
            .ok()
    })
    .await
}

/// Core of [`may_start_oauth`] with the handle→DID resolver injected as `resolve`
/// (returning `Some(did)` on success, `None` on any failure/unresolvable handle).
/// The cookie + invite fast paths run FIRST and short-circuit, so `resolve` is
/// only called when neither admits — keeping the network round-trip off the hot
/// path and preserving the fail-closed contract on resolution failure.
async fn may_start_oauth_with<F, Fut>(
    state: &AppState,
    headers: &HeaderMap,
    handle: &str,
    resolve: F,
) -> bool
where
    F: FnOnce(String) -> Fut,
    Fut: std::future::Future<Output = Option<String>>,
{
    // 1. An already-beta'd session may re-auth freely.
    if let Some(did) = current_did(state, headers).await {
        if store::has_beta_access(&state.db, &did)
            .await
            .unwrap_or(false)
        {
            return true;
        }
    }
    // 2. A valid reserving invite cookie.
    if invite_cookie_code(headers, &state.config.cookie_secret).is_some() {
        return true;
    }
    // 3. Cookie-less: honor an existing seat by resolving the submitted handle to
    //    a DID (the seeded-admin first-login / cleared-cookies case). Fail closed
    //    on any resolution error or unresolvable/malformed handle.
    match resolve(handle.to_string()).await {
        Some(did) => store::has_beta_access(&state.db, &did)
            .await
            .unwrap_or(false),
        None => {
            warn!(%handle, "handle resolution failed in pre-handshake beta gate");
            false
        }
    }
}

/// Begin the OAuth handshake for `handle`, on whichever backend is live.
///
/// **On `form-action 'self'` and this redirect.** The Rust arm answers a form
/// POST with a redirect straight to the PDS — cross-origin — while the app's CSP
/// carries `form-action 'self'`. Browsers have historically disagreed about
/// whether that directive applies to redirects following a form submission, and
/// if it did here, login would break in a browser while every test passed.
///
/// It does not, and the evidence is the SIDECAR path, which is live in
/// production today: `POST /login` -> 303 to the same-origin `/oauth/login` ->
/// 302 to the PDS, cross-origin, under this same CSP. A browser checking the
/// whole redirect chain would already be blocking that. One checking only the
/// form's action URL sees `/login` in both cases. The two arms differ only in
/// how many same-origin hops precede the cross-origin one, so any policy that
/// permits the sidecar flow permits this one.
///
/// The two arms differ in SHAPE, not just in implementation. The sidecar owns
/// its own `/login` and its own callback, so starting a login is one redirect
/// and nothing is stored here. The Rust backend pushes the authorization
/// request itself, which means this app now holds the pending login — and must
/// set the browser-binding cookie that the callback will be checked against.
async fn start_oauth(state: &AppState, handle: &str) -> Response {
    match state.config.repo_backend {
        crate::metrics::Backend::Sidecar => {
            let url = state.sidecar.login_url(handle, None);
            info!(%handle, "redirecting to OAuth sidecar login");
            Redirect::to(&url).into_response()
        }
        crate::metrics::Backend::Rust => {
            let Some(runtime) = state.oauth.as_deref() else {
                warn!("the rust backend is live but its OAuth runtime is absent");
                return login_error(state, "Login is not available right now.");
            };
            match crate::oauth::login::start(
                runtime,
                &state.http,
                &state.db,
                handle,
                crate::store::now_unix(),
            )
            .await
            {
                Ok(started) => {
                    info!(%handle, "pushed authorization request; redirecting to the PDS");
                    let mut resp = Redirect::to(&started.authorize_url).into_response();
                    set_cookie(
                        &mut resp,
                        &cookie::sign_value(
                            OAUTH_BINDING_COOKIE,
                            &started.binding_token,
                            &state.config.cookie_secret,
                            OAUTH_BINDING_MAX_AGE_SECS,
                        ),
                    );
                    resp
                }
                Err(err) => {
                    // The handle the user typed is logged; the error is not shown
                    // to them verbatim, since it can name internal hosts.
                    warn!(%err, %handle, "could not start the OAuth login");
                    login_error(state, "Could not start login for that handle.")
                }
            }
        }
    }
}

/// Clear the browser-binding cookie. Called on every terminal outcome of a
/// callback, successful or not: the pending row is consumed either way, so a
/// lingering cookie can only ever match a login that no longer exists.
fn clear_binding_cookie(resp: &mut Response) {
    set_cookie(
        resp,
        &format!("{OAUTH_BINDING_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0"),
    );
}

/// Form body for `POST /login`.
#[derive(Debug, Deserialize)]
struct LoginForm {
    handle: String,
}

/// Query for `GET /oauth/callback`.
///
/// Carries BOTH shapes, because the two backends deliver different things to
/// the same URL: the sidecar hands back a one-shot `session_id` it has already
/// exchanged, while the PDS redirects here directly with `code`/`state`/`iss`
/// for this app to exchange itself. Which fields are populated is decided by
/// which backend started the login, not by which is live now — so a flip with a
/// login already in flight still lands in the right arm.
#[derive(Debug, Deserialize, Default)]
struct CallbackQuery {
    /// Sidecar backend: the handoff id.
    #[serde(default)]
    session_id: Option<String>,
    /// Rust backend: the authorization code and its envelope.
    #[serde(default)]
    code: Option<String>,
    #[serde(default)]
    state: Option<String>,
    #[serde(default)]
    iss: Option<String>,
    /// JARM, which is not supported — carried only so it can be refused
    /// explicitly rather than read as "no code".
    #[serde(default)]
    response: Option<String>,
    #[serde(default)]
    error: Option<String>,
    #[serde(default)]
    error_description: Option<String>,
}

/// `GET /oauth/callback` — establish the cookie session.
///
/// **Invite gate:** the verified DID must hold beta access. If it already does
/// (existing member / seeded admin) it's admitted directly. Otherwise we bind
/// the DID to the reserved invite cookie: `redeem_code` atomically consumes the
/// code and grants the seat. A DID with neither is bounced to `/beta/redeem`.
async fn oauth_callback(
    State(state): State<AppState>,
    headers: HeaderMap,
    Query(q): Query<CallbackQuery>,
) -> Response {
    // An error response is handled by the SAME arm that would have handled a
    // success, not short-circuited here.
    //
    // Returning early looks obviously right and is wrong on the Rust path: it
    // skips `verify_callback`, which validates `iss` BEFORE reporting the error
    // precisely because RFC 9207 §2.4 says a client "MUST NOT assume that the
    // error originates from the intended AS". It also leaves the pending row
    // unconsumed, so a `state` that has already produced a callback stays usable
    // until it expires.
    //
    // The sidecar arm has no such check to reach, so it is short-circuited
    // below, preserving exactly what it did before.
    // **The arm is chosen by what the SERVER knows, not by what the caller
    // sent.** A `session_id` in the query used to select the sidecar arm on its
    // own — so a caller could pick which code path ran, and the sidecar arm has
    // no browser-binding check at all. It also short-circuited the error path
    // below, skipping the `iss` validation.
    //
    // Requiring the Rust runtime to be absent, or a sidecar backend to be the
    // configured one, means the selection follows this deployment's own
    // configuration. A login started before a flip still completes, because the
    // Rust arm is reached whenever the Rust runtime exists and can match the
    // `state` against a pending row it actually wrote.
    // The sidecar hands off in TWO shapes, not one: `?session_id=…` on success
    // and `?error=…&error_description=…` on its own failure. Keying only on
    // `session_id` sent the failure shape down the Rust arm, which then failed
    // with "no `state`" and replaced the specific reason with a generic one —
    // and `error_description` is exactly what the sidecar Caddy routing matches
    // to send that request here in the first place.
    let sidecar_shape =
        q.session_id.as_deref().is_some_and(|s| !s.is_empty()) || q.error_description.is_some();
    let sidecar_handoff = sidecar_shape
        && (state.oauth.is_none() || state.config.repo_backend == crate::metrics::Backend::Sidecar);
    if let Some(err) = q.error.clone() {
        // **Neither the code nor the description is echoed as sent.**
        //
        // Both are server-controlled free text arriving on a public GET, so
        // anyone who can make a browser fetch this URL chooses them. The raw
        // `error` used to go into a `warn!` AND into the rendered login page,
        // and `error_description` — arbitrary text, newlines included — went
        // into the log verbatim: a log-injection surface on one side and
        // attacker-chosen copy in the product's own voice on the other.
        //
        // `oauth::flow` already decided this exact question for the Rust arm:
        // reduce the code to a known slug, drop the description entirely. That
        // reasoning is not specific to which arm handles the callback, and this
        // one simply never got the same treatment. The description's LENGTH is
        // kept, because "the server sent a 4 KB explanation" is occasionally
        // worth knowing and cannot be used to inject anything.
        let slug = crate::oauth::flow::known_error_slug(&err);
        warn!(
            error = slug,
            desc_len = q.error_description.as_deref().map_or(0, str::len),
            "OAuth callback returned an error"
        );
        if sidecar_handoff || state.oauth.is_none() {
            return login_error(&state, &format!("Login failed: {slug}"));
        }
        // Fall through: the Rust arm consumes the pending row and validates
        // `iss` against it, and reports the failure afterwards.
    }

    // Which arm runs is decided by WHAT ARRIVED, not by which backend is
    // currently selected: a login started before a flip must still complete.
    let session = if sidecar_handoff {
        let session_id = q.session_id.clone().unwrap_or_default();
        match state.sidecar.resolve_session(&session_id).await {
            Ok(Some(s)) => s,
            Ok(None) => {
                warn!("OAuth callback session_id did not resolve (expired/unknown)");
                return login_error(&state, "Login session expired — please try again.");
            }
            Err(err) => {
                warn!(%err, "failed to resolve OAuth session via the sidecar");
                return login_error(&state, "Login failed talking to the auth service.");
            }
        }
    } else {
        let Some(runtime) = state.oauth.as_deref() else {
            warn!("an OAuth callback arrived with no sidecar session and no Rust runtime");
            return login_error(&state, "Login failed: this login could not be completed.");
        };
        let params = crate::oauth::flow::CallbackParams {
            code: q.code.clone(),
            state: q.state.clone(),
            iss: q.iss.clone(),
            // Passed through, NOT dropped: `verify_callback` checks `iss`
            // against the pending row's issuer before it reports the error, and
            // it cannot do that for an error it never sees.
            error: q.error.clone(),
            error_description: q.error_description.clone(),
            response: q.response.clone(),
        };
        let binding =
            cookie::verify_value(&headers, OAUTH_BINDING_COOKIE, &state.config.cookie_secret);
        match crate::oauth::login::complete(
            runtime,
            &state.http,
            &state.db,
            &params,
            binding.as_deref(),
            crate::store::now_unix(),
        )
        .await
        {
            Ok(done) => crate::atproto::SidecarSession {
                did: done.did,
                handle: done.handle,
            },
            Err(err) => {
                // Never echoed to the browser: the message can name the issuer,
                // the PDS, and why a binding check failed.
                warn!(%err, "could not complete the OAuth callback");
                let mut resp = login_error(&state, "Login failed — please try again.");
                clear_binding_cookie(&mut resp);
                return resp;
            }
        }
    };

    // Bind the verified DID to the invite gate. Returns a response only on the
    // (rare) failure paths; `Ok(())` means the DID now holds beta access.
    let mut clear_invite = false;
    if !store::has_beta_access(&state.db, &session.did)
        .await
        .unwrap_or(false)
    {
        // Not yet a member: consume the reserved invite code, if any.
        let code = match invite_cookie_code(&headers, &state.config.cookie_secret) {
            Some(c) => c,
            None => {
                warn!(did = %session.did, "OAuth callback with no beta access and no invite cookie");
                return Redirect::to("/beta/redeem").into_response();
            }
        };
        match store::redeem_code(
            &state.db,
            &code,
            &session.did,
            session.handle.as_deref(),
            state.config.beta_cap,
        )
        .await
        {
            Ok(Ok(())) => {
                clear_invite = true;
                info!(did = %session.did, "invite code redeemed at OAuth callback; beta access granted");
            }
            Ok(Err(policy)) => {
                warn!(did = %session.did, ?policy, "invite redeem failed at callback");
                let mut resp = redeem_bounce(&state, &policy).into_response();
                // The reservation is spent/invalid — drop the stale invite cookie.
                clear_invite_cookie(&mut resp);
                return resp;
            }
            Err(err) => {
                warn!(%err, did = %session.did, "invite redeem infra error at callback");
                return login_error(&state, "Login failed while confirming your invite.");
            }
        }
    }

    // Mint an opaque, random server-side session id and store the identity under
    // it; the cookie carries the (HMAC-signed) sid, never the DID.
    let sid = state.sessions.create(Session {
        did: session.did.clone(),
        handle: session.handle.clone(),
    });
    let cookie = cookie::sign_session(&sid, &state.config.cookie_secret);
    info!(did = %session.did, handle = ?session.handle, "OAuth login OK; session cookie set");

    let mut resp = Redirect::to("/").into_response();
    set_cookie(&mut resp, &cookie);
    clear_binding_cookie(&mut resp);
    if clear_invite {
        clear_invite_cookie(&mut resp);
    }
    resp
}

/// Revoke a DID's OAuth session on BOTH backends, best-effort.
///
/// Not "whichever backend is live": during a cutover a user's tokens can be in
/// either store — they logged in under one backend and are logging out under
/// the other. Revoking only the live one would leave a live refresh token
/// behind in the other, which is the exact failure sign-out exists to prevent,
/// and it would be invisible because the sign-out itself looks successful.
///
/// Both arms are best-effort. The caller has already decided to sign the user
/// out, and a network failure must not trap them in a half-logged-out state.
/// How long sign-out will wait for a final read-state flush before revoking
/// anyway.
///
/// Bounded because the flush talks to the user's PDS, and a user trying to leave
/// must never be held by a server that is not answering. Three seconds is long
/// enough for a healthy `applyWrites` (the production samples run 100–970 ms)
/// and short enough that a dead PDS is an inconvenience rather than a trap.
const SIGN_OUT_FLUSH_BUDGET: std::time::Duration = std::time::Duration::from_secs(3);

/// Flush whatever read-state is still dirty for `did`, then give up quietly.
///
/// **Called before revoking, because revoking first strands it (#117).**
/// `revoke_everywhere` deletes the OAuth session, and a dirty cursor with no
/// session cannot be sent by anyone — it parks until the user signs in again,
/// which may be never. Flushing first is what stops the common case from
/// becoming that.
///
/// Best-effort by construction: every failure path here falls through to the
/// revoke. A flush that times out or errors leaves the cursors dirty, which is
/// the parked state the flusher now handles deliberately rather than retrying
/// forever.
async fn flush_before_revoke(state: &AppState, did: &str) {
    match tokio::time::timeout(
        SIGN_OUT_FLUSH_BUDGET,
        crate::readstate::flush_did(state, did),
    )
    .await
    {
        Ok(Ok(())) => {}
        Ok(Err(err)) => {
            warn!(%did, %err, "sign-out: final read-state flush failed; it will park until next sign-in")
        }
        Err(_) => warn!(
            %did,
            budget = ?SIGN_OUT_FLUSH_BUDGET,
            "sign-out: final read-state flush timed out; it will park until next sign-in"
        ),
    }
}

async fn revoke_everywhere(state: &AppState, did: &str) {
    // **Counted under Backend::Sidecar, not left uncounted.** A review found
    // that recording only the rust arm let `oauth_revoke` report a clean success
    // while every sidecar revocation failed — and for anyone who logged in before
    // the cutover, the sidecar store is the ONLY one that held tokens, so the
    // rust arm correctly returns NoSession and the metric reads all-clear while
    // live refresh tokens sit at the PDS.
    //
    // Same op name, different backend: the backend column is what distinguishes
    // them, so "no revocation failures" means checking both rows, not one.
    let sidecar_started = std::time::Instant::now();
    let sidecar_ok = match state.sidecar.revoke_session(did).await {
        Ok(res) => {
            info!(%did, revoked = res.revoked, "sidecar session revoked");
            true
        }
        Err(err) => {
            warn!(%did, %err, "sidecar revoke failed; continuing");
            false
        }
    };
    state.metrics.record(
        crate::metrics::Backend::Sidecar,
        "oauth_revoke",
        sidecar_started.elapsed().as_micros() as u64,
        sidecar_ok,
    );

    if let Some(runtime) = state.oauth.as_deref() {
        let revoke_started = std::time::Instant::now();
        let outcome = crate::oauth::revoke::sign_out_discovering(
            runtime,
            &state.http,
            &state.db,
            did,
            crate::store::now_unix(),
        )
        .await;
        // **Counted, because a warn! nobody reads is not observability.** Until
        // this existed, a revocation failure left exactly one trace: a log line.
        // "No revocation failures this week" was therefore a statement about
        // nobody having looked, which is not the same claim.
        //
        // NoSession counts as a SUCCESS, deliberately. Logout is idempotent —
        // there being nothing to revoke is the correct outcome, not a failure,
        // and counting it as an error would make the metric noisy in exactly
        // the case that is fine. Only `Failed` means the PDS still holds live
        // tokens we asked it to drop.
        let revoke_ok = !matches!(outcome, crate::oauth::revoke::Revocation::Failed(_));
        state.metrics.record(
            crate::metrics::Backend::Rust,
            "oauth_revoke",
            revoke_started.elapsed().as_micros() as u64,
            revoke_ok,
        );
        match outcome {
            crate::oauth::revoke::Revocation::Revoked => {
                info!(%did, "rust OAuth session revoked at the PDS")
            }
            crate::oauth::revoke::Revocation::NoSession => {}
            crate::oauth::revoke::Revocation::Failed(reason) => {
                warn!(%did, %reason, "rust OAuth revoke failed; the local session is gone regardless")
            }
        }
    }
}

/// `POST /logout` — end the session everywhere, not just in this browser.
///
/// Clearing the cookie only stops *this* device from presenting the session;
/// the sidecar still holds live OAuth tokens for the DID. So logout now also
/// calls the sidecar `POST /internal/revoke {did}`, which revokes the refresh +
/// access tokens at the PDS and drops the sidecar's session rows. The local
/// registry entry is dropped and the cookie cleared regardless of whether the
/// revoke round-trip succeeds (best-effort — a network blip must not trap the
/// user in a half-logged-out state).
async fn logout(State(state): State<AppState>, headers: HeaderMap) -> Response {
    if let Some(user) = current_session(&state, &headers).await {
        // Only a real cookie session (`sid` present) has sidecar-held tokens to
        // revoke; the dev-DID fallback never handshook the sidecar.
        if let Some(sid) = user.sid {
            state.sessions.remove(&sid);
            // BEFORE the revoke: afterwards there is no session to send it with.
            flush_before_revoke(&state, &user.did).await;
            revoke_everywhere(&state, &user.did).await;
        }
    }
    let mut resp = Redirect::to("/login").into_response();
    set_cookie(
        &mut resp,
        &format!("{SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0"),
    );
    resp
}

/// Form body for `POST /account/delete` — the confirm-gate. The user must type
/// `DELETE` into this field for the purge to run.
#[derive(Debug, Deserialize)]
struct DeleteAccountForm {
    #[serde(default)]
    confirm: String,
}

/// The literal a user must type to confirm the destructive delete.
const DELETE_CONFIRM_PHRASE: &str = "DELETE";

/// `POST /account/delete` (authed) — the "delete my data" endpoint.
///
/// Confirm-gated: the form must carry `confirm=DELETE` or we bounce back to
/// `/manage` with an explanatory flash and touch nothing. On confirmation it:
///   1. purges **every** local row owned by the caller DID (`entry_state`,
///      `read_cursor`, `sub_ref`, `beta_access` seat, and any invite codes the
///      DID created) via [`store::purge_did_data`], then
///   2. revokes the OAuth session at the PDS via `revoke_everywhere` — the
///      sidecar's `POST /internal/revoke {did}` and, when the Rust OAuth runtime
///      is configured, its RFC 7009 revocation too — then
///   3. drops the in-memory session and clears the cookie, signing the user out.
///
/// The subscription/folder/saved *records* in the user's own PDS are
/// intentionally left alone — they are the user's data on their own server; the
/// `/about` copy and this page's UI both say so, and export stays available.
async fn account_delete(
    State(state): State<AppState>,
    headers: HeaderMap,
    Form(form): Form<DeleteAccountForm>,
) -> Result<Response, WebError> {
    let user = match current_session(&state, &headers).await {
        Some(u) => u,
        None => return Ok(Redirect::to("/login").into_response()),
    };
    let did = user.did.clone();

    // Confirm-gate: require the exact typed phrase before doing anything.
    if form.confirm.trim() != DELETE_CONFIRM_PHRASE {
        return Ok(Redirect::to(&format!(
            "/manage?flash={}",
            qenc("Type DELETE to confirm — nothing was deleted.")
        ))
        .into_response());
    }

    // 1. Purge every local row this DID owns (single transaction).
    let counts = store::purge_did_data(&state.db, &did).await?;
    info!(
        %did,
        total = counts.total(),
        entry_state = counts.entry_state,
        read_cursor = counts.read_cursor,
        sub_ref = counts.sub_ref,
        beta_access = counts.beta_access,
        invite_codes = counts.invite_codes,
        "account/delete: local rows purged"
    );

    // 2. Revoke the OAuth session at the sidecar/PDS (best-effort — the local
    //    rows are already gone; a network blip must not block the sign-out).
    revoke_everywhere(&state, &did).await;

    // 3. Drop the in-memory session and clear the cookie: sign the user out.
    if let Some(sid) = user.sid {
        state.sessions.remove(&sid);
    }
    let mut resp = Redirect::to(&format!(
        "/login?flash={}",
        qenc("Your data was deleted and you've been signed out. Thanks for trying FeatherReader.")
    ))
    .into_response();
    set_cookie(
        &mut resp,
        &format!("{SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0"),
    );
    Ok(resp)
}

/// The `/login` card, shared by the form and its error re-render.
fn login_card(config: &Config) -> Card {
    Card::public(
        config,
        "/login",
        "Sign in — FeatherReader",
        "Sign in to FeatherReader with your atproto handle. You approve access on \
         your own server — no signup, no password.",
    )
}

/// Re-render the login form with an error banner.
fn login_error(state: &AppState, msg: &str) -> Response {
    render(&LoginTemplate {
        card: login_card(&state.config),
        repo_url: REPO_URL,
        error: msg.to_string(),
        flash: String::new(),
    })
}

// ---------------------------------------------------------------------------
// Closed-beta invite gate (self-serve redeem + admin mint)
// ---------------------------------------------------------------------------

/// Form body for `POST /beta/redeem`.
#[derive(Debug, Deserialize)]
struct RedeemForm {
    code: String,
}

/// `GET /beta/redeem` — render the invite-redeem page. If the seat cap is
/// already full we render the "capacity full" variant (no form).
async fn beta_redeem_form(State(state): State<AppState>) -> Response {
    let full = store::count_beta_access(&state.db)
        .await
        .map(|n| n >= state.config.beta_cap)
        .unwrap_or(false);
    render(&BetaRedeemTemplate {
        card: redeem_card(&state.config),
        repo_url: REPO_URL,
        error: String::new(),
        capacity_full: full,
    })
}

/// `POST /beta/redeem` — the **pre-handshake** reservation.
///
/// Validates the pasted code is *redeemable right now* (exists, active,
/// unexpired, and a seat is free) WITHOUT consuming it or binding a DID — the
/// visitor has no DID yet. On success it sets a short-lived signed invite cookie
/// reserving intent to redeem this code, then sends the visitor to `/login`. The
/// OAuth callback later binds the verified DID and atomically consumes the code
/// (`store::redeem_code`). This ordering means a non-invited visitor can never
/// start OAuth (and burn a sidecar handshake).
async fn beta_redeem_submit(
    State(state): State<AppState>,
    Form(form): Form<RedeemForm>,
) -> Response {
    let code = form.code.trim().to_uppercase();
    if code.is_empty() {
        return render(&BetaRedeemTemplate {
            card: redeem_card(&state.config),
            repo_url: REPO_URL,
            error: "Enter your invite code.".to_string(),
            capacity_full: false,
        });
    }

    match preflight_code(&state, &code).await {
        Ok(()) => {
            let cookie = sign_invite(&code, &state.config.cookie_secret);
            let mut resp = Redirect::to("/login").into_response();
            set_cookie(&mut resp, &cookie);
            info!("invite code preflight OK; reserving intent + redirecting to /login");
            resp
        }
        Err(policy) => {
            warn!(?policy, "invite code preflight rejected");
            redeem_bounce(&state, &policy)
        }
    }
}

/// Read-only preflight of an invite code for the pre-handshake reservation:
/// verify it exists, is active, is not past `expires_at`, and that a seat is
/// free — mirroring the checks `store::redeem_code` will re-run atomically at
/// callback time. Does NOT consume the code or grant a seat. Returns the same
/// typed [`store::RedeemError`] variants so the two paths share one message map.
async fn preflight_code(state: &AppState, code: &str) -> Result<(), store::RedeemError> {
    // Cap check first: a clear "capacity full" beats "code invalid" when both.
    // FAIL CLOSED on a count error — an `unwrap_or(0)` would let a DB blip read as
    // "0 seats used" and wave the redeem through the preflight. (`redeem_code`
    // still backstops the real cap inside its tx, so this is a consistency /
    // defence-in-depth fix, not the only guard.) Treat an unverifiable count as
    // capacity-full: the redeemer sees "at capacity, try later" rather than a mint
    // that might overrun the cap.
    let count = match store::count_beta_access(&state.db).await {
        Ok(n) => n,
        Err(err) => {
            warn!(%err, "preflight_code: count_beta_access failed; failing closed");
            return Err(store::RedeemError::CapacityFull);
        }
    };
    if count >= state.config.beta_cap {
        return Err(store::RedeemError::CapacityFull);
    }
    // Look up the code's current status + expiry (read-only).
    let row = sqlx::query_as::<_, (String, i64)>(
        "SELECT status, expires_at FROM invite_codes WHERE code = ?1",
    )
    .bind(code)
    .fetch_optional(&state.db)
    .await
    .ok()
    .flatten();
    let (status, expires_at) = match row {
        Some(r) => r,
        None => return Err(store::RedeemError::NotFound),
    };
    let now = chrono::Utc::now().timestamp();
    match status.as_str() {
        "active" if expires_at >= now => Ok(()),
        "active" => Err(store::RedeemError::Expired),
        "expired" => Err(store::RedeemError::Expired),
        // "redeemed" or anything else non-active.
        _ => Err(store::RedeemError::AlreadyRedeemed),
    }
}

/// Map a [`store::RedeemError`] to the invite page with the right message. Used
/// by both the preflight (`POST /beta/redeem`) and the callback bind path.
fn redeem_bounce(state: &AppState, policy: &store::RedeemError) -> Response {
    use store::RedeemError::*;
    let (msg, capacity_full) = match policy {
        NotFound => ("That invite code isn't valid.", false),
        Expired => ("That invite code has expired.", false),
        AlreadyRedeemed => ("That invite code has already been used.", false),
        CapacityFull => ("", true),
    };
    render(&BetaRedeemTemplate {
        card: redeem_card(&state.config),
        repo_url: REPO_URL,
        error: msg.to_string(),
        capacity_full,
    })
}

/// The `/beta/redeem` card, shared by the form, its re-renders and the claim
/// link's bounce.
fn redeem_card(config: &Config) -> Card {
    Card::public(
        config,
        "/beta/redeem",
        "Redeem an invite — FeatherReader",
        "Redeem a closed-beta invite code for this FeatherReader instance, then sign \
         in with your atproto handle.",
    )
}

/// Query for `POST /admin/invites` — how many codes to mint (`?n=`, default 1).
#[derive(Debug, Deserialize, Default)]
struct MintQuery {
    #[serde(default)]
    n: Option<u32>,
}

/// `POST /admin/invites?n=N` — mint N invite codes.
///
/// `GET /oauth/client-metadata.json` — the client's published identity.
///
/// **This URL IS the `client_id`.** The PDS fetches it during every login and
/// caches it against every existing grant, so it must keep answering at exactly
/// this path across the cutover — the sidecar serves the same document at the
/// same URL today, proxied by the edge.
///
/// Served whatever backend is live: a request that arrives here is from a PDS
/// resolving our identity, and it has no idea which of our two implementations
/// is currently answering repo calls.
async fn oauth_client_metadata(State(state): State<AppState>) -> Response {
    let Some(runtime) = state.oauth.as_deref() else {
        // The sidecar is serving this path in front of us, or nothing is.
        return (StatusCode::NOT_FOUND, "no client metadata\n").into_response();
    };
    axum::Json(crate::oauth::metadata::client_metadata(&runtime.client)).into_response()
}

/// `GET /oauth/jwks.json` — the client's public signing key.
///
/// Production only. The localhost dev client is a PUBLIC client: it registers no
/// key and signs no assertions, so publishing a JWKS there would advertise a
/// credential that is never used — and would make a dev deployment look like a
/// confidential client to anyone reading it.
async fn oauth_jwks(State(state): State<AppState>) -> Response {
    let Some(runtime) = state.oauth.as_deref() else {
        return (StatusCode::NOT_FOUND, "no jwks\n").into_response();
    };
    match runtime.client_key.as_ref() {
        Some(key) => match key.jwks_document() {
            Ok(doc) => axum::Json(doc).into_response(),
            Err(err) => {
                warn!(%err, "could not render the client JWKS");
                (StatusCode::INTERNAL_SERVER_ERROR, "jwks unavailable\n").into_response()
            }
        },
        None => (StatusCode::NOT_FOUND, "this client publishes no jwks\n").into_response(),
    }
}

/// How many failing feeds `/admin/metrics` will name. One response, so bounded.
const ADMIN_FAILING_FEED_LIMIT: i64 = 200;

/// `GET /admin/metrics` — repo-op latency for both backends, as plain text.
///
/// Admin-gated on the same rule as the invite minter: the table names every
/// operation the reader performs and how often each fails, which is an
/// operational picture rather than public information.
///
/// Text, not JSON or HTML: it is read by a person deciding whether the cutover
/// is safe, and the comparison is two rows side by side.
async fn admin_metrics(State(state): State<AppState>, headers: HeaderMap) -> Response {
    let did = match current_did(&state, &headers).await {
        Some(d) => d,
        None => return (StatusCode::UNAUTHORIZED, "sign in first\n").into_response(),
    };
    if !state.config.admin_seed_dids().iter().any(|d| d == &did) {
        warn!(%did, "admin metrics denied: not an admin-seed DID");
        return (StatusCode::FORBIDDEN, "not an admin\n").into_response();
    }

    // Flush first, so the table includes this process's traffic up to now.
    // Then read the PERSISTED rows, which is the only place both backends can
    // appear at once -- a flip is a restart, and in-process memory only ever
    // holds the backend currently running.
    if let Err(err) =
        crate::metrics::flush(&state.metrics, &state.db, crate::store::now_unix()).await
    {
        warn!(%err, "could not flush repo timings before rendering");
    }
    let rows = match crate::metrics::persisted_rows(&state.db).await {
        Ok(rows) => rows,
        Err(err) => {
            warn!(%err, "could not read persisted repo timings");
            return (StatusCode::INTERNAL_SERVER_ERROR, "metrics unavailable\n").into_response();
        }
    };

    // The live backend is named at the top: a table of two populated rows is
    // ambiguous about which one is currently serving users.
    // Parked read-state, alongside the timings. The flusher no longer logs
    // these every round (#117), so without a number here the state would be
    // silent — which is the failure the noisy loop at least did not have.
    let parked = match crate::store::parked_readstate_dids(&state.db).await {
        Ok(n) => n.to_string(),
        Err(err) => {
            warn!(%err, "could not count parked read-state DIDs");
            "unknown".to_string()
        }
    };
    // **The half the public histogram cannot carry.** `/stats` reports counts by
    // cause and nothing else, deliberately — but `fetch` covers DNS failure,
    // timeout, SSRF refusal AND this reader's own bugs, so the count alone
    // cannot separate "the publishers are gone" from "we are broken". #159 was
    // the latter and took a production investigation to establish. Named feeds
    // and their error text belong here, behind ALLOWED_DIDS.
    let failing = match crate::store::failing_feeds(&state.db, ADMIN_FAILING_FEED_LIMIT).await {
        Ok(f) => f,
        Err(err) => {
            warn!(%err, "could not list failing feeds");
            Vec::new()
        }
    };
    let mut failing_block = String::new();
    if !failing.is_empty() {
        failing_block.push_str("\nfailing feeds (worst first)\n");
        for f in &failing {
            failing_block.push_str(&format!(
                "  {:>4}x  {:<8}  {}\n          {}\n",
                f.consecutive_errors,
                f.kind.as_deref().unwrap_or("unknown"),
                f.url,
                f.detail.as_deref().unwrap_or("(no detail recorded)"),
            ));
        }
    }

    // **Capacity that no other page can show.** The global ceiling counts every
    // row (`store::count_feeds`), but `/stats` measures the poller and excludes
    // unpollable ones — so an instance can be at its cap with every public
    // number saying otherwise. A review found exactly that gap.
    let unpollable = match crate::store::unpollable_feeds(&state.db).await {
        Ok(n) => n,
        Err(err) => {
            warn!(%err, "could not count unpollable feeds");
            -1
        }
    };
    let cached = crate::store::count_feeds(&state.db).await.unwrap_or(-1);

    let body = format!(
        "live backend: {}\nparked read-state DIDs: {}\n\
         feeds cached: {} (ceiling {}), of which unpollable: {}\n\n{}{}",
        state.config.repo_backend.as_str(),
        parked,
        cached,
        state.config.max_feeds_global,
        unpollable,
        crate::metrics::render(&rows),
        failing_block,
    );
    (StatusCode::OK, body).into_response()
}

/// Authorized ONLY for a live session whose DID is in the `ALLOWED_DIDS` admin
/// seed (`config.admin_seed_dids`). Returns the freshly-minted codes as
/// newline-separated `text/plain`. Deliberately minimal (no HTML UI).
async fn admin_mint_invites(
    State(state): State<AppState>,
    headers: HeaderMap,
    Query(q): Query<MintQuery>,
) -> Response {
    // Require a real, current session (not just a DID string) whose DID is an
    // admin-seed DID. `current_did` already re-checks the beta gate.
    let did = match current_did(&state, &headers).await {
        Some(d) => d,
        None => return (StatusCode::UNAUTHORIZED, "sign in first\n").into_response(),
    };
    if !state.config.admin_seed_dids().iter().any(|d| d == &did) {
        warn!(%did, "admin mint denied: not an admin-seed DID");
        return (StatusCode::FORBIDDEN, "not an admin\n").into_response();
    }

    let n = q.n.unwrap_or(1).clamp(1, 100);
    let mut codes = Vec::with_capacity(n as usize);
    for _ in 0..n {
        match store::mint_code(&state.db, &did, INVITE_TTL_SECS).await {
            Ok(code) => codes.push(code),
            Err(err) => {
                warn!(%err, %did, "admin mint_code failed");
                return (StatusCode::INTERNAL_SERVER_ERROR, "mint failed\n").into_response();
            }
        }
    }
    info!(%did, count = codes.len(), "admin minted invite codes");
    let mut body = codes.join("\n");
    body.push('\n');
    (StatusCode::OK, body).into_response()
}

// ---------------------------------------------------------------------------
// Bot claim link: /claim?t=<token>  +  POST /bot/claims (shared-secret mint)
// ---------------------------------------------------------------------------

/// Query for `GET /claim`.
#[derive(Debug, Deserialize)]
struct ClaimQuery {
    /// The opaque claim token from the bot's public follow-back skeet.
    t: Option<String>,
}

/// `GET /claim?t=<token>` — redeem a bot-issued claim link.
///
/// The follow→invite bot posts a public skeet mentioning a new follower with a
/// link here. The token wraps a pre-minted invite code (never the raw code — see
/// [`sign_claim_token`]). On a valid, still-redeemable token this behaves exactly
/// like a successful `POST /beta/redeem`: it sets the reserving `fr_invite`
/// cookie and sends the visitor to `/login`, so they flow through OAuth and the
/// callback atomically consumes the code (`store::redeem_code`) — the same
/// machinery as a pasted code. On any failure it bounces to the invite page with
/// the matching message.
///
/// Single-use / grabbability: a token in a public URL is grabbable. The code it
/// wraps is single-use (redeem flips `active→redeemed`), and `preflight_code`
/// here rejects an already-used / expired / capacity-full code before reserving,
/// so a replayed link past the first successful claim is refused. The residual
/// window is the same as any pasted invite code: whoever completes OAuth *first*
/// with a live reservation wins the seat. The per-IP rate limit on `/claim`
/// blunts brute-force enumeration.
async fn claim(State(state): State<AppState>, Query(q): Query<ClaimQuery>) -> Response {
    let token = match q.t {
        Some(t) if !t.is_empty() => t,
        _ => {
            warn!("claim link with no token");
            return redeem_bounce(&state, &store::RedeemError::NotFound);
        }
    };

    // Unwrap the token → the invite code it reserves. A tampered/forged token
    // yields nothing → treat as an invalid code (don't leak whether it parsed).
    let code = match claim_token_code(&token, &state.config.cookie_secret) {
        Some(c) => c,
        None => {
            warn!("claim token invalid (bad signature / malformed)");
            return redeem_bounce(&state, &store::RedeemError::NotFound);
        }
    };

    // Re-run the same preflight as the pasted-code path: exists, active,
    // unexpired, seat free. This is what makes a replayed link past first-claim
    // (or past cap) fail cleanly.
    match preflight_code(&state, &code).await {
        Ok(()) => {
            let cookie = sign_invite(&code, &state.config.cookie_secret);
            let mut resp = Redirect::to("/login").into_response();
            set_cookie(&mut resp, &cookie);
            info!("claim token preflight OK; reserving intent + redirecting to /login");
            resp
        }
        Err(policy) => {
            warn!(?policy, "claim token preflight rejected");
            redeem_bounce(&state, &policy)
        }
    }
}

/// The JSON body `POST /bot/claims` accepts — the follower the claim is FOR.
///
/// Passing the follower DID makes the APP the authoritative deduper: the app can
/// short-circuit a DID that already holds a seat, and return the SAME code for a
/// DID that already has an outstanding claim — so a bot-host state loss cannot
/// re-mint or re-post per follower. Handle is advisory (logs only).
#[derive(Debug, Default, Deserialize)]
struct BotClaimRequest {
    /// The follower's DID (the idempotency key). Optional for backward-compat: an
    /// omitted DID falls back to the old un-keyed mint (no server-side dedupe).
    #[serde(default)]
    did: Option<String>,
    /// The follower's handle (advisory; recorded for operator logs only).
    #[serde(default)]
    #[allow(dead_code)]
    handle: Option<String>,
}

/// The JSON body `POST /bot/claims` returns on success.
#[derive(Debug, serde::Serialize)]
struct BotClaimResponse {
    /// Server-side dedupe outcome, so the bot knows whether to post:
    /// `"minted"` (a fresh code — post the claim link), `"existing"` (this DID
    /// already had an outstanding claim; the SAME code/token/url is returned, so an
    /// idempotent re-post is safe), or `"already_seated"` (this DID already holds
    /// beta access; code/token/url are empty and the bot should post NOTHING).
    status: &'static str,
    /// The bare invite code (`FEATHER-…`) — for the bot's own logs/idempotency
    /// store. NEVER post this publicly; post the `url` instead. Empty when
    /// `already_seated`.
    code: String,
    /// The opaque claim token (the code wrapped + signed). Empty when
    /// `already_seated`.
    token: String,
    /// The full claim URL to put in the public skeet: `${public_url}/claim?t=…`.
    /// Empty when `already_seated`.
    url: String,
}

/// `POST /bot/claims` — headless, shared-secret mint of a claim link.
///
/// Auth is a bearer shared secret in the `X-Bot-Secret` header (== the Fly secret
/// `FEATHERREADER_BOT_SECRET`), NOT an OAuth cookie — so the homelab-hosted bot
/// can call it. When `FEATHERREADER_BOT_SECRET` is unset the endpoint is DISABLED
/// (503), so a bare/dev instance never exposes an unauthenticated mint.
///
/// Server-side DID idempotency (the authoritative dedupe backstop): the request
/// body carries the follower `did`. The app — not the bot's local SQLite — is the
/// source of truth, so a bot-host state loss cannot re-mint or re-post per
/// follower:
///   * DID already holds beta access → `200 {status:"already_seated"}` (empty
///     code/url; the bot marks it handled and posts NOTHING);
///   * DID already has an outstanding active claim → `200 {status:"existing"}`
///     returning the SAME code/token/url (idempotent — never a second mint);
///   * otherwise mint a fresh code recorded FOR that DID → `200 {status:"minted"}`.
///
/// Cap accounting: the bot must not promise more claims than seats remain, so
/// this refuses with `409 Conflict {"error":"full"}` when
/// `beta_access + outstanding active codes >= FEATHERREADER_BETA_CAP`. (The
/// redeem-time cap in `store::redeem_code` is still the hard backstop.) The count
/// queries FAIL CLOSED: a DB error propagates as `500` rather than reading 0 and
/// minting past the cap.
///
/// On a fresh mint it uses the generous claim TTL (`FEATHERREADER_CLAIM_TTL_SECS`,
/// default 14d — the admin browser flow's 30-min TTL would expire before the
/// follower taps an async-delivered link).
async fn bot_mint_claim(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: axum::body::Bytes,
) -> Response {
    // 1. The endpoint is OFF unless a bot secret is configured.
    let bot_secret = match state.config.bot_secret.as_deref() {
        Some(s) => s,
        None => {
            warn!(
                "POST /bot/claims called but FEATHERREADER_BOT_SECRET is unset (endpoint disabled)"
            );
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                "bot mint endpoint disabled (FEATHERREADER_BOT_SECRET unset)\n",
            )
                .into_response();
        }
    };

    // 2. Constant-time bearer check on the X-Bot-Secret header.
    let presented = headers
        .get("x-bot-secret")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    if !bot_secret_matches(presented, bot_secret) {
        warn!("POST /bot/claims rejected: bad or missing X-Bot-Secret");
        return (StatusCode::UNAUTHORIZED, "bad bot secret\n").into_response();
    }

    // 2b. Parse the (optional) JSON body → the follower DID/handle. An empty body
    // (legacy caller) parses to an all-None request; a malformed body is a 400.
    let req: BotClaimRequest = if body.is_empty() {
        BotClaimRequest::default()
    } else {
        match serde_json::from_slice(&body) {
            Ok(r) => r,
            Err(err) => {
                warn!(%err, "POST /bot/claims: bad JSON body");
                return (StatusCode::BAD_REQUEST, "bad json body\n").into_response();
            }
        }
    };
    let follower_did = req.did.as_deref().filter(|d| !d.is_empty());

    // 3. Server-side DID idempotency (only when a DID was supplied):
    if let Some(did) = follower_did {
        // 3a. Already seated → tell the bot to post nothing.
        match store::has_beta_access(&state.db, did).await {
            Ok(true) => {
                info!("bot mint: DID already holds beta access; already_seated");
                return bot_claim_json(BotClaimResponse {
                    status: "already_seated",
                    code: String::new(),
                    token: String::new(),
                    url: String::new(),
                });
            }
            Ok(false) => {}
            Err(err) => {
                // Fail closed: a DB error must not fall through to a fresh mint.
                warn!(%err, "bot mint: has_beta_access failed");
                return (StatusCode::INTERNAL_SERVER_ERROR, "lookup failed\n").into_response();
            }
        }
        // 3b. Outstanding active claim for this DID → return the SAME code (no
        // second mint). This is what survives a bot-host state loss.
        match store::find_active_code_for_did(&state.db, did).await {
            Ok(Some(code)) => {
                info!("bot mint: existing outstanding claim for DID; returning same code");
                let token = sign_claim_token(&code, &state.config.cookie_secret);
                let url = format!("{}/claim?t={}", state.config.public_url, qenc(&token));
                return bot_claim_json(BotClaimResponse {
                    status: "existing",
                    code,
                    token,
                    url,
                });
            }
            Ok(None) => {}
            Err(err) => {
                warn!(%err, "bot mint: find_active_code_for_did failed");
                return (StatusCode::INTERNAL_SERVER_ERROR, "lookup failed\n").into_response();
            }
        }
    }

    // 4. Cap accounting: seats already granted + outstanding unredeemed codes.
    //    FAIL CLOSED — a count error is a 500, not a silent mint past the cap.
    let granted = match store::count_beta_access(&state.db).await {
        Ok(n) => n,
        Err(err) => {
            warn!(%err, "bot mint: count_beta_access failed; failing closed");
            return (StatusCode::INTERNAL_SERVER_ERROR, "count failed\n").into_response();
        }
    };
    let outstanding = match store::count_active_codes(&state.db).await {
        Ok(n) => n,
        Err(err) => {
            warn!(%err, "bot mint: count_active_codes failed; failing closed");
            return (StatusCode::INTERNAL_SERVER_ERROR, "count failed\n").into_response();
        }
    };
    if granted + outstanding >= state.config.beta_cap {
        info!(
            granted,
            outstanding,
            cap = state.config.beta_cap,
            "bot mint refused: at capacity"
        );
        return (
            StatusCode::CONFLICT,
            [(header::CONTENT_TYPE, "application/json")],
            "{\"error\":\"full\"}\n",
        )
            .into_response();
    }

    // 5. Mint with the generous claim TTL, recording the follower DID (when given)
    //    so a re-request for the same DID returns THIS code idempotently.
    let bot_did = state
        .config
        .admin_seed_dids()
        .first()
        .cloned()
        .unwrap_or_else(|| "did:bot:featherreader".to_string());
    let minted = match follower_did {
        Some(did) => {
            store::mint_code_for_did(&state.db, &bot_did, state.config.claim_ttl_secs, did).await
        }
        None => store::mint_code(&state.db, &bot_did, state.config.claim_ttl_secs).await,
    };
    let code = match minted {
        Ok(c) => c,
        // S4: the dedupe check (3b) and this mint are separate statements, so two
        // concurrent requests for one DID can both fall through 3b's `Ok(None)`.
        // The partial unique index `idx_invite_codes_intended_active` makes the
        // loser's INSERT fail (only one active row per intended DID), which
        // surfaces here as a conflict. Recover by returning the winner's existing
        // code (same shape as the 3b idempotent path) instead of a 500.
        Err(err) if follower_did.is_some() && store::is_intended_active_conflict(&err) => {
            match store::find_active_code_for_did(&state.db, follower_did.unwrap()).await {
                Ok(Some(code)) => {
                    info!("bot mint: lost the mint race; returning the concurrently-minted code");
                    let token = sign_claim_token(&code, &state.config.cookie_secret);
                    let url = format!("{}/claim?t={}", state.config.public_url, qenc(&token));
                    return bot_claim_json(BotClaimResponse {
                        status: "existing",
                        code,
                        token,
                        url,
                    });
                }
                // The winner's row vanished between the conflict and this lookup
                // (redeemed/expired/purged in the gap) — nothing to hand back.
                // Fail closed rather than silently mint past the just-hit guard.
                Ok(None) => {
                    warn!("bot mint: conflict but no active code found on recovery");
                    return (StatusCode::INTERNAL_SERVER_ERROR, "mint failed\n").into_response();
                }
                Err(err) => {
                    warn!(%err, "bot mint: recovery lookup after conflict failed");
                    return (StatusCode::INTERNAL_SERVER_ERROR, "mint failed\n").into_response();
                }
            }
        }
        Err(err) => {
            warn!(%err, "bot mint_code failed");
            return (StatusCode::INTERNAL_SERVER_ERROR, "mint failed\n").into_response();
        }
    };
    let token = sign_claim_token(&code, &state.config.cookie_secret);
    let url = format!("{}/claim?t={}", state.config.public_url, qenc(&token));
    info!("bot minted a claim code + token");

    bot_claim_json(BotClaimResponse {
        status: "minted",
        code,
        token,
        url,
    })
}

/// Serialize a [`BotClaimResponse`] to a `200 application/json` response (or a
/// `500` if serialization somehow fails).
fn bot_claim_json(resp: BotClaimResponse) -> Response {
    match serde_json::to_string(&resp) {
        Ok(body) => (
            StatusCode::OK,
            [(header::CONTENT_TYPE, "application/json")],
            body,
        )
            .into_response(),
        Err(err) => {
            warn!(%err, "serializing bot claim response failed");
            (StatusCode::INTERNAL_SERVER_ERROR, "serialize failed\n").into_response()
        }
    }
}

/// Constant-time equality for the bot bearer secret (avoid a timing side-channel
/// on the shared secret). Delegates to the same `cookie::constant_time_eq` used
/// by the HMAC checks so there is one comparator to audit; a length mismatch
/// short-circuits to `false`, which is fine — the secret length isn't sensitive.
fn bot_secret_matches(presented: &str, expected: &str) -> bool {
    cookie::constant_time_eq(presented.as_bytes(), expected.as_bytes())
}

// ---------------------------------------------------------------------------
// Signed, short-lived invite cookie (reuses the session-cookie HMAC helper)
// ---------------------------------------------------------------------------

/// Sign the reserved invite `code` into a short-lived `Set-Cookie` value. Reuses
/// the same HMAC-SHA256 helper as the session cookie; the payload is the code
/// itself (base64url) rather than an opaque sid, since the code IS the reserved
/// intent the callback consumes.
fn sign_invite(code: &str, secret: &str) -> String {
    cookie::sign_value(INVITE_COOKIE, code, secret, INVITE_TTL_SECS)
}

/// Verify + read the reserved invite code out of the request's invite cookie
/// (`None` if absent, tampered, or forged). No expiry is enforced here beyond
/// the cookie's own `Max-Age`; the atomic `redeem_code` at the callback is the
/// authority on the code's live status.
fn invite_cookie_code(headers: &HeaderMap, secret: &str) -> Option<String> {
    cookie::verify_value(headers, INVITE_COOKIE, secret)
}

/// Domain-separation label for the claim TOKEN's HMAC (distinct from the
/// `fr_invite`/`fr_session` cookie names), so a token can never be replayed as a
/// cookie value and vice-versa.
const CLAIM_TOKEN_LABEL: &str = "claim-token";

/// Sign an invite `code` into a URL-safe claim TOKEN: `b64url(code).<sig>`
/// (HMAC-SHA256 over `"claim-token" || 0x00 || code`).
///
/// NOTE — the token is NOT confidential: the `b64url(code)` half is trivially
/// decodable by anyone, so the raw `FEATHER-…` code is effectively public in the
/// claim URL. The token's security is INTEGRITY + SINGLE-USE, not secrecy: the
/// `<sig>` HMAC means only this instance can MINT a valid token (a forged/guessed
/// code won't verify), the wrapped code is single-use (redeem flips
/// `active→redeemed`), and `/claim` is per-IP rate-limited. Wrapping keeps the
/// token one self-contained string needing no server-side token table; it does
/// NOT hide the code.
fn sign_claim_token(code: &str, secret: &str) -> String {
    cookie::sign_token(CLAIM_TOKEN_LABEL, code, secret)
}

/// Verify a claim token and return the invite code it wraps (`None` on a tampered
/// / forged / malformed token). The code's live status (active/unexpired/seat
/// free) is re-checked by `preflight_code`; this only proves the token was minted
/// by this instance.
fn claim_token_code(token: &str, secret: &str) -> Option<String> {
    cookie::verify_token(CLAIM_TOKEN_LABEL, token, secret)
}

/// Clear the invite cookie on a response (after a successful bind, or when the
/// reservation turned out to be stale).
fn clear_invite_cookie(resp: &mut Response) {
    set_cookie(
        resp,
        &format!("{INVITE_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0"),
    );
}

// ---------------------------------------------------------------------------
// OPML import + export
// ---------------------------------------------------------------------------

/// `POST /opml` — import subscriptions from an OPML document.
///
/// Accepts either a multipart file upload (field `file`) or a pasted textarea
/// (field `opml`). The parsed feeds each become a `community.lexicon.rss.folder`
/// (for any named folders) + a `community.lexicon.rss.subscription` record in the
/// user's PDS via the records layer's bulk-add (`add_subscriptions_bulk`, one
/// `applyWrites` round-trip per 200 feeds). Feeds are also upserted into the local cache so
/// they show immediately; polling is left to the background poller.
async fn import_opml(
    State(state): State<AppState>,
    headers: HeaderMap,
    mut multipart: Multipart,
) -> Result<Response, WebError> {
    let did = match current_did(&state, &headers).await {
        Some(d) => d,
        None => return Ok(Redirect::to("/login").into_response()),
    };
    let pool = &state.db;

    // Collect the OPML text from whichever field carried it. Multipart errors
    // are mapped to their axum-native response so that an over-cap upload (the
    // `DefaultBodyLimit` on this route, see `OPML_BODY_LIMIT`) surfaces as
    // `413 Payload Too Large` rather than being swallowed by the blanket
    // `WebError` → `500` conversion.
    let mut opml_text = String::new();
    while let Some(field) = multipart.next_field().await.map_err(multipart_response)? {
        let name = field.name().unwrap_or("").to_string();
        if name == "opml" || name == "file" {
            let bytes = field.bytes().await.map_err(multipart_response)?;
            if !bytes.is_empty() {
                opml_text = String::from_utf8_lossy(&bytes).into_owned();
                if name == "file" {
                    break;
                }
            }
        }
    }

    // A parse FAILURE and an empty-but-valid file are different things, and
    // `unwrap_or_default` collapsed them: a malformed export was reported to the
    // reader as "No feeds found in that OPML", which sends them looking at their
    // old reader for feeds that are right there in the file.
    let feeds =
        match opml::parse_opml(&opml_text) {
            Ok(feeds) => feeds,
            Err(err) => {
                warn!(%err, %did, "OPML import could not parse the uploaded file");
                return Ok(Redirect::to(&format!(
                "/?flash={}",
                qenc("That file could not be read as OPML. Export it again from your other reader?")
            ))
                .into_response());
            }
        };
    if feeds.is_empty() {
        info!(%did, "OPML import found no feeds");
        return Ok(
            Redirect::to(&format!("/?flash={}", qenc("No feeds found in that OPML")))
                .into_response(),
        );
    }

    // Create any named folders first, mapping folder name → at:// URI so
    // subscriptions can reference them.
    let now = now_rfc3339();
    let mut folder_uris: std::collections::HashMap<String, String> =
        std::collections::HashMap::new();
    // Reuse existing folders where the name already exists.
    if let Ok(existing) = state.repo().list_folders_sorted(&did).await {
        for (rkey, folder) in existing {
            folder_uris
                .entry(folder.name.clone())
                .or_insert_with(|| folder_uri(&did, &rkey));
        }
    }
    let mut wanted_folders: Vec<String> = feeds
        .iter()
        .filter_map(|f| f.folder.clone())
        .filter(|n| !n.is_empty())
        .collect();
    wanted_folders.sort();
    wanted_folders.dedup();
    for name in wanted_folders {
        if folder_uris.contains_key(&name) {
            continue;
        }
        let folder = Folder::new(name.clone(), now.clone());
        match state.repo().add_folder(&did, &folder).await {
            Ok(rkey) => {
                folder_uris.insert(name, folder_uri(&did, &rkey));
            }
            Err(err) => warn!(%err, %did, "OPML folder create failed"),
        }
    }

    // Build one subscription record per PUBLIC feed + upsert the local cache row.
    // Private/paid feeds are SKIPPED entirely (never stored, fetched, or written)
    // and reported back to the user — the same public-feeds-only stance as the
    // single-add path, so an OPML import can't leak a Substack/Patreon/podcast
    // token onto the public network either.
    // Per-DID subscription cap: an OPML import must not blow past the cap. Compute
    // the remaining headroom (cap − existing) once; public feeds beyond it are
    // TRIMMED (not imported) and reported. `<= 0` disables the cap.
    let sub_cap = state.config.max_subs_per_did;
    let mut headroom: Option<i64> = if sub_cap > 0 {
        let existing = store::count_subscriptions_for_did(pool, &did)
            .await
            .unwrap_or(0);
        Some((sub_cap - existing).max(0))
    } else {
        None
    };
    let mut trimmed_over_cap: usize = 0;

    // Global feeds ceiling: an OPML import must not blow past the shared cache
    // ceiling any more than the single-add path may. Seed the remaining global
    // headroom (cap − current feeds) once, and only a BRAND-NEW feed URL (one
    // not already cached) consumes it. Existing/duplicate URLs add no row and
    // are always allowed. Feeds past the ceiling are TRIMMED and reported.
    // `<= 0` disables the ceiling.
    let feeds_cap = state.config.max_feeds_global;
    let mut global_headroom: Option<i64> = if feeds_cap > 0 {
        let existing = store::count_feeds(pool).await.unwrap_or(0);
        Some((feeds_cap - existing).max(0))
    } else {
        None
    };
    let mut trimmed_over_global: usize = 0;

    let mut subs = Vec::with_capacity(feeds.len());
    let mut skipped_private: Vec<String> = Vec::new();
    // Imported into the PDS but not cached locally, so not pollable until the
    // next import touches them. Counted rather than only logged — see below.
    let mut uncached: usize = 0;
    // Entries this instance cannot store at all (an `at://` publication with
    // the flag off, an unsupported scheme). Counted, because the `continue`
    // below used to increment nothing while the privacy branch beside it
    // produced a label — so an OPML from a standard.site-enabled instance
    // imported "successfully" with entries missing and no reason given.
    let mut skipped_unsupported: usize = 0;
    for f in &feeds {
        // `xmlUrl` is whatever the uploaded file says, and nothing on this path
        // ever parsed it — the single-add path can't reach here because
        // `resolve_feed_url` must parse AND successfully fetch first. So
        // `javascript:alert(1)` and `file:///etc/passwd` were both accepted,
        // cached, and published as records to the user's PUBLIC repo. Note that
        // `classify_feed_privacy` does not catch these: both parse cleanly, and
        // it returns `Public` for anything unparseable by design.
        if !feed::is_storable_feed_url(&f.feed_url, state.config.standard_site) {
            info!(
                %did,
                "skipped an OPML entry whose xmlUrl is not a storable feed URL"
            );
            skipped_unsupported += 1;
            continue;
        }
        if let feed::FeedPrivacy::Private(reason) = feed::classify_feed_privacy(&f.feed_url) {
            info!(feed = %f.feed_url, %reason, %did, "skipped private/paid feed on OPML import (not stored)");
            // Report by title where we have one, else the (public-safe) host.
            let label = f
                .title
                .clone()
                .filter(|t| !t.trim().is_empty())
                .unwrap_or_else(|| private_feed_label(&f.feed_url));
            skipped_private.push(label);
            continue;
        }

        // Over-cap: stop importing once headroom is exhausted (count the rest so
        // we can tell the user how many were dropped).
        if let Some(h) = headroom.as_mut() {
            if *h <= 0 {
                trimmed_over_cap += 1;
                continue;
            }
        }

        // Global ceiling: a brand-new feed URL consumes global headroom. Once
        // it's exhausted, refuse to cache further NEW feeds (existing URLs are
        // free — they add no row). Checked before decrementing the per-DID
        // headroom so a dropped feed doesn't burn the caller's own quota.
        let is_new = match store::get_feed_by_url(pool, &f.feed_url).await {
            Ok(existing) => existing.is_none(),
            // On a lookup error, treat as existing (don't consume global
            // headroom) but still allow the upsert to proceed.
            Err(err) => {
                warn!(%err, feed = %f.feed_url, "get_feed_by_url failed during OPML global-cap check");
                false
            }
        };
        if is_new {
            if let Some(g) = global_headroom.as_mut() {
                if *g <= 0 {
                    trimmed_over_global += 1;
                    continue;
                }
                *g -= 1;
            }
        }

        // Passed both caps: consume the per-DID headroom now that the feed is
        // actually being imported.
        if let Some(h) = headroom.as_mut() {
            *h -= 1;
        }

        let mut sub = Subscription::new(f.feed_url.clone(), now.clone());
        sub.title = f.title.clone();
        sub.site_url = f.site_url.clone();
        sub.folder = f
            .folder
            .as_ref()
            .and_then(|name| folder_uris.get(name).cloned());
        subs.push(sub);
        // Same support ticket as the single-add path: no `feeds` row means the
        // poller never selects this subscription, so the import looks like it
        // worked and the feed silently never updates. Counted as well as logged,
        // because one line per feed in a 200-feed import is not something anyone
        // reads — the count goes to the reader.
        if let Err(err) = store::upsert_feed(
            pool,
            &store::NewFeed {
                url: f.feed_url.clone(),
                title: f.title.clone(),
                site_url: f.site_url.clone(),
                ..Default::default()
            },
        )
        .await
        {
            warn!(%err, %did, url = %f.feed_url, "OPML import could not cache a feed; \
                                                  it will not be polled");
            uncached += 1;
        }
    }

    // **A failed PDS write is not an import.**
    //
    // The subscriptions live in the reader's repo; a local `feeds` row is just a
    // poller hint. This used to `warn!` and then report "Imported N feeds"
    // regardless, so a total failure read as a total success — and the reader
    // would only discover otherwise on their next visit, with an empty sidebar.
    //
    // **And a part-landed write is not a failed one.** The batch goes out in
    // calls of at most 200 (#240: the reference PDS refuses more), sent in
    // order and stopped at the first failure, so what landed is a prefix of
    // `subs` and the error says how long. Saying "nothing was imported" after
    // the first 200 of 450 landed would send the reader to import the file
    // again, which adds those 200 a second time. Nothing local needs undoing
    // either way: the reader's `sub_ref` projection is rebuilt from the repo on
    // the next read, and a cached `feeds` row with no subscriber is the same
    // poller hint the total-failure path has always left behind.
    let landed = match state.repo().add_subscriptions_bulk(&did, &subs).await {
        Ok(rkeys) => {
            info!(%did, count = rkeys.len(), skipped = skipped_private.len(), "imported OPML subscriptions to PDS (batched)");
            rkeys.len()
        }
        Err(err) => {
            let landed = crate::atproto::ApplyWritesIncomplete::of(&err).map_or(0, |p| p.landed);
            warn!(%err, %did, landed, total = subs.len(), "OPML PDS batch write failed (feeds cached locally)");
            landed
        }
    };
    if landed == 0 && !subs.is_empty() {
        return Ok(Redirect::to(&format!(
            "/?flash={}",
            qenc(
                "Could not save those subscriptions to your PDS, so nothing was imported. \
                 Try again in a moment."
            )
        ))
        .into_response());
    }

    // Report the import count, plus any private/paid feeds skipped as unsupported.
    let mut flash = if landed < subs.len() {
        format!(
            "Imported {landed} of {} feeds: your PDS stopped accepting them part-way, so the \
             other {} may not have been saved. Importing the same file again would add the first \
             {landed} a second time",
            subs.len(),
            subs.len() - landed
        )
    } else {
        format!("Imported {} feeds", subs.len())
    };
    if uncached > 0 {
        flash.push_str(&format!(
            ". {uncached} of them could not be cached locally and may not update until the next import."
        ));
    }
    if trimmed_over_cap > 0 {
        flash.push_str(&format!(
            ". {trimmed_over_cap} feed(s) not imported: your subscription limit ({sub_cap}) was reached."
        ));
    }
    if trimmed_over_global > 0 {
        flash.push_str(&format!(
            ". {trimmed_over_global} feed(s) not imported: this instance is at its feed capacity right now."
        ));
    }
    if !skipped_private.is_empty() {
        flash.push_str(&format!(
            ". {} feed(s) skipped as private/paid: {} — not supported yet (public feeds only for now).",
            skipped_private.len(),
            skipped_private.join(", ")
        ));
    }
    if skipped_unsupported > 0 {
        // By count only — the URL is whatever the file said, and unlike the
        // private branch there is no public-safe label to give.
        flash.push_str(&format!(
            ". {skipped_unsupported} feed(s) skipped: not a kind of feed this instance can subscribe to."
        ));
    }
    Ok(Redirect::to(&format!("/?flash={}", qenc(&flash))).into_response())
}

/// A public-safe label for a skipped private feed when it has no title: just the
/// host, so we never echo the secret-bearing path/query back to the user.
fn private_feed_label(url: &str) -> String {
    url::Url::parse(url)
        .ok()
        .and_then(|u| u.host_str().map(str::to_string))
        .unwrap_or_else(|| "a private feed".to_string())
}

/// `GET /opml/export` — export the user's subscriptions + folders as OPML.
async fn export_opml(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> Result<Response, WebError> {
    let did = match current_did(&state, &headers).await {
        Some(d) => d,
        None => return Ok(Redirect::to("/login").into_response()),
    };

    // **An export must never be silently empty.** `unwrap_or_default` here turned
    // a failed read into a 200 carrying a zero-feed OPML file — the reader's
    // backup, blank, at exactly the moment they reached for it. That was survivable
    // while a truncated walk returned `Ok`; now that the walk refuses a short list,
    // this is the one caller that converts a refusal into data loss, and it is also
    // the recovery route the changelog points a locked-out reader at.
    let subs = match state.repo().list_subscriptions_sorted(&did).await {
        Ok(subs) => subs,
        Err(err) => {
            tracing::warn!(%err, did = %did, "refusing to export an OPML we could not read in full");
            return Ok(Redirect::to(&format!(
                "/manage?flash={}",
                qenc(EXPORT_INCOMPLETE_REFUSAL)
            ))
            .into_response());
        }
    };
    let folders = match state.repo().list_folders_sorted(&did).await {
        Ok(folders) => folders,
        Err(err) => {
            tracing::warn!(%err, did = %did, "refusing to export an OPML without its folders");
            return Ok(Redirect::to(&format!(
                "/manage?flash={}",
                qenc(EXPORT_INCOMPLETE_REFUSAL)
            ))
            .into_response());
        }
    };
    // The exporter matches a subscription's `folder` at-uri against the folder's
    // pair key; our folder pairs are keyed by rkey, so rebuild them as at-uris.
    let folder_pairs: Vec<(String, Folder)> = folders
        .into_iter()
        .map(|(rkey, f)| (folder_uri(&did, &rkey), f))
        .collect();

    let body = opml::to_opml(&subs, &folder_pairs);
    let mut resp = (StatusCode::OK, body).into_response();
    resp.headers_mut().insert(
        header::CONTENT_TYPE,
        "text/x-opml; charset=utf-8".parse().unwrap(),
    );
    resp.headers_mut().insert(
        header::CONTENT_DISPOSITION,
        "attachment; filename=\"featherreader-subscriptions.opml\""
            .parse()
            .unwrap(),
    );
    Ok(resp)
}

// ---------------------------------------------------------------------------
// Signed session cookie (HMAC-SHA256, dependency-free)
// ---------------------------------------------------------------------------

/// Set a `Set-Cookie` header on a response (append, so logout+redirect compose).
fn set_cookie(resp: &mut Response, cookie: &str) {
    if let Ok(value) = axum::http::HeaderValue::from_str(cookie) {
        resp.headers_mut()
            .append(axum::http::header::SET_COOKIE, value);
    }
}

/// Whether the request came from htmx (the `HX-Request` header).
fn is_htmx(headers: &HeaderMap) -> bool {
    headers
        .get("HX-Request")
        .is_some_and(|v| v.as_bytes().eq_ignore_ascii_case(b"true"))
}

/// Whether a mark-read / star request originated from the single-entry READER
/// (as opposed to the list view). The reader's forms tag themselves with
/// `X-FR-Reader: 1` via `hx-headers`; the list view's do not. This selects the
/// swap fragment: the reader gets an out-of-band action-bar update (its `<li>`
/// isn't in the DOM), the list gets the row (`entry_row.html`).
fn is_reader_request(headers: &HeaderMap) -> bool {
    headers
        .get("X-FR-Reader")
        .is_some_and(|v| v.as_bytes() == b"1")
}

/// A tiny, self-contained signed-cookie layer: HMAC-SHA256 over an opaque,
/// server-minted **session id** (never the DID — so the cookie can't be forged
/// from a resolved victim DID; forging it needs the HMAC secret *and* a live
/// server-side session id).
mod cookie {
    use super::{HeaderMap, SESSION_COOKIE};

    /// Sign a session id into a `Set-Cookie` header value: `fr_session=<sid>.<sig>`.
    pub fn sign_session(sid: &str, secret: &str) -> String {
        sign_value(SESSION_COOKIE, sid, secret, 2_592_000)
    }

    /// Verify the request's session cookie and return the session id it carries.
    pub fn verify_session(headers: &HeaderMap, secret: &str) -> Option<String> {
        verify_value(headers, SESSION_COOKIE, secret)
    }

    /// The HMAC message binding the cookie NAME to its value (`name || 0x00 ||
    /// value`), so a signature minted for one cookie can't verify under another —
    /// e.g. a value validly signed as `fr_invite` is not accepted as `fr_session`.
    /// The NUL separator can't appear in a cookie name, so the encoding is
    /// unambiguous.
    fn cookie_hmac_msg(name: &str, value: &str) -> Vec<u8> {
        let mut msg = Vec::with_capacity(name.len() + 1 + value.len());
        msg.extend_from_slice(name.as_bytes());
        msg.push(0);
        msg.extend_from_slice(value.as_bytes());
        msg
    }

    /// Sign an arbitrary string `value` into a `Set-Cookie` header for `name`,
    /// HMAC-SHA256 over `name || 0x00 || value`: `name=<b64url(value)>.<sig>`. The
    /// generic form behind both the session cookie and the short-lived invite
    /// cookie; domain-separating by name keeps a signature valid only for the
    /// cookie it was minted for.
    pub fn sign_value(name: &str, value: &str, secret: &str, max_age_secs: i64) -> String {
        let sig = hmac_sha256_hex(secret.as_bytes(), &cookie_hmac_msg(name, value));
        let b64 = b64url_encode(value.as_bytes());
        format!(
            "{name}={b64}.{sig}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age={max_age_secs}"
        )
    }

    /// Verify + read a value out of the named signed cookie (`None` on absent /
    /// tampered / forged / cross-cookie). The generic form behind both readers.
    pub fn verify_value(headers: &HeaderMap, name: &str, secret: &str) -> Option<String> {
        let raw = cookie_value(headers, name)?;
        let (b64, sig) = raw.split_once('.')?;
        let bytes = b64url_decode(b64)?;
        let value = String::from_utf8(bytes).ok()?;
        let expected = hmac_sha256_hex(secret.as_bytes(), &cookie_hmac_msg(name, &value));
        if constant_time_eq(expected.as_bytes(), sig.as_bytes()) {
            Some(value)
        } else {
            None
        }
    }

    /// Sign an arbitrary `value` into an opaque, URL-safe token string
    /// `b64url(value).<sig>` (HMAC-SHA256 over `label || 0x00 || value`). Unlike
    /// [`sign_value`] this is NOT a `Set-Cookie` header — it's a bare token for a
    /// URL query param (the bot's claim link). `label` domain-separates it from
    /// the cookies so a token can't be replayed as a cookie value.
    pub fn sign_token(label: &str, value: &str, secret: &str) -> String {
        let sig = hmac_sha256_hex(secret.as_bytes(), &cookie_hmac_msg(label, value));
        let b64 = b64url_encode(value.as_bytes());
        format!("{b64}.{sig}")
    }

    /// Verify a token minted by [`sign_token`] and return the wrapped value
    /// (`None` on tamper / forge / malformed). Constant-time signature compare.
    pub fn verify_token(label: &str, token: &str, secret: &str) -> Option<String> {
        let (b64, sig) = token.split_once('.')?;
        let bytes = b64url_decode(b64)?;
        let value = String::from_utf8(bytes).ok()?;
        let expected = hmac_sha256_hex(secret.as_bytes(), &cookie_hmac_msg(label, &value));
        if constant_time_eq(expected.as_bytes(), sig.as_bytes()) {
            Some(value)
        } else {
            None
        }
    }

    /// Pull one cookie value out of the `Cookie` request header.
    fn cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
        let header = headers.get(axum::http::header::COOKIE)?.to_str().ok()?;
        for part in header.split(';') {
            let part = part.trim();
            if let Some((k, v)) = part.split_once('=') {
                if k == name {
                    return Some(v.to_string());
                }
            }
        }
        None
    }

    /// Constant-time byte comparison (avoid signature-timing leaks). Public
    /// within the module so the bot-secret bearer check reuses the exact same
    /// comparator as the cookie/token HMAC checks (one implementation to audit).
    pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
        if a.len() != b.len() {
            return false;
        }
        let mut diff = 0u8;
        for (x, y) in a.iter().zip(b.iter()) {
            diff |= x ^ y;
        }
        diff == 0
    }

    // -- URL-safe base64 (no padding), std-only --------------------------------

    const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

    fn b64url_encode(input: &[u8]) -> String {
        let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
        for chunk in input.chunks(3) {
            let b = [
                chunk[0],
                *chunk.get(1).unwrap_or(&0),
                *chunk.get(2).unwrap_or(&0),
            ];
            let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | (b[2] as u32);
            out.push(B64[((n >> 18) & 63) as usize] as char);
            out.push(B64[((n >> 12) & 63) as usize] as char);
            if chunk.len() > 1 {
                out.push(B64[((n >> 6) & 63) as usize] as char);
            }
            if chunk.len() > 2 {
                out.push(B64[(n & 63) as usize] as char);
            }
        }
        out
    }

    fn b64url_decode(input: &str) -> Option<Vec<u8>> {
        fn val(c: u8) -> Option<u32> {
            match c {
                b'A'..=b'Z' => Some((c - b'A') as u32),
                b'a'..=b'z' => Some((c - b'a' + 26) as u32),
                b'0'..=b'9' => Some((c - b'0' + 52) as u32),
                b'-' => Some(62),
                b'_' => Some(63),
                _ => None,
            }
        }
        let bytes = input.as_bytes();
        let mut out = Vec::with_capacity(input.len() / 4 * 3 + 2);
        for chunk in bytes.chunks(4) {
            let mut n = 0u32;
            let mut valid = 0;
            for (i, &c) in chunk.iter().enumerate() {
                n |= val(c)? << (18 - 6 * i);
                valid += 1;
            }
            out.push((n >> 16) as u8);
            if valid > 2 {
                out.push((n >> 8) as u8);
            }
            if valid > 3 {
                out.push(n as u8);
            }
        }
        Some(out)
    }

    // -- HMAC-SHA256, std-only -------------------------------------------------

    /// HMAC-SHA256(key, msg) as lowercase hex.
    fn hmac_sha256_hex(key: &[u8], msg: &[u8]) -> String {
        const BLOCK: usize = 64;
        let mut k = [0u8; BLOCK];
        if key.len() > BLOCK {
            let d = sha256(key);
            k[..32].copy_from_slice(&d);
        } else {
            k[..key.len()].copy_from_slice(key);
        }
        let mut ipad = [0x36u8; BLOCK];
        let mut opad = [0x5cu8; BLOCK];
        for i in 0..BLOCK {
            ipad[i] ^= k[i];
            opad[i] ^= k[i];
        }
        let mut inner = Vec::with_capacity(BLOCK + msg.len());
        inner.extend_from_slice(&ipad);
        inner.extend_from_slice(msg);
        let inner_hash = sha256(&inner);
        let mut outer = Vec::with_capacity(BLOCK + 32);
        outer.extend_from_slice(&opad);
        outer.extend_from_slice(&inner_hash);
        let mac = sha256(&outer);
        let mut hex = String::with_capacity(64);
        for b in mac {
            hex.push_str(&format!("{b:02x}"));
        }
        hex
    }

    /// SHA-256 (FIPS 180-4), std-only.
    fn sha256(data: &[u8]) -> [u8; 32] {
        const K: [u32; 64] = [
            0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
            0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
            0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
            0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
            0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
            0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
            0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
            0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
            0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
            0xc67178f2,
        ];
        let mut h: [u32; 8] = [
            0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
            0x5be0cd19,
        ];

        let bit_len = (data.len() as u64) * 8;
        let mut msg = data.to_vec();
        msg.push(0x80);
        while msg.len() % 64 != 56 {
            msg.push(0);
        }
        msg.extend_from_slice(&bit_len.to_be_bytes());

        for block in msg.chunks(64) {
            let mut w = [0u32; 64];
            for i in 0..16 {
                w[i] = u32::from_be_bytes([
                    block[i * 4],
                    block[i * 4 + 1],
                    block[i * 4 + 2],
                    block[i * 4 + 3],
                ]);
            }
            for i in 16..64 {
                let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
                let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
                w[i] = w[i - 16]
                    .wrapping_add(s0)
                    .wrapping_add(w[i - 7])
                    .wrapping_add(s1);
            }
            let mut a = h;
            for i in 0..64 {
                let s1 = a[4].rotate_right(6) ^ a[4].rotate_right(11) ^ a[4].rotate_right(25);
                let ch = (a[4] & a[5]) ^ ((!a[4]) & a[6]);
                let t1 = a[7]
                    .wrapping_add(s1)
                    .wrapping_add(ch)
                    .wrapping_add(K[i])
                    .wrapping_add(w[i]);
                let s0 = a[0].rotate_right(2) ^ a[0].rotate_right(13) ^ a[0].rotate_right(22);
                let maj = (a[0] & a[1]) ^ (a[0] & a[2]) ^ (a[1] & a[2]);
                let t2 = s0.wrapping_add(maj);
                a[7] = a[6];
                a[6] = a[5];
                a[5] = a[4];
                a[4] = a[3].wrapping_add(t1);
                a[3] = a[2];
                a[2] = a[1];
                a[1] = a[0];
                a[0] = t1.wrapping_add(t2);
            }
            for i in 0..8 {
                h[i] = h[i].wrapping_add(a[i]);
            }
        }

        let mut out = [0u8; 32];
        for (i, word) in h.iter().enumerate() {
            out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
        }
        out
    }

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

        #[test]
        fn sha256_known_vector() {
            let d = sha256(b"abc");
            let hex: String = d.iter().map(|b| format!("{b:02x}")).collect();
            assert_eq!(
                hex,
                "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
            );
        }

        #[test]
        fn hmac_known_vector() {
            let mac = hmac_sha256_hex(b"Jefe", b"what do ya want for nothing?");
            assert_eq!(
                mac,
                "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
            );
        }

        #[test]
        fn sign_verify_round_trips() {
            let secret = "test-secret";
            let sid = "9f2c-opaque-session-id";
            let cookie = sign_session(sid, secret);
            let pair = cookie.split(';').next().unwrap().to_string();
            let mut headers = HeaderMap::new();
            headers.insert(axum::http::header::COOKIE, pair.parse().unwrap());
            assert_eq!(verify_session(&headers, secret).as_deref(), Some(sid));
            // Wrong secret → rejected (an attacker without the HMAC key can't forge).
            assert!(verify_session(&headers, "other-secret").is_none());
        }

        #[test]
        fn forged_and_tampered_cookies_are_rejected() {
            let secret = "test-secret";

            // 1. A fully forged cookie: attacker knows a victim's DID/sid but not
            //    the secret, so an arbitrary signature must not verify.
            let forged = format!(
                "{SESSION_COOKIE}={}.{}",
                b64url_encode(b"attacker-chosen-sid"),
                "deadbeef".repeat(8) // 64 hex chars, wrong sig
            );
            let mut headers = HeaderMap::new();
            headers.insert(axum::http::header::COOKIE, forged.parse().unwrap());
            assert!(verify_session(&headers, secret).is_none());

            // 2. A tampered cookie: take a VALID cookie and mutate the sid while
            //    keeping the original signature — must not verify.
            let cookie = sign_session("real-sid", secret);
            let pair = cookie.split(';').next().unwrap();
            let (_b64, sig) = pair.split_once('=').unwrap().1.split_once('.').unwrap();
            let tampered = format!(
                "{SESSION_COOKIE}={}.{}",
                b64url_encode(b"different-sid"),
                sig
            );
            let mut headers2 = HeaderMap::new();
            headers2.insert(axum::http::header::COOKIE, tampered.parse().unwrap());
            assert!(verify_session(&headers2, secret).is_none());
        }

        #[test]
        fn b64url_round_trips() {
            for s in ["did:plc:abc", "", "a", "ab", "abc", "abcd"] {
                let enc = b64url_encode(s.as_bytes());
                assert_eq!(b64url_decode(&enc).unwrap(), s.as_bytes());
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Small store helpers local to the web layer
// ---------------------------------------------------------------------------

/// Fetch a single cached entry by id — SCOPED to `did`'s subscriptions.
///
/// Returns `None` (→ 404 at the handler) if the entry does not exist OR if
/// `did` does not subscribe to its feed. This is the per-DID read gate for the
/// `GET /entries/:id` reader and the htmx row rebuild: the shared cache is
/// deduped by URL, but no DID can read another DID's cached article.
///
/// **The only `SELECT e.*` left, and deliberately so.** This is the one surface
/// that renders `content_html`, and it fetches exactly one row. The list views
/// go through [`store::list_entries`], which is both paged and body-free — see
/// [`store::EntryListRow`] for why they had to stop sharing this projection.
async fn get_entry_by_id(
    pool: &store::Pool,
    did: &str,
    id: i64,
) -> anyhow::Result<Option<store::Entry>> {
    let entry = sqlx::query_as::<_, store::Entry>(
        r#"
        SELECT e.* FROM entries e
        WHERE e.id = ?2
          AND EXISTS (
              SELECT 1 FROM sub_ref sr
              WHERE sr.did = ?1 AND sr.feed_id = e.feed_id
          )
        "#,
    )
    .bind(did)
    .bind(id)
    .fetch_optional(pool)
    .await?;
    Ok(entry)
}

/// Whether `entry_id` is marked read for `did` (absent state row = unread).
async fn entry_is_read(pool: &store::Pool, did: &str, entry_id: i64) -> anyhow::Result<bool> {
    let read: Option<bool> =
        sqlx::query_scalar("SELECT read FROM entry_state WHERE did = ?1 AND entry_id = ?2")
            .bind(did)
            .bind(entry_id)
            .fetch_optional(pool)
            .await?
            .flatten();
    Ok(read.unwrap_or(false))
}

/// Whether `entry_id` is starred for `did` (absent state row = not starred).
async fn entry_is_starred(pool: &store::Pool, did: &str, entry_id: i64) -> anyhow::Result<bool> {
    let starred: Option<bool> =
        sqlx::query_scalar("SELECT starred FROM entry_state WHERE did = ?1 AND entry_id = ?2")
            .bind(did)
            .bind(entry_id)
            .fetch_optional(pool)
            .await?
            .flatten();
    Ok(starred.unwrap_or(false))
}

/// Feed display title for one entry's feed id (via a single lookup).
async fn feed_title_by_entry(pool: &store::Pool, feed_id: i64) -> String {
    match sqlx::query_as::<_, store::Feed>("SELECT * FROM feeds WHERE id = ?1")
        .bind(feed_id)
        .fetch_optional(pool)
        .await
    {
        Ok(Some(f)) => display_title(f.title.as_deref(), &f.url),
        _ => String::new(),
    }
}

/// Rebuild an [`EntryRow`] for an htmx swap after a read/star toggle. `read` may
/// be forced (mark-read path) or looked up (`None` — star path).
async fn build_entry_row(
    pool: &store::Pool,
    did: &str,
    id: i64,
    read: Option<bool>,
) -> anyhow::Result<Option<EntryRow>> {
    let entry = match get_entry_by_id(pool, did, id).await? {
        Some(e) => e,
        None => return Ok(None),
    };
    let read = match read {
        Some(r) => r,
        None => entry_is_read(pool, did, id).await?,
    };
    let starred = entry_is_starred(pool, did, id).await?;
    Ok(Some(EntryRow {
        id: entry.id,
        title: entry
            .title
            .clone()
            .filter(|t| !t.trim().is_empty())
            .unwrap_or_else(|| "(untitled)".to_string()),
        feed_title: feed_title_by_entry(pool, entry.feed_id).await,
        published: display_date(entry.published.as_deref()),
        read,
        starred,
        link: SafeLink::entry(id, ""),
        cached: true,
        rkey: String::new(),
    }))
}

/// RFC3339 "now" (UTC) — shared by handlers that stamp/compare timestamps.
fn now_rfc3339() -> String {
    chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}

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

    #[test]
    fn qenc_encodes_reserved() {
        assert_eq!(qenc("a b"), "a%20b");
        assert_eq!(
            qenc("https://example.com/feed.xml"),
            "https%3A%2F%2Fexample.com%2Ffeed.xml"
        );
        assert_eq!(
            qenc("at://did:plc:x/c/r"),
            "at%3A%2F%2Fdid%3Aplc%3Ax%2Fc%2Fr"
        );
        // Unreserved chars pass through untouched.
        assert_eq!(qenc("A-Za-z0-9-_.~"), "A-Za-z0-9-_.~");
    }

    #[test]
    fn folder_uri_shape() {
        assert_eq!(
            folder_uri("did:plc:abc", "3kfolder"),
            "at://did:plc:abc/community.lexicon.rss.folder/3kfolder"
        );
    }

    // -- public-feeds-only: private/paid feeds are refused --------------------

    #[test]
    fn private_feeds_are_classified_private_across_providers() {
        // The add + OPML paths both gate on this classifier; assert it flags a
        // spread of paid providers (newsletters + private podcasts) and the
        // generic credential-in-URL shapes.
        for url in [
            "https://author.substack.com/feed/private/deadbeefcafe1234",
            "https://www.patreon.com/rss/author?auth=Zm9vYmFyc2VjcmV0dG9rZW4",
            "https://blog.ghost.io/rss/?uuid=1f2e3d4c-5b6a-7089-90ab-cdef01234567",
            "https://feeds.supportingcast.fm/show/abcdef0123456789abcdef01",
            "https://example.com/feed?token=Zm9vYmFyc2VjcmV0",
            "https://user:pass@example.com/feed",
        ] {
            assert!(
                feed::classify_feed_privacy(url).is_private(),
                "expected private: {url}"
            );
        }
    }

    #[test]
    fn public_feeds_stay_public() {
        for url in [
            "https://author.substack.com/feed",
            "https://wordpress.example.com/feed/",
            "https://example.com/rss.xml",
            "https://example.org/atom.xml",
            // YouTube channel/playlist RSS is fully public — must not false-block.
            "https://www.youtube.com/feeds/videos.xml?channel_id=UC-lHJZR3Gqxm24_Vd_AJ5Yw",
            "https://www.youtube.com/feeds/videos.xml?playlist_id=PLFgquLnL59alCl_2TQvOiD5Vgm1",
        ] {
            assert!(
                !feed::classify_feed_privacy(url).is_private(),
                "expected public: {url}"
            );
        }
    }

    #[test]
    fn private_feed_label_is_public_safe_host_only() {
        // The OPML skip report must never echo the secret path/query, only the host.
        let label =
            private_feed_label("https://author.substack.com/feed/private/deadbeefcafe1234token");
        assert_eq!(label, "author.substack.com");
        assert!(!label.contains("deadbeefcafe1234token"));
        assert!(!label.contains("/private/"));
        // An unparseable URL degrades to a generic label.
        assert_eq!(private_feed_label("not a url"), "a private feed");
    }

    #[test]
    fn refusal_message_promises_nothing_stored() {
        assert!(PRIVATE_FEED_REFUSAL.contains("not saved or sent anywhere"));
        assert!(PRIVATE_FEED_REFUSAL.contains("public feeds"));
    }

    #[test]
    fn scope_query_preserves_context() {
        let q = EntryQuery {
            feed: Some("https://example.com/feed.xml".to_string()),
            folder: None,
            view: Some("all".to_string()),
        };
        let s = scope_query(&q);
        assert!(s.contains("feed=https%3A%2F%2Fexample.com%2Ffeed.xml"));
        assert!(s.contains("view=all"));

        // Default view is omitted.
        let q2 = EntryQuery {
            feed: None,
            folder: None,
            view: Some("unread".to_string()),
        };
        assert_eq!(scope_query(&q2), "");
    }

    // -- closed-beta invite gate + rate-limit + cache-control ------------------

    use axum::body::Body;
    use axum::http::Request;
    use tower::ServiceExt; // for `oneshot`

    /// Build an [`AppState`] over a fresh in-memory DB, seeding the given admin
    /// DIDs (via ALLOWED_DIDS → ensure_seed) and a fixed cookie secret so tests
    /// can forge matching cookies.
    async fn test_state(allowed: &[&str]) -> AppState {
        let db = store::init_url("sqlite::memory:").await.unwrap();
        let dids: Vec<String> = allowed.iter().map(|s| s.to_string()).collect();
        store::ensure_seed(&db, &dids).await.unwrap();
        let config = Config {
            allowed_dids: dids,
            cookie_secret: "test-cookie-secret-000".to_string(),
            beta_cap: 3,
            ..Config::default()
        };
        AppState::new(config, db).unwrap()
    }

    /// A `Cookie` header carrying a valid signed session for `sid` (the sid is
    /// looked up in the registry, so create the session first).
    fn session_cookie(state: &AppState, did: &str, handle: Option<&str>) -> String {
        let sid = state.sessions.create(Session {
            did: did.to_string(),
            handle: handle.map(str::to_string),
        });
        let sc = cookie::sign_session(&sid, &state.config.cookie_secret);
        sc.split(';').next().unwrap().to_string()
    }

    /// The bucket map is bounded by COUNT, not only by idle time. An hour is a
    /// long time to accept distinct source IPs on two unauthenticated guarded
    /// routes.
    #[test]
    fn the_rate_limit_map_is_bounded() {
        let rl = RateLimiter::shared();
        let now = Instant::now();
        for i in 0..(MAX_RATE_BUCKETS + 2_000) {
            // Distinct IPv6 addresses, all "seen" at increasing times so the LRU
            // ordering below is well-defined.
            let ip: IpAddr = format!("2001:db8::{i:x}").parse().unwrap();
            rl.check_at(ip, now + Duration::from_millis(i as u64));
        }
        let len = rl.inner.lock().unwrap().buckets.len();
        assert!(
            len <= MAX_RATE_BUCKETS,
            "the rate-limit map grew to {len}, past its {MAX_RATE_BUCKETS} cap"
        );
    }

    /// Eviction must not hand a throttled attacker a fresh burst.
    ///
    /// The bound is LRU, so the one bucket an attacker can never evict is their
    /// own — it is the most recently touched thing in the map. If this inverted,
    /// the size cap would become a rate-limit bypass: spray addresses until the
    /// map overflows, then resume.
    #[test]
    fn flooding_the_map_does_not_reset_the_flooders_own_bucket() {
        let rl = RateLimiter::shared();
        let base = Instant::now();
        let attacker: IpAddr = "203.0.113.7".parse().unwrap();
        // Nanosecond steps: enough to keep the LRU ordering strictly increasing,
        // far too little for `RATE_REFILL_PER_SEC` to hand back a token. A
        // millisecond step made the whole flood take a second, and the refill —
        // working correctly — then looked exactly like an eviction bypass.
        let at = |n: u64| base + Duration::from_nanos(n);

        // Spend the burst. `RATE_BURST` allowed, then refused.
        for i in 0..(RATE_BURST as u64) {
            assert!(rl.check_at(attacker, at(i)));
        }
        assert!(
            !rl.check_at(attacker, at(RATE_BURST as u64)),
            "burst was not exhausted; the rest of this test proves nothing"
        );

        // Now overflow the map from other addresses, interleaving the attacker
        // so their bucket stays hot — the realistic shape of the attack.
        for i in 0..(MAX_RATE_BUCKETS + 2_000) {
            let t = at(100 + i as u64 * 2);
            let ip: IpAddr = format!("2001:db8:1::{i:x}").parse().unwrap();
            rl.check_at(ip, t);
            assert!(
                !rl.check_at(attacker, t),
                "the attacker got a token back after evictions at i={i}"
            );
        }
    }

    /// The idle sweep is amortised, not per-request. It used to be an O(n) scan
    /// of the whole map on every guarded request, on one shared core.
    #[test]
    fn the_idle_sweep_does_not_run_on_every_request() {
        let rl = RateLimiter::shared();
        let start = Instant::now();
        let a: IpAddr = "198.51.100.1".parse().unwrap();
        let b: IpAddr = "198.51.100.2".parse().unwrap();

        rl.check_at(a, start);
        // `b` arrives an hour later: `a` is now idle past `RATE_IDLE_EVICT`, but
        // the sweep interval has elapsed too, so this request does sweep it.
        rl.check_at(b, start + RATE_IDLE_EVICT + Duration::from_secs(1));
        assert!(
            !rl.inner.lock().unwrap().buckets.contains_key(&a),
            "an idle bucket survived a sweep that was due"
        );

        // A second request moments later must NOT re-sweep — `b` is still there,
        // and the recorded sweep time must not have moved.
        let before = rl.inner.lock().unwrap().last_sweep;
        rl.check_at(b, start + RATE_IDLE_EVICT + Duration::from_secs(2));
        assert_eq!(
            rl.inner.lock().unwrap().last_sweep,
            before,
            "the sweep ran again within the interval"
        );
    }

    #[test]
    fn rate_limited_paths_match_expected() {
        use axum::http::Method;
        assert!(is_rate_limited_path("/login", &Method::GET));
        assert!(is_rate_limited_path("/login", &Method::POST));
        assert!(is_rate_limited_path("/beta/redeem", &Method::POST));
        assert!(is_rate_limited_path("/subscriptions", &Method::POST));
        assert!(is_rate_limited_path("/opml", &Method::POST));
        assert!(is_rate_limited_path("/read-all", &Method::POST));
        assert!(is_rate_limited_path("/admin/invites", &Method::POST));
        assert!(is_rate_limited_path("/entries/42/read", &Method::POST));
        assert!(is_rate_limited_path("/entries/42/star", &Method::POST));
        // Read-only navigation is NOT limited.
        assert!(!is_rate_limited_path("/", &Method::GET));
        assert!(!is_rate_limited_path("/about", &Method::GET));
        assert!(!is_rate_limited_path("/entries/42", &Method::GET));
        assert!(!is_rate_limited_path("/login", &Method::HEAD));
    }

    #[test]
    fn rate_limiter_allows_burst_then_429s() {
        let rl = RateLimiter::shared();
        let ip: IpAddr = "203.0.113.7".parse().unwrap();
        // The full burst passes.
        for _ in 0..(RATE_BURST as usize) {
            assert!(rl.check(ip));
        }
        // The next one (no time elapsed → no refill) is rejected.
        assert!(!rl.check(ip));
        // A different IP has its own bucket.
        let ip2: IpAddr = "203.0.113.8".parse().unwrap();
        assert!(rl.check(ip2));
    }

    #[test]
    fn client_ip_ignores_spoofed_xff_without_trusted_header() {
        // With NO trusted header configured, a client-supplied X-Forwarded-For
        // must be ignored entirely — the limiter keys on the real socket peer,
        // so an attacker can't mint a fresh bucket per forged XFF value.
        let mut h = HeaderMap::new();
        h.insert("x-forwarded-for", "198.51.100.9, 10.0.0.1".parse().unwrap());
        let sock: SocketAddr = "203.0.113.55:1234".parse().unwrap();
        assert_eq!(
            client_ip(&h, Some(&sock), None),
            Some("203.0.113.55".parse().unwrap()),
            "spoofed XFF must not override the socket peer"
        );
    }

    #[test]
    fn client_ip_uses_trusted_header_last_hop() {
        // With a trusted proxy header configured, the client IP comes from THAT
        // header (the proxy overwrites any client copy). On a comma list we take
        // the RIGHT-most hop — the one the trusted proxy appended — so a
        // client-forged left-most value is ignored.
        let sock: SocketAddr = "10.0.0.1:1234".parse().unwrap();

        let mut h = HeaderMap::new();
        h.insert("fly-client-ip", "198.51.100.9".parse().unwrap());
        assert_eq!(
            client_ip(&h, Some(&sock), Some("fly-client-ip")),
            Some("198.51.100.9".parse().unwrap())
        );

        // Attacker prepends a forged hop; the trusted proxy appends the real one.
        let mut h2 = HeaderMap::new();
        h2.insert("x-forwarded-for", "1.2.3.4, 198.51.100.9".parse().unwrap());
        assert_eq!(
            client_ip(&h2, Some(&sock), Some("x-forwarded-for")),
            Some("198.51.100.9".parse().unwrap()),
            "must take the right-most (trusted) hop, not the forged left-most"
        );

        // Trusted header absent → fall back to the socket peer.
        let h3 = HeaderMap::new();
        assert_eq!(
            client_ip(&h3, Some(&sock), Some("fly-client-ip")),
            Some("10.0.0.1".parse().unwrap())
        );
    }

    #[test]
    fn invite_cookie_round_trips_and_rejects_tamper() {
        let secret = "test-cookie-secret-000";
        let sc = sign_invite("FEATHER-ABCDWXYZ", secret);
        let pair = sc.split(';').next().unwrap();
        let mut h = HeaderMap::new();
        h.insert(header::COOKIE, pair.parse().unwrap());
        assert_eq!(
            invite_cookie_code(&h, secret).as_deref(),
            Some("FEATHER-ABCDWXYZ")
        );
        // Wrong secret → rejected.
        assert!(invite_cookie_code(&h, "other").is_none());
    }

    #[tokio::test]
    async fn preflight_valid_expired_and_full() {
        let state = test_state(&["did:plc:admin"]).await;
        // A minted, active code preflights OK.
        let code = store::mint_code(&state.db, "did:plc:admin", 3600)
            .await
            .unwrap();
        assert!(preflight_code(&state, &code).await.is_ok());

        // A code whose expiry is in the past preflights as Expired. (mint_code
        // clamps negative ttl to 0, so back-date the row directly for a
        // deterministic past expiry.)
        let expired = store::mint_code(&state.db, "did:plc:admin", 3600)
            .await
            .unwrap();
        sqlx::query("UPDATE invite_codes SET expires_at = ?1 WHERE code = ?2")
            .bind(chrono::Utc::now().timestamp() - 3600)
            .bind(&expired)
            .execute(&state.db)
            .await
            .unwrap();
        assert_eq!(
            preflight_code(&state, &expired).await,
            Err(store::RedeemError::Expired)
        );

        // Unknown code → NotFound.
        assert_eq!(
            preflight_code(&state, "FEATHER-NOPENOPE").await,
            Err(store::RedeemError::NotFound)
        );

        // Fill to cap (cap=3; the admin seed already took 1 seat) then preflight
        // must report CapacityFull.
        store::grant_access(&state.db, "did:plc:b", None, "admin", None)
            .await
            .unwrap();
        store::grant_access(&state.db, "did:plc:c", None, "admin", None)
            .await
            .unwrap();
        assert_eq!(store::count_beta_access(&state.db).await.unwrap(), 3);
        assert_eq!(
            preflight_code(&state, &code).await,
            Err(store::RedeemError::CapacityFull)
        );
    }

    // -- Bot claim link + shared-secret mint ---------------------------------

    /// A test state with a configured bot secret (so `/bot/claims` is live).
    async fn bot_state(bot_secret: &str) -> AppState {
        let db = store::init_url("sqlite::memory:").await.unwrap();
        store::ensure_seed(&db, &["did:plc:admin".to_string()])
            .await
            .unwrap();
        let config = Config {
            allowed_dids: vec!["did:plc:admin".to_string()],
            cookie_secret: "test-cookie-secret-000".to_string(),
            beta_cap: 3,
            bot_secret: Some(bot_secret.to_string()),
            public_url: "https://feather-reader.com".to_string(),
            ..Config::default()
        };
        AppState::new(config, db).unwrap()
    }

    #[test]
    fn claim_token_round_trips_and_rejects_tamper() {
        let secret = "test-cookie-secret-000";
        let token = sign_claim_token("FEATHER-ABCDWXYZ", secret);
        // No cookie framing — a bare URL-safe token.
        assert!(!token.contains(';'));
        assert_eq!(
            claim_token_code(&token, secret).as_deref(),
            Some("FEATHER-ABCDWXYZ")
        );
        // Wrong secret → rejected.
        assert!(claim_token_code(&token, "other").is_none());
        // Tampered token → rejected.
        let mut bad = token.clone();
        bad.push('x');
        assert!(claim_token_code(&bad, secret).is_none());
        // The token is NOT confidential: it is `b64url(code).<sig>`, so the code is
        // only base64-obscured (not verbatim, but TRIVIALLY decodable — anyone can
        // recover it WITHOUT the secret). The security is single-use + HMAC
        // integrity + rate-limit, not secrecy of the code. Assert the code half is
        // publicly decodable (a plain base64url decode, no secret involved).
        let (b64, _sig) = token.split_once('.').expect("token is b64.sig");
        assert_eq!(
            test_b64url_decode(b64).as_deref(),
            Some("FEATHER-ABCDWXYZ".as_bytes()),
            "the code half of the token is plain base64url, decodable by anyone"
        );
    }

    /// Minimal URL-safe base64 (no padding) decoder for the test above, proving the
    /// claim token's code half needs NO secret to recover (it is not confidential).
    fn test_b64url_decode(input: &str) -> Option<Vec<u8>> {
        fn val(c: u8) -> Option<u32> {
            match c {
                b'A'..=b'Z' => Some((c - b'A') as u32),
                b'a'..=b'z' => Some((c - b'a' + 26) as u32),
                b'0'..=b'9' => Some((c - b'0' + 52) as u32),
                b'-' => Some(62),
                b'_' => Some(63),
                _ => None,
            }
        }
        let mut out = Vec::with_capacity(input.len() / 4 * 3);
        for chunk in input.as_bytes().chunks(4) {
            let mut n = 0u32;
            let mut bits = 0;
            for &c in chunk {
                n = (n << 6) | val(c)?;
                bits += 6;
            }
            let bytes = bits / 8;
            n <<= 24 - bits;
            for i in 0..bytes {
                out.push((n >> (16 - i * 8)) as u8);
            }
        }
        Some(out)
    }

    #[tokio::test]
    async fn bot_mint_then_claim_grants_a_seat() {
        let state = bot_state("bot-secret-abcdef").await;
        let app = router(state.clone());

        // 1. Mint a claim via the shared-secret endpoint.
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/bot/claims")
                    .header("x-bot-secret", "bot-secret-abcdef")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        let token = json["token"].as_str().unwrap().to_string();
        let url = json["url"].as_str().unwrap();
        assert!(url.starts_with("https://feather-reader.com/claim?t="));
        // The raw code is returned for the bot's records but not embedded in url.
        assert!(json["code"].as_str().unwrap().starts_with("FEATHER-"));
        assert!(!url.contains("FEATHER-"));

        // 2. Follow the claim link → reserves the invite cookie + redirects to /login.
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri(format!("/claim?t={}", qenc(&token)))
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert_eq!(resp.headers().get(header::LOCATION).unwrap(), "/login");
        let set_cookie = resp
            .headers()
            .get(header::SET_COOKIE)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(set_cookie.starts_with(INVITE_COOKIE), "{set_cookie}");

        // 3. The reserved cookie carries the same code the token wrapped, and
        //    redeeming it (the callback's machinery) grants a seat.
        let code = claim_token_code(&token, &state.config.cookie_secret).unwrap();
        let out = store::redeem_code(
            &state.db,
            &code,
            "did:plc:follower",
            None,
            state.config.beta_cap,
        )
        .await
        .unwrap();
        assert_eq!(out, Ok(()));
        assert!(store::has_beta_access(&state.db, "did:plc:follower")
            .await
            .unwrap());
    }

    #[tokio::test]
    async fn claim_with_invalid_token_bounces() {
        let state = bot_state("bot-secret-abcdef").await;
        let app = router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/claim?t=not-a-real-token")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        // Renders the invite page (200), NOT a redirect to /login.
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn claim_with_used_token_is_refused() {
        let state = bot_state("bot-secret-abcdef").await;
        // Mint a code + wrap it, then redeem it out from under the token.
        let code = store::mint_code(&state.db, "did:plc:admin", 3600)
            .await
            .unwrap();
        let token = sign_claim_token(&code, &state.config.cookie_secret);
        store::redeem_code(
            &state.db,
            &code,
            "did:plc:someone",
            None,
            state.config.beta_cap,
        )
        .await
        .unwrap()
        .unwrap();
        let app = router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri(format!("/claim?t={}", qenc(&token)))
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        // A used code → the invite page (AlreadyRedeemed), not a fresh reservation.
        assert_eq!(resp.status(), StatusCode::OK);
        assert!(resp.headers().get(header::SET_COOKIE).is_none());
    }

    #[tokio::test]
    async fn bot_claims_rejects_bad_and_missing_secret() {
        let state = bot_state("bot-secret-abcdef").await;
        let app = router(state);
        // Wrong secret.
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/bot/claims")
                    .header("x-bot-secret", "wrong")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        // Missing secret.
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/bot/claims")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn bot_claims_disabled_when_secret_unset() {
        // test_state configures NO bot secret → the endpoint is off (503).
        let state = test_state(&["did:plc:admin"]).await;
        let app = router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/bot/claims")
                    .header("x-bot-secret", "anything")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    #[tokio::test]
    async fn bot_claims_refuses_at_capacity() {
        let state = bot_state("bot-secret-abcdef").await;
        // cap=3, admin seed took 1 seat. Grant 2 more to fill it.
        store::grant_access(&state.db, "did:plc:b", None, "admin", None)
            .await
            .unwrap();
        store::grant_access(&state.db, "did:plc:c", None, "admin", None)
            .await
            .unwrap();
        assert_eq!(store::count_beta_access(&state.db).await.unwrap(), 3);
        let app = router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/bot/claims")
                    .header("x-bot-secret", "bot-secret-abcdef")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::CONFLICT);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        assert!(String::from_utf8_lossy(&bytes).contains("full"));
    }

    #[tokio::test]
    async fn bot_claims_counts_outstanding_codes_against_cap() {
        let state = bot_state("bot-secret-abcdef").await;
        // cap=3, admin seed = 1 seat. Two outstanding active codes = 3 committed.
        store::mint_code(&state.db, "did:plc:admin", 3600)
            .await
            .unwrap();
        store::mint_code(&state.db, "did:plc:admin", 3600)
            .await
            .unwrap();
        let app = router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/bot/claims")
                    .header("x-bot-secret", "bot-secret-abcdef")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        // 1 seat + 2 outstanding >= cap 3 → refused even though only 1 real seat used.
        assert_eq!(resp.status(), StatusCode::CONFLICT);
    }

    /// POST /bot/claims with a JSON body carrying the follower DID.
    async fn post_bot_claim_for(
        app: &axum::Router,
        secret: &str,
        did: &str,
    ) -> (StatusCode, serde_json::Value) {
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/bot/claims")
                    .header("x-bot-secret", secret)
                    .header("content-type", "application/json")
                    .body(Body::from(format!(
                        "{{\"did\":\"{did}\",\"handle\":\"who.test\"}}"
                    )))
                    .unwrap(),
            )
            .await
            .unwrap();
        let status = resp.status();
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let json = if bytes.is_empty() {
            serde_json::Value::Null
        } else {
            serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null)
        };
        (status, json)
    }

    #[tokio::test]
    async fn bot_claims_returns_already_seated_for_a_member() {
        // A DID that already holds beta access must get `already_seated` with NO
        // code/url — the bot posts nothing. This is the server-side backstop that
        // survives a bot-host state loss (it would otherwise re-mint + re-post).
        let state = bot_state("bot-secret-abcdef").await;
        store::grant_access(&state.db, "did:plc:member", None, "admin", None)
            .await
            .unwrap();
        let app = router(state.clone());
        let (status, json) = post_bot_claim_for(&app, "bot-secret-abcdef", "did:plc:member").await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(json["status"], "already_seated");
        assert_eq!(json["code"], "");
        assert_eq!(json["url"], "");
        // No new invite code was minted for the seated DID.
        assert!(store::find_active_code_for_did(&state.db, "did:plc:member")
            .await
            .unwrap()
            .is_none());
    }

    #[tokio::test]
    async fn bot_claims_is_idempotent_per_did_returns_same_code() {
        // Two mint requests for the SAME follower DID must return the SAME code
        // (the app is authoritative), never a second one — so a bot-host state loss
        // re-requesting cannot double-mint or double-post.
        let state = bot_state("bot-secret-abcdef").await;
        let app = router(state.clone());

        let (s1, j1) = post_bot_claim_for(&app, "bot-secret-abcdef", "did:plc:follower1").await;
        assert_eq!(s1, StatusCode::OK);
        assert_eq!(j1["status"], "minted");
        let code1 = j1["code"].as_str().unwrap().to_string();

        let (s2, j2) = post_bot_claim_for(&app, "bot-secret-abcdef", "did:plc:follower1").await;
        assert_eq!(s2, StatusCode::OK);
        assert_eq!(j2["status"], "existing");
        assert_eq!(j2["code"].as_str().unwrap(), code1, "same code returned");
        assert_eq!(j2["url"], j1["url"], "same url returned");

        // Exactly ONE active code exists for that DID.
        assert_eq!(store::count_active_codes(&state.db).await.unwrap(), 1);
    }

    #[tokio::test]
    async fn bot_claims_records_intended_did_at_mint() {
        // A fresh mint records the follower DID so the lookup finds it.
        let state = bot_state("bot-secret-abcdef").await;
        let app = router(state.clone());
        let (status, json) =
            post_bot_claim_for(&app, "bot-secret-abcdef", "did:plc:follower2").await;
        assert_eq!(status, StatusCode::OK);
        let code = json["code"].as_str().unwrap();
        assert_eq!(
            store::find_active_code_for_did(&state.db, "did:plc:follower2")
                .await
                .unwrap()
                .as_deref(),
            Some(code)
        );
    }

    #[tokio::test]
    async fn bot_claims_concurrent_same_did_never_double_mints() {
        // S4: two concurrent /bot/claims for ONE follower DID must not both mint an
        // active code. The dedupe check (3b) and the mint are separate statements,
        // so a race can slip both past 3b's `Ok(None)`; the partial unique index
        // then makes the loser's INSERT conflict, and the handler recovers by
        // returning the winner's code (status `existing`) rather than 500-ing.
        // Result: exactly ONE active code, and BOTH callers get a usable code.
        let state = bot_state("bot-secret-abcdef").await;
        let app = router(state.clone());

        let a = post_bot_claim_for(&app, "bot-secret-abcdef", "did:plc:racer");
        let b = post_bot_claim_for(&app, "bot-secret-abcdef", "did:plc:racer");
        let ((sa, ja), (sb, jb)) = tokio::join!(a, b);

        assert_eq!(sa, StatusCode::OK, "first response: {ja:?}");
        assert_eq!(sb, StatusCode::OK, "second response: {jb:?}");

        // Exactly one active code for the DID — the whole point of the fix.
        assert_eq!(
            store::count_active_codes(&state.db).await.unwrap(),
            1,
            "concurrent mints must not create two active codes"
        );

        // Both callers received the SAME (single) code, and neither got a 500.
        let ca = ja["code"].as_str().unwrap_or("");
        let cb = jb["code"].as_str().unwrap_or("");
        assert!(!ca.is_empty() && !cb.is_empty(), "both must return a code");
        assert_eq!(ca, cb, "both callers must get the one minted code");
        // One is `minted` (the winner), the other `minted` or `existing` depending
        // on interleaving — but never an error status.
        for st in [&ja["status"], &jb["status"]] {
            let s = st.as_str().unwrap_or("");
            assert!(s == "minted" || s == "existing", "unexpected status {s:?}");
        }
    }

    #[tokio::test]
    async fn bot_claims_rejects_malformed_json_body() {
        let state = bot_state("bot-secret-abcdef").await;
        let app = router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/bot/claims")
                    .header("x-bot-secret", "bot-secret-abcdef")
                    .header("content-type", "application/json")
                    .body(Body::from("{not json"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn favicon_ico_served_at_root() {
        // Browsers request bare /favicon.ico regardless of the <link rel="icon">
        // tags in <head>; the root route must serve the icon, not 404.
        let state = test_state(&[]).await;
        let app = router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/favicon.ico")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let ct = resp
            .headers()
            .get(header::CONTENT_TYPE)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            ct.contains("icon") || ct.starts_with("image/"),
            "content-type = {ct}"
        );
    }

    #[tokio::test]
    async fn login_without_invite_redirects_to_beta_redeem() {
        // No allow-list seed, no invite cookie: starting OAuth must be refused.
        let state = test_state(&[]).await;
        let app = router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/login")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from("handle=alice.bsky.social"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert_eq!(
            resp.headers().get(header::LOCATION).unwrap(),
            "/beta/redeem"
        );
    }

    #[tokio::test]
    async fn login_with_valid_invite_cookie_starts_oauth() {
        let state = test_state(&[]).await;
        let cookie = sign_invite("FEATHER-ABCDWXYZ", &state.config.cookie_secret);
        let cookie = cookie.split(';').next().unwrap().to_string();
        let app = router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/login")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header(header::COOKIE, cookie)
                    .body(Body::from("handle=alice.bsky.social"))
                    .unwrap(),
            )
            .await
            .unwrap();
        // Redirects into the sidecar login (not to /beta/redeem).
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(loc.contains("/login"), "loc = {loc}");
        assert_ne!(loc, "/beta/redeem");
    }

    /// A resolver that always fails — proves the fast paths short-circuit BEFORE
    /// any network resolution and that a resolution failure fails closed.
    async fn resolver_never(_handle: String) -> Option<String> {
        None
    }

    /// A resolver that maps every handle to `did`.
    fn resolver_to(did: &'static str) -> impl FnOnce(String) -> std::future::Ready<Option<String>> {
        move |_handle| std::future::ready(Some(did.to_string()))
    }

    /// Path 3: a cookie-less visitor whose submitted handle resolves to a DID
    /// that already holds a seat (the seeded-admin first-login case) passes the
    /// gate — no session cookie, no invite code.
    #[tokio::test]
    async fn may_start_oauth_honors_seat_via_resolved_handle() {
        // The seeded admin holds a seat (via ALLOWED_DIDS → ensure_seed) but has
        // no cookie on a fresh deploy.
        let state = test_state(&["did:plc:admin"]).await;
        let headers = HeaderMap::new();
        assert!(
            may_start_oauth_with(
                &state,
                &headers,
                "admin.example",
                resolver_to("did:plc:admin")
            )
            .await,
            "a handle resolving to a seated DID must pass the gate"
        );
    }

    /// Path 3, negative: a handle that resolves to a DID with NO seat is bounced
    /// — the anti-abuse intent is preserved (resolution succeeds, seat check
    /// fails).
    #[tokio::test]
    async fn may_start_oauth_bounces_non_member_handle() {
        let state = test_state(&["did:plc:admin"]).await;
        let headers = HeaderMap::new();
        assert!(
            !may_start_oauth_with(
                &state,
                &headers,
                "rando.example",
                resolver_to("did:plc:rando")
            )
            .await,
            "a resolved DID with no seat must be bounced"
        );
    }

    /// Fail-closed: an unresolvable/malformed handle (resolver returns `None`)
    /// bounces gracefully — no panic, no handshake.
    #[tokio::test]
    async fn may_start_oauth_fails_closed_on_unresolvable_handle() {
        let state = test_state(&["did:plc:admin"]).await;
        let headers = HeaderMap::new();
        assert!(
            !may_start_oauth_with(&state, &headers, "not a handle", resolver_never).await,
            "an unresolvable handle must fail closed"
        );
    }

    /// The session-cookie fast path admits a seated member WITHOUT calling the
    /// resolver (proven by injecting `resolver_never`, which would otherwise
    /// bounce).
    #[tokio::test]
    async fn may_start_oauth_session_cookie_shortcircuits_resolution() {
        let state = test_state(&[]).await;
        let did = "did:plc:member";
        store::grant_access(&state.db, did, Some("member.example"), "test", None)
            .await
            .unwrap();
        let cookie = session_cookie(&state, did, Some("member.example"));
        let mut headers = HeaderMap::new();
        headers.insert(header::COOKIE, cookie.parse().unwrap());
        assert!(
            may_start_oauth_with(&state, &headers, "member.example", resolver_never).await,
            "a seated session cookie must pass without resolution"
        );
    }

    /// The invite-cookie fast path admits WITHOUT calling the resolver.
    #[tokio::test]
    async fn may_start_oauth_invite_cookie_shortcircuits_resolution() {
        let state = test_state(&[]).await;
        let cookie = sign_invite("FEATHER-ABCDWXYZ", &state.config.cookie_secret);
        let cookie = cookie.split(';').next().unwrap().to_string();
        let mut headers = HeaderMap::new();
        headers.insert(header::COOKIE, cookie.parse().unwrap());
        assert!(
            may_start_oauth_with(&state, &headers, "someone.example", resolver_never).await,
            "a valid invite cookie must pass without resolution"
        );
    }

    #[tokio::test]
    async fn admin_mint_requires_admin_seed_did() {
        let state = test_state(&["did:plc:admin"]).await;
        // A non-admin (but beta'd) session is forbidden.
        store::grant_access(&state.db, "did:plc:rando", None, "test", None)
            .await
            .unwrap();
        let rando_cookie = session_cookie(&state, "did:plc:rando", None);
        // An admin session is allowed.
        let admin_cookie = session_cookie(&state, "did:plc:admin", None);
        let app = router(state);

        let forbidden = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/admin/invites?n=2")
                    .header(header::COOKIE, rando_cookie)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(forbidden.status(), StatusCode::FORBIDDEN);

        let ok = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/admin/invites?n=2")
                    .header(header::COOKIE, admin_cookie)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(ok.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(ok.into_body(), 64 * 1024)
            .await
            .unwrap();
        let body = String::from_utf8(bytes.to_vec()).unwrap();
        let minted: Vec<&str> = body.lines().filter(|l| !l.is_empty()).collect();
        assert_eq!(minted.len(), 2);
        assert!(minted.iter().all(|c| c.starts_with("FEATHER-")));
    }

    #[tokio::test]
    async fn admin_mint_unauthenticated_is_401() {
        let state = test_state(&["did:plc:admin"]).await;
        let app = router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/admin/invites")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    /// A state whose `/about` renders the adoption line, seeded with one
    /// observation.
    async fn adoption_state(repos: i64, truncated: bool) -> AppState {
        let db = store::init_url("sqlite::memory:").await.unwrap();
        store::record_network_stat(
            &db,
            &store::NetworkStat {
                key: store::ADOPTION_STAT_KEY.to_string(),
                source: "https://relay1.us-west.bsky.network".to_string(),
                value: repos,
                truncated,
                observed_at: "2026-08-13T04:05:06Z".to_string(),
            },
        )
        .await
        .unwrap();
        let config = Config {
            cookie_secret: "test-cookie-secret-000".to_string(),
            show_adoption: true,
            ..Config::default()
        };
        AppState::new(config, db).unwrap()
    }

    async fn about_body(state: AppState) -> String {
        let resp = router(state)
            .oneshot(
                Request::builder()
                    .uri("/about")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), 256 * 1024)
            .await
            .unwrap();
        String::from_utf8(bytes.to_vec()).unwrap()
    }

    /// Default config ⇒ the flag is off ⇒ no line, and no query is issued.
    #[tokio::test]
    async fn about_omits_adoption_line_by_default() {
        let state = test_state(&[]).await;
        assert!(!state.config.show_adoption);
        let body = about_body(state).await;
        assert!(
            !body.contains("atproto network"),
            "the adoption line must not render by default"
        );
    }

    #[tokio::test]
    async fn about_renders_adoption_line_when_enabled() {
        // **A distinctive count, and asserted IN ITS SENTENCE.**
        //
        // This used to seed 4 and assert `body.contains("4")`, which the
        // colophon's `width="44"` satisfies whatever the count is — so
        // hardcoding the rendered number passed. Both halves are needed: a
        // digit that does not occur incidentally, and the assertion tied to the
        // phrase it belongs to.
        let body = about_body(adoption_state(7_318, false).await).await;
        // The count and its phrase are on separate template lines, so compare
        // against a whitespace-collapsed copy rather than the raw HTML.
        let flat = body.split_whitespace().collect::<Vec<_>>().join(" ");
        assert!(
            flat.contains("7318 accounts on the atproto network hold"),
            "the count did not render in its own sentence: {flat}",
        );
        assert!(
            body.contains("accounts on the atproto network hold"),
            "{body}"
        );
        assert!(
            body.contains("2026-08-13"),
            "the observation date must render"
        );
        assert!(
            body.contains("lower bound"),
            "the non-archival caveat must ride along with the number"
        );
        assert!(
            !body.contains("At least"),
            "an untruncated count is exact-ish"
        );
    }

    /// A count of one must read as "1 account … holds", not "1 accounts … hold".
    #[tokio::test]
    async fn about_adoption_line_is_singular_at_one() {
        let body = about_body(adoption_state(1, false).await).await;
        assert!(
            body.contains("account on the atproto network holds"),
            "{body}"
        );
    }

    /// A truncated observation is a floor, and must say so.
    #[tokio::test]
    async fn about_adoption_line_says_at_least_when_truncated() {
        let body = about_body(adoption_state(25_000, true).await).await;
        assert!(body.contains("At least"), "{body}");
    }

    /// Flag on but no observation (or a zero) ⇒ 200, no line, no error.
    #[tokio::test]
    async fn about_omits_line_when_enabled_with_no_observation() {
        let db = store::init_url("sqlite::memory:").await.unwrap();
        let config = Config {
            cookie_secret: "test-cookie-secret-000".to_string(),
            show_adoption: true,
            ..Config::default()
        };
        let body = about_body(AppState::new(config, db).unwrap()).await;
        assert!(!body.contains("atproto network"));
    }

    // ---- standard.site on the public pages and the subscribe form ----------
    //
    // `FEATHERREADER_STANDARD_SITE` gates what may be STORED (`add_subscription`
    // refuses every `at://` paste with it off), so a page that tells the reader
    // to paste a publication URI is advertising a form that will be refused
    // unless the flag is on. These pin both halves: with the flag on the pages
    // say how; with it off they do not.

    /// A state with the standard.site flag chosen, and `did` holding a seat so
    /// `/manage` renders for it.
    async fn standard_site_state(standard_site: bool, did: &str) -> AppState {
        let db = store::init_url("sqlite::memory:").await.unwrap();
        store::ensure_seed(&db, &[did.to_string()]).await.unwrap();
        let config = Config {
            allowed_dids: vec![did.to_string()],
            cookie_secret: "test-cookie-secret-000".to_string(),
            beta_cap: 3,
            standard_site,
            ..Config::default()
        };
        AppState::new(config, db).unwrap()
    }

    /// `GET path` as `did`, asserted 200, body as a string.
    async fn signed_in_body(state: AppState, path: &str, did: &str) -> String {
        let cookie = session_cookie(&state, did, Some("reader.example"));
        let resp = router(state)
            .oneshot(
                Request::builder()
                    .uri(path)
                    .header(header::COOKIE, cookie)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK, "{path}");
        let bytes = axum::body::to_bytes(resp.into_body(), 512 * 1024)
            .await
            .unwrap();
        String::from_utf8(bytes.to_vec()).unwrap()
    }

    /// `GET path` signed out, asserted 200, body as a string.
    async fn public_body(state: AppState, path: &str) -> String {
        let resp = router(state)
            .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK, "{path}");
        let bytes = axum::body::to_bytes(resp.into_body(), 512 * 1024)
            .await
            .unwrap();
        String::from_utf8(bytes.to_vec()).unwrap()
    }

    /// The `<input … id="feed-url" …>` tag of the subscribe form, whole.
    fn feed_url_input(body: &str) -> &str {
        let start = body
            .find("id=\"feed-url\"")
            .and_then(|i| body[..i].rfind("<input"))
            .expect("the subscribe form's URL input renders");
        let end = body[start..].find('>').expect("the input tag closes") + start + 1;
        &body[start..end]
    }

    /// Flag on: the subscribe form says a publication URI is accepted, and shows
    /// both spellings the handler takes (DID and handle).
    #[tokio::test]
    async fn manage_hints_at_publications_when_the_flag_is_on() {
        let did = "did:plc:reader";
        let body = signed_in_body(standard_site_state(true, did).await, "/manage", did).await;
        assert!(
            body.contains("at://did:plc:…/site.standard.publication/…"),
            "the DID form must be shown: {body}"
        );
        assert!(
            body.contains("at://alice.example.com/site.standard.publication/…"),
            "the handle form must be shown: {body}"
        );
    }

    /// Flag on: the URL input must not be `type="url"`. A browser validates
    /// that type with the WHATWG URL parser, which REJECTS the DID form —
    /// `at://did:plc:…/…` fails as an invalid port, the same failure
    /// `url::Url::parse` has (see `feed::is_storable_feed_url`) — so the form
    /// would refuse to submit the very string the hint asks for.
    #[tokio::test]
    async fn manage_url_input_accepts_a_did_uri_when_the_flag_is_on() {
        let did = "did:plc:reader";
        let body = signed_in_body(standard_site_state(true, did).await, "/manage", did).await;
        let input = feed_url_input(&body);
        assert!(
            input.contains("type=\"text\""),
            "the input must be type=text so a DID-form at:// URI can be submitted: {input}"
        );
        assert!(
            input.contains("inputmode=\"url\""),
            "the URL keyboard is still wanted: {input}"
        );
    }

    /// Flag on, `type="text"` drops the browser's scheme check, so a pasted
    /// `example.com/blog` would reach the handler and come back as "Couldn't
    /// find a feed" — wrong, the site likely has one. A `pattern` keeps the
    /// browser asking for a scheme while still admitting `at://` (both cases:
    /// the handler canonicalises the scheme).
    #[tokio::test]
    async fn manage_url_input_still_requires_a_scheme_when_the_flag_is_on() {
        let did = "did:plc:reader";
        let body = signed_in_body(standard_site_state(true, did).await, "/manage", did).await;
        let input = feed_url_input(&body);
        assert!(
            input.contains(&format!("pattern=\"{FEED_URL_PATTERN}\"")),
            "the text input must keep a scheme check: {input}"
        );
    }

    /// Flag off: every `at://` paste is refused, so the form must not say
    /// publications are accepted — and the input keeps browser URL validation.
    #[tokio::test]
    async fn manage_does_not_advertise_publications_when_the_flag_is_off() {
        let did = "did:plc:reader";
        let state = standard_site_state(false, did).await;
        assert!(!state.config.standard_site);
        let page = signed_in_body(state, "/manage", did).await;
        // The `<head>` carries the site's link card, whose one-line description
        // names standard.site whatever the flag says — as the landing page does
        // with the flag off (a stored publication is polled regardless). What
        // must not advertise is the page: everything after `</head>`.
        let body = &page[page.find("</head>").expect("a <head>")..];
        assert!(
            !body.contains("site.standard.publication"),
            "a refused form must not be advertised: {body}"
        );
        // The shared footer links the `/standard-site` feature page on every
        // page, flag on or off — that page itself says the instance isn't
        // accepting new publication subscriptions — so the check is on the
        // page above the footer, where the form and its hints are.
        let above_footer = body
            .split("<footer")
            .next()
            .expect("split yields at least one piece");
        assert!(
            above_footer.contains("id=\"feed-url\""),
            "the form must be above the footer: {body}"
        );
        assert!(
            !above_footer.contains("standard.site"),
            "a refused form must not be advertised: {body}"
        );
        assert!(
            feed_url_input(body).contains("type=\"url\""),
            "with the flag off the input is unchanged"
        );
    }

    /// Flag on: the landing page says publications sit beside feeds AND how to
    /// subscribe to one.
    #[tokio::test]
    async fn landing_describes_publications_and_how_to_subscribe_when_on() {
        let body = public_body(standard_site_state(true, "did:plc:x").await, "/").await;
        assert!(body.contains("standard.site"), "{body}");
        assert!(
            body.contains("at://did:plc:…/site.standard.publication/…"),
            "the landing page must show the DID form: {body}"
        );
        assert!(
            body.contains("at://alice.example.com/site.standard.publication/…"),
            "the landing page must show the handle form: {body}"
        );
    }

    /// Flag off: the landing page still says what a publication is (a stored
    /// one is polled whatever the flag says), but shows no paste instructions
    /// and says new ones are not accepted here.
    #[tokio::test]
    async fn landing_does_not_tell_visitors_to_paste_a_publication_when_off() {
        let body = public_body(standard_site_state(false, "did:plc:x").await, "/").await;
        assert!(body.contains("standard.site"), "{body}");
        assert!(
            !body.contains("at://did:plc:…/site.standard.publication/…"),
            "no paste instructions with the flag off: {body}"
        );
        assert!(
            !body.contains("at://alice.example.com/site.standard.publication/…"),
            "no paste instructions with the flag off: {body}"
        );
        assert!(
            body.contains("isn't accepting new publication subscriptions"),
            "the page must say the form is closed here: {body}"
        );
    }

    /// Flag on: /about has a publications section with both spellings.
    #[tokio::test]
    async fn about_describes_publications_and_how_to_subscribe_when_on() {
        let body = public_body(standard_site_state(true, "did:plc:x").await, "/about").await;
        assert!(body.contains("site.standard.publication"), "{body}");
        assert!(body.contains("site.standard.document"), "{body}");
        assert!(
            body.contains("at://did:plc:…/site.standard.publication/…"),
            "{body}"
        );
        assert!(
            body.contains("at://alice.example.com/site.standard.publication/…"),
            "{body}"
        );
    }

    /// Flag off: /about keeps the description, drops the paste instructions.
    #[tokio::test]
    async fn about_does_not_tell_visitors_to_paste_a_publication_when_off() {
        let body = public_body(standard_site_state(false, "did:plc:x").await, "/about").await;
        assert!(body.contains("site.standard.publication"), "{body}");
        assert!(
            !body.contains("at://did:plc:…/site.standard.publication/…"),
            "no paste instructions with the flag off: {body}"
        );
        assert!(
            !body.contains("at://alice.example.com/site.standard.publication/…"),
            "no paste instructions with the flag off: {body}"
        );
        assert!(
            body.contains("isn't accepting new publication subscriptions"),
            "{body}"
        );
    }

    // ---- the standard.site feature page (`/standard-site`) -----------------
    //
    // A public page, like `/about`: what a publication is, what is shown from
    // it, how to subscribe (flag-conditional, as on the other public pages),
    // and the honest limits. It also carries the "latest releases" call-out.

    /// Signed out, with the default config, the page renders.
    #[tokio::test]
    async fn standard_site_page_renders_signed_out() {
        let body = public_body(test_state(&[]).await, "/standard-site").await;
        assert!(body.contains("site.standard.publication"), "{body}");
        assert!(body.contains("site.standard.document"), "{body}");
        assert!(
            body.contains("<title>standard.site — FeatherReader</title>"),
            "{body}"
        );
    }

    /// Flag on: the page says how to subscribe, in both spellings, and that a
    /// handle is resolved to its DID.
    #[tokio::test]
    async fn standard_site_page_tells_how_to_subscribe_when_on() {
        let body = public_body(
            standard_site_state(true, "did:plc:x").await,
            "/standard-site",
        )
        .await;
        assert!(
            body.contains("at://did:plc:…/site.standard.publication/…"),
            "the DID form must be shown: {body}"
        );
        assert!(
            body.contains("at://alice.example.com/site.standard.publication/…"),
            "the handle form must be shown: {body}"
        );
        assert!(
            body.contains("resolved to its DID"),
            "the handle resolution must be stated: {body}"
        );
        assert!(
            !body.contains("isn't accepting new publication subscriptions"),
            "{body}"
        );
    }

    /// Flag off: `add_subscription` refuses every `at://` paste, so the page
    /// must not tell visitors to paste one — it says new publication
    /// subscriptions are not accepted here, and that stored ones are still read.
    #[tokio::test]
    async fn standard_site_page_does_not_tell_visitors_to_paste_when_off() {
        let state = standard_site_state(false, "did:plc:x").await;
        assert!(!state.config.standard_site);
        let body = public_body(state, "/standard-site").await;
        assert!(body.contains("site.standard.publication"), "{body}");
        assert!(
            !body.contains("at://did:plc:…/site.standard.publication/…"),
            "no paste instructions with the flag off: {body}"
        );
        assert!(
            !body.contains("at://alice.example.com/site.standard.publication/…"),
            "no paste instructions with the flag off: {body}"
        );
        assert!(
            body.contains("isn't accepting new publication subscriptions"),
            "the page must say the form is closed here: {body}"
        );
        assert!(
            body.contains("already follows are still read"),
            "stored publications are polled whatever the flag says: {body}"
        );
    }

    /// The releases call-out links each release's GitHub page and the
    /// changelog, on the feature page and on the landing page.
    #[tokio::test]
    async fn releases_callout_links_the_release_pages() {
        for path in ["/standard-site", "/"] {
            let body = public_body(test_state(&[]).await, path).await;
            for tag in ["v0.4.1", "v0.4.0"] {
                let href = format!(
                    "href=\"https://github.com/justin-stanley/feather-reader/releases/tag/{tag}\""
                );
                assert!(body.contains(&href), "{path} must link {tag}: {body}");
            }
            assert!(
                body.contains(
                    "https://github.com/justin-stanley/feather-reader/blob/main/CHANGELOG.md"
                ),
                "{path} must link the changelog: {body}"
            );
        }
    }

    /// The feature page is reachable from the landing page, from `/about`, and
    /// from the shared footer (`/privacy` renders nothing but prose and that
    /// footer, so it stands in for every page that includes it).
    #[tokio::test]
    async fn landing_about_and_footer_link_the_standard_site_page() {
        for path in ["/", "/about", "/privacy"] {
            let body = public_body(test_state(&[]).await, path).await;
            assert!(
                body.contains("href=\"/standard-site\""),
                "{path} must link the feature page: {body}"
            );
        }
    }

    /// `RELEASES` is the one place a release is described, so its shape is
    /// pinned: newest first, dates as the CHANGELOG headings spell them, and
    /// both derived links pointing where the template promises.
    #[test]
    fn releases_are_newest_first_and_link_the_tag_and_changelog() {
        assert!(!RELEASES.is_empty());
        let parse = |v: &str| -> Vec<u32> {
            v.split('.')
                .map(|p| p.parse::<u32>().expect("a numeric version part"))
                .collect()
        };
        for pair in RELEASES.windows(2) {
            assert!(
                parse(pair[0].version) > parse(pair[1].version),
                "{} must come before {}",
                pair[0].version,
                pair[1].version
            );
        }
        for r in RELEASES {
            assert_eq!(parse(r.version).len(), 3, "{}", r.version);
            assert!(
                chrono::NaiveDate::parse_from_str(r.date, "%Y-%m-%d").is_ok(),
                "{} is not YYYY-MM-DD",
                r.date
            );
            assert!(!r.summary.trim().is_empty());
            assert!(!r.summary.contains('<'), "the summary is plain text");
            assert_eq!(
                r.url(),
                format!(
                    "https://github.com/justin-stanley/feather-reader/releases/tag/v{}",
                    r.version
                )
            );
        }
        // The newest entry is this build's own version, so a release cannot
        // ship without adding itself to the call-out.
        let latest = &RELEASES[0];
        assert_eq!(latest.version, env!("CARGO_PKG_VERSION"));
        assert_eq!(
            latest.changelog_url(),
            "https://github.com/justin-stanley/feather-reader/blob/main/CHANGELOG.md#045--2026-10-06"
        );
    }

    /// Public and static like `/about`, so it is cacheable on the same terms.
    #[tokio::test]
    async fn standard_site_page_is_publicly_cacheable() {
        let resp = router(test_state(&[]).await)
            .oneshot(
                Request::builder()
                    .uri("/standard-site")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            resp.headers().get(header::CACHE_CONTROL).unwrap(),
            "public, max-age=300"
        );
    }

    #[tokio::test]
    async fn cache_control_public_on_about_no_store_on_authed() {
        let state = test_state(&["did:plc:admin"]).await;
        let admin_cookie = session_cookie(&state, "did:plc:admin", None);
        let app = router(state);

        // /about → public, cacheable.
        let about = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/about")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            about.headers().get(header::CACHE_CONTROL).unwrap(),
            "public, max-age=300"
        );
        // The security headers are still intact.
        // The VALUE, spelled out here rather than compared to the constant —
        // `== CONTENT_SECURITY_POLICY` passes with the constant gutted. This
        // used to assert only that the header existed, which a policy of
        // `default-src *` satisfies.
        assert_eq!(
            about.headers()["content-security-policy"],
            EXPECTED_CSP,
            "the CSP is not the policy the router promises"
        );
        assert_eq!(about.headers().get("x-frame-options").unwrap(), "DENY");

        // /privacy and /terms are static public pages → public, cacheable.
        for path in ["/privacy", "/terms"] {
            let resp = app
                .clone()
                .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::OK);
            assert_eq!(
                resp.headers().get(header::CACHE_CONTROL).unwrap(),
                "public, max-age=300",
                "{path} should be publicly cacheable"
            );
            // Security headers apply to these pages too.
            assert_eq!(resp.headers()["content-security-policy"], EXPECTED_CSP);
            assert_eq!(resp.headers().get("x-frame-options").unwrap(), "DENY");
        }

        // The bare /login landing → public, cacheable.
        let login = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/login")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            login.headers().get(header::CACHE_CONTROL).unwrap(),
            "public, max-age=300"
        );

        // An authenticated page → no-store.
        let home = app
            .oneshot(
                Request::builder()
                    .uri("/")
                    .header(header::COOKIE, admin_cookie)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            home.headers().get(header::CACHE_CONTROL).unwrap(),
            "no-store"
        );
    }

    // -- link cards (Open Graph) -----------------------------------------------
    //
    // Bluesky's card service fetches the HTML server-side, runs no JS, and
    // resolves nothing relative. Measured before these tags existed:
    // `cardyb.bsky.app/v1/extract?url=https://feather-reader.com/` returned
    // `{"title":"FeatherReader — read, quietly","description":"","image":""}`.

    /// Everything up to `</head>` — the only part a card fetcher reads.
    fn head(body: &str) -> &str {
        let end = body.find("</head>").expect("a <head>");
        &body[..end]
    }

    /// The `content` of the first `<meta …>` tag carrying `attr` (e.g.
    /// `property="og:title"`), or `None` when no tag carries it.
    fn meta(head: &str, attr: &str) -> Option<String> {
        let tag_start = head.find(attr)?;
        let rest = &head[tag_start..];
        let tag_end = rest.find('>')?;
        let tag = &rest[..tag_end];
        let content = tag.find("content=\"")? + "content=\"".len();
        let close = tag[content..].find('"')?;
        Some(tag[content..content + close].to_string())
    }

    /// A state whose public origin is production's. The card URLs must be
    /// absolute on THAT origin: a relative `/static/…` is what the card
    /// fetcher cannot use.
    async fn production_origin_state() -> AppState {
        let db = store::init_url("sqlite::memory:").await.unwrap();
        store::ensure_seed(&db, &["did:plc:admin".to_string()])
            .await
            .unwrap();
        let config = Config {
            allowed_dids: vec!["did:plc:admin".to_string()],
            cookie_secret: "test-cookie-secret-000".to_string(),
            beta_cap: 3,
            public_url: "https://feather-reader.com".to_string(),
            ..Config::default()
        };
        AppState::new(config, db).unwrap()
    }

    /// The landing page and /about each carry a complete card with absolute
    /// https URLs, and the two describe different things.
    #[tokio::test]
    async fn landing_and_about_render_open_graph_cards_with_absolute_urls() {
        let landing = public_body(production_origin_state().await, "/").await;
        let about = public_body(production_origin_state().await, "/about").await;
        let (lh, ah) = (head(&landing), head(&about));

        assert_eq!(
            meta(lh, "property=\"og:title\"").as_deref(),
            Some("FeatherReader — read, quietly"),
            "{lh}"
        );
        assert_eq!(
            meta(ah, "property=\"og:title\"").as_deref(),
            Some("About — FeatherReader"),
            "{ah}"
        );
        for (h, path) in [(lh, "/"), (ah, "/about")] {
            let url = format!("https://feather-reader.com{path}");
            assert_eq!(
                meta(h, "property=\"og:url\"").as_deref(),
                Some(url.as_str())
            );
            assert!(
                h.contains(&format!("<link rel=\"canonical\" href=\"{url}\"")),
                "{path} must carry a canonical link: {h}"
            );
            let image = meta(h, "property=\"og:image\"").unwrap_or_default();
            assert!(
                image.starts_with("https://feather-reader.com/static/"),
                "{path}: og:image must be absolute on the public origin, got {image:?}"
            );
            assert_eq!(
                meta(h, "name=\"twitter:card\"").as_deref(),
                Some("summary_large_image")
            );
            assert_eq!(meta(h, "property=\"og:type\"").as_deref(), Some("website"));
            assert_eq!(
                meta(h, "property=\"og:site_name\"").as_deref(),
                Some("FeatherReader")
            );
            let description = meta(h, "property=\"og:description\"").unwrap_or_default();
            assert!(!description.is_empty(), "{path}: og:description is empty");
            assert_eq!(
                meta(h, "name=\"description\"").as_deref(),
                Some(description.as_str()),
                "{path}: the meta description and og:description must agree"
            );
        }
        assert_ne!(
            meta(lh, "property=\"og:description\""),
            meta(ah, "property=\"og:description\""),
            "the landing page and /about must not share a description"
        );
    }

    /// The origin comes from `FEATHERREADER_PUBLIC_URL`, not a constant.
    #[tokio::test]
    async fn card_urls_follow_the_configured_public_url() {
        let db = store::init_url("sqlite::memory:").await.unwrap();
        store::ensure_seed(&db, &[]).await.unwrap();
        let config = Config {
            cookie_secret: "test-cookie-secret-000".to_string(),
            public_url: "https://reader.example.org".to_string(),
            ..Config::default()
        };
        let body = public_body(AppState::new(config, db).unwrap(), "/privacy").await;
        let h = head(&body);
        assert_eq!(
            meta(h, "property=\"og:url\"").as_deref(),
            Some("https://reader.example.org/privacy")
        );
        assert_eq!(
            meta(h, "property=\"og:image\"").as_deref(),
            Some("https://reader.example.org/static/social-card.png")
        );
    }

    /// Every signed-out page describes itself: no two share a description,
    /// and each `og:url` is its own path.
    #[tokio::test]
    async fn public_pages_each_carry_their_own_description() {
        let paths = [
            "/",
            "/about",
            "/privacy",
            "/terms",
            "/stats",
            "/standard-site",
            "/login",
            "/beta/redeem",
        ];
        let mut seen = std::collections::HashSet::new();
        for path in paths {
            let body = public_body(production_origin_state().await, path).await;
            let h = head(&body);
            let description = meta(h, "name=\"description\"").unwrap_or_default();
            assert!(!description.is_empty(), "{path} has no description: {h}");
            assert!(
                seen.insert(description.clone()),
                "{path} repeats another page's description: {description:?}"
            );
            assert_eq!(
                meta(h, "property=\"og:url\"").as_deref(),
                Some(format!("https://feather-reader.com{path}").as_str()),
                "{path}"
            );
            assert!(
                !h.contains("name=\"robots\""),
                "{path} is public and must not be noindex: {h}"
            );
        }
    }

    /// The share image is served from `/static` as a PNG of the dimensions the
    /// tags promise, well under the 1 MB card fetchers tolerate, and cacheable.
    #[tokio::test]
    async fn share_image_is_served_as_a_png_of_the_advertised_size() {
        let landing = public_body(production_origin_state().await, "/").await;
        let h = head(&landing);
        let image = meta(h, "property=\"og:image\"").unwrap();
        let path = image.strip_prefix("https://feather-reader.com").unwrap();
        let width: u32 = meta(h, "property=\"og:image:width\"")
            .unwrap()
            .parse()
            .unwrap();
        let height: u32 = meta(h, "property=\"og:image:height\"")
            .unwrap()
            .parse()
            .unwrap();
        assert_eq!((width, height), (1200, 630), "Bluesky renders ~1.91:1");
        assert_eq!(
            meta(h, "property=\"og:image:type\"").as_deref(),
            Some("image/png")
        );
        assert!(
            !meta(h, "property=\"og:image:alt\"")
                .unwrap_or_default()
                .is_empty(),
            "the image needs alt text"
        );

        let resp = router(production_origin_state().await)
            .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK, "{path}");
        assert_eq!(resp.headers()[header::CONTENT_TYPE], "image/png");
        assert_eq!(resp.headers()[header::CACHE_CONTROL], "public, max-age=300");
        let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
            .await
            .expect("the image is under 1 MB");
        assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n", "not a PNG");
        // IHDR: width and height, big-endian, at offsets 16 and 20.
        let be = |at: usize| u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap());
        assert_eq!(
            (be(16), be(20)),
            (width, height),
            "the PNG's own dimensions must match the tags"
        );
    }

    /// A page that renders a session's private view carries the site's generic
    /// card — nothing from the view reaches `<head>` — and is `noindex`.
    #[tokio::test]
    async fn private_pages_keep_user_data_out_of_the_card() {
        for path in ["/", "/manage"] {
            let state = production_origin_state().await;
            let body = signed_in_body(state, path, "did:plc:admin").await;
            let h = head(&body);
            assert!(
                h.contains("<meta name=\"robots\" content=\"noindex\""),
                "{path}: a private view must be noindex: {h}"
            );
            assert_eq!(
                meta(h, "property=\"og:title\"").as_deref(),
                Some("FeatherReader — read, quietly"),
                "{path}: the card of a private view is the site's generic one"
            );
            assert_eq!(
                meta(h, "property=\"og:url\"").as_deref(),
                Some("https://feather-reader.com/"),
                "{path}: og:url of a private view is the front door, not the private path"
            );
            for private in ["reader.example", "did:plc:admin"] {
                assert!(
                    !h.contains(private),
                    "{path}: {private:?} must not reach <head>: {h}"
                );
            }
        }
    }

    #[tokio::test]
    async fn beta_redeem_page_renders() {
        let state = test_state(&[]).await;
        let app = router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/beta/redeem")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), 256 * 1024)
            .await
            .unwrap();
        let html = String::from_utf8(bytes.to_vec()).unwrap();
        assert!(html.contains("Invite code"));
        assert!(html.contains("/beta/redeem"));
    }

    #[tokio::test]
    async fn rate_limit_returns_429_after_burst() {
        // Configure a trusted proxy header so the limiter keys on the forwarded
        // IP (the oneshot harness sets no ConnectInfo socket peer).
        let db = store::init_url("sqlite::memory:").await.unwrap();
        store::ensure_seed(&db, &[]).await.unwrap();
        let config = Config {
            cookie_secret: "test-cookie-secret-000".to_string(),
            beta_cap: 3,
            trusted_ip_header: Some("cf-connecting-ip".to_string()),
            ..Config::default()
        };
        let state = AppState::new(config, db).unwrap();
        let app = router(state);
        // Hammer POST /beta/redeem past the burst from a single (trusted) IP. The
        // handler itself returns 200 (re-render) on a bad code; the limiter is
        // what eventually yields 429.
        let mut saw_429 = false;
        for _ in 0..(RATE_BURST as usize + 5) {
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/beta/redeem")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("cf-connecting-ip", "203.0.113.200")
                        .body(Body::from("code=FEATHER-NOPENOPE"))
                        .unwrap(),
                )
                .await
                .unwrap();
            if resp.status() == StatusCode::TOO_MANY_REQUESTS {
                saw_429 = true;
                break;
            }
        }
        assert!(saw_429, "expected a 429 after exhausting the burst");
    }

    /// **A forged `X-Forwarded-For` does not key the limiter** — the property
    /// the middleware's comment cites this test as proof of.
    ///
    /// The previous version rotated the forged header and asserted that no
    /// request was EVER 429'd. Rotating addresses can never exhaust a per-IP
    /// burst, so that assertion held whether the header was trusted or
    /// ignored — it passed in the vulnerable configuration too. And with no
    /// socket peer the limiter fails open, so nothing could have been keyed on
    /// anything. Now one real peer sends `RATE_BURST + 5` requests, each with
    /// a DIFFERENT forged header, and the last must be 429: they all landed in
    /// the peer's bucket. A limiter keying on the header mints a fresh bucket
    /// per request and never trips — which is exactly what the mutation does.
    #[tokio::test]
    async fn a_forged_forwarded_for_header_does_not_key_the_limiter() {
        let state = test_state(&[]).await;
        assert!(
            state.config.trusted_ip_header.is_none(),
            "no proxy header is trusted here"
        );
        let app = router(state);
        let peer = std::net::SocketAddr::from(([203, 0, 113, 7], 40000));
        let mut saw_429 = false;
        for i in 0..(RATE_BURST as usize + 5) {
            let forged = format!("10.9.8.{}", i % 250);
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/beta/redeem")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("x-forwarded-for", forged)
                        .extension(axum::extract::ConnectInfo(peer))
                        .body(Body::from("code=FEATHER-NOPENOPE"))
                        .unwrap(),
                )
                .await
                .unwrap();
            if resp.status() == StatusCode::TOO_MANY_REQUESTS {
                saw_429 = true;
                break;
            }
        }
        assert!(
            saw_429,
            "rotating a forged X-Forwarded-For minted fresh buckets: the limiter is keyed on an attacker-chosen header"
        );
    }

    // -- OPML import body cap (DefaultBodyLimit → 413) -------------------------

    /// **A private feed is refused BEFORE it is fetched.** The add path's
    /// privacy gate had no test at all — `private_feeds_are_classified_private_
    /// across_providers` says "the add + OPML paths both gate on this
    /// classifier" and nothing checked either. The gate exists so a
    /// token-bearing URL never reaches the network; the assertion that
    /// matters is the server's hit count: zero.
    #[tokio::test]
    async fn subscribing_to_a_private_feed_never_reaches_the_network() {
        let did = "did:plc:privateadder";
        let state = test_state_with_caps(did, 0, 0).await;
        let (base, hits) = crate::net::tests::serve_body_counted(b"<rss/>".to_vec()).await;
        let port: u16 = base
            .trim_end_matches('/')
            .rsplit(':')
            .next()
            .unwrap()
            .parse()
            .unwrap();
        crate::net::test_host_override(
            "private-add.test",
            std::net::SocketAddr::from(([127, 0, 0, 1], port)),
        );
        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(format!(
                        "url=http%3A%2F%2Fprivate-add.test%3A{port}%2Ffeed%2Fprivate%2Fdeadbeefcafe1234"
                    )))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(loc.contains("Private"), "not refused as private: {loc}");
        assert_eq!(
            hits.load(std::sync::atomic::Ordering::SeqCst),
            0,
            "the private feed was FETCHED before being refused"
        );
        assert_eq!(store::count_feeds(&state.db).await.unwrap(), 0);
    }

    /// **OPML import skips a private feed without storing or publishing it.**
    /// The import path does not fetch, so "never fetched" is not the signal
    /// here; "never stored, never written to the PDS" is. The batch write's
    /// bytes are captured and must not carry the URL.
    #[tokio::test]
    async fn opml_import_skips_a_private_feed_without_storing_or_publishing_it() {
        let did = "did:plc:renamer4";
        let (sidecar, bodies) = spawn_logging_sidecar().await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        let tokened = "https://www.patreon.com/rss/author?auth=Zm9vYmFyc2VjcmV0dG9rZW4";
        let opml = format!(
            "<?xml version=\"1.0\"?>\n<opml version=\"2.0\"><head><title>t</title></head><body>\n\
             <outline type=\"rss\" text=\"Public\" xmlUrl=\"https://public.example/feed.xml\"/>\n\
             <outline type=\"rss\" text=\"Paid\" xmlUrl=\"{tokened}\"/>\n\
             </body></opml>"
        );
        let (ct, body) = opml_multipart(opml.as_bytes());
        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/opml")
                    .header(header::COOKIE, cookie)
                    .header("content-type", ct)
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            loc.contains("skipped%20as%20private"),
            "not reported as skipped: {loc}"
        );
        assert!(store::get_feed_by_url(&state.db, tokened)
            .await
            .unwrap()
            .is_none());
        let sent = bodies.lock().unwrap().join("\n");
        assert!(
            sent.contains("public.example"),
            "the public feed was not written: {sent}"
        );
        assert!(
            !sent.contains("Zm9vYmFyc2VjcmV0dG9rZW4"),
            "the secret was PUBLISHED to the PDS: {sent}"
        );
    }

    /// **`GET /login?handle=` is gated like `POST /login`.** Only the POST was
    /// tested; the GET form starts the same handshake and had no test, so
    /// deleting its gate left the suite green.
    #[tokio::test]
    async fn get_login_without_a_seat_is_refused() {
        let state = test_state(&[]).await;
        let resp = router(state)
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/login?handle=alice.bsky.social")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert_eq!(
            resp.headers().get(header::LOCATION).unwrap(),
            "/beta/redeem"
        );
    }

    /// A sidecar fake that answers every request `ok` and records the PATH of
    /// each in arrival order, plus every body — for asserting what was sent,
    /// and in what order.
    async fn spawn_logging_sidecar() -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
        use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = log.clone();
        tokio::spawn(async move {
            loop {
                let Ok((mut sock, _)) = listener.accept().await else {
                    break;
                };
                let mut raw: Vec<u8> = Vec::new();
                let mut chunk = [0u8; 4096];
                let text = loop {
                    let Ok(n) = sock.read(&mut chunk).await else {
                        break String::new();
                    };
                    if n == 0 {
                        break String::from_utf8_lossy(&raw).to_string();
                    }
                    raw.extend_from_slice(&chunk[..n]);
                    let Some(split) = raw.windows(4).position(|w| w == b"\r\n\r\n") else {
                        continue;
                    };
                    let (head, body) = raw.split_at(split + 4);
                    let want = String::from_utf8_lossy(head).lines().find_map(|l| {
                        let (k, v) = l.split_once(':')?;
                        k.eq_ignore_ascii_case("content-length")
                            .then(|| v.trim().parse::<usize>().ok())?
                    });
                    if want.is_none_or(|w| body.len() >= w) {
                        break String::from_utf8_lossy(&raw).to_string();
                    }
                };
                let path = text
                    .lines()
                    .next()
                    .and_then(|l| l.split_whitespace().nth(1))
                    .unwrap_or("")
                    .to_string();
                let body_text = text
                    .split_once("\r\n\r\n")
                    .map(|(_, b)| b)
                    .unwrap_or("")
                    .to_string();
                sink.lock().unwrap().push(format!("{path} {body_text}"));
                let body = serde_json::json!({ "ok": true, "did": "did:plc:x", "revoked": true, "hadSession": true, "data": {"uri": "at://did:plc:x/c/r", "cid": "bafy"} }).to_string();
                let resp = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = sock.write_all(resp.as_bytes()).await;
                let _ = sock.flush().await;
            }
        });
        (format!("http://{addr}"), log)
    }

    /// **The sign-out flush settles a split flush's landed prefix too.** It is
    /// `readstate::flush_did` under a timeout, so it shares the fix — pinned
    /// here so a sign-out path that grew its own flush would not silently lose
    /// it. Call 1 of 2 lands, call 2's connection drops: the landed cursors are
    /// created and clean, the rest stay dirty to park until the next sign-in.
    #[tokio::test]
    async fn the_sign_out_flush_settles_what_a_split_flush_landed() {
        use crate::readstate::tests as rs;
        for backend in [
            crate::metrics::Backend::Sidecar,
            crate::metrics::Backend::Rust,
        ] {
            let fake = std::sync::Arc::new(std::sync::Mutex::new(rs::FakeRepo::default()));
            let state = rs::state_on(backend, &fake).await;
            for i in 0..250 {
                rs::mark_read(&state, i, "1").await;
            }
            fake.lock().unwrap().drop_call = Some(2);

            flush_before_revoke(&state, rs::DID).await;

            let order = rs::send_order(250);
            let (landed, rest) = order.split_at(crate::atproto::APPLY_WRITES_MAX_OPS);
            for &i in landed {
                let c = rs::cursor(&state, i).await;
                assert!(c.pds_created && !c.dirty, "{backend:?}: feed {i}");
            }
            for &i in rest {
                let c = rs::cursor(&state, i).await;
                assert!(c.dirty && !c.pds_created, "{backend:?}: feed {i}");
            }
            assert_eq!(fake.lock().unwrap().apply_calls, 2, "{backend:?}");
        }
    }

    /// **Sign-out flushes dirty read-state BEFORE it revokes — through the
    /// route.** The previous version of this test called
    /// `flush_before_revoke` and `revoke_everywhere` itself and asserted one
    /// flush attempt; its doc claimed deleting the call from the handler
    /// "drops that to zero", which was false — the handler was never run.
    /// Deleting the call left the suite green: #117 regressing in full, with
    /// the test named after it still passing. Now `POST /logout` is driven and
    /// the sidecar's log must show a repo write BEFORE the revoke.
    #[tokio::test]
    async fn signing_out_flushes_before_it_revokes_through_the_route() {
        let did = "did:plc:ewvi7nxzyoun6zhxrhs64oiz";
        let (sidecar, log) = spawn_logging_sidecar().await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        crate::store::upsert_cursor(
            &state.db,
            &crate::store::ReadCursor {
                did: did.to_string(),
                feed_url: "https://example.com/feed.xml".into(),
                read_through: None,
                read_ids: "[\"1\"]".into(),
                unread_ids: "[]".into(),
                dirty: true,
                pds_created: false,
                updated_at: "2026-09-13T21:22:40Z".into(),
            },
        )
        .await
        .unwrap();
        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/logout")
                    .header(header::COOKIE, cookie)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);

        let entries = log.lock().unwrap().clone();
        let flush = entries
            .iter()
            .position(|e| e.starts_with("/internal/repo "));
        let revoke = entries
            .iter()
            .position(|e| e.starts_with("/internal/revoke "));
        assert!(revoke.is_some(), "sign-out did not revoke: {entries:?}");
        assert!(
            flush.is_some(),
            "sign-out did not attempt a flush before revoking: {entries:?}"
        );
        assert!(
            flush < revoke,
            "the flush arrived AFTER the revoke — no session left to send it with: {entries:?}"
        );
    }

    /// The policy, as a literal: the backstop the router calls "neutralises any
    /// XSS that slips past sanitization". `script-src 'self'` and no
    /// `'unsafe-inline'` on it are the two clauses that make it one.
    const EXPECTED_CSP: &str = "default-src 'self'; \
     script-src 'self'; \
     style-src 'self' 'unsafe-inline'; \
     img-src 'self' https: data:; \
     font-src 'self'; \
     connect-src 'self'; \
     form-action 'self'; \
     base-uri 'self'; \
     frame-ancestors 'none'; \
     object-src 'none'";

    /// Build a `multipart/form-data` body carrying a single `file` field whose
    /// contents are `payload`, returning `(content_type, body_bytes)`.
    fn opml_multipart(payload: &[u8]) -> (String, Vec<u8>) {
        let boundary = "----featherreadertestboundary";
        let mut body = Vec::new();
        body.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
        body.extend_from_slice(
            b"Content-Disposition: form-data; name=\"file\"; filename=\"feeds.opml\"\r\n",
        );
        body.extend_from_slice(b"Content-Type: text/x-opml\r\n\r\n");
        body.extend_from_slice(payload);
        body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
        (format!("multipart/form-data; boundary={boundary}"), body)
    }

    #[tokio::test]
    async fn opml_import_oversize_upload_returns_413() {
        let state = test_state(&["did:plc:admin"]).await;
        let cookie = session_cookie(&state, "did:plc:admin", None);
        let app = router(state);

        // A payload comfortably above the route cap.
        let payload = vec![b'a'; OPML_BODY_LIMIT + 1024];
        let (content_type, body) = opml_multipart(&payload);

        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/opml")
                    .header("content-type", content_type)
                    .header(header::COOKIE, cookie)
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::PAYLOAD_TOO_LARGE,
            "an over-cap OPML upload must be rejected with 413, not collapsed to 500"
        );
    }

    /// **The route's own cap is what refuses this, not the framework's.**
    ///
    /// `OPML_BODY_LIMIT` used to equal axum's `DefaultBodyLimit` (2 MiB), so
    /// the route's layer was a no-op — deleting it left every test green, and
    /// `opml_import_oversize_upload_returns_413` was really testing axum. The
    /// limit is 1 MiB now, strictly tighter, and this uploads a payload that
    /// sits BETWEEN the two: over ours, under the framework's. Only the
    /// route's layer can refuse it — remove the layer and this payload is
    /// accepted, which is also what demonstrates the framework's default is
    /// the larger of the two.
    #[tokio::test]
    async fn opml_import_over_the_route_cap_is_refused_below_the_framework_default() {
        let state = test_state(&["did:plc:admin"]).await;
        let cookie = session_cookie(&state, "did:plc:admin", None);
        let app = router(state);

        // Between the two ceilings: the framework would accept this.
        let payload = vec![b'a'; (OPML_BODY_LIMIT + AXUM_DEFAULT_BODY_LIMIT) / 2];
        let (content_type, body) = opml_multipart(&payload);

        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/opml")
                    .header("content-type", content_type)
                    .header(header::COOKIE, cookie)
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::PAYLOAD_TOO_LARGE,
            "a payload over the route's cap but under the framework's was accepted — \
             the route's own DefaultBodyLimit layer is not doing anything"
        );
    }

    #[tokio::test]
    async fn opml_import_under_limit_upload_is_accepted() {
        let state = test_state(&["did:plc:admin"]).await;
        let cookie = session_cookie(&state, "did:plc:admin", None);
        let db = state.db.clone();
        let app = router(state);

        // A small, valid OPML well under the cap: must be accepted (the handler
        // redirects to `/` or a flash), i.e. never 413.
        let opml = br#"<?xml version="1.0"?>
<opml version="2.0"><body>
  <outline text="Example" type="rss" xmlUrl="https://example.com/feed.xml"/>
</body></opml>"#;
        let (content_type, body) = opml_multipart(opml);

        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/opml")
                    .header("content-type", content_type)
                    .header(header::COOKIE, cookie)
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        // **Assert it was ACCEPTED, not merely that it was not a 413.**
        //
        // The old assertion was `assert_ne!(status, PAYLOAD_TOO_LARGE)`, which a
        // 500 satisfies — so making `import_opml` fail unconditionally left this
        // green. Three other OPML tests caught that mutation; the one whose name
        // promises to cover the under-cap case did not.
        assert_eq!(
            resp.status(),
            StatusCode::SEE_OTHER,
            "an under-cap OPML upload was not accepted (status {})",
            resp.status(),
        );
        // **303 alone is not acceptance.** `import_opml` redirects on several
        // FAILURES too — unparseable OPML, zero feeds found, every feed trimmed
        // by a cap — so an import that stored nothing satisfied the status check.
        let stored: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM feeds WHERE url = ?1")
            .bind("https://example.com/feed.xml")
            .fetch_one(&db)
            .await
            .unwrap();
        assert_eq!(stored, 1, "the upload was redirected but imported nothing");
        let location = resp
            .headers()
            .get(header::LOCATION)
            .and_then(|v| v.to_str().ok())
            .unwrap_or_default()
            .to_string();
        assert!(
            !location.starts_with("/login"),
            "the import bounced to login instead of being accepted: {location}",
        );
    }

    #[tokio::test]
    async fn opml_import_logged_out_redirects_to_login() {
        // Logged-out callers are redirected before the body is consumed; assert
        // the auth short-circuit rather than a body-cap rejection.
        let state = test_state(&["did:plc:admin"]).await;
        let app = router(state);

        let opml = b"<opml version=\"2.0\"><body></body></opml>";
        let (content_type, body) = opml_multipart(opml);

        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/opml")
                    .header("content-type", content_type)
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert_eq!(resp.headers().get(header::LOCATION).unwrap(), "/login");
    }

    // -- delete-my-data (POST /account/delete) --------------------------------

    /// A one-shot mock sidecar: binds a loopback port, answers exactly one
    /// `POST /internal/revoke` with `{ok:true,…}`, and reports (via the returned
    /// channel) the DID it was asked to revoke. Enough to prove the delete
    /// handler triggers the sidecar revoke without pulling in an HTTP-mock crate.
    async fn spawn_revoke_sidecar() -> (String, tokio::sync::oneshot::Receiver<String>) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let (tx, rx) = tokio::sync::oneshot::channel::<String>();
        tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = vec![0u8; 4096];
            let n = sock.read(&mut buf).await.unwrap();
            let req = String::from_utf8_lossy(&buf[..n]).to_string();
            // Pull the DID out of the JSON body (last line of the request).
            let did = req
                .split("\r\n\r\n")
                .nth(1)
                .and_then(|body| {
                    let v: serde_json::Value = serde_json::from_str(body.trim()).ok()?;
                    v.get("did")?.as_str().map(str::to_string)
                })
                .unwrap_or_default();
            let is_revoke = req.starts_with("POST /internal/revoke");
            let body = serde_json::json!({
                "ok": true, "did": did, "revoked": true, "hadSession": true
            })
            .to_string();
            let resp = format!(
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
                body.len(),
                body
            );
            sock.write_all(resp.as_bytes()).await.unwrap();
            sock.flush().await.unwrap();
            let _ = tx.send(if is_revoke { did } else { String::new() });
        });
        (format!("http://{addr}"), rx)
    }

    /// Build an [`AppState`] whose sidecar points at `sidecar_url`.
    async fn test_state_with_sidecar(allowed: &[&str], sidecar_url: &str) -> AppState {
        let defaults = Config::default();
        test_state_with_sidecar_and(
            allowed,
            sidecar_url,
            defaults.standard_site,
            defaults.max_feeds_global,
        )
        .await
    }

    /// [`test_state_with_sidecar`] with the standard.site flag and the global
    /// feeds ceiling chosen — the two settings the at:// paths branch on.
    async fn test_state_with_sidecar_and(
        allowed: &[&str],
        sidecar_url: &str,
        standard_site: bool,
        max_feeds_global: i64,
    ) -> AppState {
        let db = store::init_url("sqlite::memory:").await.unwrap();
        let dids: Vec<String> = allowed.iter().map(|s| s.to_string()).collect();
        store::ensure_seed(&db, &dids).await.unwrap();
        let mut config = Config {
            allowed_dids: dids,
            cookie_secret: "test-cookie-secret-000".to_string(),
            beta_cap: 3,
            standard_site,
            max_feeds_global,
            ..Config::default()
        };
        config.sidecar.public_url = sidecar_url.to_string();
        config.sidecar.internal_url = sidecar_url.to_string();
        AppState::new(config, db).unwrap()
    }

    /// A confirmed `POST /account/delete` purges the caller's local rows, calls
    /// the sidecar revoke for that DID, and clears the session cookie.
    #[tokio::test]
    async fn account_delete_purges_rows_and_triggers_revoke() {
        let (sidecar_url, revoke_rx) = spawn_revoke_sidecar().await;
        let did = "did:plc:leaver";
        let state = test_state_with_sidecar(&[], &sidecar_url).await;

        // Seed the DID with local rows across the per-DID tables.
        store::grant_access(&state.db, did, Some("leaver.example"), "test", None)
            .await
            .unwrap();
        store::replace_sub_refs(&state.db, did, &[]).await.unwrap();
        store::mint_code(&state.db, did, 3600).await.unwrap();
        assert!(store::has_beta_access(&state.db, did).await.unwrap());

        let cookie = session_cookie(&state, did, Some("leaver.example"));
        let app = router(state.clone());

        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/account/delete")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from("confirm=DELETE"))
                    .unwrap(),
            )
            .await
            .unwrap();

        // Signed out: redirect to /login with the cookie cleared.
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert!(resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap()
            .starts_with("/login"));
        let set_cookie = resp
            .headers()
            .get(header::SET_COOKIE)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(set_cookie.contains("Max-Age=0"), "cookie must be cleared");

        // The sidecar revoke was called for exactly this DID.
        //
        // BOUNDED. A bare `await` here meant a broken `revoke_everywhere` — one
        // that simply never called the sidecar — hung this test forever instead
        // of failing it: a wedged CI job rather than a red one, which is the
        // worse of the two signals because nobody reads it as a defect.
        let revoked_did = tokio::time::timeout(std::time::Duration::from_secs(10), revoke_rx)
            .await
            .expect("the sidecar revoke never fired; revoke_everywhere did not call it")
            .unwrap();
        assert_eq!(
            revoked_did, did,
            "sidecar revoke must fire for the caller DID"
        );

        // Local rows are gone.
        assert!(!store::has_beta_access(&state.db, did).await.unwrap());
        let codes: i64 =
            sqlx::query_scalar("SELECT COUNT(*) FROM invite_codes WHERE creator_did = ?1")
                .bind(did)
                .fetch_one(&state.db)
                .await
                .unwrap();
        assert_eq!(codes, 0);
    }

    /// An UN-confirmed `POST /account/delete` (wrong/blank `confirm`) deletes
    /// nothing and bounces back to /manage.
    #[tokio::test]
    async fn account_delete_without_confirm_is_a_noop() {
        let did = "did:plc:staying";
        let state = test_state(&[]).await;
        store::grant_access(&state.db, did, None, "test", None)
            .await
            .unwrap();
        let cookie = session_cookie(&state, did, None);
        let app = router(state.clone());

        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/account/delete")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from("confirm=nope"))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert!(resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap()
            .starts_with("/manage"));
        // Nothing deleted.
        assert!(store::has_beta_access(&state.db, did).await.unwrap());
    }

    /// PDS-outage authorization: when the sidecar is unreachable (as it is in
    /// this harness — the default sidecar URL is not served), a DID must STILL
    /// be unable to read or mutate an entry in a feed it does not subscribe to.
    /// This guards the `resolve_subscriptions` fallback: it must fail CLOSED
    /// (serve only the DID's own `sub_ref`), never widen the caller's surface to
    /// every cached feed.
    #[tokio::test]
    async fn pds_outage_does_not_widen_cross_did_access() {
        let did_a = "did:plc:aaaa";
        let state = test_state(&[]).await;
        store::grant_access(&state.db, did_a, None, "test", None)
            .await
            .unwrap();

        // Shared cache: feed_a (A subscribes) + feed_b (A does NOT). An entry
        // lives in feed_b — the one A must never touch during the outage.
        let feed_a = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://a.example/feed.xml".to_string(),
                title: Some("A".to_string()),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        let feed_b = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://b.example/feed.xml".to_string(),
                title: Some("B".to_string()),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        store::insert_entries(
            &state.db,
            feed_b,
            &[store::NewEntry {
                guid: "b-1".to_string(),
                url: Some("https://b.example/1".to_string()),
                title: Some("B one".to_string()),
                published: Some("2026-07-11T00:00:00Z".to_string()),
                content_html: Some("<p>secret B body</p>".to_string()),
                ..Default::default()
            }],
            0,
        )
        .await
        .unwrap();
        // A subscribes ONLY to feed_a.
        store::replace_sub_refs(&state.db, did_a, &[feed_a])
            .await
            .unwrap();
        // Read B's entry id via a transient sub_ref, then drop it so only the
        // shared cache holds B's entry (no DID subscribes to feed_b anymore).
        store::replace_sub_refs(&state.db, "did:plc:bbbb", &[feed_b])
            .await
            .unwrap();
        let b_entry_id = store::entries_for_feed(&state.db, "did:plc:bbbb", feed_b)
            .await
            .unwrap()[0]
            .id;
        store::replace_sub_refs(&state.db, "did:plc:bbbb", &[])
            .await
            .unwrap();

        let cookie = session_cookie(&state, did_a, None);
        let app = router(state.clone());

        // GET /entries/{b} as A → 404 even during the outage.
        let get_b = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri(format!("/entries/{b_entry_id}"))
                    .header(header::COOKIE, cookie.clone())
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            get_b.status(),
            StatusCode::NOT_FOUND,
            "A must not read B's entry during a PDS outage"
        );

        // POST /entries/{b}/read as A → 404, and no entry_state row is written.
        let read_b = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(format!("/entries/{b_entry_id}/read"))
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from("read=true"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            read_b.status(),
            StatusCode::NOT_FOUND,
            "A must not mark B's entry read during a PDS outage"
        );

        // The fallback must NOT have widened A's sub_ref to feed_b.
        let a_feed_ids: Vec<i64> = sqlx::query_scalar("SELECT feed_id FROM sub_ref WHERE did = ?1")
            .bind(did_a)
            .fetch_all(&state.db)
            .await
            .unwrap();
        assert_eq!(
            a_feed_ids,
            vec![feed_a],
            "outage fallback must not add feeds A never subscribed to"
        );
        // And B's entry has zero read-state (A's attempt did not mutate).
        let es_count: i64 =
            sqlx::query_scalar("SELECT COUNT(*) FROM entry_state WHERE did = ?1 AND entry_id = ?2")
                .bind(did_a)
                .bind(b_entry_id)
                .fetch_one(&state.db)
                .await
                .unwrap();
        assert_eq!(es_count, 0, "no cross-DID mutation during the outage");
    }

    /// **A logout with nothing to revoke is a SUCCESS — on the arm that had
    /// nothing. The other arm is counted separately.**
    ///
    /// Logout is idempotent, so `NoSession` must record as ok; counting it as an
    /// error would make the metric noisy in exactly the case that is fine.
    ///
    /// But `revoke_everywhere` has TWO arms, and a review found that counting
    /// only the rust one let `oauth_revoke` report all-clear while every sidecar
    /// revocation failed. For anyone who logged in before the cutover the sidecar
    /// store is the only one holding tokens, so the rust arm correctly says
    /// NoSession and the metric said nothing was wrong. Both arms are now
    /// recorded, distinguished by the backend column — so this test pins the
    /// BACKEND as well as the outcome.
    #[tokio::test]
    async fn a_logout_with_no_session_counts_as_success() {
        let did = "did:plc:aaaa";
        let state = test_state(&[]).await;
        assert!(
            state.oauth.is_some(),
            "meaningless without an oauth runtime; the revoke arm would be skipped",
        );

        revoke_everywhere(&state, did).await;
        let rows = state.metrics.snapshot();
        let find = |b: crate::metrics::Backend| {
            rows.iter()
                .find(|r| r.op == "oauth_revoke" && r.backend == b)
                .unwrap_or_else(|| panic!("no oauth_revoke row for {b:?}"))
        };

        // Rust arm: nothing stored for this DID, so NoSession -> ok.
        let rust = find(crate::metrics::Backend::Rust);
        assert_eq!(
            rust.stats.err_count, 0,
            "NoSession was counted as a failure; logout is idempotent",
        );
        assert_eq!(rust.stats.ok_count, 1);

        // Sidecar arm: unreachable in a test, so it must be recorded as an
        // ERROR under its own backend — not silently dropped, and not folded
        // into the rust row.
        let sidecar = find(crate::metrics::Backend::Sidecar);
        assert_eq!(
            sidecar.stats.err_count, 1,
            "a failed sidecar revoke was not counted",
        );
    }

    /// **`Failed` must count as an error — the half the metric exists for.**
    ///
    /// A review found this unpinned: replacing the mapping with
    /// `let revoke_ok = true;` passed all 682 tests. The only revoke test
    /// asserted the `NoSession -> ok` half, so the branch that actually means
    /// "the PDS still holds tokens we asked it to drop" was untested.
    ///
    /// Driven through the same handler, with a session present but the PDS
    /// unreachable, so `sign_out_discovering` returns `Failed`.
    #[tokio::test]
    async fn a_failed_rust_revoke_counts_as_an_error() {
        let did = "did:plc:ewvi7nxzyoun6zhxrhs64oiz";
        let state = test_state(&[]).await;
        let runtime = state.oauth.as_deref().expect("oauth runtime");
        crate::oauth::store::put_session(
            &state.db,
            &runtime.codec,
            &crate::oauth::store::OAuthSession {
                sub: did.into(),
                issuer: "https://auth.invalid".into(),
                aud: "https://pds.invalid".into(),
                dpop_key_jwk: crate::oauth::keys::SigningKey::generate("session-dpop")
                    .to_jwk_json()
                    .unwrap(),
                access_token: "at".into(),
                refresh_token: "rt".into(),
                token_type: "DPoP".into(),
                granted_scope: "atproto".into(),
                expires_at: Some(crate::store::now_unix() + 3600),
            },
        )
        .await
        .unwrap();

        revoke_everywhere(&state, did).await;

        let rows = state.metrics.snapshot();
        let rust = rows
            .iter()
            .find(|r| r.op == "oauth_revoke" && r.backend == crate::metrics::Backend::Rust)
            .expect("no rust oauth_revoke row");
        assert_eq!(
            rust.stats.err_count, 1,
            "an unreachable PDS must count as a revocation failure",
        );
        assert_eq!(rust.stats.ok_count, 0);
    }

    /// **The `href` defence is now carried by the TYPE, not by remembering.**
    ///
    /// `EntryRow.link` used to be a `String`, and the guard was "call
    /// `net::safe_link` before assigning it". Deleting that call left all 679
    /// tests passing — a live XSS defence with nothing protecting it.
    ///
    /// `SafeLink` has no `From<String>` and no public member, so the only way to
    /// get foreign input into an `href` is `external`, which does the check
    /// itself. This test pins that constructor; the *wiring* is now pinned by
    /// the compiler, which is the part a test could never hold down.
    ///
    /// Note the empty-not-absent behaviour: a rejected URL yields an EMPTY link
    /// so the template renders the row WITHOUT an anchor. Dropping the row
    /// instead would make the record unremovable, because the un-save button
    /// lives on it.
    #[test]
    fn a_hostile_scheme_cannot_reach_an_href_through_safelink() {
        for hostile in [
            "javascript:alert(1)",
            "JavaScript:alert(1)",
            "  javascript:alert(1)",
            "data:text/html;base64,PHNjcmlwdD4=",
            "vbscript:msgbox(1)",
            "file:///etc/passwd",
            // Protocol-relative: inherits the page's scheme, so it is an
            // off-site link wearing a same-site costume. Carried over from the
            // test this one replaces, which was its only unique input.
            "//evil.example/path",
        ] {
            let link = SafeLink::external(hostile);
            assert!(
                link.is_empty(),
                "{hostile:?} produced a non-empty href: {link}",
            );
            assert!(
                !link.to_string().to_ascii_lowercase().contains("script"),
                "{hostile:?} leaked into the rendered link",
            );
        }

        // And the other direction: a check that rejects everything would satisfy
        // the loop above while breaking every real saved record.
        for good in ["https://example.com/a?b=c#d", "http://example.com/"] {
            let link = SafeLink::external(good);
            assert!(!link.is_empty(), "{good:?} was wrongly rejected");
            assert_eq!(link.to_string(), good);
        }
    }

    /// **The WIRING, not the helper — this is the one that catches the real
    /// mistake.**
    ///
    /// `a_hostile_scheme_cannot_reach_an_href_through_safelink` pins what
    /// `SafeLink::external` *does*. It cannot pin that the saved-record path
    /// *calls* it, and a review proved that gap was live twice over: swapping
    /// `external` for the app-path constructor, and constructing the tuple
    /// directly, both restored the whole `javascript:` hole with every test
    /// green. The type now blocks both — `entry` takes an `i64`, and the field
    /// lives in another module — but the wiring deserves a test of its own
    /// rather than resting on the shape of a signature.
    ///
    /// Renders the actual row through the actual handler, from a record whose
    /// URL is hostile.
    #[tokio::test]
    async fn a_saved_record_with_a_hostile_url_renders_no_anchor() {
        let did = "did:plc:ewvi7nxzyoun6zhxrhs64oiz";
        let sidecar = spawn_saved_sidecar("javascript:alert(1)", "Hostile record").await;
        let mut state = test_state_with_sidecar(&[did], &sidecar).await;
        std::sync::Arc::get_mut(&mut state.config).unwrap().dev_did = Some(did.to_string());

        let resp = router(state)
            .oneshot(
                Request::builder()
                    .uri("/?view=starred")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = String::from_utf8(
            axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap()
                .to_vec(),
        )
        .unwrap();

        // Not in an href, and not as the title either — the title falls back to
        // the URL for links we DO render, so both paths must withhold it.
        assert!(
            !body.to_ascii_lowercase().contains("javascript:"),
            "the hostile scheme reached the rendered page",
        );
        // But the row must survive: the un-save button lives on it, so dropping
        // the row would make the record unremovable from here.
        assert!(
            body.contains("unusable link"),
            "the row was dropped instead of rendering without an anchor",
        );
    }

    /// **The reader view's two `href`s, through the actual handler.**
    ///
    /// The sibling above covers the LIST row. `entry.html` has its own pair of
    /// `href`s fed by `EntryTemplate.url`, and they were a raw `Option<String>`
    /// taken straight off the `entries.url` column — a remote feed's `<link>`.
    ///
    /// Ingest already scheme-checks that column (`feed.rs`'s `entry_link`), so
    /// this was never a live hole. But that guard is procedural and sits a long
    /// way from the `href`: it holds only as long as every future writer to
    /// `entries.url` remembers to go through `feed.rs`. This test does not
    /// depend on it — it writes the hostile URL into the column DIRECTLY, which
    /// is precisely the state the ingest check cannot speak for.
    ///
    /// **Both directions, deliberately.** A fix that renders no link at all
    /// satisfies every negative assertion here, and would break every real
    /// entry. The second half is what makes the first half mean something.
    #[tokio::test]
    async fn a_hostile_entry_url_renders_the_reader_without_an_original_link() {
        let did = "did:plc:readerhref";
        let state = test_state(&[]).await;
        store::grant_access(&state.db, did, None, "test", None)
            .await
            .unwrap();
        let feed = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://href.example/feed.xml".to_string(),
                title: Some("Href".to_string()),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        // Straight into the column, bypassing `feed.rs` — the whole point.
        store::insert_entries(
            &state.db,
            feed,
            &[
                store::NewEntry {
                    guid: "hostile-1".to_string(),
                    url: Some("javascript:alert(1)".to_string()),
                    title: Some("Hostile entry".to_string()),
                    published: Some("2026-07-11T00:00:00Z".to_string()),
                    ..Default::default()
                },
                store::NewEntry {
                    guid: "benign-1".to_string(),
                    url: Some("https://href.example/post".to_string()),
                    title: Some("Benign entry".to_string()),
                    published: Some("2026-07-10T00:00:00Z".to_string()),
                    ..Default::default()
                },
            ],
            0,
        )
        .await
        .unwrap();
        store::replace_sub_refs(&state.db, did, &[feed])
            .await
            .unwrap();
        let rows = store::entries_for_feed(&state.db, did, feed).await.unwrap();
        let id_of = |guid: &str| {
            rows.iter()
                .find(|r| r.guid == guid)
                .unwrap_or_else(|| panic!("{guid} was not inserted"))
                .id
        };

        let cookie = session_cookie(&state, did, None);
        let app = router(state.clone());

        let render = |id: i64| {
            let app = app.clone();
            let cookie = cookie.clone();
            async move {
                let resp = app
                    .oneshot(
                        Request::builder()
                            .method("GET")
                            .uri(format!("/entries/{id}"))
                            .header(header::COOKIE, cookie)
                            .body(Body::empty())
                            .unwrap(),
                    )
                    .await
                    .unwrap();
                assert_eq!(resp.status(), StatusCode::OK);
                String::from_utf8(
                    axum::body::to_bytes(resp.into_body(), usize::MAX)
                        .await
                        .unwrap()
                        .to_vec(),
                )
                .unwrap()
            }
        };

        let hostile = render(id_of("hostile-1")).await;
        // The reader page for THIS entry actually rendered. Without this the
        // three negatives below are satisfied by an empty body.
        assert!(
            hostile.contains("Hostile entry"),
            "the reader did not render the entry: {hostile}",
        );
        assert!(
            !hostile.to_ascii_lowercase().contains("javascript:"),
            "the hostile scheme reached the reader page: {hostile}",
        );
        // Not merely escaped — the template took its no-link branch. Both
        // `href`s are gated on the same `Option`, so this covers the byline
        // link and the action-bar button together.
        assert!(
            !hostile.contains("actionbar-open"),
            "the action bar rendered an open-original link for a refused URL: {hostile}",
        );
        assert!(
            !hostile.contains("Original \u{2197}"),
            "the byline rendered an original link for a refused URL: {hostile}",
        );

        // The other direction: a legitimate entry still links out, so "render
        // nothing" cannot pass as a fix.
        let benign = render(id_of("benign-1")).await;
        assert!(
            benign.contains("Benign entry"),
            "the reader did not render the benign entry: {benign}",
        );
        // BOTH `href`s, counted. The negatives above fire on the action bar
        // first, so without this the byline needle `Original \u{2197}` is never
        // once observed failing — a misspelled needle would pass forever.
        assert_eq!(
            benign
                .matches(r#"href="https://href.example/post""#)
                .count(),
            2,
            "entry.html has two `href`s for the entry URL — the byline link and \
             the action-bar button — and this render produced a different \
             number: {benign}",
        );
        assert!(
            benign.contains("actionbar-open"),
            "a legitimate entry lost its open-original button: {benign}",
        );
        assert!(
            benign.contains("Original \u{2197}"),
            "a legitimate entry lost its byline link: {benign}",
        );
    }

    /// **The outage fallback must not widen what the caller can READ — and the
    /// sibling test above can only see what it WRITES.**
    ///
    /// `pds_outage_does_not_widen_cross_did_access` asserts on `sub_ref` rows and
    /// on `entry_state`: the fallback's side effects. But the fail-open it names
    /// returns **early**, before `sync_sub_refs` runs, so it touches neither. It
    /// leaks through the list it *hands back* — the sidebar and the reader render
    /// from that list, so a caller sees another DID's feeds while `sub_ref` stays
    /// perfectly honest and every existing assertion stays green.
    ///
    /// Measured, not assumed: replacing `feeds_for_did(pool, did)` with
    /// `due_feeds(pool, "9999-…", 10_000)` over the whole shared cache — the
    /// exact historical bug the fallback's comment describes — left **all 663
    /// tests passing**. Cross-tenant isolation is the one property this project
    /// cannot regress quietly, and nothing observed it.
    ///
    /// So this asserts on the RETURN VALUE, which is the thing that reaches the
    /// user, and it deliberately does not look at `sub_ref` at all — that half is
    /// already covered above.
    #[tokio::test]
    async fn the_outage_fallback_returns_only_the_callers_own_feeds() {
        let did_a = "did:plc:aaaa";
        let state = test_state(&[]).await;
        store::grant_access(&state.db, did_a, None, "test", None)
            .await
            .unwrap();

        let feed_a = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://a.example/feed.xml".to_string(),
                title: Some("A".to_string()),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        let _feed_b = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://b.example/feed.xml".to_string(),
                title: Some("B".to_string()),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        // A subscribes ONLY to feed_a. feed_b is in the shared cache and belongs
        // to nobody — exactly the row a whole-cache fallback would hand to A.
        store::replace_sub_refs(&state.db, did_a, &[feed_a])
            .await
            .unwrap();

        // No sidecar and no PDS are reachable from a test, so
        // `list_subscriptions_sorted` fails and this IS the outage path. Assert
        // that, rather than assuming it: if the repo ever starts succeeding here,
        // this test would silently stop exercising the fallback at all.
        assert!(
            state.repo().list_subscriptions_sorted(did_a).await.is_err(),
            "this test is only meaningful on the outage path; the repo answered",
        );

        let resolved = resolve_subscriptions(&state, did_a).await;

        let urls: Vec<&str> = resolved.iter().map(|r| r.sub.url.as_str()).collect();
        assert_eq!(
            urls,
            vec!["https://a.example/feed.xml"],
            "the outage fallback must return the caller's OWN subscriptions only; \
             any other feed here is cross-tenant read access granted by an outage",
        );
    }

    /// Build an [`AppState`] over a fresh in-memory DB with explicit feed caps,
    /// seeding `did` a beta seat + session-capable state.
    async fn test_state_with_caps(
        did: &str,
        max_subs_per_did: i64,
        max_feeds_global: i64,
    ) -> AppState {
        let db = store::init_url("sqlite::memory:").await.unwrap();
        let config = Config {
            cookie_secret: "test-cookie-secret-000".to_string(),
            beta_cap: 100,
            max_subs_per_did,
            max_feeds_global,
            ..Config::default()
        };
        store::grant_access(&db, did, None, "test", None)
            .await
            .unwrap();
        AppState::new(config, db).unwrap()
    }

    /// An OPML document with `n` distinct public feeds.
    fn opml_with_feeds(n: usize) -> String {
        let mut outlines = String::new();
        for i in 0..n {
            outlines.push_str(&format!(
                "<outline type=\"rss\" text=\"F{i}\" xmlUrl=\"https://f{i}.example/feed.xml\"/>\n"
            ));
        }
        format!(
            "<?xml version=\"1.0\"?>\n<opml version=\"2.0\"><head><title>t</title></head><body>\n{outlines}</body></opml>"
        )
    }

    /// OPML bulk import must honour the GLOBAL feeds ceiling: importing more
    /// distinct new feeds than the shared cache can hold caches only up to the
    /// ceiling — the rest are trimmed. (Regression: the import loop previously
    /// bypassed `max_feeds_global` entirely.)
    #[tokio::test]
    async fn opml_import_enforces_global_feeds_ceiling() {
        let did = "did:plc:importer";
        // Cap the shared cache at 3 feeds; import 10 distinct new ones.
        let state = test_state_with_caps(did, 0, 3).await;
        let cookie = session_cookie(&state, did, None);
        let (ct, body) = opml_multipart(opml_with_feeds(10).as_bytes());
        let app = router(state.clone());

        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/opml")
                    .header(header::COOKIE, cookie)
                    .header("content-type", ct)
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);

        let feeds = store::count_feeds(&state.db).await.unwrap();
        assert!(
            feeds <= 3,
            "OPML import blew past the global ceiling: {feeds} feeds cached with cap=3"
        );
    }

    /// POST an OPML of `n` feeds as `did` against a strict fake PDS behind the
    /// sidecar, and return the flash it redirected with plus the fake's log.
    async fn import_against_strict_pds(
        did: &str,
        n: usize,
        fail_call: Option<usize>,
    ) -> (String, crate::atproto::tests::ApplyWritesLog) {
        let (sidecar, log) = crate::atproto::tests::serve_apply_writes(fail_call).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        let cookie = session_cookie(&state, did, None);
        let (ct, body) = opml_multipart(opml_with_feeds(n).as_bytes());
        let resp = router(state)
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/opml")
                    .header(header::COOKIE, cookie)
                    .header("content-type", ct)
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp.headers()[header::LOCATION].to_str().unwrap();
        let flash = url::Url::parse(&format!("http://x{loc}"))
            .unwrap()
            .query_pairs()
            .find(|(k, _)| k == "flash")
            .map(|(_, v)| v.into_owned())
            .unwrap_or_default();
        (flash, log)
    }

    /// **An OPML import of more than 200 feeds succeeds** against a PDS that
    /// refuses more than 200 writes a call, as the reference PDS does. It used
    /// to go out as one `applyWrites` and fail outright, importing nothing.
    #[tokio::test]
    async fn opml_import_of_450_feeds_succeeds_against_a_pds_capping_at_200() {
        let (flash, log) = import_against_strict_pds("did:plc:bigimport", 450, None).await;
        assert_eq!(flash, "Imported 450 feeds", "{flash}");
        assert_eq!(crate::atproto::tests::call_sizes(&log), vec![200, 200, 50]);
    }

    /// **A part-landed import says so.** Chunk 2 of 3 fails: chunk 1's 200
    /// feeds are in the reader's repo, and "nothing was imported" — what the
    /// handler said for any failure — would be false.
    #[tokio::test]
    async fn opml_import_that_part_lands_reports_what_landed() {
        let (flash, log) = import_against_strict_pds("did:plc:partimport", 450, Some(2)).await;
        assert_eq!(crate::atproto::tests::call_sizes(&log), vec![200, 200]);
        assert!(
            flash.contains("200 of 450"),
            "the landed count is not reported: {flash}"
        );
        assert!(
            !flash.contains("nothing was imported"),
            "200 feeds landed and the reader was told none did: {flash}"
        );
    }

    /// A batch that failed on its first call still reports that nothing was
    /// imported — true, since nothing after a failed call is sent.
    #[tokio::test]
    async fn opml_import_that_fails_on_the_first_call_imports_nothing() {
        let (flash, log) = import_against_strict_pds("did:plc:noimport", 450, Some(1)).await;
        assert_eq!(crate::atproto::tests::call_sizes(&log), vec![200]);
        assert!(flash.contains("nothing was imported"), "{flash}");
    }

    /// **A malformed `at://` on the add path is "not a kind of feed we take",
    /// not "private/paid".** The first gate was the privacy classifier, whose
    /// at:// arm fails closed as `Private` for anything not a well-formed
    /// publication URI — so a typo (`did:plc:TOOSHORT`, a missing rkey) drew
    /// the private-feed flash and a "refused private/paid feed" log line. On
    /// main the same input reached `resolve_feed_url` and got "Couldn't find a
    /// feed". Storability is decided first for an at:// input, with its own
    /// message.
    #[tokio::test]
    async fn a_malformed_at_uri_on_the_add_path_is_refused_as_unsupported_not_private() {
        let did = "did:plc:typoist";
        let state = test_state_with_caps(did, 0, 0).await;
        let cookie = session_cookie(&state, did, None);
        for input in [
            "at%3A%2F%2Falice.example.com%2Fsite.standard.publication",
            "at%3A%2F%2Fdid%3Aplc%3ATOOSHORT%2Fsite.standard.publication%2F3lab2c4d5e6f7g8h",
        ] {
            let resp = router(state.clone())
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/subscriptions")
                        .header(header::COOKIE, cookie.clone())
                        .header("content-type", "application/x-www-form-urlencoded")
                        .body(Body::from(format!("url={input}")))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::SEE_OTHER);
            let loc = resp
                .headers()
                .get(header::LOCATION)
                .unwrap()
                .to_str()
                .unwrap();
            assert!(
                loc.contains("kind%20of%20feed"),
                "expected the unsupported-feed flash for {input}, got {loc}"
            );
            assert!(
                !loc.contains("Private"),
                "a storability refusal was reported as a privacy one for {input}: {loc}"
            );
        }
        assert_eq!(store::count_feeds(&state.db).await.unwrap(), 0);
    }

    /// **An OPML entry this instance cannot store is counted and reported, not
    /// silently dropped.** The storability `continue` incremented nothing,
    /// while the privacy branch beside it produced a user-visible label — so
    /// an OPML exported from a standard.site-enabled instance imported
    /// "successfully" with entries missing and no reason given. The reader is
    /// told how many, and why.
    #[tokio::test]
    async fn opml_import_reports_entries_this_instance_cannot_store() {
        let did = "did:plc:renamer4";
        let (sidecar, _puts) = spawn_rename_sidecar(seeded_subscription()).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        assert!(!state.config.standard_site);
        let opml = format!(
            "<?xml version=\"1.0\"?>\n<opml version=\"2.0\"><head><title>t</title></head><body>\n\
             <outline type=\"rss\" text=\"Real\" xmlUrl=\"https://real.example/feed.xml\"/>\n\
             <outline type=\"rss\" text=\"Pub\" xmlUrl=\"{AT_URI_SUB}\"/>\n\
             </body></opml>"
        );
        let (ct, body) = opml_multipart(opml.as_bytes());
        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/opml")
                    .header(header::COOKIE, cookie)
                    .header("content-type", ct)
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            loc.contains("Imported%201%20feed"),
            "unexpected flash: {loc}"
        );
        assert!(
            loc.contains("1%20feed%28s%29%20skipped") && loc.contains("can%20subscribe%20to"),
            "the dropped entry was not reported: {loc}"
        );
        // Reported by count only: the at-URI itself is not echoed back.
        assert!(
            !loc.contains("site.standard.publication"),
            "the URI was echoed: {loc}"
        );
    }

    /// OPML bulk import must honour the PER-DID subscription cap: a DID at its
    /// cap imports zero new feeds.
    #[tokio::test]
    async fn opml_import_enforces_per_did_cap() {
        let did = "did:plc:capped";
        // Per-DID cap 2, global unlimited. Pre-seed the DID at its cap.
        let state = test_state_with_caps(did, 2, 0).await;
        let existing_a = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://have-a.example/feed.xml".to_string(),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        let existing_b = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://have-b.example/feed.xml".to_string(),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        store::replace_sub_refs(&state.db, did, &[existing_a, existing_b])
            .await
            .unwrap();
        let before = store::count_feeds(&state.db).await.unwrap();

        let cookie = session_cookie(&state, did, None);
        let (ct, body) = opml_multipart(opml_with_feeds(10).as_bytes());
        let app = router(state.clone());
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/opml")
                    .header(header::COOKIE, cookie)
                    .header("content-type", ct)
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        // Headroom was 0 → no new feeds imported into the shared cache.
        let after = store::count_feeds(&state.db).await.unwrap();
        assert_eq!(after, before, "over-cap DID imported new feeds anyway");
    }

    /// Single-add per-DID cap: a DID at its subscription cap is refused before
    /// any fetch, with the limit flash.
    #[tokio::test]
    async fn single_add_enforces_per_did_cap() {
        let did = "did:plc:subcapped";
        let state = test_state_with_caps(did, 1, 0).await;
        let f = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://have.example/feed.xml".to_string(),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        store::replace_sub_refs(&state.db, did, &[f]).await.unwrap();
        let cookie = session_cookie(&state, did, None);
        let app = router(state.clone());
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from("url=https://another.example/feed.xml"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            loc.contains("Subscription%20limit%20reached"),
            "expected sub-limit flash, got {loc}"
        );
    }

    /// `GET /` renders at most one page of rows and offers a way to the rest.
    ///
    /// The handler used to materialize EVERY unread entry — `SELECT e.*`, no
    /// `LIMIT`, article bodies included — and hand the lot to the template. With
    /// 250 entries that is the whole list in one response; with a real backlog on
    /// a 512 MB box it is the OOM the operator review flagged. Asserts the page
    /// is capped, the heading still reports the true total, and page 2 is
    /// reachable and disjoint.
    #[tokio::test]
    async fn the_reader_index_pages_instead_of_rendering_everything() {
        let did = "did:plc:pager";
        let state = test_state(&[]).await;
        store::grant_access(&state.db, did, None, "test", None)
            .await
            .unwrap();
        let feed = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://pager.example/feed.xml".to_string(),
                title: Some("Pager".to_string()),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        let total = 250_usize;
        let entries: Vec<store::NewEntry> = (0..total)
            .map(|i| store::NewEntry {
                guid: format!("p-{i:04}"),
                url: Some(format!("https://pager.example/{i}")),
                title: Some(format!("Article {i:04}")),
                published: Some(format!("2026-07-{:02}T00:00:00Z", (i % 28) + 1)),
                content_html: Some("x".repeat(4_000)),
                ..Default::default()
            })
            .collect();
        store::insert_entries(&state.db, feed, &entries, 0)
            .await
            .unwrap();
        store::replace_sub_refs(&state.db, did, &[feed])
            .await
            .unwrap();

        let cookie = session_cookie(&state, did, None);
        let app = router(state.clone());
        let get = |uri: &str| {
            let app = app.clone();
            let cookie = cookie.clone();
            let uri = uri.to_string();
            async move {
                let resp = app
                    .oneshot(
                        Request::builder()
                            .uri(uri)
                            .header(header::COOKIE, cookie)
                            .body(Body::empty())
                            .unwrap(),
                    )
                    .await
                    .unwrap();
                assert_eq!(resp.status(), StatusCode::OK);
                let bytes = axum::body::to_bytes(resp.into_body(), 8 * 1024 * 1024)
                    .await
                    .unwrap();
                String::from_utf8(bytes.to_vec()).unwrap()
            }
        };

        let page1 = get("/").await;
        // One `<li class="entry…>` per rendered row. Counting "/entries/" would
        // over-count: each row carries several (the link plus the read/star
        // forms).
        let rows1 = page1.matches("<li class=\"entry").count();
        assert!(
            rows1 <= ENTRIES_PER_PAGE as usize,
            "page 1 rendered {rows1} entry links; the list is unbounded"
        );
        assert!(
            rows1 > 0,
            "page 1 rendered nothing at all: the page bound swallowed the list"
        );
        // The count is the TRUE total, not the page size — otherwise paging
        // would quietly relabel a 250-entry backlog as a 100-entry one.
        assert!(
            page1.contains("250 entries"),
            "heading must report the full total, not the page"
        );
        assert!(
            page1.contains("page=2"),
            "no way to reach the rest of the list: {}",
            &page1[..page1.len().min(400)]
        );
        // The body never belongs in a list response.
        assert!(
            !page1.contains(&"x".repeat(4_000)),
            "the list response carried an article body"
        );

        let page2 = get("/?page=2").await;
        assert!(
            page2.matches("<li class=\"entry").count() > 0,
            "page 2 rendered no rows at all"
        );
        assert!(
            page2.contains("page=1") || page2.contains("Newer"),
            "page 2 offers no way back"
        );
        // Disjoint: an article on page 1 must not reappear on page 2.
        let first_title = (0..total)
            .map(|i| format!("Article {i:04}"))
            .find(|t| page1.contains(t))
            .expect("page 1 shows at least one titled article");
        assert!(
            !page2.contains(&first_title),
            "{first_title} appears on both pages"
        );

        // A page past the end must not be a dead end. The empty state renders
        // instead of the pager, so an out-of-range page would leave a reader
        // with no link back — reachable by typing a number, and reachable
        // WITHOUT typing anything by paging to the end and then marking entries
        // read, which shrinks the list under the URL already in the address bar.
        let past_end = get("/?page=999").await;
        assert!(
            past_end.matches("<li class=\"entry").count() > 0,
            "an out-of-range page rendered nothing and offered no way back"
        );
        assert!(
            past_end.contains("page=2"),
            "the clamped page offers no pager"
        );
    }

    /// Reader-view mark-read (a request tagged `X-FR-Reader: 1`) must return the
    /// out-of-band action-bar fragment with FRESHLY re-read state so a second
    /// keypress reverses the toggle: `hx-swap-oob="outerHTML"` is present, and
    /// the hidden `read` input + `aria-pressed` reflect the NEW state. The list
    /// view (no reader header) instead swaps the row. This guards the reader OOB
    /// toggle wiring, which had no test.
    #[tokio::test]
    async fn reader_mark_read_returns_oob_actionbar_with_flipped_state() {
        let did = "did:plc:reader";
        let state = test_state(&[]).await;
        store::grant_access(&state.db, did, None, "test", None)
            .await
            .unwrap();
        let feed = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://reader.example/feed.xml".to_string(),
                title: Some("Reader".to_string()),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        store::insert_entries(
            &state.db,
            feed,
            &[store::NewEntry {
                guid: "r-1".to_string(),
                url: Some("https://reader.example/1".to_string()),
                title: Some("Article".to_string()),
                published: Some("2026-07-11T00:00:00Z".to_string()),
                content_html: Some("<p>body</p>".to_string()),
                ..Default::default()
            }],
            0,
        )
        .await
        .unwrap();
        store::replace_sub_refs(&state.db, did, &[feed])
            .await
            .unwrap();
        let entry_id = store::entries_for_feed(&state.db, did, feed).await.unwrap()[0].id;

        let cookie = session_cookie(&state, did, None);
        let app = router(state.clone());

        // Reader-tagged mark-read → OOB action-bar fragment, entry now READ.
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(format!("/entries/{entry_id}/read"))
                    .header(header::COOKIE, cookie.clone())
                    .header("HX-Request", "true")
                    .header("X-FR-Reader", "1")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from("read=true"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
            .await
            .unwrap();
        let html = String::from_utf8(bytes.to_vec()).unwrap();
        assert!(
            html.contains("hx-swap-oob=\"outerHTML\""),
            "reader response must be an OOB swap: {html}"
        );
        assert!(
            html.contains(r#"id="entry-actionbar""#),
            "reader response must be the action-bar fragment: {html}"
        );
        // Now READ: the read button reflects it (aria-pressed=true) and the
        // hidden value flips to `false` so the next tap marks it UNREAD.
        assert!(
            html.contains(r#"aria-pressed="true""#),
            "read button must show pressed after marking read: {html}"
        );
        assert!(
            html.contains(r#"name="read" value="false""#),
            "hidden read value must flip to false so a second tap reverses: {html}"
        );

        // A second reader mark-read (submitting the flipped `read=false`) marks
        // it UNREAD again — the toggle reverses.
        let resp2 = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(format!("/entries/{entry_id}/read"))
                    .header(header::COOKIE, cookie)
                    .header("HX-Request", "true")
                    .header("X-FR-Reader", "1")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from("read=false"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp2.status(), StatusCode::OK);
        let bytes2 = axum::body::to_bytes(resp2.into_body(), 64 * 1024)
            .await
            .unwrap();
        let html2 = String::from_utf8(bytes2.to_vec()).unwrap();
        assert!(
            html2.contains(r#"aria-pressed="false""#),
            "read button must show un-pressed after reversing: {html2}"
        );
        assert!(
            html2.contains(r#"name="read" value="true""#),
            "hidden read value must flip back to true: {html2}"
        );
    }

    /// The LIST view (no `X-FR-Reader` header) swaps the row, not the OOB
    /// action-bar — the counterpart to the reader-OOB test above.
    #[tokio::test]
    async fn list_mark_read_returns_row_not_oob_actionbar() {
        let did = "did:plc:listv";
        let state = test_state(&[]).await;
        store::grant_access(&state.db, did, None, "test", None)
            .await
            .unwrap();
        let feed = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://list.example/feed.xml".to_string(),
                title: Some("List".to_string()),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        store::insert_entries(
            &state.db,
            feed,
            &[store::NewEntry {
                guid: "l-1".to_string(),
                url: Some("https://list.example/1".to_string()),
                title: Some("Article".to_string()),
                published: Some("2026-07-11T00:00:00Z".to_string()),
                ..Default::default()
            }],
            0,
        )
        .await
        .unwrap();
        store::replace_sub_refs(&state.db, did, &[feed])
            .await
            .unwrap();
        let entry_id = store::entries_for_feed(&state.db, did, feed).await.unwrap()[0].id;

        let cookie = session_cookie(&state, did, None);
        let app = router(state.clone());

        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(format!("/entries/{entry_id}/read"))
                    .header(header::COOKIE, cookie)
                    .header("HX-Request", "true")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from("read=true"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
            .await
            .unwrap();
        let html = String::from_utf8(bytes.to_vec()).unwrap();
        assert!(
            !html.contains("hx-swap-oob"),
            "list-view response must NOT be an OOB swap: {html}"
        );
        // **And it must actually BE the row.** The assertion above is satisfied
        // by an empty body, or by any response that simply omits the attribute —
        // so on its own it pins half a property and the name promises the other
        // half.
        assert!(
            html.contains(&format!("/entries/{entry_id}")),
            "the response is not the row for this entry: {html}",
        );
        assert!(
            html.contains("Article"),
            "the row rendered without its title: {html}",
        );
        // **The row comes back carrying read state. That is all this proves.**
        //
        // It does NOT prove the state was persisted: the handler renders
        // `Some(read)` from the form value, so making `mark_read` roll back
        // instead of commit fails 11 store tests and leaves this one green.
        //
        // It does not prove the OVERRIDE either, which an earlier version of
        // this comment claimed. Verified: changing the call site to
        // `build_entry_row(pool, &did, id, None)` — deleting the override
        // wholesale — keeps the whole suite green, because `mark_read` has
        // already persisted the same value two lines earlier, so reading it back
        // from the database produces an identical row.
        //
        // Distinguishing the two needs a case where the override and the stored
        // state DISAGREE, which this handler never produces: it writes the value
        // it then renders. Left as a known gap rather than described as covered.
        assert!(
            html.contains("is-read"),
            "the row came back without the read state it was just given: {html}",
        );
    }

    // -----------------------------------------------------------------------
    // Rename parity (POST /subscriptions/{rkey}/rename)
    // -----------------------------------------------------------------------

    /// **Autodiscovery cannot smuggle a non-http(s) URL into storage.**
    ///
    /// The add path gates the URL the user *typed*; the URL it *stores* is
    /// whatever `resolve_feed_url` returns, which for an HTML page is a
    /// publisher-controlled `<link rel="alternate">` href. Two layers stop
    /// that: `discover_feed` yields only http(s), and the add path re-checks
    /// storability on the resolved URL. This test pins the DISJUNCTION —
    /// each layer alone holds it, both removed fails it — driven through the
    /// real route against a real local server.
    ///
    /// **Why the fixture is `ftp://`, not `at://`.** This began as the
    /// at-URI bypass test from #164, and it was vacuous twice over. Handle
    /// form: once storage became DID-only the privacy classifier refused it
    /// at its own gate. DID form: `Url::parse` cannot read it (invalid port
    /// — the colons in the DID), so `discover_feed` drops it before either
    /// layer exists. An at:// link cannot come out of autodiscovery under
    /// ANY mutation of the layers, so no test through this route can pin
    /// them with one. `ftp://` reaches both. The at:// case is guaranteed by
    /// structure and pinned where it lives: `discover_skips_a_non_http_
    /// alternate` and the storability tests in `feed.rs`.
    #[tokio::test]
    async fn autodiscovery_cannot_smuggle_a_non_http_url_into_storage() {
        let did = "did:plc:autodiscovered";
        // Access granted, both caps disabled — the only gates left are the
        // two under test.
        let state = test_state_with_caps(did, 0, 0).await;

        let page = r#"<!doctype html><html><head><title>Blog</title>
            <link rel="alternate" type="application/rss+xml" href="ftp://files.example/feed.xml">
            </head><body>hi</body></html>"#;
        let base = crate::net::tests::serve_body(page.as_bytes().to_vec()).await;
        let port: u16 = base
            .trim_end_matches('/')
            .rsplit(':')
            .next()
            .unwrap()
            .parse()
            .unwrap();
        crate::net::test_host_override(
            "autodiscover-ftp.test",
            std::net::SocketAddr::from(([127, 0, 0, 1], port)),
        );

        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(format!(
                        "url=http://autodiscover-ftp.test:{port}/"
                    )))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert_ne!(loc, "/login", "the test never reached the add path");
        assert_ne!(loc, "/", "the subscribe succeeded");

        assert_eq!(
            store::count_feeds(&state.db).await.unwrap(),
            0,
            "a non-http(s) URL from autodiscovery was stored"
        );
        assert_eq!(
            store::count_subscriptions_for_did(&state.db, did)
                .await
                .unwrap(),
            0
        );
    }

    /// A rename that points at a BRAND-NEW feed URL while the shared cache is at
    /// its global ceiling must be refused (capacity flash) and must NOT insert a
    /// new `feeds` row — parity with add_subscription's global-cap guard, so a
    /// rename loop can't inflate the shared cache past the cap.
    #[tokio::test]
    async fn rename_to_new_url_refused_at_global_feeds_cap() {
        let did = "did:plc:renamer4";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_subscription()).await;
        // Global cap 1; pre-fill it with one feed so headroom is 0.
        let state = test_state_with_sidecar_and(&[did], &sidecar, false, 1).await;
        store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://existing.example/feed.xml".to_string(),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        let before = store::count_feeds(&state.db).await.unwrap();
        assert_eq!(before, 1);

        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions/rk-keep/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    // A URL not in the cache → would be a NEW feeds row.
                    .body(Body::from(
                        "url=https://brand-new.example/feed.xml&title=Renamed",
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            loc.contains("feed%20capacity"),
            "expected the feed-capacity flash, got {loc}"
        );
        // No new feeds row was inserted, and nothing reached the PDS.
        assert_eq!(store::count_feeds(&state.db).await.unwrap(), before);
        assert!(
            puts.lock().unwrap().is_empty(),
            "a refused repoint reached the PDS"
        );
    }

    /// A repoint to an EXISTING URL adds no row, so it is allowed even at the
    /// global cap (only new URLs are gated) — the other half of the guard.
    ///
    /// On the sidecar fake, so "allowed" means the put actually happened: the
    /// earlier harness had no sidecar, and this passed on a "could not reach
    /// your PDS" flash that merely was not the capacity one.
    #[tokio::test]
    async fn rename_to_existing_url_allowed_at_global_feeds_cap() {
        let did = "did:plc:renamer4";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_subscription()).await;
        let state = test_state_with_sidecar_and(&[did], &sidecar, false, 1).await;
        store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://existing.example/feed.xml".to_string(),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        let before = store::count_feeds(&state.db).await.unwrap();

        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions/rk-keep/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(
                        "url=https://existing.example/feed.xml&title=Retitled",
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert_eq!(loc, "/", "the repoint to a cached URL was refused: {loc}");
        assert_eq!(
            puts.lock().unwrap().len(),
            1,
            "the repoint did not reach the PDS"
        );
        assert_eq!(store::count_feeds(&state.db).await.unwrap(), before);
    }

    /// A rename with a blank URL writes nothing anywhere.
    #[tokio::test]
    async fn rename_with_blank_url_writes_nothing() {
        let did = "did:plc:renamer3";
        let state = test_state_with_caps(did, 0, 0).await;
        let before = store::count_feeds(&state.db).await.unwrap();
        assert_eq!(before, 0);

        let cookie = session_cookie(&state, did, None);
        let app = router(state.clone());
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions/rkey123/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    // Whitespace-only URL trims to empty.
                    .body(Body::from("url=%20%20&title=Nope"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert_eq!(
            resp.headers()
                .get(header::LOCATION)
                .unwrap()
                .to_str()
                .unwrap(),
            "/",
        );
        // Nothing was cached.
        assert_eq!(
            store::count_feeds(&state.db).await.unwrap(),
            0,
            "blank-URL rename wrote a junk feeds row"
        );
    }

    /// A sidecar mock that serves ONE existing subscription record and captures
    /// every `put` body a rename produces.
    ///
    /// **Reads to `content-length` rather than taking one `read`.** A single
    /// read gets whatever one segment carried; if the head and body land
    /// separately the capture holds no record and every field assertion below
    /// passes for the wrong reason. Each captured body must also mention the
    /// collection, so an empty capture fails loudly instead of quietly.
    async fn spawn_rename_sidecar(
        existing: serde_json::Value,
    ) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
        use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let puts = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = puts.clone();
        tokio::spawn(async move {
            loop {
                let Ok((mut sock, _)) = listener.accept().await else {
                    break;
                };
                let mut raw: Vec<u8> = Vec::new();
                let mut chunk = [0u8; 4096];
                let body_text = loop {
                    let Ok(n) = sock.read(&mut chunk).await else {
                        break String::new();
                    };
                    if n == 0 {
                        break String::from_utf8_lossy(&raw).to_string();
                    }
                    raw.extend_from_slice(&chunk[..n]);
                    let Some(split) = raw.windows(4).position(|w| w == b"\r\n\r\n") else {
                        continue;
                    };
                    let (head, body) = raw.split_at(split + 4);
                    let want = String::from_utf8_lossy(head).lines().find_map(|l| {
                        let (k, v) = l.split_once(':')?;
                        k.eq_ignore_ascii_case("content-length")
                            .then(|| v.trim().parse::<usize>().ok())?
                    });
                    if want.is_none_or(|want| body.len() >= want) {
                        break String::from_utf8_lossy(body).to_string();
                    }
                };

                // `"action":"put"` is the rename write; anything else is the read.
                let is_put = body_text.contains("\"action\":\"put\"");
                let data = if is_put {
                    sink.lock().unwrap().push(body_text.clone());
                    serde_json::json!({
                        "uri": "at://did:plc:x/community.lexicon.rss.subscription/rk-keep",
                        "cid": "bafyreiafter"
                    })
                } else {
                    serde_json::json!({ "records": [existing.clone()] })
                };
                let body = serde_json::json!({ "ok": true, "data": data }).to_string();
                let resp = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = sock.write_all(resp.as_bytes()).await;
                let _ = sock.flush().await;
            }
        });
        (format!("http://{addr}"), puts)
    }

    /// The existing record a rename must not destroy.
    fn seeded_subscription() -> serde_json::Value {
        serde_json::json!({
            "uri": "at://did:plc:renamer4/community.lexicon.rss.subscription/rk-keep",
            "cid": "bafyreibefore",
            "value": {
                "$type": "community.lexicon.rss.subscription",
                "url": "https://example.com/feed.xml",
                "title": "Old title",
                "siteUrl": "https://example.com/blog",
                "fetchHint": "hourly",
                "private": false,
                "createdAt": "2024-03-01T00:00:00.000Z"
            }
        })
    }

    /// An existing standard.site subscription, as the 19 in production are:
    /// written before this reader refused the scheme, still in the repo.
    fn seeded_at_uri_subscription() -> serde_json::Value {
        seeded_subscription_with_url(AT_URI_SUB)
    }
    /// An existing subscription record at `rk-keep` with the given URL.
    fn seeded_subscription_with_url(url: &str) -> serde_json::Value {
        serde_json::json!({
            "uri": "at://did:plc:renamer5/community.lexicon.rss.subscription/rk-keep",
            "cid": "bafyreibefore",
            "value": {
                "$type": "community.lexicon.rss.subscription",
                "url": url,
                "title": "Old title",
                "private": false,
                "createdAt": "2024-03-01T00:00:00.000Z"
            }
        })
    }
    const AT_URI_SUB: &str =
        "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab2c4d5e6f7g8h";
    const AT_URI_SUB_ENC: &str =
        "at%3A%2F%2Fdid%3Aplc%3Aohutz6x5acjmpuulp3x7wxxc%2Fsite.standard.publication%2F3lab2c4d5e6f7g8h";

    /// **Retitling an existing `at://` subscription must work with the flag off.**
    ///
    /// The storability guard was placed before the repo lookup, so it refused
    /// any rename whose URL is an at-URI — including a pure title or folder
    /// change on a record that already exists. On main that rename succeeded;
    /// the 19 production records would have become un-editable. The flag gates
    /// what may be STORED in the cache, not whether a reader may edit their own
    /// record: the PDS write goes through, the cache row is simply not created.
    #[tokio::test]
    async fn retitling_an_existing_at_uri_subscription_survives_the_flag_being_off() {
        let did = "did:plc:renamer5";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_at_uri_subscription()).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        assert!(
            !state.config.standard_site,
            "the flag must be off for this test"
        );
        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions/rk-keep/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(format!("url={AT_URI_SUB_ENC}&title=New+title")))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert_eq!(loc, "/", "the retitle was refused: {loc}");

        let bodies = puts.lock().unwrap().clone();
        assert_eq!(bodies.len(), 1, "expected exactly one put, got {bodies:?}");
        let sent: serde_json::Value = serde_json::from_str(&bodies[0]).expect("put body is JSON");
        assert_eq!(
            sent["record"]["title"], "New title",
            "the rename did not apply"
        );
        assert_eq!(
            sent["record"]["url"], AT_URI_SUB,
            "the rename changed the URL"
        );

        // The flag still means what it says for the CACHE: no at:// row.
        let cached: i64 = store::count_unpollable_feeds(&state.db).await.unwrap();
        assert_eq!(cached, 0, "a retitle stored an at:// row with the flag off");
    }

    /// **Repointing a subscription AT an `at://` URI is still refused with the
    /// flag off** — the half of the guard that has to survive the fix above.
    /// Nothing reaches the PDS and nothing reaches the cache.
    #[tokio::test]
    async fn repointing_a_subscription_at_an_at_uri_is_refused_with_the_flag_off() {
        let did = "did:plc:renamer4";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_subscription()).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions/rk-keep/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(format!("url={AT_URI_SUB_ENC}&title=Moved")))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(loc.contains("flash="), "the repoint was not refused: {loc}");
        assert!(
            !loc.contains("Private"),
            "a storability refusal was reported as a privacy one: {loc}"
        );
        assert!(
            puts.lock().unwrap().is_empty(),
            "the repoint reached the PDS"
        );
        let cached: i64 = store::count_unpollable_feeds(&state.db).await.unwrap();
        assert_eq!(cached, 0);
    }

    /// Posts a retitle of `rk-keep` with its URL unchanged; returns the
    /// redirect location.
    async fn retitle_unchanged(state: &AppState, did: &str, url_enc: &str) -> String {
        let cookie = session_cookie(state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions/rk-keep/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(format!("url={url_enc}&title=New+title")))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        resp.headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap()
            .to_string()
    }

    /// **The privacy gate has the same ordering bug the storable gate had.**
    ///
    /// Another client can write a subscription whose URL is an at-URI that is
    /// not a well-formed publication URI at all — a feed generator, say. On
    /// main a retitle of it succeeded (the DID form fails `Url::parse`, which
    /// the classifier reads as `Public`). The narrowed at:// arm now fails
    /// closed as `Private` for it, and the gate ran before `url_changed` was
    /// known — so the record became un-editable, with a flash claiming it "was
    /// not saved or sent anywhere". Both gates now apply to a repoint only.
    #[tokio::test]
    async fn retitling_an_existing_at_uri_record_that_is_not_a_publication_survives() {
        let did = "did:plc:renamer5";
        let other = "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/app.bsky.feed.generator/whats-hot";
        let other_enc =
            "at%3A%2F%2Fdid%3Aplc%3Aohutz6x5acjmpuulp3x7wxxc%2Fapp.bsky.feed.generator%2Fwhats-hot";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_subscription_with_url(other)).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        let loc = retitle_unchanged(&state, did, other_enc).await;
        assert_eq!(loc, "/", "the retitle was refused: {loc}");
        let bodies = puts.lock().unwrap().clone();
        assert_eq!(bodies.len(), 1, "expected exactly one put, got {bodies:?}");
        let sent: serde_json::Value = serde_json::from_str(&bodies[0]).unwrap();
        assert_eq!(sent["record"]["title"], "New title");
        assert_eq!(sent["record"]["url"], other);
    }

    /// **A repoint to a secret-bearing URL is still refused** — the half of
    /// the privacy gate that has to survive moving it behind `url_changed`.
    /// Found by mutation: with the gate deleted outright, nothing failed.
    #[tokio::test]
    async fn repointing_a_subscription_at_a_private_feed_is_refused() {
        let did = "did:plc:renamer4";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_subscription()).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions/rk-keep/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(
                        "url=https%3A%2F%2Fpaid.example%2Ffeed.xml%3Ftoken%3DZm9vYmFyc2VjcmV0dG9rZW4&title=Moved",
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            loc.contains("Private"),
            "the private repoint was not refused: {loc}"
        );
        assert!(
            puts.lock().unwrap().is_empty(),
            "a secret-bearing URL reached the PDS"
        );
        // The repo's fixture token: opaque enough for the classifier, not a real
        // key shape (a Stripe-shaped fixture tripped the secret scanner — rightly).
        let leaked = "https://paid.example/feed.xml?token=Zm9vYmFyc2VjcmV0dG9rZW4";
        assert!(store::get_feed_by_url(&state.db, leaked)
            .await
            .unwrap()
            .is_none());
    }

    /// **A retitle of a never-cached at:// subscription is not "at feed
    /// capacity".** The global-ceiling check keyed on "URL not in the cache",
    /// and an at:// record is never cached with the flag off — so at capacity,
    /// a pure retitle was refused for a row the handler would not insert. The
    /// check now runs once `url_changed` is known and only for a repoint.
    #[tokio::test]
    async fn retitling_an_uncached_at_uri_subscription_is_not_refused_at_feed_capacity() {
        let did = "did:plc:renamer5";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_at_uri_subscription()).await;
        // Ceiling 1, and one real feed already fills it.
        let state = test_state_with_sidecar_and(&[did], &sidecar, false, 1).await;
        store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://filler.example/feed.xml".to_string(),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        let loc = retitle_unchanged(&state, did, AT_URI_SUB_ENC).await;
        assert_eq!(loc, "/", "the retitle was refused: {loc}");
        assert_eq!(
            puts.lock().unwrap().len(),
            1,
            "the retitle did not reach the PDS"
        );
        assert_eq!(
            store::count_feeds(&state.db).await.unwrap(),
            1,
            "a row was inserted"
        );
    }

    /// POST `/subscriptions` with `url`, returning the redirect target.
    async fn subscribe(state: &AppState, did: &str, url_enc: &str) -> String {
        let cookie = session_cookie(state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(format!("url={url_enc}")))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        resp.headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap()
            .to_string()
    }

    /// A `com.atproto.identity.resolveHandle` that answers `did` for anything.
    async fn serve_resolver(did: &str) -> String {
        let base = crate::net::tests::serve_body(
            serde_json::json!({ "did": did }).to_string().into_bytes(),
        )
        .await;
        let port: u16 = base
            .trim_end_matches('/')
            .rsplit(':')
            .next()
            .unwrap()
            .parse()
            .unwrap();
        let host = format!("resolver-{port}.test");
        crate::net::test_host_override(&host, std::net::SocketAddr::from(([127, 0, 0, 1], port)));
        format!("http://{host}:{port}")
    }

    fn with_config(mut state: AppState, f: impl FnOnce(&mut Config)) -> AppState {
        let mut config = (*state.config).clone();
        f(&mut config);
        state.config = std::sync::Arc::new(config);
        state
    }

    /// **0.4.0 step 3: with the flag ON, a well-formed at:// paste is
    /// subscribed.** It was refused as unsupported while nothing could read a
    /// publication; the poller reads them now. Stored in DID form, as a
    /// `publication`, and written to the reader's PDS like any subscription.
    #[tokio::test]
    async fn a_well_formed_at_uri_paste_is_subscribed_with_the_flag_on() {
        let did = "did:plc:renamer5";
        let (sidecar, log) = spawn_logging_sidecar().await;
        let state = with_config(
            test_state_with_sidecar_and(&[did], &sidecar, true, 0).await,
            |c| {
                c.oauth.plc_directory = "http://plc.nowhere.invalid".into();
            },
        );
        let loc = subscribe(&state, did, AT_URI_SUB_ENC).await;
        assert_eq!(loc, "/", "the paste was refused: {loc}");
        let row = store::get_feed_by_url(&state.db, AT_URI_SUB)
            .await
            .unwrap()
            .expect("no feed row");
        assert_eq!(feed::FeedKind::of(&row.url), feed::FeedKind::Publication);
        let sent = log.lock().unwrap().join("\n");
        assert!(
            sent.contains(AT_URI_SUB),
            "the subscription was not written to the PDS: {sent}"
        );
    }

    /// **A0 through the form** — the 0.4.0 exit test, end to end: a reader
    /// pastes a publication, it is stored and written to their PDS, and the
    /// first poll — the one subscribing runs at once — stores its documents.
    #[tokio::test]
    async fn a0_subscribing_from_the_form_delivers_entries() {
        let did = "did:plc:renamer5";
        let author = "did:plc:ohutz6x5acjmpuulp3x7wxxc";
        let site = AT_URI_SUB;
        let (plc, _) = crate::standard_site::tests::serve_repo(
            author,
            vec![
                (
                    lexicon::nsid::STANDARD_PUBLICATION,
                    "3lab2c4d5e6f7g8h",
                    serde_json::json!({ "name": "A0 Journal", "url": "https://a0.example" }),
                ),
                (
                    lexicon::nsid::STANDARD_DOCUMENT,
                    "3l2a0frmaaa2a",
                    serde_json::json!({ "title": "From the form", "path": "/f",
                        "publishedAt": "2026-07-11T00:00:00Z", "site": site }),
                ),
            ],
        )
        .await;
        let (sidecar, _log) = spawn_logging_sidecar().await;
        let state = with_config(
            test_state_with_sidecar_and(&[did], &sidecar, true, 0).await,
            |c| {
                c.oauth.plc_directory = plc;
            },
        );
        assert_eq!(subscribe(&state, did, AT_URI_SUB_ENC).await, "/");
        let row = store::get_feed_by_url(&state.db, site)
            .await
            .unwrap()
            .unwrap();
        let titles: Vec<String> = sqlx::query_scalar("SELECT title FROM entries WHERE feed_id = ?")
            .bind(row.id)
            .fetch_all(&state.db)
            .await
            .unwrap();
        assert_eq!(
            titles,
            vec!["From the form".to_string()],
            "the first poll stored nothing"
        );
        assert_eq!(row.title.as_deref(), Some("A0 Journal"));
    }

    /// A handle-form paste is resolved to the DID before it is stored: a
    /// handle is a mutable name, and `feeds.url` is keyed on identity.
    #[tokio::test]
    async fn a_handle_form_paste_is_stored_by_its_did() {
        let did = "did:plc:renamer5";
        let author = "did:plc:ohutz6x5acjmpuulp3x7wxxc";
        let (sidecar, _log) = spawn_logging_sidecar().await;
        let resolver = serve_resolver(author).await;
        let state = with_config(
            test_state_with_sidecar_and(&[did], &sidecar, true, 0).await,
            |c| {
                c.resolver_base = resolver;
                c.oauth.plc_directory = "http://plc.nowhere.invalid".into();
            },
        );
        let loc = subscribe(
            &state,
            did,
            "at%3A%2F%2Falice.example.com%2Fsite.standard.publication%2F3lab2c4d5e6f7g8h",
        )
        .await;
        assert_eq!(loc, "/", "the paste was refused: {loc}");
        assert!(
            store::get_feed_by_url(&state.db, AT_URI_SUB)
                .await
                .unwrap()
                .is_some(),
            "not stored by its DID"
        );
        assert_eq!(
            store::count_feeds(&state.db).await.unwrap(),
            1,
            "the handle form was stored too"
        );
    }

    /// A resolver answering `did` that counts how often it was asked.
    async fn serve_counting_resolver(
        did: &str,
    ) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
        let (base, hits) = crate::net::tests::serve_body_counted(
            serde_json::json!({ "did": did }).to_string().into_bytes(),
        )
        .await;
        let port: u16 = base
            .trim_end_matches('/')
            .rsplit(':')
            .next()
            .unwrap()
            .parse()
            .unwrap();
        let host = format!("counting-resolver-{port}.test");
        crate::net::test_host_override(&host, std::net::SocketAddr::from(([127, 0, 0, 1], port)));
        (format!("http://{host}:{port}"), hits)
    }

    /// Review of #230: the per-DID cap is documented as checked "BEFORE any
    /// fetch/resolve so an over-cap account can't even trigger an outbound
    /// request" — a handle paste resolved the handle first.
    #[tokio::test]
    async fn an_over_cap_handle_paste_makes_no_outbound_request() {
        let did = "did:plc:renamer5";
        let (sidecar, _log) = spawn_logging_sidecar().await;
        let (resolver, hits) = serve_counting_resolver("did:plc:ohutz6x5acjmpuulp3x7wxxc").await;
        let state = with_config(
            test_state_with_sidecar_and(&[did], &sidecar, true, 0).await,
            |c| {
                c.resolver_base = resolver;
                c.max_subs_per_did = 1;
            },
        );
        let feed_id = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://already.example/feed.xml".into(),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        store::replace_sub_refs(&state.db, did, &[feed_id])
            .await
            .unwrap();
        let loc = subscribe(
            &state,
            did,
            "at%3A%2F%2Falice.example.com%2Fsite.standard.publication%2F3lab2c4d5e6f7g8h",
        )
        .await;
        assert!(
            loc.contains("Subscription%20limit"),
            "expected the cap flash: {loc}"
        );
        assert_eq!(
            hits.load(std::sync::atomic::Ordering::SeqCst),
            0,
            "an over-cap paste resolved a handle"
        );
    }

    /// Review of #230: an authority that is neither a valid DID nor a valid
    /// handle — `did:plc:TOOSHORT`, an uppercase DID — went to the resolver as
    /// a "handle". It is unsupported, and asks nobody anything.
    #[tokio::test]
    async fn a_malformed_did_paste_is_unsupported_with_the_flag_on() {
        let did = "did:plc:renamer5";
        let (sidecar, _log) = spawn_logging_sidecar().await;
        let (resolver, hits) = serve_counting_resolver("did:plc:ohutz6x5acjmpuulp3x7wxxc").await;
        let state = with_config(
            test_state_with_sidecar_and(&[did], &sidecar, true, 0).await,
            |c| {
                c.resolver_base = resolver;
            },
        );
        for authority in [
            "did%3Aplc%3ATOOSHORT",
            "did%3Aplc%3AOHUTZ6X5ACJMPUULP3X7WXXC",
            "bad%0Ahandle.example",
        ] {
            let loc = subscribe(
                &state,
                did,
                &format!("at%3A%2F%2F{authority}%2Fsite.standard.publication%2F3lab2c4d5e6f7g8h"),
            )
            .await;
            assert!(
                loc.contains("kind%20of%20feed"),
                "{authority}: expected the unsupported flash: {loc}"
            );
        }
        assert_eq!(
            hits.load(std::sync::atomic::Ordering::SeqCst),
            0,
            "a malformed authority reached the resolver"
        );
        assert_eq!(store::count_feeds(&state.db).await.unwrap(), 0);
    }

    /// A handle that does not resolve is refused, and nothing is stored.
    #[tokio::test]
    async fn an_unresolvable_handle_paste_is_refused() {
        let did = "did:plc:renamer5";
        let (sidecar, _log) = spawn_logging_sidecar().await;
        let state = with_config(
            test_state_with_sidecar_and(&[did], &sidecar, true, 0).await,
            |c| {
                c.resolver_base = "http://resolver.nowhere.invalid".into();
            },
        );
        let loc = subscribe(
            &state,
            did,
            "at%3A%2F%2Fnobody.example.com%2Fsite.standard.publication%2F3lab2c4d5e6f7g8h",
        )
        .await;
        assert!(
            loc.contains("resolve%20the%20handle"),
            "expected the unresolvable-handle flash: {loc}"
        );
        assert_eq!(store::count_feeds(&state.db).await.unwrap(), 0);
    }

    /// An at:// URI that is not a publication is refused, flag on or off.
    #[tokio::test]
    async fn a_non_publication_at_uri_paste_is_refused() {
        let did = "did:plc:renamer5";
        let (sidecar, _log) = spawn_logging_sidecar().await;
        let state = test_state_with_sidecar_and(&[did], &sidecar, true, 0).await;
        let loc = subscribe(
            &state,
            did,
            "at%3A%2F%2Fdid%3Aplc%3Aohutz6x5acjmpuulp3x7wxxc%2Fapp.bsky.feed.post%2F3lab2c4d5e6f7g8h",
        )
        .await;
        assert!(
            loc.contains("kind%20of%20feed"),
            "expected the unsupported flash: {loc}"
        );
        assert_eq!(store::count_feeds(&state.db).await.unwrap(), 0);
    }

    /// A mixed-case scheme is canonicalised at input, not refused and not
    /// stored as a second spelling of the same publication.
    #[tokio::test]
    async fn a_mixed_case_at_scheme_paste_is_stored_canonically() {
        let did = "did:plc:renamer5";
        let (sidecar, _log) = spawn_logging_sidecar().await;
        let state = with_config(
            test_state_with_sidecar_and(&[did], &sidecar, true, 0).await,
            |c| {
                c.oauth.plc_directory = "http://plc.nowhere.invalid".into();
            },
        );
        let loc = subscribe(&state, did, &AT_URI_SUB_ENC.replacen("at", "At", 1)).await;
        assert_eq!(loc, "/", "the paste was refused: {loc}");
        assert!(store::get_feed_by_url(&state.db, AT_URI_SUB)
            .await
            .unwrap()
            .is_some());
    }

    /// **With the flag ON, an OPML at:// entry is stored.** The one storage
    /// path that is meant to work today, asserted with the flag actually on.
    #[tokio::test]
    async fn opml_import_stores_an_at_uri_entry_with_the_flag_on() {
        let did = "did:plc:renamer5";
        let (sidecar, _puts) = spawn_rename_sidecar(seeded_subscription()).await;
        let state = test_state_with_sidecar_and(&[did], &sidecar, true, 0).await;
        let opml = format!(
            "<?xml version=\"1.0\"?>\n<opml version=\"2.0\"><head><title>t</title></head><body>\n\
             <outline type=\"rss\" text=\"Real\" xmlUrl=\"https://real.example/feed.xml\"/>\n\
             <outline type=\"rss\" text=\"Pub\" xmlUrl=\"{AT_URI_SUB}\"/>\n\
             </body></opml>"
        );
        let (ct, body) = opml_multipart(opml.as_bytes());
        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/opml")
                    .header(header::COOKIE, cookie)
                    .header("content-type", ct)
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            loc.contains("Imported%202%20feeds"),
            "unexpected flash: {loc}"
        );
        assert!(
            !loc.contains("skipped"),
            "the at:// entry was skipped with the flag on: {loc}"
        );
        let stored = store::get_feed_by_url(&state.db, AT_URI_SUB).await.unwrap();
        assert!(
            stored.is_some(),
            "the at:// entry was not stored with the flag on"
        );
    }

    /// **A retitle must not cache a secret-bearing URL.** Moving the privacy
    /// gate behind `url_changed` was right for the PDS write — the record is
    /// the reader's — but the cache write was gated only on `storable`, which
    /// any http(s) URL is. So a retitle of a record another client wrote with
    /// a tokened feed URL inserted that URL into the shared `feeds` table,
    /// where the poller would fail it every cycle and print it on the admin
    /// page. main refused the whole rename; this keeps the record editable and
    /// the cache clean, as `resolve_subscriptions` already does for the same
    /// record.
    #[tokio::test]
    async fn retitling_a_secret_bearing_record_does_not_cache_its_url() {
        let did = "did:plc:renamer5";
        let tokened = "https://www.patreon.com/rss/author?auth=Zm9vYmFyc2VjcmV0dG9rZW4";
        let tokened_enc =
            "https%3A%2F%2Fwww.patreon.com%2Frss%2Fauthor%3Fauth%3DZm9vYmFyc2VjcmV0dG9rZW4";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_subscription_with_url(tokened)).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        let loc = retitle_unchanged(&state, did, tokened_enc).await;
        assert_eq!(loc, "/", "the retitle was refused: {loc}");
        assert_eq!(
            puts.lock().unwrap().len(),
            1,
            "the retitle did not reach the PDS"
        );
        assert!(
            store::get_feed_by_url(&state.db, tokened)
                .await
                .unwrap()
                .is_none(),
            "a secret-bearing URL was written to the shared cache by a retitle"
        );
    }

    /// **On a repoint, storability is decided before privacy and capacity** —
    /// the same ordering the add path got. A malformed at:// target drew the
    /// private/paid flash, and at capacity a well-formed one drew "try again
    /// later" for a URL that can never be accepted with the flag off.
    #[tokio::test]
    async fn repointing_at_a_malformed_at_uri_is_refused_as_unsupported() {
        let did = "did:plc:renamer4";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_subscription()).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions/rk-keep/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(
                        "url=at%3A%2F%2Fdid%3Aplc%3ATOOSHORT%2Fsite.standard.publication%2F3lab&title=Moved",
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            loc.contains("kind%20of%20feed"),
            "expected the unsupported flash: {loc}"
        );
        assert!(
            !loc.contains("Private"),
            "a typo was reported as a paid feed: {loc}"
        );
        assert!(puts.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn repointing_at_an_at_uri_at_capacity_is_refused_as_unsupported_not_capacity() {
        let did = "did:plc:renamer4";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_subscription()).await;
        let state = test_state_with_sidecar_and(&[did], &sidecar, false, 1).await;
        store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://filler.example/feed.xml".to_string(),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions/rk-keep/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(format!("url={AT_URI_SUB_ENC}&title=Moved")))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            loc.contains("kind%20of%20feed"),
            "expected the unsupported flash: {loc}"
        );
        assert!(
            !loc.contains("capacity"),
            "an unacceptable URL was reported as a capacity problem: {loc}"
        );
        assert!(puts.lock().unwrap().is_empty());
    }

    /// **`url_changed` compares like for like.** The form value is trimmed;
    /// the record's URL was compared raw, so a record another client wrote
    /// with a trailing space read as a repoint on every retitle and re-armed
    /// every gate — including the one that made an at:// record un-editable.
    #[tokio::test]
    async fn retitling_a_record_whose_url_carries_whitespace_is_not_a_repoint() {
        let did = "did:plc:renamer5";
        let padded = format!("{AT_URI_SUB} ");
        let (sidecar, puts) = spawn_rename_sidecar(seeded_subscription_with_url(&padded)).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        // The manage row posts the record's URL verbatim, padding included.
        let loc = retitle_unchanged(&state, did, &format!("{AT_URI_SUB_ENC}%20")).await;
        assert_eq!(
            loc, "/",
            "the retitle was treated as a repoint and refused: {loc}"
        );
        let bodies = puts.lock().unwrap().clone();
        assert_eq!(bodies.len(), 1);
        let sent: serde_json::Value = serde_json::from_str(&bodies[0]).unwrap();
        assert_eq!(
            sent["record"]["url"], AT_URI_SUB,
            "the padding was not normalised away"
        );
    }

    /// **A retitle inserts no cache row.** The ceiling is checked on a repoint
    /// only, so the trailing upsert must not create a row for an unchanged URL
    /// that has none — with the flag on and the cache full, each retitle of a
    /// never-cached at:// record was a row past the cap. An existing row still
    /// gets its title kept in step.
    #[tokio::test]
    async fn retitling_an_uncached_record_at_capacity_inserts_no_row() {
        let did = "did:plc:renamer5";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_at_uri_subscription()).await;
        let state = test_state_with_sidecar_and(&[did], &sidecar, true, 1).await;
        store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://filler.example/feed.xml".to_string(),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        let loc = retitle_unchanged(&state, did, AT_URI_SUB_ENC).await;
        assert_eq!(loc, "/", "the retitle was refused: {loc}");
        assert_eq!(puts.lock().unwrap().len(), 1);
        assert_eq!(
            store::count_feeds(&state.db).await.unwrap(),
            1,
            "a retitle inserted a cache row past the ceiling"
        );
    }

    /// **The add path's at:// pre-check is about the MESSAGE, so it is
    /// case-insensitive.** `Url::parse` folds the scheme, so `AT://…` skipped
    /// the pre-check and the classifier's at:// arm alike, parsed as `at`, and
    /// tripped the secret heuristic on the rkey — the private/paid flash the
    /// pre-check exists to avoid. Storage stays case-sensitive; this does not
    /// touch it.
    #[tokio::test]
    async fn an_uppercase_at_scheme_paste_is_refused_as_unsupported() {
        let did = "did:plc:typoist";
        let state = test_state_with_caps(did, 0, 0).await;
        let cookie = session_cookie(&state, did, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(
                        "url=AT%3A%2F%2Falice.example.com%2Fsite.standard.publication%2F3lab2c4d5e6f7g8h",
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            loc.contains("kind%20of%20feed"),
            "expected the unsupported flash: {loc}"
        );
        assert!(!loc.contains("Private"), "reported as a paid feed: {loc}");
    }

    /// **A rename must not destroy the fields the form never carries.**
    ///
    /// `update_subscription` is a `putRecord` — the WHOLE record is replaced, per
    /// its own doc. The handler built a fresh `Subscription::new(url, now())`, so
    /// every field absent from `templates/manage_row.html` (which posts only
    /// `url`, `title`, `folder`) was written back as its default:
    ///
    /// | field | before | after |
    /// |---|---|---|
    /// | `siteUrl` | whatever the feed advertised | gone |
    /// | `fetchHint` | as set | gone |
    /// | `private` | as set | gone |
    /// | `createdAt` | original subscribe time | reset to now |
    ///
    /// `createdAt` is the worst of the four: it is the sort key for "when did I
    /// subscribe", it is unrecoverable once overwritten, and nothing in the UI
    /// tells the reader it moved.
    ///
    /// Asserted on the BYTES THE SIDECAR RECEIVES, not on a `Subscription` built
    /// in the test — the record only becomes wrong on the way out, so checking
    /// the value we passed in would pass just as happily with the fix removed.
    #[tokio::test]
    async fn renaming_preserves_the_fields_the_form_never_carries() {
        let did = "did:plc:renamer4";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_subscription()).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        let cookie = session_cookie(&state, did, None);

        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions/rk-keep/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    // Exactly what the manage row posts: url, title, folder.
                    .body(Body::from(
                        "url=https%3A%2F%2Fexample.com%2Ffeed.xml&title=New+title&folder=Tech",
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);

        let bodies = puts.lock().unwrap().clone();
        assert_eq!(bodies.len(), 1, "expected exactly one put, got {bodies:?}");
        let body = &bodies[0];
        // Anchors the negative assertions: an empty capture would satisfy them.
        assert!(
            body.contains("community.lexicon.rss.subscription"),
            "captured no usable put body: {body:?}"
        );

        let sent: serde_json::Value = serde_json::from_str(body).expect("put body is JSON");
        let record = &sent["record"];

        // What the form DID carry must be applied.
        assert_eq!(record["title"], "New title", "the rename did not apply");
        assert_eq!(record["folder"], "Tech", "the re-folder did not apply");

        // What the form did NOT carry must survive.
        assert_eq!(
            record["createdAt"], "2024-03-01T00:00:00.000Z",
            "the rename reset createdAt — the reader's subscribe time is gone \
             from their own repo, and nothing told them"
        );
        assert_eq!(
            record["siteUrl"], "https://example.com/blog",
            "the rename erased siteUrl"
        );
        assert_eq!(record["fetchHint"], "hourly", "the rename erased fetchHint");
        assert_eq!(record["private"], false, "the rename erased private");
    }

    /// **Repointing at a different feed drops that feed's properties, but not
    /// the subscription's.**
    ///
    /// `siteUrl` and `fetchHint` describe the feed the subscription points at,
    /// so carrying them onto a different URL would leave a site link for the old
    /// feed hanging off the new one. `createdAt` and `private` are properties of
    /// the SUBSCRIPTION and survive a repoint — the reader subscribed when they
    /// subscribed, whatever the URL was later corrected to.
    #[tokio::test]
    async fn repointing_a_feed_drops_the_old_feeds_properties_but_keeps_the_subscriptions() {
        let did = "did:plc:renamer4";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_subscription()).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        let cookie = session_cookie(&state, did, None);

        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions/rk-keep/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    // A DIFFERENT feed URL from the seeded record.
                    .body(Body::from(
                        "url=https%3A%2F%2Fother.example%2Ffeed.xml&title=Repointed",
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);

        let bodies = puts.lock().unwrap().clone();
        assert_eq!(bodies.len(), 1, "expected exactly one put, got {bodies:?}");
        assert!(
            bodies[0].contains("community.lexicon.rss.subscription"),
            "captured no usable put body: {:?}",
            bodies[0]
        );
        let sent: serde_json::Value = serde_json::from_str(&bodies[0]).expect("put body is JSON");
        let record = &sent["record"];

        assert_eq!(record["url"], "https://other.example/feed.xml");
        // The old feed's properties are gone rather than misattributed.
        assert!(
            record.get("siteUrl").is_none() || record["siteUrl"].is_null(),
            "the old feed's site link followed the subscription to a new feed: {record}"
        );
        assert!(
            record.get("fetchHint").is_none() || record["fetchHint"].is_null(),
            "the old feed's fetch hint followed the subscription to a new feed: {record}"
        );
        // The subscription's own properties survive.
        assert_eq!(
            record["createdAt"], "2024-03-01T00:00:00.000Z",
            "a repoint is still not a new subscription; createdAt must not move"
        );
        assert_eq!(record["private"], false, "the repoint erased private");
    }

    /// **A rename against an rkey that is not in the repo writes NOTHING.**
    ///
    /// `update_subscription` is a `putRecord`, which CREATES the record when the
    /// rkey does not exist — with whatever `createdAt` we hand it. So without
    /// this refusal a rename against a stale or wrong rkey manufactures a
    /// subscription dated today, which is the bug this whole change exists to
    /// fix, arriving by a different door.
    ///
    /// The guard was untested when first written: removing it left all 733 tests
    /// green. An untested guard against the exact defect being fixed is how the
    /// two previous rounds of this problem got through.
    #[tokio::test]
    async fn renaming_an_unknown_rkey_writes_nothing() {
        let did = "did:plc:renamer4";
        // The sidecar serves exactly one record, at rkey `rk-keep`.
        let (sidecar, puts) = spawn_rename_sidecar(seeded_subscription()).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        let cookie = session_cookie(&state, did, None);

        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    // ...and this is not it.
                    .uri("/subscriptions/rk-does-not-exist/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(
                        "url=https%3A%2F%2Fexample.com%2Ffeed.xml&title=Ghost",
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            loc.contains("flash="),
            "an unknown rkey redirected as though the rename had worked: {loc}"
        );
        assert!(
            puts.lock().unwrap().is_empty(),
            "a rename against an unknown rkey wrote a record — putRecord would \
             CREATE it, dated today: {:?}",
            puts.lock().unwrap()
        );
    }

    /// **A `site_url` the client actually sends is applied, not dropped.**
    ///
    /// `templates/manage_row.html` does not post this field, so it is tempting
    /// to read the arm that handles it as dead code. It is not:
    /// `RenameSubForm` carries `site_url`, so a hand-crafted POST reaches it
    /// today. Discarding the value instead of applying it left all 733 tests
    /// green.
    ///
    /// The value is scheme-checked on the way out by the repo-boundary vet, so
    /// this is a coverage gap rather than an exposure — but an untested path
    /// that writes a URL into the reader's PDS should not stay untested.
    #[tokio::test]
    async fn a_client_supplied_site_url_reaches_the_record() {
        let did = "did:plc:renamer4";
        let (sidecar, puts) = spawn_rename_sidecar(seeded_subscription()).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        let cookie = session_cookie(&state, did, None);

        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions/rk-keep/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    // Same feed URL, but carrying a site_url the manage row
                    // never sends.
                    .body(Body::from(
                        "url=https%3A%2F%2Fexample.com%2Ffeed.xml&title=Kept\
                         &site_url=https%3A%2F%2Ftyped.example%2Fsite",
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);

        let bodies = puts.lock().unwrap().clone();
        assert_eq!(bodies.len(), 1, "expected exactly one put, got {bodies:?}");
        assert!(
            bodies[0].contains("community.lexicon.rss.subscription"),
            "captured no usable put body: {:?}",
            bodies[0]
        );
        let sent: serde_json::Value = serde_json::from_str(&bodies[0]).expect("put body is JSON");
        assert_eq!(
            sent["record"]["siteUrl"], "https://typed.example/site",
            "the client's siteUrl was dropped; the seeded record's survived instead"
        );
    }

    /// **A rename whose read fails writes NOTHING.**
    ///
    /// This is the property most easily lost when someone later touches this
    /// handler: falling back to `Subscription::new` on a read error looks like
    /// graceful degradation and is in fact the original bug, reinstated on
    /// exactly the path where it is hardest to notice. The reader must be told
    /// instead.
    #[tokio::test]
    async fn a_rename_whose_read_fails_writes_nothing() {
        let did = "did:plc:renamer5";
        // A port that accepts nothing: the read cannot succeed.
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let dead = format!("http://{}", listener.local_addr().unwrap());
        drop(listener);

        let state = test_state_with_sidecar(&[did], &dead).await;
        let cookie = session_cookie(&state, did, None);
        let before = store::count_feeds(&state.db).await.unwrap();

        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/subscriptions/rk-keep/rename")
                    .header(header::COOKIE, cookie)
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(
                        "url=https%3A%2F%2Fexample.com%2Ffeed.xml&title=Doomed",
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        let loc = resp
            .headers()
            .get(header::LOCATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            loc.contains("flash="),
            "a failed read redirected as though the rename had worked: {loc}"
        );
        assert_eq!(
            store::count_feeds(&state.db).await.unwrap(),
            before,
            "a rename that could not read the record still wrote to the cache"
        );
    }

    /// Folder pre-selection regression: the manage rename row must mark the
    /// feed's CURRENT folder `<option>` as `selected`, so an untouched Save
    /// re-submits the current folder instead of silently un-foldering the feed.
    /// A loose (un-foldered) feed must mark "No folder" selected instead. Renders
    /// `ManageTemplate` directly so no PDS/sidecar round-trip is needed.
    #[test]
    fn manage_rename_row_preselects_current_folder() {
        let nav = Nav {
            handle: "@reader.example".to_string(),
            avatar: "RE".to_string(),
            view: "unread".to_string(),
            scope_qs: String::new(),
            folders: Vec::new(),
            loose_feeds: Vec::new(),
            manage_active: true,
        };
        let folder_options = vec![
            FolderOption {
                uri: "at://did:plc:x/app.folder/work".to_string(),
                name: "Work".to_string(),
            },
            FolderOption {
                uri: "at://did:plc:x/app.folder/fun".to_string(),
                name: "Fun".to_string(),
            },
        ];
        // A foldered feed (in "Work") and a loose feed (no folder), each with a
        // non-empty rkey so the rename form renders.
        let foldered = FeedView {
            rkey: "sub-foldered".to_string(),
            url: "https://work.example/feed.xml".to_string(),
            title: "Work Feed".to_string(),
            unread: 0,
            selected: false,
            folder: Some("at://did:plc:x/app.folder/work".to_string()),
        };
        let loose = FeedView {
            rkey: "sub-loose".to_string(),
            url: "https://loose.example/feed.xml".to_string(),
            title: "Loose Feed".to_string(),
            unread: 0,
            selected: false,
            folder: None,
        };
        let tmpl = ManageTemplate {
            card: Card::private(&Config::default()),
            version: VERSION,
            repo_url: REPO_URL,
            kofi_url: KOFI_URL,
            flash: String::new(),
            alert: String::new(),
            nav,
            folder_options,
            folders: vec![FolderView {
                rkey: "folder-work".to_string(),
                uri: "at://did:plc:x/app.folder/work".to_string(),
                name: "Work".to_string(),
                feeds: vec![foldered],
                selected: false,
            }],
            loose_feeds: vec![loose],
            standard_site: false,
        };
        let html = tmpl.render().unwrap();

        // The foldered feed's "Work" option is pre-selected.
        assert!(
            html.contains(
                r#"<option value="at://did:plc:x/app.folder/work" selected>Work</option>"#
            ),
            "foldered feed must pre-select its current folder: {html}"
        );
        // The loose feed's "No folder" option is pre-selected (appears for the
        // loose row, which has folder=None).
        assert!(
            html.contains(r#"<option value="" selected>No folder</option>"#),
            "loose feed must pre-select 'No folder': {html}"
        );
    }

    /// **The public stats page carries no user data.**
    ///
    /// It is reachable by anyone, so the thing worth pinning is what it does
    /// NOT say: nothing about how many people use the instance, nothing about
    /// which feeds fail, nothing about who reads what.
    #[tokio::test]
    async fn the_public_stats_page_exposes_no_user_data() {
        let state = test_state(&[]).await;
        store::ensure_seed(&state.db, &["did:plc:someone".to_string()])
            .await
            .unwrap();

        let resp = router(state)
            .oneshot(
                Request::builder()
                    .uri("/stats")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK, "stats must be public");

        let body = String::from_utf8(
            axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap()
                .to_vec(),
        )
        .unwrap();

        // Structural checks, not word checks. The page's own prose says it
        // publishes no error rates, so searching for that PHRASE finds the
        // disclaimer rather than a leak — the first version of this test failed
        // on exactly that. What matters is whether identifiers or the
        // admin-only figures are present.
        assert!(
            !body.contains("did:"),
            "the public stats page leaked an identifier"
        );
        for admin_only in ["errp50ms", "p95ms", "live backend", "ok_count"] {
            assert!(
                !body.contains(admin_only),
                "the public page is showing the admin metrics column {admin_only:?}"
            );
        }
        // And it does render the aggregate it exists for.
        assert!(body.contains("Feeds tracked"));
        assert!(body.contains("Waiting to be polled"));
    }

    /// **The two states that stop feeds updating must be visible.**
    ///
    /// `overdue` and `polled_last_hour` move in BOTH and distinguish neither —
    /// and `overdue` moves the WRONG WAY for backoff, because backoff is applied
    /// by pushing `next_poll` forward, so a feed failing every fetch drops out of
    /// the backlog and makes the page read healthier. That inversion is what this
    /// test pins: a broken feed must raise a number, not lower one.
    #[tokio::test]
    async fn stats_distinguishes_backoff_from_a_watermark_pause() {
        let state = test_state(&[]).await;
        // Three feeds: one healthy, one flaky, one long dead.
        for (url, errors) in [
            ("https://ok.example/f.xml", 0),
            ("https://flaky.example/f.xml", 2),
            ("https://dead.example/f.xml", 9),
        ] {
            store::upsert_feed(
                &state.db,
                &store::NewFeed {
                    url: url.to_string(),
                    // Pushed forward, exactly as backoff does — so none of these
                    // are counted as `overdue`.
                    next_poll: Some("2099-01-01T00:00:00Z".to_string()),
                    ..Default::default()
                },
            )
            .await
            .unwrap();
            for _ in 0..errors {
                store::bump_feed_errors(
                    &state.db,
                    url,
                    feed::FailureKind::Fetch,
                    "connection refused",
                )
                .await
                .unwrap();
            }
        }

        let render_stats = |state: AppState| async move {
            let resp = router(state)
                .oneshot(
                    Request::builder()
                        .uri("/stats")
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::OK);
            String::from_utf8(
                axum::body::to_bytes(resp.into_body(), usize::MAX)
                    .await
                    .unwrap()
                    .to_vec(),
            )
            .unwrap()
        };

        // **The fixture must actually be RUNNING, or this test measures nothing.**
        // `test_state` leaves `schedulers_enabled` false, and `fetching_state`
        // checks that BEFORE the watermark — so without these two lines every
        // render below reports "off" and the watermark can never surface. The
        // assertions still passed, for reasons unrelated to what they name: see
        // the two comments below.
        state.runtime_health.set_schedulers_enabled(true);
        state
            .runtime_health
            .poll_tick_completed(crate::store::now_unix());

        let body = render_stats(state.clone()).await;
        assert!(
            body.contains("Failing"),
            "backoff is still invisible on the public page"
        );
        // 2 failing, 1 of them badly (>= BADLY_BROKEN_ERRORS). Matched on the
        // value rather than on surrounding whitespace, so re-indenting the
        // template cannot break this.
        assert!(
            body.contains("2, 1 badly"),
            "expected '2, 1 badly' in the failing row; got:\n{}",
            body.split("Failing")
                .nth(1)
                .unwrap_or("")
                .chars()
                .take(300)
                .collect::<String>()
        );
        // Not paused, and the backlog is genuinely empty — which is exactly the
        // reading that used to be indistinguishable from healthy.
        //
        // **Asserted by EXCLUDING the other states, not by matching "running".**
        // The `off` row reads "the poller is not running on this instance", which
        // contains "running" — so the bare substring passed while the page was
        // reporting the exact opposite of what this line claims to check.
        assert!(
            !body.contains("the poller is not running")
                && !body.contains("the cache is at its size limit")
                && !body.contains("has not completed a round"),
            "expected the running state; the page reported a stopped one",
        );

        // Now trip the watermark. Nothing in the database changes; only the
        // recorded runtime state does — which is the whole reason it needed a
        // home outside the log stream.
        state.runtime_health.set_watermark(true);
        let paused = render_stats(state.clone()).await;
        // Matched on the paused row's OWN sentence. The bare word "paused" also
        // appeared in the page's explanatory prose, so this assertion passed
        // whether or not the row rendered — and trimming that prose is what
        // exposed it. This phrase exists only inside the `paused` branch.
        assert!(
            paused.contains("the cache is at its size limit"),
            "a watermark pause is still invisible on the public page"
        );

        // Still no identifiers: these are counts, not feeds.
        for leak in ["ok.example", "flaky.example", "dead.example", "did:"] {
            assert!(
                !paused.contains(leak),
                "the public page leaked {leak:?} while reporting failures"
            );
        }
    }

    /// **`/admin/metrics` is gated, and nothing checked that it was.**
    ///
    /// Deleting the `admin_seed_dids` check left the entire suite green. That
    /// was survivable while the page held only aggregate timings; it is not now,
    /// because this branch puts **per-feed URLs and remote error text** behind
    /// that gate. A guarantee nothing checks is a comment, and this one is now
    /// the only thing standing between a signed-in stranger and the operational
    /// picture the handler's own doc says is not public.
    ///
    /// All three doors: no session, a session that is not an admin, and the
    /// admin itself.
    #[tokio::test]
    async fn admin_metrics_is_refused_to_everyone_but_an_admin() {
        let admin = "did:plc:adminseed";
        // **Only the admin is in ALLOWED_DIDS**, because `admin_seed_dids()`
        // IS that list — deliberately, per its doc: "the same people I trust on
        // this instance". Production sets it to the bootstrap DID alone.
        //
        // A genuine non-admin is therefore someone holding a beta seat granted
        // by an invite, not by the allow-list. Seeding both would have made
        // both admins and quietly turned the 403 assertion below into a test of
        // nothing — which is exactly what the first draft of this did.
        let state = test_state(&[admin]).await;
        store::grant_access(&state.db, "did:plc:ordinaryuser", None, "invite", None)
            .await
            .unwrap();
        let url = "https://broken.example/f.xml";
        store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: url.to_string(),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        store::bump_feed_errors(
            &state.db,
            url,
            feed::FailureKind::Fetch,
            "SENTINEL_ADMIN_ONLY",
        )
        .await
        .unwrap();

        let get = |state: AppState, cookie: Option<String>| async move {
            let mut req = Request::builder().uri("/admin/metrics");
            if let Some(c) = cookie {
                req = req.header(header::COOKIE, c);
            }
            let resp = router(state)
                .oneshot(req.body(Body::empty()).unwrap())
                .await
                .unwrap();
            let status = resp.status();
            let body = String::from_utf8(
                axum::body::to_bytes(resp.into_body(), usize::MAX)
                    .await
                    .unwrap()
                    .to_vec(),
            )
            .unwrap();
            (status, body)
        };

        // No session at all.
        let (status, body) = get(state.clone(), None).await;
        assert_eq!(status, StatusCode::UNAUTHORIZED);
        assert!(
            !body.contains("SENTINEL_ADMIN_ONLY"),
            "leaked to anonymous: {body}"
        );

        // A real, signed-in user who is not an admin.
        let ordinary = session_cookie(&state, "did:plc:ordinaryuser", None);
        let (status, body) = get(state.clone(), Some(ordinary)).await;
        assert_eq!(
            status,
            StatusCode::FORBIDDEN,
            "a non-admin session was let in"
        );
        assert!(
            !body.contains("SENTINEL_ADMIN_ONLY") && !body.contains("broken.example"),
            "leaked to a non-admin: {body}",
        );

        // The admin does get it — otherwise the two refusals above are
        // satisfied by the endpoint being broken for everyone.
        let admin_cookie = session_cookie(&state, admin, None);
        let (status, body) = get(state, Some(admin_cookie)).await;
        assert_eq!(status, StatusCode::OK);
        assert!(
            body.contains("SENTINEL_ADMIN_ONLY"),
            "admin cannot see it: {body}"
        );
    }

    /// **The cause a public count cannot carry belongs on the admin page.**
    ///
    /// The public histogram is four coarse buckets, and `fetch` is the coarsest:
    /// #159's own error — `guarded_get` bailing on a 304 — lands there beside
    /// DNS failure, timeout and SSRF refusal. So the histogram alone would NOT
    /// have separated "sixty dead publishers" from "one bug here", which is the
    /// case it was justified by.
    ///
    /// The answer is not a finer public vocabulary — `/stats` promises never
    /// which feed and never whose, and a bucket per error string would break
    /// that. It is to put the detail where per-feed data is already allowed.
    /// `/admin/metrics` is gated on `ALLOWED_DIDS` and already carries an
    /// operational picture.
    ///
    /// Asserts both halves: the detail IS on the admin page, and is NOT on the
    /// public one.
    #[tokio::test]
    async fn the_admin_page_names_failing_feeds_and_the_public_page_does_not() {
        let admin = "did:plc:adminseed";
        let state = test_state(&[admin]).await;
        let url = "https://broken.example/f.xml";
        store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: url.to_string(),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        store::bump_feed_errors(
            &state.db,
            url,
            feed::FailureKind::Fetch,
            "SENTINEL_REDIRECT_NO_LOCATION",
        )
        .await
        .unwrap();

        let cookie = session_cookie(&state, admin, None);
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .uri("/admin/metrics")
                    .header(header::COOKIE, cookie)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let admin_body = String::from_utf8(
            axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap()
                .to_vec(),
        )
        .unwrap();
        assert!(
            admin_body.contains("SENTINEL_REDIRECT_NO_LOCATION"),
            "the admin page does not carry the failure detail: {admin_body}",
        );
        assert!(
            admin_body.contains("broken.example"),
            "the admin page does not name the failing feed: {admin_body}",
        );

        // The public page still carries neither.
        let resp = router(state)
            .oneshot(
                Request::builder()
                    .uri("/stats")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let public = String::from_utf8(
            axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap()
                .to_vec(),
        )
        .unwrap();
        for secret in ["SENTINEL_REDIRECT_NO_LOCATION", "broken.example"] {
            assert!(
                !public.contains(secret),
                "{secret:?} reached the PUBLIC stats page: {public}",
            );
        }
    }

    /// **A direct poll must settle the error columns, like the scheduler does.**
    ///
    /// `add_subscription` polls through `feed::poll_feed` rather than the
    /// scheduler, and `poll_feed` writes validators and `last_polled` but never
    /// touches `consecutive_errors` — that is the scheduler's job, and this path
    /// is not the scheduler.
    ///
    /// So a feed that was failing, is re-subscribed, and polls SUCCESSFULLY kept
    /// its old count and its old cause: the public page went on reporting it
    /// under `Failing`, under `badly_broken`, and under a cause, for as long as
    /// the stale backoff horizon lasted — up to 24h — while the reader was
    /// demonstrably fetching it.
    #[tokio::test]
    async fn a_successful_direct_poll_clears_a_stale_failure() {
        let state = test_state(&[]).await;
        let url = "https://recovered.example/f.xml";
        store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: url.to_string(),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        store::bump_feed_errors(&state.db, url, feed::FailureKind::Fetch, "SENTINEL_OLD")
            .await
            .unwrap();
        // Park it on a stale backoff horizon, as a real failing feed would be.
        sqlx::query("UPDATE feeds SET next_poll = '2099-01-01T00:00:00Z' WHERE url = ?1")
            .bind(url)
            .execute(&state.db)
            .await
            .unwrap();

        // The publisher is fixed: a successful poll happens on this path.
        feed::settle_poll(
            &state.db,
            url,
            &feed::PollOutcome::NotModified,
            state.config.poll_interval,
        )
        .await;

        let row: (i64, Option<String>, Option<String>) = sqlx::query_as(
            "SELECT consecutive_errors, last_error_kind, next_poll FROM feeds WHERE url = ?1",
        )
        .bind(url)
        .fetch_one(&state.db)
        .await
        .unwrap();
        assert_eq!(row.0, 0, "a successful direct poll left the error streak");
        assert_eq!(row.1, None, "a successful direct poll left a stale cause");
        // **The half the first fix missed.** Clearing the count fixed the
        // REPORTING; the feed stayed parked until 2099. A working feed must be
        // rescheduled on its normal cadence, not left on the failure horizon.
        let next = row.2.expect("next_poll was cleared to NULL");
        // Not merely "moved off 2099" — rescheduled on the CADENCE, not a
        // backoff. A mutation that reschedules successes with backoff_for(1)
        // (5 min) also moves it off 2099, so the interval is asserted.
        let parsed = chrono::DateTime::parse_from_rfc3339(&next).unwrap();
        let delta = parsed
            .signed_duration_since(chrono::Utc::now())
            .num_seconds();
        let cadence = state.config.poll_interval.as_secs() as i64;
        assert!(
            (cadence - 60..=cadence + 60).contains(&delta),
            "expected rescheduling on the {cadence}s cadence, got {delta}s (next_poll={next})"
        );
    }

    /// The mirror case: a first poll that FAILS must be visible at all.
    ///
    /// `Ok(outcome) => info!(...)` discarded a `PollOutcome::Failed`, so a
    /// subscription whose very first fetch failed sat at `consecutive_errors = 0`
    /// with a NULL cause — invisible to the page built to count exactly that.
    #[tokio::test]
    async fn a_failing_direct_poll_is_recorded() {
        let state = test_state(&[]).await;
        let url = "https://born-broken.example/f.xml";
        store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: url.to_string(),
                ..Default::default()
            },
        )
        .await
        .unwrap();

        feed::settle_poll(
            &state.db,
            url,
            &feed::PollOutcome::Failed {
                backoff: std::time::Duration::from_secs(300),
                kind: feed::FailureKind::Parse,
                detail: "SENTINEL_BORN_BROKEN".to_string(),
            },
            state.config.poll_interval,
        )
        .await;

        let row: (i64, Option<String>, Option<String>) = sqlx::query_as(
            "SELECT consecutive_errors, last_error_kind, next_poll FROM feeds WHERE url = ?1",
        )
        .bind(url)
        .fetch_one(&state.db)
        .await
        .unwrap();
        assert_eq!(row.0, 1, "a failed first poll was not counted");
        assert_eq!(
            row.1.as_deref(),
            Some("parse"),
            "its cause was not recorded"
        );
        // And it is BACKED OFF on the schedule the scheduler would use — not
        // left with a NULL next_poll that `due_feeds` sorts first and re-polls
        // on the very next tick.
        let next = row.2.expect("a failed direct poll left next_poll NULL");
        let parsed = chrono::DateTime::parse_from_rfc3339(&next).unwrap();
        let delta = parsed
            .signed_duration_since(chrono::Utc::now())
            .num_seconds();
        assert!(
            (240..=360).contains(&delta),
            "expected ~300s backoff after one failure, got {delta}s (next_poll={next})"
        );
    }

    /// **The breakdown must sum to the Failing figure above it.**
    ///
    /// The histogram counts `last_error_kind IS NOT NULL`; `Failing` counts
    /// `consecutive_errors > 0`. On a migrated database every row that was
    /// already failing has a NULL kind — correctly, it was never recorded — so
    /// the two do not reconcile and the page shows "70 failing" beside "3
    /// fetch" with 67 silently unaccounted for. On deploy day the row vanishes
    /// entirely while the prose still promises a breakdown.
    ///
    /// An explicit `unknown` bucket is the honest shape: the page says how many
    /// it cannot explain rather than omitting them.
    #[tokio::test]
    async fn the_failure_breakdown_accounts_for_every_failing_feed() {
        let state = test_state(&[]).await;
        // Two legacy rows: failing, with no recorded cause.
        for url in [
            "https://legacy1.example/f.xml",
            "https://legacy2.example/f.xml",
        ] {
            store::upsert_feed(
                &state.db,
                &store::NewFeed {
                    url: url.to_string(),
                    next_poll: Some("2099-01-01T00:00:00Z".to_string()),
                    ..Default::default()
                },
            )
            .await
            .unwrap();
            sqlx::query("UPDATE feeds SET consecutive_errors = 4 WHERE url = ?1")
                .bind(url)
                .execute(&state.db)
                .await
                .unwrap();
        }
        // One row with a recorded cause.
        store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://known.example/f.xml".to_string(),
                next_poll: Some("2099-01-01T00:00:00Z".to_string()),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        store::bump_feed_errors(
            &state.db,
            "https://known.example/f.xml",
            feed::FailureKind::Status,
            "SENTINEL",
        )
        .await
        .unwrap();

        let now = chrono::Utc::now();
        let health = store::poll_health(
            &state.db,
            &now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            &(now - chrono::Duration::hours(1)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
        )
        .await
        .unwrap();
        let counted: i64 = health.failure_kinds.iter().map(|(_, n)| n).sum();
        assert_eq!(
            counted, health.in_backoff,
            "the breakdown ({counted}) does not account for all {} failing feeds: {:?}",
            health.in_backoff, health.failure_kinds,
        );
        assert!(
            health
                .failure_kinds
                .iter()
                .any(|(k, n)| k == "unknown" && *n == 2),
            "no unknown bucket for the legacy rows: {:?}",
            health.failure_kinds,
        );
    }

    /// **The breakdown is ordered by count, and the assertion can see it.**
    ///
    /// The first version of this asserted with three `contains` calls, which
    /// cannot observe order — deleting `ORDER BY` from the query passed.
    #[tokio::test]
    async fn the_failure_breakdown_is_ordered_by_count() {
        let state = test_state(&[]).await;
        for (url, kind, n) in [
            ("https://p1.example/f.xml", feed::FailureKind::Parse, 1),
            ("https://f1.example/f.xml", feed::FailureKind::Fetch, 1),
            ("https://f2.example/f.xml", feed::FailureKind::Fetch, 1),
            ("https://f3.example/f.xml", feed::FailureKind::Fetch, 1),
            ("https://s1.example/f.xml", feed::FailureKind::Status, 1),
            ("https://s2.example/f.xml", feed::FailureKind::Status, 1),
        ] {
            store::upsert_feed(
                &state.db,
                &store::NewFeed {
                    url: url.to_string(),
                    next_poll: Some("2099-01-01T00:00:00Z".to_string()),
                    ..Default::default()
                },
            )
            .await
            .unwrap();
            for _ in 0..n {
                store::bump_feed_errors(&state.db, url, kind, "d")
                    .await
                    .unwrap();
            }
        }
        let now = chrono::Utc::now();
        let health = store::poll_health(
            &state.db,
            &now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            &(now - chrono::Duration::hours(1)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
        )
        .await
        .unwrap();
        let labels: Vec<&str> = health
            .failure_kinds
            .iter()
            .map(|(k, _)| k.as_str())
            .collect();
        assert_eq!(
            labels,
            ["fetch", "status", "parse"],
            "not ordered by count, descending: {:?}",
            health.failure_kinds,
        );
    }

    /// **Failing feeds are grouped by CAUSE, and still never named.**
    ///
    /// `badly_broken` could say that sixty feeds were failing and not whether
    /// that was sixty dead publishers or one bug here. It was the latter — #159,
    /// a `304 Not Modified` read as a malformed redirect — and the page could
    /// not say so, which is most of why it went unexamined.
    ///
    /// The second half of this test is the constraint that shapes the first:
    /// `/stats` is public and promises machines-not-people, *never which feed
    /// and never whose*. A histogram of causes keeps that promise; a list of
    /// failing URLs would break it, and is the obvious way to build this.
    #[tokio::test]
    async fn stats_groups_failures_by_cause_without_naming_any_feed() {
        let state = test_state(&[]).await;
        for (url, kind, detail, errors) in [
            // Detail strings are distinctive SENTINELS, not plausible English.
            // A first pass used "not a feed", which the page's own explanation
            // of the `parse` kind contains verbatim — the privacy assertion
            // fired on static copy rather than on a leak. A sentinel cannot
            // collide with prose.
            (
                "https://a.example/f.xml",
                feed::FailureKind::Fetch,
                "SENTINEL_CONNREFUSED",
                3,
            ),
            (
                "https://b.example/f.xml",
                feed::FailureKind::Fetch,
                "SENTINEL_DNSFAIL",
                2,
            ),
            (
                "https://c.example/f.xml",
                feed::FailureKind::Status,
                "SENTINEL_404",
                1,
            ),
            (
                "https://d.example/f.xml",
                feed::FailureKind::Parse,
                "SENTINEL_UNPARSEABLE",
                1,
            ),
        ] {
            store::upsert_feed(
                &state.db,
                &store::NewFeed {
                    url: url.to_string(),
                    next_poll: Some("2099-01-01T00:00:00Z".to_string()),
                    ..Default::default()
                },
            )
            .await
            .unwrap();
            for _ in 0..errors {
                store::bump_feed_errors(&state.db, url, kind, detail)
                    .await
                    .unwrap();
            }
        }

        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .uri("/stats")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = String::from_utf8(
            axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap()
                .to_vec(),
        )
        .unwrap();

        // Descending by count: two fetch, then one each, tie-broken by name.
        assert!(
            body.contains("2 fetch") && body.contains("1 status") && body.contains("1 parse"),
            "the cause histogram did not render: {body}",
        );

        // **The privacy half.** No feed URL, host, or error detail reaches the
        // public page — only counts by kind.
        for secret in [
            "a.example",
            "b.example",
            "c.example",
            "d.example",
            "SENTINEL_CONNREFUSED",
            "SENTINEL_DNSFAIL",
            "SENTINEL_404",
            "SENTINEL_UNPARSEABLE",
        ] {
            assert!(
                !body.contains(secret),
                "{secret:?} reached the PUBLIC stats page: {body}",
            );
        }
    }

    /// `/health` must prove the process can reach its database, and must report
    /// the loop state without letting it change the status code.
    #[tokio::test]
    async fn health_checks_the_database_and_reports_the_loops() {
        let state = test_state(&[]).await;
        let body_of = |state: AppState| async move {
            let resp = router(state)
                .oneshot(
                    Request::builder()
                        .uri("/health")
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
            let status = resp.status();
            let body = String::from_utf8(
                axum::body::to_bytes(resp.into_body(), usize::MAX)
                    .await
                    .unwrap()
                    .to_vec(),
            )
            .unwrap();
            (status, body)
        };

        // The boot stamp is what `main` sets; the router alone does not, so this
        // starts "unknown" and the uptime branch below drives it explicitly.
        state
            .runtime_health
            .set_started_at(chrono::Utc::now().timestamp());

        let (status, body) = body_of(state.clone()).await;
        assert_eq!(status, StatusCode::OK);
        assert!(
            body.contains("db: ok"),
            "health did not probe the DB: {body}"
        );
        assert!(
            body.contains("uptime:"),
            "no uptime — the first thing anyone asks about a container that may \
             be restarting: {body}"
        );
        assert!(body.contains("poller:"), "no scheduler heartbeat: {body}");
        assert!(body.contains("polling-paused: no"), "{body}");
        assert!(body.contains("backend:"), "{body}");
        assert!(body.contains("oauth-runtime:"), "{body}");

        // A watermark pause is REPORTED but must not fail the check. A failed
        // check DEREGISTERS this machine from the proxy — and it is the only
        // machine — so it would turn "feeds are behind" into "the site is down"
        // for as long as the disk stays full.
        state.runtime_health.set_watermark(true);
        state.runtime_health.set_schedulers_enabled(true);
        let (status, body) = body_of(state.clone()).await;
        assert_eq!(
            status,
            StatusCode::OK,
            "a watermark pause must not fail the liveness check: {body}"
        );
        assert!(body.contains("polling-paused: yes"), "{body}");
        // Schedulers on but no tick yet — and that must not read as "0s ago",
        // which is the healthiest possible answer to an unanswered question.
        assert!(
            body.contains("poller: not-yet-ticked"),
            "a never-ticked poller must say so: {body}"
        );

        // A stale heartbeat is likewise reported, not fatal.
        let stale_after = health_tick_stale_secs(configured_poll_tick());
        let long_ago = chrono::Utc::now().timestamp() - (stale_after + 60);
        state.runtime_health.poll_tick_completed(long_ago);
        let (status, body) = body_of(state.clone()).await;
        assert_eq!(
            status,
            StatusCode::OK,
            "a stale poller must not 503: {body}"
        );
        assert!(body.contains("poller: stale"), "{body}");

        // **A poller that has never ticked stops being benign.**
        //
        // In a crash loop with 30 s+ boot cycles the poller never reaches its
        // first tick, so `not-yet-ticked` was reported forever and the heartbeat
        // could not detect the one failure mode the startup delays were added
        // for. It is read against uptime now.
        state.runtime_health.poll_tick_completed(0); // reset to "never"
        state
            .runtime_health
            .set_started_at(chrono::Utc::now().timestamp() - (HEALTH_FIRST_TICK_GRACE_SECS + 60));
        let (status, body) = body_of(state.clone()).await;
        assert_eq!(status, StatusCode::OK);
        assert!(
            body.contains("poller: stale never-ticked"),
            "a poller that never ticked long after boot still reads as benign: {body}"
        );

        // A closed pool is a real outage: nothing can be served, and a restart is
        // the correct response. THIS is what the status code is for.
        state.db.close().await;
        let (status, body) = body_of(state.clone()).await;
        assert_eq!(
            status,
            StatusCode::SERVICE_UNAVAILABLE,
            "an unreachable database must fail the check: {body}"
        );
        assert!(body.starts_with("FAIL"), "{body}");
        // Coarse, not the raw sqlx error: an unauthenticated caller learning
        // exactly which failure it hit is an attack-progress oracle, and this
        // endpoint is exempt from the origin lock.
        assert!(
            !body.contains("PoolClosed") && !body.contains("sqlx"),
            "health leaked the raw database error to an unauthenticated caller: {body}"
        );
    }

    /// The staleness threshold must track the configured tick.
    ///
    /// Hardcoded at 15 minutes, an operator who raised
    /// `FEATHERREADER_POLL_TICK_SECS` above 900 got a permanent `poller: stale`
    /// in the body the deployment docs tell them to alert on.
    #[test]
    fn the_stale_threshold_follows_the_poll_tick() {
        // A fast tick keeps the floor — five 60 s ticks is 5 minutes, and
        // alerting that early would fire on any brief hiccup.
        assert_eq!(
            health_tick_stale_secs(Duration::from_secs(60)),
            HEALTH_TICK_STALE_FLOOR_SECS
        );
        // A slow tick raises it, so a legitimately-configured loop is never
        // permanently "stale".
        let slow = Duration::from_secs(30 * 60);
        assert!(
            health_tick_stale_secs(slow) > slow.as_secs() as i64,
            "a 30-minute tick must not be stale after one interval"
        );
        assert_eq!(health_tick_stale_secs(slow), 30 * 60 * 5);
        // And it cannot overflow into nonsense on an absurd value.
        assert!(health_tick_stale_secs(Duration::from_secs(u64::MAX)) > 0);
    }

    /// `/stats` must distinguish "nothing is polling" from "polling is fine".
    ///
    /// `polling_paused` alone rendered "running" for three different states,
    /// including the two where nothing polls at all — on the page added to
    /// answer exactly that question.
    #[tokio::test]
    async fn stats_does_not_call_a_stopped_poller_running() {
        let state = test_state(&[]).await;
        let render = |state: AppState| async move {
            let resp = router(state)
                .oneshot(
                    Request::builder()
                        .uri("/stats")
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::OK);
            String::from_utf8(
                axum::body::to_bytes(resp.into_body(), usize::MAX)
                    .await
                    .unwrap()
                    .to_vec(),
            )
            .unwrap()
        };

        // Schedulers never started: not "running".
        let body = render(state.clone()).await;
        assert!(
            body.contains("the poller is not running on this instance"),
            "a disabled poller renders as healthy"
        );

        // Started, but no tick has finished yet.
        state.runtime_health.set_schedulers_enabled(true);
        let body = render(state.clone()).await;
        assert!(
            body.contains("no poll has finished since this instance booted"),
            "a poller that has not ticked renders as healthy"
        );

        // Ticking: running.
        state
            .runtime_health
            .poll_tick_completed(chrono::Utc::now().timestamp());
        let body = render(state.clone()).await;
        assert!(
            body.contains("running"),
            "a healthy poller must read as running"
        );

        // Paused at the watermark still wins over "running".
        state.runtime_health.set_watermark(true);
        let body = render(state.clone()).await;
        assert!(
            body.contains("the cache is at its size limit"),
            "a watermark pause is hidden once the poller is ticking"
        );
    }

    /// **An UNMEASURED database must not fail the check.**
    ///
    /// `/health` is the one path exempt from the Cloudflare origin lock and
    /// absent from the rate limiter, and `DbProbeGuard` releases its claim on
    /// drop WITHOUT recording a verdict — so a cancelled request (a client
    /// disconnect is enough) leaves the verdict at "none", and a concurrent
    /// caller reads it. Treating that as a failure turned an unauthenticated
    /// request into a lever on the only signal the platform acts on. The
    /// previous version of this code had the opposite bug and reported `ok` for
    /// a database nothing had read; "unknown" is neither.
    #[tokio::test]
    async fn health_reports_an_unmeasured_database_without_failing() {
        use crate::runtime_health::DbProbe;
        let state = test_state(&[]).await;

        // Hold the probe claim, exactly as an in-flight request would, and never
        // record a verdict — the cancelled-request state.
        let held = state
            .runtime_health
            .begin_db_probe()
            .unwrap_or_else(|_| panic!("a fresh RuntimeHealth must grant the first claim"));

        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let status = resp.status();
        let body = String::from_utf8(
            axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap()
                .to_vec(),
        )
        .unwrap();
        drop(held);

        assert_eq!(
            status,
            StatusCode::OK,
            "an unmeasured database failed the check, which an unauthenticated \
             caller can cause on demand: {body}"
        );
        assert!(
            body.contains("db: unknown"),
            "the unmeasured state must still be REPORTED: {body}"
        );
        assert!(!body.starts_with("FAIL"), "{body}");
        // **And it must not read as `ok` either.** `fly.toml` tells operators to
        // alert on the BODY for everything the status code ignores, so a first
        // line identical to the healthy one makes a monitor keying on `^ok` read
        // green in exactly the state this enum exists to surface.
        assert!(
            !body.starts_with("ok"),
            "the unmeasured state is indistinguishable from healthy to a \
             body-matching monitor: {body}"
        );
        assert!(body.starts_with("unknown"), "{body}");

        // **A BORROWED failure must 503 too.**
        //
        // This previously recorded `Failed` and then closed the pool — but
        // `record` consumes the guard and releases the claim, so the request won
        // it, ran a live probe against the closed pool, and failed on its own.
        // The 503 passed for the wrong reason and the borrow path — the whole
        // point of the three-state enum on the read side — had no coverage.
        //
        // Holding the claim forces the borrow, so the recorded verdict is what
        // gets reported.
        let held = state
            .runtime_health
            .begin_db_probe()
            .unwrap_or_else(|_| panic!("claim"));
        state
            .runtime_health
            .record_for_test(DbProbe::Failed("unavailable".to_string()));
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let status = resp.status();
        let body = String::from_utf8(
            axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap()
                .to_vec(),
        )
        .unwrap();
        drop(held);
        assert_eq!(
            status,
            StatusCode::SERVICE_UNAVAILABLE,
            "a BORROWED failure verdict must fail the check, not just a freshly \
             measured one: {body}"
        );
        assert!(body.starts_with("FAIL"), "{body}");

        state.db.close().await;
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::SERVICE_UNAVAILABLE,
            "a measured database failure must still fail the check"
        );
    }

    /// **A disconnected client must not be able to cancel the probe.**
    ///
    /// Axum drops the handler future when a caller goes away. With the probe
    /// inline that dropped it mid-flight and released the claim WITHOUT
    /// recording a verdict — which let an unauthenticated caller manufacture the
    /// no-verdict state on demand and freeze what every other caller, including
    /// Fly's own check, reads. The probe runs detached now, so the verdict is
    /// recorded whatever happens to the request that started it.
    #[tokio::test]
    async fn an_abandoned_request_still_records_its_probe() {
        use crate::runtime_health::DbProbe;
        let state = test_state(&[]).await;
        let rh = state.runtime_health.clone();

        // Drive /health and abandon it immediately — the disconnect case.
        let app = router(state.clone());
        let fut = app.oneshot(
            Request::builder()
                .uri("/health")
                .body(Body::empty())
                .unwrap(),
        );
        let handle = tokio::spawn(fut);
        handle.abort();
        let _ = handle.await;

        // The detached probe still completes and publishes a verdict, so the
        // claim is free and the next caller gets a MEASURED answer.
        for _ in 0..50 {
            if rh.begin_db_probe().is_ok() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        let resp = router(state.clone())
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let body = String::from_utf8(
            axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap()
                .to_vec(),
        )
        .unwrap();
        assert!(
            body.contains("db: ok"),
            "after an abandoned request the next caller still reads an \
             unmeasured database — the probe was cancelled with it: {body}"
        );
        // Sanity: the type still distinguishes the three states.
        assert_ne!(DbProbe::Unknown, DbProbe::Ok);
    }

    /// **The probe must read a real page.**
    ///
    /// `SELECT 1` compiles to `Init/Integer/ResultRow/Halt` — no `OpenRead`, so
    /// it never touches a b-tree and returns success against a corrupted
    /// database. Asserted by asking SQLite what the statement actually compiles
    /// to, so it survives someone "simplifying" the query later.
    #[tokio::test]
    async fn the_health_probe_opens_a_real_table() {
        use sqlx::Row;
        let state = test_state(&[]).await;
        // `EXPLAIN` lists the VM program; the `opcode` column is the second.
        let opcodes = |sql: &'static str| {
            let db = state.db.clone();
            async move {
                sqlx::query(sql)
                    .fetch_all(&db)
                    .await
                    .unwrap()
                    .into_iter()
                    .map(|r| r.get::<String, _>("opcode"))
                    .collect::<Vec<String>>()
            }
        };

        // The statement `health_db_probe` really runs — it is the sole path, so
        // there is no second string for the handler to use instead.
        let explain: &'static str =
            Box::leak(format!("EXPLAIN {HEALTH_DB_PROBE_SQL}").into_boxed_str());
        let probe = opcodes(explain).await;
        // And the probe itself works against a real schema.
        assert!(
            health_db_probe(&state.db).await.is_ok(),
            "the probe does not run against the real schema",
        );
        assert!(
            probe.iter().any(|op| op == "OpenRead"),
            "the health probe reads no page; it cannot detect a broken database: {probe:?}"
        );
        // And the bare form genuinely does not, which is the whole point.
        let bare = opcodes("EXPLAIN SELECT 1").await;
        assert!(
            !bare.iter().any(|op| op == "OpenRead"),
            "premise check failed: bare SELECT 1 now reads a page: {bare:?}"
        );
    }

    /// A fresh instance says "never", not "0" — which would read as "polled
    /// just now", the opposite of the truth.
    #[test]
    fn an_instance_that_has_never_polled_says_so() {
        assert_eq!(humanise_ago(None), "never");
        assert_eq!(humanise_ago(Some(0)), "0s ago");
        assert_eq!(humanise_ago(Some(59)), "59s ago");
        assert_eq!(humanise_ago(Some(60)), "1m ago");
        assert_eq!(humanise_ago(Some(3600)), "1h 0m ago");
        assert_eq!(humanise_ago(Some(11_460)), "3h 11m ago");
    }

    /// A sidecar mock that answers `/internal/repo` listRecords with one saved
    /// record, and anything else with an empty list. Serves repeatedly.
    async fn spawn_saved_sidecar(saved_url: &str, saved_title: &str) -> String {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let (url, title) = (saved_url.to_string(), saved_title.to_string());
        tokio::spawn(async move {
            loop {
                let Ok((mut sock, _)) = listener.accept().await else {
                    break;
                };
                let mut buf = vec![0u8; 8192];
                let Ok(n) = sock.read(&mut buf).await else {
                    continue;
                };
                let req = String::from_utf8_lossy(&buf[..n]).to_string();
                let wants_saved = req.contains("community.lexicon.rss.saved");
                let records = if wants_saved {
                    serde_json::json!([{
                        "uri": "at://did:plc:x/community.lexicon.rss.saved/rk1",
                        "cid": "bafy",
                        "value": {
                            "$type": "community.lexicon.rss.saved",
                            "url": url,
                            "title": title,
                            "createdAt": "2026-01-01T00:00:00Z"
                        }
                    }])
                } else {
                    serde_json::json!([])
                };
                let body = serde_json::json!({
                    "ok": true, "data": { "records": records }
                })
                .to_string();
                let resp = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
                    body.len(), body
                );
                let _ = sock.write_all(resp.as_bytes()).await;
                let _ = sock.flush().await;
            }
        });
        format!("http://{addr}")
    }

    /// A sidecar mock serving `n` distinct saved records, none of them cached
    /// locally — the shape that exercises the uncached-row append.
    async fn spawn_saved_sidecar_many(n: usize, subscribed_feed: &str) -> String {
        let feed = subscribed_feed.to_string();
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            loop {
                let Ok((mut sock, _)) = listener.accept().await else {
                    break;
                };
                let mut buf = vec![0u8; 8192];
                let Ok(read) = sock.read(&mut buf).await else {
                    continue;
                };
                let req = String::from_utf8_lossy(&buf[..read]).to_string();
                let records = if req.contains("community.lexicon.rss.saved") {
                    serde_json::Value::Array(
                        (0..n)
                            .map(|i| {
                                serde_json::json!({
                                    "uri": format!("at://did:plc:x/community.lexicon.rss.saved/rk{i}"),
                                    "cid": "bafy",
                                    "value": {
                                        "$type": "community.lexicon.rss.saved",
                                        "url": format!("https://elsewhere.example/{i}"),
                                        "title": format!("Elsewhere {i}"),
                                        "createdAt": "2026-01-01T00:00:00Z"
                                    }
                                })
                            })
                            .collect(),
                    )
                } else if req.contains("community.lexicon.rss.subscription") {
                    // Without this the handler's `sync_sub_refs` would REPLACE
                    // sub_ref with an empty set on every render, and every
                    // sub_ref-scoped read — including the cached starred list
                    // this test is about — would come back empty.
                    serde_json::json!([{
                        "uri": "at://did:plc:x/community.lexicon.rss.subscription/sub1",
                        "cid": "bafy",
                        "value": {
                            "$type": "community.lexicon.rss.subscription",
                            "url": feed,
                            "createdAt": "2026-01-01T00:00:00Z"
                        }
                    }])
                } else {
                    serde_json::json!([])
                };
                let body =
                    serde_json::json!({ "ok": true, "data": { "records": records } }).to_string();
                let resp = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
                    body.len(), body
                );
                let _ = sock.write_all(resp.as_bytes()).await;
                let _ = sock.flush().await;
            }
        });
        format!("http://{addr}")
    }

    /// **The pager must not advertise a page the clamp cannot reach.**
    ///
    /// The page clamp is computed from the CACHED total; the uncached PDS rows
    /// are appended to the last page rather than paged. Inflating `total` with
    /// them made `page_count` and the "Older →" link point one page past the end:
    /// requesting it clamped straight back, re-rendered the same last page, and
    /// still offered the link. An infinite "next" that never advances.
    #[tokio::test]
    async fn the_starred_pager_does_not_advertise_an_unreachable_page() {
        let did = "did:plc:pagerloop";
        let sidecar = spawn_saved_sidecar_many(80, "https://loop.example/feed.xml").await;
        let state = test_state_with_sidecar(&[], &sidecar).await;
        store::grant_access(&state.db, did, None, "test", None)
            .await
            .unwrap();
        let feed = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: "https://loop.example/feed.xml".to_string(),
                title: Some("Loop".to_string()),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        // 250 cached starred entries: the last page holds 50, so 50 + 80 > 100
        // and the old arithmetic reported a fourth page.
        let entries: Vec<store::NewEntry> = (0..250)
            .map(|i| store::NewEntry {
                guid: format!("s-{i:04}"),
                url: Some(format!("https://loop.example/{i}")),
                title: Some(format!("Starred {i:04}")),
                published: Some(format!("2026-06-{:02}T00:00:00Z", (i % 28) + 1)),
                ..Default::default()
            })
            .collect();
        store::insert_entries(&state.db, feed, &entries, 0)
            .await
            .unwrap();
        store::replace_sub_refs(&state.db, did, &[feed])
            .await
            .unwrap();
        for row in store::list_entries(&state.db, did, store::ListView::All, None, 1_000, 0)
            .await
            .unwrap()
        {
            store::mark_starred(&state.db, did, row.id, true)
                .await
                .unwrap();
        }

        let cookie = session_cookie(&state, did, None);
        let app = router(state.clone());
        let get = |uri: &str| {
            let (app, cookie, uri) = (app.clone(), cookie.clone(), uri.to_string());
            async move {
                let resp = app
                    .oneshot(
                        Request::builder()
                            .uri(uri)
                            .header(header::COOKIE, cookie)
                            .body(Body::empty())
                            .unwrap(),
                    )
                    .await
                    .unwrap();
                assert_eq!(resp.status(), StatusCode::OK);
                String::from_utf8(
                    axum::body::to_bytes(resp.into_body(), 16 * 1024 * 1024)
                        .await
                        .unwrap()
                        .to_vec(),
                )
                .unwrap()
            }
        };

        // 250 cached + 80 uncached = 330 rows over 4 pages. The pager and the
        // clamp must agree on that, and EVERY page it offers must have content —
        // the original bug advertised a fourth page that clamped back to the
        // third and re-rendered it, still offering the link.
        let p3 = get("/?view=starred&page=3").await;
        assert!(
            p3.contains("Page 3 of 4"),
            "the pager and the clamp disagree on the total: {}",
            p3.split("pager-pos")
                .nth(1)
                .unwrap_or("")
                .chars()
                .take(120)
                .collect::<String>()
        );
        // Page 3 is the boundary: the last 50 cached rows, then the first 50
        // uncached ones.
        assert!(
            p3.contains("Elsewhere 0"),
            "page 3 should start the uncached run"
        );
        assert_eq!(
            p3.matches("<li class=\"entry").count(),
            ENTRIES_PER_PAGE as usize,
            "the boundary page is not full"
        );

        // **The heading, which the previous round broke by deleting this.**
        //
        // `total` includes the uncached records, so the parenthetical is a
        // SUBSET of it, not an addition — "330 entries (80 saved elsewhere)".
        // The version that said "plus N" double counted once `total` started
        // including them, and N had become page-local in the same commit while
        // the template stayed put. It shipped because this assertion was deleted
        // rather than updated.
        {
            let body = &p3;
            assert!(
                body.contains("330 entries"),
                "the heading must count the whole sequence: {}",
                body.split("content-count")
                    .nth(1)
                    .unwrap_or("")
                    .chars()
                    .take(120)
                    .collect::<String>()
            );
            assert!(
                body.contains("(80 saved elsewhere)"),
                "the heading must say how many of the total the cache cannot show, \
                 as a whole-list figure and not a per-page one: {}",
                body.split("content-count")
                    .nth(1)
                    .unwrap_or("")
                    .chars()
                    .take(120)
                    .collect::<String>()
            );
            assert!(
                !body.contains("plus 50") && !body.contains("plus 80"),
                "the heading is adding the uncached rows to a total that already \
                 includes them"
            );
        }

        let p4 = get("/?view=starred&page=4").await;
        assert!(
            p4.contains("Page 4 of 4"),
            "page 4 was advertised but clamps somewhere else — the unreachable-page bug"
        );
        assert_eq!(
            p4.matches("<li class=\"entry").count(),
            30,
            "page 4 should hold the remaining 30 uncached records"
        );
        assert!(
            p4.contains("Elsewhere 79"),
            "the LAST saved record is unreachable — it can only be removed from here"
        );

        // No uncached record appears on two pages.
        assert!(
            !p4.contains("Elsewhere 0"),
            "an uncached record was rendered on more than one page"
        );
        // Page 1 is all cached — and still reports the same whole-list heading,
        // because the parenthetical describes the LIST, not the page.
        let first = get("/?view=starred").await;
        assert!(
            first.contains("330 entries") && first.contains("(80 saved elsewhere)"),
            "the heading changed between pages; it describes the list, not the page"
        );
        assert!(
            !first.contains("Elsewhere "),
            "uncached saved records leaked onto the first page"
        );
    }

    /// **A saved record whose article is not cached here is still shown.**
    ///
    /// The starred view is built from local `entries`, so before this a record
    /// starred in ANOTHER atproto reader — the portability the shared lexicon
    /// exists for — was simply invisible. It now renders from the PDS record,
    /// visually distinct, linking straight out.
    #[tokio::test]
    async fn a_saved_record_with_no_cached_entry_is_shown_as_a_link() {
        let did = "did:plc:ewvi7nxzyoun6zhxrhs64oiz";
        let sidecar =
            spawn_saved_sidecar("https://elsewhere.example/article", "Starred elsewhere").await;
        let mut state = test_state_with_sidecar(&[did], &sidecar).await;
        std::sync::Arc::get_mut(&mut state.config).unwrap().dev_did = Some(did.to_string());

        let resp = router(state)
            .oneshot(
                Request::builder()
                    .uri("/?view=starred")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = String::from_utf8(
            axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap()
                .to_vec(),
        )
        .unwrap();

        assert!(
            body.contains("Starred elsewhere"),
            "the saved record was not rendered at all"
        );
        assert!(
            body.contains("entry-uncached"),
            "it was not marked as uncached, so it looks like a normal entry"
        );
        assert!(
            body.contains("https://elsewhere.example/article"),
            "the row must link straight to the article"
        );
        assert!(
            !body.contains("/entries/0/"),
            "an uncached row must not offer entry actions against a nonexistent id"
        );
    }

    /// **A PDS `createdAt` must not be able to panic the starred view.**
    ///
    /// `display_date` byte-sliced `p[..10]`. Every prior caller passed a
    /// timestamp the feed parser produced; the saved-record path passes a bare
    /// string off a PDS record, written by whatever client the reader used. A
    /// multi-byte value panicked the handler, and with no catch-panic layer the
    /// view stayed down until the record was removed — from that same view.
    #[test]
    fn a_multibyte_timestamp_does_not_panic_the_date_formatter() {
        for hostile in [
            "日本語日本語日本",
            "é",
            "",
            "2026",
            "🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂",
        ] {
            let out = display_date(Some(hostile));
            assert!(out.chars().count() <= 10, "{hostile:?} -> {out:?}");
        }
        assert_eq!(display_date(Some("2026-01-01T00:00:00Z")), "2026-01-01");
        assert_eq!(display_date(None), "");
    }

    /// Unsaving makes a DPoP-signed PDS round-trip, which is the stated reason
    /// its neighbours are limited. It was added as a route and not added here.
    #[test]
    fn the_unsave_route_is_rate_limited() {
        use axum::http::Method;
        assert!(is_rate_limited_path("/saved/3abc/delete", &Method::POST));
        // And the neighbours still are.
        assert!(is_rate_limited_path("/entries/1/star", &Method::POST));
    }

    /// **The probe detects a broken database — asserted through `/health`
    /// itself, not through a string.**
    ///
    /// A named constant did not bind the handler: it stayed free to call
    /// `query_scalar` with a different literal, so degrading the real probe to
    /// `SELECT 1` shipped green twice over. This drops the table the probe reads
    /// and asserts the endpoint stops saying `ok` — behaviour no substituted SQL
    /// can fake, because `SELECT 1` still succeeds against a wrecked schema.
    #[tokio::test]
    async fn health_reports_a_broken_database() {
        let state = test_state(&[]).await;
        // Sanity: healthy first, so the assertion below is about the damage.
        assert!(
            health_db_probe(&state.db).await.is_ok(),
            "the fixture was not healthy to begin with",
        );

        sqlx::query("DROP TABLE feeds")
            .execute(&state.db)
            .await
            .unwrap();

        assert!(
            health_db_probe(&state.db).await.is_err(),
            "the probe reported success against a database missing the table it \
             claims to read; `SELECT 1` would do exactly this",
        );

        let resp = router(state)
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let body = String::from_utf8(
            axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap()
                .to_vec(),
        )
        .unwrap();
        // The documented contract: the FIRST token is the state.
        assert!(
            body.starts_with("FAIL"),
            "/health did not report FAIL for a broken database: {body}",
        );
        assert!(
            !body.contains("db: ok"),
            "/health still called the database ok: {body}",
        );
    }

    /// A sidecar mock for the OPML export: serves one subscription and one
    /// folder, except for the collection named in `fail_on`, which answers
    /// `500` — the shape a refused (short or unreadable) walk takes at this
    /// boundary.
    async fn spawn_export_sidecar(fail_on: Option<&'static str>) -> String {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            loop {
                let Ok((mut sock, _)) = listener.accept().await else {
                    break;
                };
                let mut buf = vec![0u8; 8192];
                let Ok(n) = sock.read(&mut buf).await else {
                    continue;
                };
                let req = String::from_utf8_lossy(&buf[..n]).to_string();
                let wants = |c: &str| req.contains(c);
                if fail_on.is_some_and(wants) {
                    let body = r#"{"ok":false,"error":"ShortList"}"#;
                    let resp = format!(
                        "HTTP/1.1 500 Internal Server Error\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
                        body.len(),
                        body
                    );
                    let _ = sock.write_all(resp.as_bytes()).await;
                    let _ = sock.flush().await;
                    continue;
                }
                let records = if wants(crate::lexicon::nsid::SUBSCRIPTION) {
                    serde_json::json!([{
                        "uri": "at://did:plc:exporter/community.lexicon.rss.subscription/sub1",
                        "cid": "bafy",
                        "value": {
                            "$type": crate::lexicon::nsid::SUBSCRIPTION,
                            "url": "https://kept.example/feed.xml",
                            "title": "Kept",
                            // Inside the folder, so the healthy export has to
                            // carry BOTH walks' results: an exporter that lost
                            // the folder list would flatten this outline out of
                            // its group with nothing else changing.
                            "folder": "at://did:plc:exporter/community.lexicon.rss.folder/fold1",
                            "createdAt": "2026-01-01T00:00:00Z"
                        }
                    }])
                } else if wants(crate::lexicon::nsid::FOLDER) {
                    serde_json::json!([{
                        "uri": "at://did:plc:exporter/community.lexicon.rss.folder/fold1",
                        "cid": "bafy",
                        "value": {
                            "$type": crate::lexicon::nsid::FOLDER,
                            "name": "Kept folder",
                            "createdAt": "2026-01-01T00:00:00Z"
                        }
                    }])
                } else {
                    serde_json::json!([])
                };
                let body =
                    serde_json::json!({ "ok": true, "data": { "records": records } }).to_string();
                let resp = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = sock.write_all(resp.as_bytes()).await;
                let _ = sock.flush().await;
            }
        });
        format!("http://{addr}")
    }

    /// A sidecar whose every `listRecords` page carries one good record and
    /// one with no `uri` — the #177 shape — for any collection.
    async fn spawn_malformed_sidecar() -> String {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            loop {
                let Ok((mut sock, _)) = listener.accept().await else {
                    break;
                };
                let mut buf = vec![0u8; 8192];
                let _ = sock.read(&mut buf).await;
                let body = serde_json::json!({ "ok": true, "data": { "records": [
                    { "uri": "at://did:plc:alerted/c/3labGOOD", "cid": "bafy", "value": {} },
                    { "cid": "bafy", "value": {} },
                ]}})
                .to_string();
                let resp = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = sock.write_all(resp.as_bytes()).await;
                let _ = sock.flush().await;
            }
        });
        format!("http://{addr}")
    }

    async fn page_body(state: AppState, did: &str, uri: &str) -> (StatusCode, String) {
        let cookie = session_cookie(&state, did, None);
        let resp = router(state)
            .oneshot(
                Request::builder()
                    .uri(uri)
                    .header(header::COOKIE, cookie)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let status = resp.status();
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        (status, String::from_utf8_lossy(&body).to_string())
    }

    /// **0.4.0 step 4: a publication document with neither summary field
    /// renders as a title, a date and a link** — 8% of measured documents
    /// (37 of 449) carry neither `description` nor `textContent`. That is what
    /// an RSS reader shows for a title-only feed, not an error, in the list and
    /// on the article page alike.
    #[tokio::test]
    async fn a_publication_entry_with_no_summary_renders_title_date_and_link() {
        let did = "did:plc:displayer";
        let state = test_state(&[did]).await;
        let url = "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab";
        let feed_id = store::upsert_feed(
            &state.db,
            &store::NewFeed {
                url: url.into(),
                title: Some("Quiet Journal".into()),
                ..Default::default()
            },
        )
        .await
        .unwrap();
        store::replace_sub_refs(&state.db, did, &[feed_id])
            .await
            .unwrap();
        store::insert_entries(
            &state.db,
            feed_id,
            &[store::NewEntry {
                guid: "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.document/3l2nosumaaa2a"
                    .into(),
                url: Some("https://quiet.example/no-summary".into()),
                title: Some("A title-only article".into()),
                published: Some("2026-07-11T00:00:00Z".into()),
                content_html: None,
                ..Default::default()
            }],
            0,
        )
        .await
        .unwrap();
        let (status, list) = page_body(state.clone(), did, "/?view=all").await;
        assert_eq!(status, StatusCode::OK);
        assert!(
            list.contains("A title-only article"),
            "the entry is missing from the list"
        );

        let id: i64 = sqlx::query_scalar("SELECT id FROM entries WHERE feed_id = ?")
            .bind(feed_id)
            .fetch_one(&state.db)
            .await
            .unwrap();
        let (status, page) = page_body(state, did, &format!("/entries/{id}")).await;
        assert_eq!(
            status,
            StatusCode::OK,
            "the article page failed for an entry with no body"
        );
        assert!(page.contains("A title-only article"));
        assert!(
            page.contains("https://quiet.example/no-summary"),
            "no link to the original"
        );
        assert!(
            page.contains(r#"<time datetime=""#),
            "no date on the article page"
        );
    }

    /// **#177: a malformed record in the reader's own repo is refused, and the
    /// reader is told.** Refusing keeps `replace_sub_refs` from dropping the
    /// subscription that record was; telling them keeps the stale list from
    /// looking like the real one. Both the reading page and the manage page.
    #[tokio::test]
    async fn a_malformed_subscription_record_raises_an_alert() {
        let did = "did:plc:alerted";
        for page in ["/", "/manage"] {
            let sidecar = spawn_malformed_sidecar().await;
            let state = test_state_with_sidecar(&[did], &sidecar).await;
            let (status, body) = page_body(state, did, page).await;
            assert_eq!(status, StatusCode::OK, "{page} did not render");
            assert!(
                body.contains(r#"role="alert""#) && body.contains("could not be read"),
                "{page} rendered no alert for a refused subscription list"
            );
            assert!(
                body.contains("1 record(s) in your subscription list"),
                "{page} gave the generic alert, not the malformed-record one"
            );
        }
    }

    /// The control: a healthy listing raises no alert.
    #[tokio::test]
    async fn a_healthy_subscription_listing_raises_no_alert() {
        let did = "did:plc:exporter";
        let sidecar = spawn_export_sidecar(None).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        let (status, body) = page_body(state, did, "/").await;
        assert_eq!(status, StatusCode::OK);
        assert!(
            !body.contains("could not be read"),
            "a healthy listing raised an alert"
        );
    }

    /// `GET /opml/export` against the mock, returning `(status, headers, body)`.
    async fn export_opml_response(
        fail_on: Option<&'static str>,
    ) -> (StatusCode, HeaderMap, String) {
        let did = "did:plc:exporter";
        let sidecar = spawn_export_sidecar(fail_on).await;
        let state = test_state_with_sidecar(&[did], &sidecar).await;
        let cookie = session_cookie(&state, did, None);
        let resp = router(state)
            .oneshot(
                Request::builder()
                    .uri("/opml/export")
                    .header(header::COOKIE, cookie)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let status = resp.status();
        let headers = resp.headers().clone();
        let body = String::from_utf8_lossy(
            &axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .to_string();
        (status, headers, body)
    }

    /// **An empty export is worse than no export, and this is the caller that
    /// used to produce one.**
    ///
    /// `export_opml` read both walks through `unwrap_or_default()`. Now that a
    /// truncated walk refuses instead of returning a short list, that turned the
    /// refusal into `200 OK` carrying a zero-feed
    /// `featherreader-subscriptions.opml` — a blank backup handed over at exactly
    /// the moment a locked-out reader reached for one, and the changelog points
    /// them at this route as the recovery path.
    ///
    /// Asserts the three things a reader can actually observe: no success status,
    /// no download offered, and no OPML document in the body.
    #[tokio::test]
    async fn an_export_that_cannot_read_the_subscriptions_serves_no_opml() {
        let (status, headers, body) =
            export_opml_response(Some(crate::lexicon::nsid::SUBSCRIPTION)).await;

        assert_ne!(
            status,
            StatusCode::OK,
            "a failed subscription walk answered 200: {body}",
        );
        assert!(
            !headers.contains_key(header::CONTENT_DISPOSITION),
            "a failed subscription walk still offered a download: {headers:?}",
        );
        assert!(
            !body.contains("<opml"),
            "a failed subscription walk still served an OPML document: {body}",
        );
    }

    /// The folders half of the same hole. The two walks are separate calls, and
    /// fixing only the first leaves an export that silently loses every folder —
    /// a flat list that reimports as one, with no sign anything was lost.
    #[tokio::test]
    async fn an_export_that_cannot_read_the_folders_serves_no_opml() {
        let (status, headers, body) =
            export_opml_response(Some(crate::lexicon::nsid::FOLDER)).await;

        assert_ne!(
            status,
            StatusCode::OK,
            "a failed folder walk answered 200: {body}",
        );
        assert!(
            !headers.contains_key(header::CONTENT_DISPOSITION),
            "a failed folder walk still offered a download: {headers:?}",
        );
        assert!(
            !body.contains("<opml"),
            "a failed folder walk still served an OPML document: {body}",
        );
    }

    /// The other direction, without which "refuse everything" would pass both
    /// tests above: a healthy read still serves the file, with the feed in it.
    #[tokio::test]
    async fn a_healthy_export_serves_the_subscriptions_as_a_download() {
        let (status, headers, body) = export_opml_response(None).await;

        assert_eq!(
            status,
            StatusCode::OK,
            "a healthy export did not answer 200"
        );
        assert_eq!(
            headers
                .get(header::CONTENT_DISPOSITION)
                .and_then(|v| v.to_str().ok()),
            Some("attachment; filename=\"featherreader-subscriptions.opml\""),
            "a healthy export did not offer the download",
        );
        assert!(
            body.contains("https://kept.example/feed.xml"),
            "the exported OPML lost the subscription: {body}",
        );
        assert!(
            body.contains("Kept folder"),
            "the exported OPML lost the folder: {body}",
        );
    }
}