autumn-cli 0.10.0

CLI tool for the Autumn web framework
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
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
//! `autumn generate auth` — generate a complete browser authentication flow.
//!
//! Creates a User model, Diesel migration, auth route handlers (signup / login /
//! logout / account / forgot-password / reset-password), generated request-level
//! tests, and a documentation file — all as ordinary app-owned code that the
//! user can edit freely after generation.
//!
//! Security properties of the generated code:
//! - Passwords are hashed with bcrypt (cost=12) via `autumn_web::auth`.
//! - Reset tokens are random values; only SHA-256 digests are persisted.
//! - Duplicate signup and failed login return identical non-enumerating errors.
//! - Login and reset-password rotate the session ID (prevents session fixation).
//! - Logout clears the session data and rotates the ID, invalidating the old
//!   session (old cookie cannot be replayed) while carrying a one-shot notice.

use std::fmt::Write as _;
use std::path::Path;

use super::emit::Plan;
use super::model::ensure_cargo_dependencies;
use super::naming::{pascal, pluralize, snake};
use super::schema_edit::{
    add_mod_declaration, add_remember_middleware_to_app, append_schema_table, declares_package,
    schema_has_table, unique_index_sql, update_main_rs,
};
use super::{Flags, GenerateError, ensure_project_root, read_or_empty, timestamp_now};

/// Extra Cargo dependencies the auth generator needs on top of the model deps.
const AUTH_EXTRA_DEPS: &[(&str, &str)] = &[
    ("axum", "\"0.8\""),
    ("maud", "{ version = \"0.27\", features = [\"axum\"] }"),
    ("sha2", "{ version = \"0.11\", features = [] }"),
    ("hex", "\"0.4\""),
    ("rand", "{ version = \"0.10\", features = [\"sys_rng\"] }"),
    ("tokio", "{ version = \"1\", features = [\"time\"] }"),
    ("tracing", "\"0.1\""),
];

/// Extra Cargo dependencies pulled in only by `--passkeys`.
///
/// - `webauthn-rs` (with `danger-allow-state-serialisation`) provides the
///   `WebAuthn` ceremony implementation. State serialisation lets the in-progress
///   ceremony challenge survive across requests via the session.
/// - `uuid` generates random credential IDs if the authenticator doesn't supply one.
/// - `conditional-ui` gates `start/finish_discoverable_authentication` in webauthn-rs.
const PASSKEY_EXTRA_DEPS: &[(&str, &str)] = &[
    (
        "webauthn-rs",
        "{ version = \"0.6\", features = [\"danger-allow-state-serialisation\", \"conditional-ui\"] }",
    ),
    ("uuid", "{ version = \"1\", features = [\"v4\"] }"),
    ("base64", "\"0.23\""),
];

/// The byte index of the first occurrence of `needle` in `s` that falls
/// outside any quoted string. A `#`, `]`, `,`, or similar character inside a
/// quoted TOML value is not syntax at all — Cargo allows unusual feature
/// names (and git-fork path fragments) containing any of these for a
/// path/git dependency — so a raw, quote-blind search risks mistaking part
/// of a value for the comment marker, the array's closing bracket, or an
/// element separator.
fn find_unquoted(s: &str, needle: char) -> Option<usize> {
    #[derive(PartialEq)]
    enum Quote {
        None,
        Double,
        Single,
    }
    let mut quote = Quote::None;
    let mut chars = s.char_indices();
    while let Some((i, c)) = chars.next() {
        match (c, &quote) {
            ('"', Quote::None) => quote = Quote::Double,
            ('\'', Quote::None) => quote = Quote::Single,
            ('"', Quote::Double) | ('\'', Quote::Single) => quote = Quote::None,
            ('\\', Quote::Double) => {
                chars.next(); // skip the escaped character
            }
            (c, Quote::None) if c == needle => return Some(i),
            _ => {}
        }
    }
    None
}

/// The byte index of the first occurrence of the literal substring `needle`
/// in `s` that starts outside any quoted string — the same guard
/// `find_unquoted` gives a single character, extended to a key name like
/// `"features = ["` that could coincidentally appear inside an unrelated
/// quoted path or URL fragment (`path = "../features = [fork"` is valid
/// TOML), which would otherwise anchor every later bracket search to the
/// wrong position inside that quoted value.
fn find_unquoted_str(s: &str, needle: &str) -> Option<usize> {
    #[derive(PartialEq)]
    enum Quote {
        None,
        Double,
        Single,
    }
    let mut quote = Quote::None;
    let mut chars = s.char_indices();
    while let Some((i, c)) = chars.next() {
        if quote == Quote::None && s[i..].starts_with(needle) {
            return Some(i);
        }
        match (c, &quote) {
            ('"', Quote::None) => quote = Quote::Double,
            ('\'', Quote::None) => quote = Quote::Single,
            ('"', Quote::Double) | ('\'', Quote::Single) => quote = Quote::None,
            ('\\', Quote::Double) => {
                chars.next();
            }
            _ => {}
        }
    }
    None
}

/// Splits `s` on `,` characters that fall outside any quoted string, so a
/// quoted feature name containing a literal comma is kept whole rather than
/// torn into two garbage entries.
fn split_unquoted_commas(s: &str) -> Vec<&str> {
    #[derive(PartialEq)]
    enum Quote {
        None,
        Double,
        Single,
    }
    let mut quote = Quote::None;
    let mut parts = Vec::new();
    let mut start = 0;
    let mut chars = s.char_indices();
    while let Some((i, c)) = chars.next() {
        match (c, &quote) {
            ('"', Quote::None) => quote = Quote::Double,
            ('\'', Quote::None) => quote = Quote::Single,
            ('"', Quote::Double) | ('\'', Quote::Single) => quote = Quote::None,
            ('\\', Quote::Double) => {
                chars.next();
            }
            (',', Quote::None) => {
                parts.push(&s[start..i]);
                start = i + 1;
            }
            _ => {}
        }
    }
    parts.push(&s[start..]);
    parts
}

/// The code portion of a Cargo.toml line, up to (not including) its first
/// `#` outside any quoted string — the start of a TOML comment. A raw
/// substring/character search over a whole line risks matching text that
/// isn't syntax at all: a feature name mentioned in a comment, a stray
/// `]`/`}` inside one, or (the reverse mistake) a `#` that is itself inside
/// a quoted value rather than starting a comment — a git-fork path/URL
/// fragment like `"../autumn#fork"` is valid TOML, not a comment marker.
fn strip_line_comment(s: &str) -> &str {
    find_unquoted(s, '#').map_or(s, |i| &s[..i])
}

/// Required features for the `webauthn-rs` dependency.
///
/// `danger-allow-state-serialisation` enables session storage of ceremony state.
/// `conditional-ui` gates `start/finish_discoverable_authentication`.
const WEBAUTHN_RS_FEATURES: &[&str] = &["danger-allow-state-serialisation", "conditional-ui"];

/// Ensure an existing `webauthn-rs` dependency carries the features the generated
/// routes need.
///
/// `ensure_cargo_dependencies` skips a crate that is already declared, so a project
/// that already lists `webauthn-rs` without `conditional-ui` would scaffold but fail
/// to compile. This merges the missing features into the existing declaration —
/// shorthand, inline-table, or `[dependencies.webauthn-rs]` subtable form.
#[allow(clippy::too_many_lines)]
fn ensure_webauthn_rs_features(toml: &str) -> String {
    const CRATE: &str = "webauthn-rs";
    let trailing_newline = toml.ends_with('\n');
    let mut lines: Vec<String> = toml.lines().map(str::to_owned).collect();
    let simple_prefix = format!("{CRATE} = \"");
    let table_prefix = format!("{CRATE} = {{");
    let subtable_header = format!("[dependencies.{CRATE}]");
    let subtable_header_underscore = format!("[dependencies.{}]", CRATE.replace('-', "_"));
    let feats_csv = WEBAUTHN_RS_FEATURES
        .iter()
        .map(|f| format!("\"{f}\""))
        .collect::<Vec<_>>()
        .join(", ");

    let merge_missing = |line: &str| -> Option<String> {
        let feat_bracket = find_unquoted_str(strip_line_comment(line), "features = [")?;
        let list_start = feat_bracket + "features = [".len();
        let close_off = find_unquoted(&line[list_start..], ']')?;
        let list_end = close_off + list_start;
        let existing_list = &line[list_start..list_end];
        let additions: Vec<String> = WEBAUTHN_RS_FEATURES
            .iter()
            .filter(|f| !existing_list.contains(&format!("\"{f}\"")))
            .map(|f| format!("\"{f}\""))
            .collect();
        if additions.is_empty() {
            return None; // already complete
        }
        let sep = if existing_list.trim().is_empty() || existing_list.trim().ends_with(',') {
            ""
        } else {
            ", "
        };
        Some(format!(
            "{}{sep}{}{}",
            &line[..list_end],
            additions.join(", "),
            &line[list_end..]
        ))
    };

    let mut i = 0;
    while i < lines.len() {
        let trimmed = lines[i].trim().to_owned();
        let indent: String = lines[i]
            .chars()
            .take_while(char::is_ascii_whitespace)
            .collect();

        if let Some(rest) = trimmed.strip_prefix(&simple_prefix) {
            let version = rest.split('"').next().unwrap_or("0.6");
            lines[i] = format!(
                "{indent}{CRATE} = {{ version = \"{version}\", features = [{feats_csv}] }}"
            );
            break;
        }

        if trimmed.starts_with(&table_prefix) {
            if let Some(new_line) = merge_missing(&trimmed) {
                lines[i] = format!("{indent}{new_line}");
            } else if find_unquoted_str(strip_line_comment(&trimmed), "features = [").is_none() {
                // No `features` key at all — insert one before the closing brace.
                if let Some(close_brace) = trimmed.rfind('}') {
                    let before = trimmed[..close_brace].trim_end();
                    let sep = if before.ends_with('{') { " " } else { ", " };
                    lines[i] = format!("{indent}{before}{sep}features = [{feats_csv}] }}");
                }
            }
            break;
        }

        if trimmed == subtable_header || trimmed == subtable_header_underscore {
            let mut j = i + 1;
            while j < lines.len() && !lines[j].trim().starts_with('[') {
                let t = lines[j].trim().to_owned();
                if t.starts_with("features") {
                    let ind2: String = lines[j]
                        .chars()
                        .take_while(char::is_ascii_whitespace)
                        .collect();
                    if find_unquoted(strip_line_comment(&t), ']').is_some() {
                        // Single-line `features = [...]`.
                        if let Some(new_line) = merge_missing(&t) {
                            lines[j] = format!("{ind2}{new_line}");
                        }
                    } else {
                        // Multiline `features = [` … `]` array: find the closing
                        // `]`, collect the existing entries, and rebuild the list
                        // (collapsed to one line) with the missing features
                        // appended. A `#` comment is not TOML, so a stray `]`
                        // or trailing text inside one is never real syntax —
                        // every raw-text scan and join below works only on
                        // each line's code portion (before its first `#`), and
                        // only outside any quoted value (Cargo allows unusual
                        // feature names on a path/git dependency, so a quoted
                        // `]` or `,` is data, not an array boundary).
                        let mut close_line = None;
                        let mut k = j;
                        while k < lines.len() {
                            let tk = lines[k].trim();
                            if k > j && tk.starts_with('[') {
                                break; // next table header — array never closed
                            }
                            if find_unquoted(strip_line_comment(&lines[k]), ']').is_some() {
                                close_line = Some(k);
                                break;
                            }
                            k += 1;
                        }
                        if let Some(cl) = close_line {
                            let j_bracket = lines[j].find('[').unwrap_or(lines[j].len());
                            let mut list_text =
                                strip_line_comment(&lines[j][j_bracket + 1..]).to_owned();
                            for line in &lines[j + 1..cl] {
                                list_text.push(' ');
                                list_text.push_str(strip_line_comment(line.trim()));
                            }
                            let cl_close = find_unquoted(strip_line_comment(&lines[cl]), ']')
                                .unwrap_or(lines[cl].len());
                            list_text.push(' ');
                            list_text.push_str(strip_line_comment(&lines[cl][..cl_close]));
                            let trailing = lines[cl]
                                [cl_close.saturating_add(1).min(lines[cl].len())..]
                                .to_owned();

                            let mut entries: Vec<String> = split_unquoted_commas(&list_text)
                                .into_iter()
                                .map(str::trim)
                                .filter(|t| !t.is_empty())
                                .map(str::to_owned)
                                .collect();
                            let mut changed = false;
                            for f in WEBAUTHN_RS_FEATURES {
                                let quoted = format!("\"{f}\"");
                                if !entries.iter().any(|e| e == &quoted) {
                                    entries.push(quoted);
                                    changed = true;
                                }
                            }
                            if changed {
                                let rebuilt =
                                    format!("{ind2}features = [{}]{trailing}", entries.join(", "));
                                lines.splice(j..=cl, std::iter::once(rebuilt));
                            }
                        }
                    }
                    let mut out = lines.join("\n");
                    if trailing_newline {
                        out.push('\n');
                    }
                    return out;
                }
                j += 1;
            }
            // No `features` key found in the subtable — insert one.
            lines.insert(i + 1, format!("features = [{feats_csv}]"));
            break;
        }

        i += 1;
    }

    let mut out = lines.join("\n");
    if trailing_newline {
        out.push('\n');
    }
    out
}

/// Extra Cargo dependencies pulled in only by `--totp`.
///
/// - `totp-rs` (with the `qr` feature) provides RFC 6238 TOTP plus QR rendering.
/// - `aes-gcm` encrypts the TOTP secret at rest.
/// - `base64` encodes the encrypted secret / decodes the encryption key.
///
/// Recovery codes are hashed with bcrypt via the existing `autumn_web::auth`
/// hashing path, so no extra hashing dependency is required.
const TOTP_EXTRA_DEPS: &[(&str, &str)] = &[
    (
        "totp-rs",
        "{ version = \"5\", features = [\"qr\", \"gen_secret\", \"otpauth\"] }",
    ),
    ("aes-gcm", "\"0.11\""),
    ("base64", "\"0.23\""),
];

/// `totp-rs` cargo features the generated `--totp` routes rely on
/// (`Secret::generate_secret`, `TOTP::new` with `otpauth`, `get_qr_base64`).
const TOTP_RS_FEATURES: &[&str] = &["qr", "gen_secret", "otpauth"];

/// Ensure an existing `totp-rs` dependency carries the features the generated
/// routes need.
///
/// `ensure_cargo_dependencies` skips a crate that is already declared, so an app
/// that already lists `totp-rs` (perhaps without `qr`/`gen_secret`/`otpauth`)
/// would scaffold but fail to compile. This merges the missing features into the
/// existing declaration — shorthand, inline-table, or `[dependencies.totp-rs]`
/// subtable form — mirroring the `autumn-web` feature helpers.
#[allow(clippy::too_many_lines)]
fn ensure_totp_rs_features(toml: &str) -> String {
    const CRATE: &str = "totp-rs";
    let trailing_newline = toml.ends_with('\n');
    let mut lines: Vec<String> = toml.lines().map(str::to_owned).collect();
    let simple_prefix = format!("{CRATE} = \"");
    let table_prefix = format!("{CRATE} = {{");
    let subtable_header = format!("[dependencies.{CRATE}]");
    let subtable_header_underscore = format!("[dependencies.{}]", CRATE.replace('-', "_"));
    let feats_csv = TOTP_RS_FEATURES
        .iter()
        .map(|f| format!("\"{f}\""))
        .collect::<Vec<_>>()
        .join(", ");

    // Merge `TOTP_RS_FEATURES` into the `[ ... ]` list embedded in `line`,
    // returning the rewritten line, or `None` if nothing changed (already
    // complete) / no list found.
    let merge_into_list = |line: &str, bracket_search: &str| -> Option<Option<String>> {
        let feat_bracket = find_unquoted_str(strip_line_comment(line), bracket_search)?;
        let list_start = feat_bracket + bracket_search.len();
        let close_off = find_unquoted(&line[list_start..], ']')?;
        let list_end = close_off + list_start;
        let existing_list = &line[list_start..list_end];
        let additions: Vec<String> = TOTP_RS_FEATURES
            .iter()
            .filter(|f| !existing_list.contains(&format!("\"{f}\"")))
            .map(|f| format!("\"{f}\""))
            .collect();
        if additions.is_empty() {
            return Some(None); // list present and already complete
        }
        let sep = if existing_list.trim().is_empty() || existing_list.trim().ends_with(',') {
            ""
        } else {
            ", "
        };
        Some(Some(format!(
            "{}{sep}{}{}",
            &line[..list_end],
            additions.join(", "),
            &line[list_end..]
        )))
    };

    let mut i = 0;
    while i < lines.len() {
        let trimmed = lines[i].trim().to_owned();
        let indent: String = lines[i]
            .chars()
            .take_while(char::is_ascii_whitespace)
            .collect();

        // `totp-rs = "5"` → promote to a table carrying the required features.
        if let Some(rest) = trimmed.strip_prefix(&simple_prefix) {
            // `rest` is everything after `totp-rs = "`. Take up to the closing
            // quote so a trailing inline comment (`"5" # note`) isn't folded into
            // the version string (which would make Cargo.toml invalid).
            let (version, trailing) = rest.find('"').map_or_else(
                || (rest.trim_end_matches('"'), ""),
                |close| (&rest[..close], rest[close + 1..].trim()),
            );
            let trailing = if trailing.is_empty() {
                String::new()
            } else {
                format!(" {trailing}")
            };
            lines[i] = format!(
                "{indent}{CRATE} = {{ version = \"{version}\", features = [{feats_csv}] }}{trailing}"
            );
            break;
        }

        // `totp-rs = { ... }` inline table → merge any missing features.
        if trimmed.starts_with(&table_prefix) {
            if let Some(result) = merge_into_list(&trimmed, "features = [") {
                match result {
                    Some(new_line) => lines[i] = format!("{indent}{new_line}"),
                    None => return toml.to_owned(),
                }
                break;
            } else if let Some(close_brace) = trimmed.rfind('}') {
                // No `features` key — insert one before the closing brace.
                let before = trimmed[..close_brace].trim_end();
                let sep = if before.ends_with('{') { " " } else { ", " };
                lines[i] = format!("{indent}{before}{sep}features = [{feats_csv}] }}");
                break;
            }
        }

        // `[dependencies.totp-rs]` subtable form → merge into (or add) a
        // `features = [...]` key within the subtable body.
        if trimmed == subtable_header || trimmed == subtable_header_underscore {
            let mut feature_line: Option<usize> = None;
            let mut j = i + 1;
            while j < lines.len() {
                let tj = lines[j].trim();
                if tj.starts_with('[') {
                    break;
                }
                if tj.starts_with("features") && tj.contains('[') {
                    feature_line = Some(j);
                    break;
                }
                j += 1;
            }
            if let Some(fl) = feature_line {
                let tj = lines[fl].trim().to_owned();
                let indent_j: String = lines[fl]
                    .chars()
                    .take_while(char::is_ascii_whitespace)
                    .collect();
                if find_unquoted(strip_line_comment(&tj), ']').is_some() {
                    // Single-line `features = [...]`.
                    match merge_into_list(&tj, "[") {
                        Some(Some(new_line)) => lines[fl] = format!("{indent_j}{new_line}"),
                        Some(None) => return toml.to_owned(),
                        None => {}
                    }
                } else {
                    // Multiline `features = [` … `]` array: find the closing `]`,
                    // collect the existing entries, and rebuild the list (collapsed
                    // to one line) with the missing features appended. A `#`
                    // comment is not TOML, so a stray `]` or trailing text
                    // inside one is never real syntax — every raw-text scan
                    // and join below works only on each line's code portion
                    // (before its first `#`), and only outside any quoted value
                    // (Cargo allows unusual feature names on a path/git
                    // dependency, so a quoted `]` or `,` is data, not an array
                    // boundary).
                    let mut close_line = None;
                    let mut k = fl;
                    while k < lines.len() {
                        let tk = lines[k].trim();
                        if k > fl && tk.starts_with('[') {
                            break; // next table header — array never closed
                        }
                        if find_unquoted(strip_line_comment(&lines[k]), ']').is_some() {
                            close_line = Some(k);
                            break;
                        }
                        k += 1;
                    }
                    if let Some(cl) = close_line {
                        let fl_bracket = lines[fl].find('[').unwrap_or(lines[fl].len());
                        let mut list_text =
                            strip_line_comment(&lines[fl][fl_bracket + 1..]).to_owned();
                        for line in &lines[fl + 1..cl] {
                            list_text.push(' ');
                            list_text.push_str(strip_line_comment(line.trim()));
                        }
                        let cl_close = find_unquoted(strip_line_comment(&lines[cl]), ']')
                            .unwrap_or(lines[cl].len());
                        list_text.push(' ');
                        list_text.push_str(strip_line_comment(&lines[cl][..cl_close]));
                        let trailing =
                            lines[cl][cl_close.saturating_add(1).min(lines[cl].len())..].to_owned();

                        let mut entries: Vec<String> = split_unquoted_commas(&list_text)
                            .into_iter()
                            .map(str::trim)
                            .filter(|t| !t.is_empty())
                            .map(str::to_owned)
                            .collect();
                        let mut changed = false;
                        for f in TOTP_RS_FEATURES {
                            let q = format!("\"{f}\"");
                            if !entries.iter().any(|e| e == &q) {
                                entries.push(q);
                                changed = true;
                            }
                        }
                        if !changed {
                            return toml.to_owned();
                        }
                        let rebuilt =
                            format!("{indent_j}features = [{}]{trailing}", entries.join(", "));
                        lines.splice(fl..=cl, std::iter::once(rebuilt));
                    }
                }
            } else {
                // No `features` key in the subtable — add one right after the header.
                lines.insert(i + 1, format!("features = [{feats_csv}]"));
            }
            break;
        }
        i += 1;
    }

    let mut out = lines.join("\n");
    if trailing_newline {
        out.push('\n');
    }
    out
}

/// OAuth2/OIDC options for `autumn generate auth --oauth`.
#[derive(Debug, Clone, Default)]
pub struct AuthOAuthOptions {
    /// Provider keys to scaffold (e.g. `["github", "google"]`).
    /// An empty list produces the same output as [`plan_auth`].
    pub providers: Vec<String>,
}

/// Compute the file actions for `autumn generate auth`.
///
/// Pure planning step — no I/O happens here. Tests use this directly so they
/// can inspect the emitted file list and contents without touching the disk.
///
/// # Errors
/// Returns [`GenerateError::NotInProject`] when run outside an Autumn project
/// root, or [`GenerateError::InvalidName`] for a bad resource name.
#[allow(dead_code)]
pub fn plan_auth(project_root: &Path, name: &str, timestamp: &str) -> Result<Plan, GenerateError> {
    plan_auth_with_providers(project_root, name, timestamp, &[], false)
}

pub fn plan_auth_with_providers(
    project_root: &Path,
    name: &str,
    timestamp: &str,
    providers: &[String],
    totp: bool,
) -> Result<Plan, GenerateError> {
    plan_auth_with_providers_ex(project_root, name, timestamp, providers, totp, false)
}

/// Extended base scaffold that additionally threads the `--magic-link` flag
/// (issue #1328) through the migration, model, schema, routes, docs, and tests.
///
/// `plan_auth_with_providers` delegates here with `magic_link = false` so all
/// existing call sites keep their behaviour byte-for-byte.
///
/// # Errors
/// Same as [`plan_auth`].
pub fn plan_auth_with_providers_ex(
    project_root: &Path,
    name: &str,
    timestamp: &str,
    providers: &[String],
    totp: bool,
    magic_link: bool,
) -> Result<Plan, GenerateError> {
    // Generation path: run the full plan, including the shared-layout preflight.
    // `autumn destroy auth` recomputes the identical plan before reverting it,
    // and must bypass that generate-only preflight (issue #1353 follow-up); it
    // reaches the builder through `plan_auth_full_ex2_for_revert` instead.
    plan_auth_with_providers_ex_impl(
        project_root,
        name,
        timestamp,
        providers,
        totp,
        magic_link,
        false,
    )
}

/// Shared implementation of [`plan_auth_with_providers_ex`]. `for_revert`
/// suppresses the generate-only shared-layout preflight so `autumn destroy
/// auth` (which recomputes this same plan before [`Plan::revert`]) can remove
/// generated files even in a project whose shared `pub fn layout` is missing or
/// renamed — a regression the preflight would otherwise introduce.
#[allow(clippy::too_many_lines)]
fn plan_auth_with_providers_ex_impl(
    project_root: &Path,
    name: &str,
    timestamp: &str,
    providers: &[String],
    totp: bool,
    magic_link: bool,
    for_revert: bool,
) -> Result<Plan, GenerateError> {
    ensure_project_root(project_root)?;
    super::model::validate_resource_name(name)?;

    // Determine the target app's database backend so the scaffolded migrations
    // emit backend-aware DDL (issue #1927): a SQLite app gets SQLite-dialect DDL
    // (`INTEGER PRIMARY KEY AUTOINCREMENT`, `DEFAULT CURRENT_TIMESTAMP`) instead
    // of the Postgres-only `BIGSERIAL`/`NOW()` form. Detected identically on the
    // generate and destroy/revert paths (both read the same config), so a
    // `destroy auth` round-trip recomputes byte-identical migration content.
    let backend = super::detect_backend(project_root);

    let pascal_name = pascal(name);
    let snake_name = snake(name);
    let table = pluralize(&snake_name);

    // Under `--totp` the generator unconditionally emits a `recovery_code` model
    // and a `recovery_codes` table. If the auth resource itself resolves to those
    // names, the two collide — the same model file and `CREATE TABLE` would be
    // emitted twice, producing an unusable app. Reject it up front.
    if totp && (snake_name == "recovery_code" || table == "recovery_codes") {
        return Err(GenerateError::InvalidName(
            name.to_owned(),
            "collides with the reserved `recovery_code` model/table generated by \
             `--totp`; choose a different resource name."
                .to_owned(),
        ));
    }

    // Under `--magic-link` the generator unconditionally emits a `magic_link_token`
    // model and a `magic_link_tokens` table. If the auth resource itself resolves to
    // those names, the two collide — the same `CREATE TABLE` would be emitted twice
    // and the helper model file would overwrite the auth model file, producing an
    // unusable scaffold. Reject it up front (mirrors the `--totp` guard above).
    if magic_link && (snake_name == "magic_link_token" || table == "magic_link_tokens") {
        return Err(GenerateError::InvalidName(
            name.to_owned(),
            "collides with the reserved `magic_link_token` model/table generated by \
             `--magic-link`; choose a different resource name."
                .to_owned(),
        ));
    }

    // Issue #1353: the generated auth views render through the application's
    // shared `crate::layout(title, current_path, flash, content)` (nav bar,
    // stylesheet links, skip-link, footer) rather than a private per-file
    // layout stub, so the target app must expose a shared layout with the
    // matching 4-arg signature (as `autumn new` emits). Detect it by looking
    // for a `pub fn layout` in `src/main.rs`. If it is missing — or present
    // with the wrong arity (e.g. an older/custom 2-arg
    // `pub fn layout(title, content)`) — fail early with an actionable message
    // rather than emitting routes that call a nonexistent or mismatched
    // `crate::layout`. This mirrors the scaffold generator's preflight
    // (issue #1130) and reuses its lexically-aware detector.
    //
    // The preflight is a generate-time guard only. `autumn destroy auth`
    // recomputes this same plan before reverting it, so running the preflight
    // on that path would hard-fail cleanup in a project whose shared
    // `pub fn layout` is missing or renamed — stranding the very files destroy
    // is meant to remove. Skip it when `for_revert` is set.
    if !for_revert {
        let main_for_layout_check = project_root.join("src").join("main.rs");
        let main_src = match std::fs::read_to_string(&main_for_layout_check) {
            Ok(src) => src,
            // `main.rs` genuinely absent: surface the actionable message below by
            // treating it as an empty source (no `pub fn layout` present).
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
            // Any other io error (e.g. PermissionDenied) preserves its original
            // `ErrorKind` + OS message rather than being masked.
            Err(e) => return Err(GenerateError::Io(e)),
        };
        if !super::scaffold::has_shared_layout(&main_src) {
            return Err(GenerateError::Config(
                "`autumn generate auth` requires a shared `pub fn layout` in src/main.rs \
                 so the generated views can render through \
                 `crate::layout(title, current_path, flash, content)` (4 args). Run this inside \
                 an app created by `autumn new`, or add a shared \
                 `pub fn layout(title: &str, current_path: &str, flash: maud::Markup, content: maud::Markup) -> maud::Markup` \
                 to src/main.rs and re-run."
                    .to_owned(),
            ));
        }
    }

    let mut plan = Plan::new(project_root);

    // ── Migration ──────────────────────────────────────────────────────────
    let mig_dir = project_root
        .join("migrations")
        .join(format!("{timestamp}_create_{table}"));
    plan.create(
        mig_dir.join("up.sql"),
        render_migration_up(backend, &snake_name, &table, totp, magic_link),
    );
    plan.create(
        mig_dir.join("down.sql"),
        render_migration_down(&snake_name, &table, totp, magic_link),
    );

    // ── Model ──────────────────────────────────────────────────────────────
    let models_dir = project_root.join("src").join("models");
    plan.create(
        models_dir.join(format!("{snake_name}.rs")),
        render_model_file(&pascal_name, &snake_name, &table, totp),
    );
    let model_mod_path = models_dir.join("mod.rs");
    let mut model_mod = add_mod_declaration(&read_or_empty(&model_mod_path), &snake_name);
    if totp {
        // Recovery codes live in their own model + table.
        plan.create(
            models_dir.join("recovery_code.rs"),
            render_recovery_code_model_file(&pascal_name, &table),
        );
        model_mod = add_mod_declaration(&model_mod, "recovery_code");
    }
    // Active login sessions (issue #819) live in their own model + table.
    plan.create(
        models_dir.join(format!("{snake_name}_session.rs")),
        render_session_model_file(&pascal_name, &snake_name, &table),
    );
    let session_mod_name = format!("{snake_name}_session");
    model_mod = add_mod_declaration(&model_mod, &session_mod_name);
    // Persistent remember-me chains (issue #1397) live in their own model + table.
    plan.create(
        models_dir.join(format!("{snake_name}_remember_token.rs")),
        render_remember_model_file(&pascal_name, &snake_name, &table),
    );
    let remember_mod_name = format!("{snake_name}_remember_token");
    model_mod = add_mod_declaration(&model_mod, &remember_mod_name);
    // Passwordless magic-link tokens (issue #1328) live in their own model +
    // table, mirroring the reset-token invariants: only the SHA-256 digest is
    // stored, plus an expiry and a single-use `consumed_at` marker.
    if magic_link {
        plan.create(
            models_dir.join("magic_link_token.rs"),
            render_magic_link_token_model_file(&pascal_name, &table),
        );
        model_mod = add_mod_declaration(&model_mod, "magic_link_token");
    }
    plan.modify(model_mod_path.clone(), model_mod);
    plan.push_revert(crate::generate::emit::Revert::ModDecl {
        path: model_mod_path.clone(),
        name: snake_name.clone(),
    });
    if totp {
        plan.push_revert(crate::generate::emit::Revert::ModDecl {
            path: model_mod_path.clone(),
            name: "recovery_code".to_owned(),
        });
    }
    plan.push_revert(crate::generate::emit::Revert::ModDecl {
        path: model_mod_path.clone(),
        name: session_mod_name,
    });
    if magic_link {
        plan.push_revert(crate::generate::emit::Revert::ModDecl {
            path: model_mod_path.clone(),
            name: "magic_link_token".to_owned(),
        });
    }
    plan.push_revert(crate::generate::emit::Revert::ModDecl {
        path: model_mod_path,
        name: remember_mod_name,
    });

    // ── src/schema.rs entry ────────────────────────────────────────────────
    // The generated model references `crate::schema::<table>`, so we must
    // emit a `diesel::table! { }` block just like `generate model` does.
    // Auth-specific fields (id and created_at are added automatically):
    //   email            String   → Text      NOT NULL
    //   password_digest  String   → Text      NOT NULL
    //   reset_token_digest         Option<String>         → Nullable<Text>
    //   reset_token_expires_at     Option<NaiveDateTime>  → Nullable<Timestamp>
    let mut user_field_tokens: Vec<&str> = vec![
        "email:String",
        "time_zone:Option<String>",
        "password_digest:String",
    ];
    if totp {
        user_field_tokens.push("totp_secret_encrypted:Option<String>");
        user_field_tokens.push("totp_enabled:bool");
        user_field_tokens.push("totp_last_used_step:Option<i64>");
    }
    user_field_tokens.push("failed_attempts:i32");
    user_field_tokens.push("locked_at:Option<NaiveDateTime>");
    user_field_tokens.push("reset_token_digest:Option<String>");
    user_field_tokens.push("reset_token_expires_at:Option<NaiveDateTime>");
    user_field_tokens.push("confirm_token_digest:Option<String>");
    user_field_tokens.push("confirm_token_expires_at:Option<NaiveDateTime>");
    user_field_tokens.push("email_confirmed_at:Option<NaiveDateTime>");
    user_field_tokens.push("pending_email:Option<String>");
    user_field_tokens.push("export_requested_at:Option<NaiveDateTime>");
    user_field_tokens.push("delete_requested_at:Option<NaiveDateTime>");
    user_field_tokens.push("delete_scheduled_at:Option<NaiveDateTime>");
    let auth_fields: Vec<super::dsl::Field> = user_field_tokens
        .iter()
        .map(|t| super::dsl::parse_field(t).expect("auth field tokens are always valid"))
        .collect();

    let schema_path = project_root.join("src").join("schema.rs");
    let schema_existing = read_or_empty(&schema_path);
    // Under `--totp` we unconditionally create a helper `recovery_codes` table.
    // If the project already declares one (in `src/schema.rs`), the migration
    // would emit a second `CREATE TABLE recovery_codes` and `diesel migration
    // run` would fail with "relation already exists" (or clobber an unrelated
    // table). Reject up front rather than generate an unusable app.
    //
    // Only reject a *foreign* `recovery_codes` table: when the auth table
    // itself is also already present, this is a re-run over our own output
    // (`--force`, or `autumn destroy` recomputing this same plan against
    // already-generated files — issue #1048), where the schema append below
    // is an idempotent no-op. Mirrors the analogous `sess_table` guard below.
    if totp
        && schema_has_table(&schema_existing, "recovery_codes")
        && !schema_has_table(&schema_existing, &table)
    {
        return Err(GenerateError::InvalidName(
            name.to_owned(),
            "this project already defines a `recovery_codes` table, which `--totp` \
             needs for its helper model; rename or remove the existing table first."
                .to_owned(),
        ));
    }
    // Same guard for the session-tracking helper table (issue #819). Only
    // reject a *foreign* table: when the auth table itself is also present,
    // this is a re-run over our own output (`--force`), where the schema
    // append below is an idempotent no-op.
    let sess_table = sessions_table_name(&snake_name);
    if schema_has_table(&schema_existing, &sess_table)
        && !schema_has_table(&schema_existing, &table)
    {
        return Err(GenerateError::InvalidName(
            name.to_owned(),
            format!(
                "this project already defines a `{sess_table}` table, which the auth \
                 starter needs for login-session tracking; rename or remove the \
                 existing table first."
            ),
        ));
    }
    // Same guard for the remember-me helper table (issue #1397).
    let rem_table_guard = remember_table_name(&snake_name);
    if schema_has_table(&schema_existing, &rem_table_guard)
        && !schema_has_table(&schema_existing, &table)
    {
        return Err(GenerateError::InvalidName(
            name.to_owned(),
            format!(
                "this project already defines a `{rem_table_guard}` table, which the auth \
                 starter needs for persistent remember-me login; rename or remove the \
                 existing table first."
            ),
        ));
    }
    // Same guard for the magic-link helper table (issue #1328). Only under
    // `--magic-link`, and only reject a *foreign* table: when the auth table
    // itself is also present, this is a re-run over our own output (`--force`),
    // where the schema append below is an idempotent no-op.
    if magic_link
        && schema_has_table(&schema_existing, "magic_link_tokens")
        && !schema_has_table(&schema_existing, &table)
    {
        return Err(GenerateError::InvalidName(
            name.to_owned(),
            "this project already defines a `magic_link_tokens` table, which \
             `--magic-link` needs for its helper model; rename or remove the \
             existing table first."
                .to_owned(),
        ));
    }
    let mut schema_new = append_schema_table(&schema_existing, &table, &auth_fields);
    if totp {
        let recovery_fields: Vec<super::dsl::Field> = [
            "user_id:i64",
            "code_digest:String",
            "used_at:Option<NaiveDateTime>",
        ]
        .iter()
        .map(|t| super::dsl::parse_field(t).expect("recovery field tokens are always valid"))
        .collect();
        schema_new = append_schema_table(&schema_new, "recovery_codes", &recovery_fields);
    }
    let session_fields: Vec<super::dsl::Field> = [
        "user_id:i64",
        "token_digest:String",
        "ip:String",
        "user_agent:String",
        "ua_family:String",
        "ua_os:String",
        "ua_device:String",
        "label:Option<String>",
        "last_seen_at:NaiveDateTime",
    ]
    .iter()
    .map(|t| super::dsl::parse_field(t).expect("session field tokens are always valid"))
    .collect();
    schema_new = append_schema_table(&schema_new, &sess_table, &session_fields);
    // Persistent "remember-me" login chains (issue #1397). Mirrors the sessions
    // table shape: a synthetic `id` primary key plus a unique opaque `series`
    // that is the stable per-device lookup key.
    let rem_table = remember_table_name(&snake_name);
    let remember_fields: Vec<super::dsl::Field> = [
        "series:String",
        "user_id:i64",
        "token_hash:String",
        "previous_token_hash:Option<String>",
        "rotated_at:Option<NaiveDateTime>",
        "expires_at:NaiveDateTime",
        "ip:String",
        "user_agent:String",
        "ua_family:String",
        "ua_os:String",
        "ua_device:String",
        "label:Option<String>",
        "last_used_at:Option<NaiveDateTime>",
    ]
    .iter()
    .map(|t| super::dsl::parse_field(t).expect("remember field tokens are always valid"))
    .collect();
    schema_new = append_schema_table(&schema_new, &rem_table, &remember_fields);
    // Passwordless magic-link tokens (issue #1328). Dedicated table mirroring
    // the reset-token invariants: only the SHA-256 digest of the raw token is
    // stored, plus an expiry and a single-use `consumed_at` marker.
    let magic_link_fields: Vec<super::dsl::Field> = magic_link_token_fields();
    if magic_link {
        schema_new = append_schema_table(&schema_new, "magic_link_tokens", &magic_link_fields);
    }
    plan.modify(schema_path.clone(), schema_new);
    plan.push_revert(crate::generate::emit::Revert::SchemaTable {
        path: schema_path.clone(),
        table: table.clone(),
        expected_block: append_schema_table("", &table, &auth_fields),
    });
    if totp {
        let recovery_fields: Vec<super::dsl::Field> = [
            "user_id:i64",
            "code_digest:String",
            "used_at:Option<NaiveDateTime>",
        ]
        .iter()
        .map(|t| super::dsl::parse_field(t).expect("recovery field tokens are always valid"))
        .collect();
        plan.push_revert(crate::generate::emit::Revert::SchemaTable {
            path: schema_path.clone(),
            table: "recovery_codes".to_owned(),
            expected_block: append_schema_table("", "recovery_codes", &recovery_fields),
        });
    }
    let sess_table_expected_block = append_schema_table("", &sess_table, &session_fields);
    plan.push_revert(crate::generate::emit::Revert::SchemaTable {
        path: schema_path.clone(),
        table: sess_table,
        expected_block: sess_table_expected_block,
    });
    // Remember-me table is appended last (before the optional magic-link table),
    // so it is reverted just after it (issue #1397).
    let rem_table_expected_block = append_schema_table("", &rem_table, &remember_fields);
    plan.push_revert(crate::generate::emit::Revert::SchemaTable {
        path: schema_path.clone(),
        table: rem_table,
        expected_block: rem_table_expected_block,
    });
    // Magic-link table is appended last, so it is reverted first (issue #1328).
    if magic_link {
        let magic_link_expected_block =
            append_schema_table("", "magic_link_tokens", &magic_link_fields);
        plan.push_revert(crate::generate::emit::Revert::SchemaTable {
            path: schema_path,
            table: "magic_link_tokens".to_owned(),
            expected_block: magic_link_expected_block,
        });
    }

    // ── Auth routes ────────────────────────────────────────────────────────
    let routes_dir = project_root.join("src").join("routes");
    plan.create(
        routes_dir.join("auth.rs"),
        render_routes_file(
            &pascal_name,
            &snake_name,
            &table,
            providers,
            totp,
            magic_link,
        ),
    );
    let route_mod_path = routes_dir.join("mod.rs");
    plan.modify(
        route_mod_path.clone(),
        add_mod_declaration(&read_or_empty(&route_mod_path), "auth"),
    );
    plan.push_revert(crate::generate::emit::Revert::ModDecl {
        path: route_mod_path,
        name: "auth".to_owned(),
    });

    // ── Generated tests ────────────────────────────────────────────────────
    let tests_dir = project_root.join("tests");
    plan.create(
        tests_dir.join("auth.rs"),
        render_tests_file(&pascal_name, &snake_name, magic_link),
    );
    if totp {
        plan.create(
            tests_dir.join("auth_2fa.rs"),
            render_2fa_tests_file(&pascal_name, &snake_name),
        );
    }
    // Active-session management integration tests (issue #819).
    plan.create(
        tests_dir.join("auth_sessions.rs"),
        render_sessions_tests_file(&pascal_name, &snake_name),
    );

    // ── Documentation ─────────────────────────────────────────────────────
    let docs_dir = project_root.join("docs").join("guide");
    plan.create(
        docs_dir.join("authentication.md"),
        render_docs_file(backend, &pascal_name, totp, magic_link),
    );
    plan.create(docs_dir.join("gdpr-compliance.md"), render_gdpr_docs_file());
    plan.create(
        docs_dir.join("session-management.md"),
        render_sessions_docs_file(backend, &pascal_name, &snake_name, &table),
    );

    // ── src/main.rs — module declarations + route registration ────────────
    let main_path = project_root.join("src").join("main.rs");
    let main_existing = std::fs::read_to_string(&main_path).map_err(|_| {
        GenerateError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("missing {}", main_path.display()),
        ))
    })?;
    let entries = auth_route_entries(totp, magic_link);
    let updated = update_main_rs(&main_existing, &["models", "routes", "schema"], &entries);
    // Auto-wire the remember-me middleware layer + startup hook into the
    // `AppBuilder` chain so a freshly generated app actually consumes the
    // remember cookie it issues (issue #1397.7).
    let updated = add_remember_middleware_to_app(&updated);
    plan.modify(main_path.clone(), updated);
    plan.push_revert(crate::generate::emit::Revert::RoutesEntries {
        path: main_path.clone(),
        entries,
    });
    plan.push_revert(crate::generate::emit::Revert::RememberMiddleware { path: main_path });

    // ── Cargo.toml deps + autumn-web/mail feature ─────────────────────────
    let cargo_toml_path = project_root.join("Cargo.toml");
    let cargo_existing = read_or_empty(&cargo_toml_path);
    let all_deps: Vec<(&str, &str)> = super::model::MODEL_DEPS
        .iter()
        .copied()
        .chain(AUTH_EXTRA_DEPS.iter().copied())
        .chain(if totp { TOTP_EXTRA_DEPS } else { &[] }.iter().copied())
        .collect();
    // `ensure_cargo_dependencies` is name-only, so an app that pins an older
    // crate keeps it. The generated code uses the `rand` 0.10 API. Warn.
    super::model::warn_if_existing_dep_below_version(&mut plan, &cargo_existing, "rand", 0, 10);
    // The `--totp` routes add `base64 = "0.23"` and use its 0.21+ `Engine`
    // API; `ensure_cargo_dependencies` is name-only, so an app pinning an older
    // `base64` keeps it and the generated 2FA code won't compile. Warn instead.
    if totp {
        super::model::warn_if_existing_dep_below_version(
            &mut plan,
            &cargo_existing,
            "base64",
            0,
            22,
        );
    }
    // Apply dep additions then enable the mail feature in a single write.
    let with_deps = ensure_cargo_dependencies(&cargo_existing, &all_deps);
    // `ensure_cargo_dependencies` no-ops on an already-declared `totp-rs`, so
    // merge the required features into any pre-existing declaration.
    let with_deps = if totp {
        ensure_totp_rs_features(&with_deps)
    } else {
        with_deps
    };
    let final_cargo = ensure_autumn_web_mail_feature(&with_deps);
    if final_cargo != cargo_existing {
        plan.modify(cargo_toml_path.clone(), final_cargo);
    }
    // Pushed unconditionally — see `plan_cargo_deps`'s matching comment in
    // model.rs: destroy recomputes this plan against the already-generated
    // Cargo.toml, where these entries are by definition already present.
    // `owner_dir` is `src/models`: every auth resource always creates at
    // least `<snake>.rs` and `<snake>_session.rs` there, and (unlike
    // channels/mailers) an auth resource's routes file isn't
    // name-parameterized (`src/routes/auth.rs` always, regardless of the
    // resource name), so a second auth resource can't coexist under a
    // different name anyway — `src/models` is a reliable "this auth resource
    // still exists" marker.
    let models_owner_dir = project_root.join("src").join("models");
    let dep_names: Vec<String> = all_deps
        .iter()
        .map(|(name, _)| *name)
        .filter(|name| !super::model::TEMPLATE_SHIPPED_CARGO_DEPS.contains(name))
        .map(str::to_owned)
        .collect();
    if !dep_names.is_empty() {
        plan.push_revert(crate::generate::emit::Revert::CargoDeps {
            path: cargo_toml_path.clone(),
            names: dep_names,
            owner_dir: models_owner_dir.clone(),
        });
    }
    plan.push_revert(crate::generate::emit::Revert::CargoAutumnWebFeature {
        path: cargo_toml_path,
        feature: "mail".to_owned(),
        owner_dir: Some(models_owner_dir),
    });

    Ok(plan)
}

/// Compute the file actions for `autumn generate auth --oauth <providers>`.
///
/// When `oauth.providers` is empty this is identical to [`plan_auth`].
/// When providers are specified the plan additionally includes:
/// - An `oauth_identities` migration keyed by `(provider, subject)`.
/// - `src/routes/oauth.rs` with `oauth_redirect` and `oauth_callback` handlers.
/// - `docs/guide/oauth.md` covering provider setup, security properties, and troubleshooting.
/// - The `oauth2` feature on `autumn-web` in `Cargo.toml`.
///
/// # Errors
/// Same as [`plan_auth`].
///
/// Retained as stable public API; internal call sites use [`plan_auth_full`].
#[allow(dead_code)]
pub fn plan_auth_with_options(
    project_root: &Path,
    name: &str,
    timestamp: &str,
    oauth: &AuthOAuthOptions,
) -> Result<Plan, GenerateError> {
    plan_auth_options_impl(
        project_root,
        name,
        timestamp,
        oauth,
        false,
        false,
        false,
        false,
    )
}

/// Compute the file actions for `autumn generate auth [--oauth …] [--totp]`.
///
/// Layers optional TOTP two-factor authentication on top of the base (and
/// optional OAuth) auth scaffold.
///
/// # Errors
/// Same as [`plan_auth`].
#[allow(dead_code)]
pub fn plan_auth_full(
    project_root: &Path,
    name: &str,
    timestamp: &str,
    oauth: &AuthOAuthOptions,
    totp: bool,
) -> Result<Plan, GenerateError> {
    plan_auth_options_impl(
        project_root,
        name,
        timestamp,
        oauth,
        totp,
        false,
        false,
        false,
    )
}

/// Compute the file actions for `autumn generate auth [--oauth …] [--totp] [--passkeys]`.
///
/// Extended version of [`plan_auth_full`] that additionally supports `WebAuthn` passkeys.
///
/// # Errors
/// Same as [`plan_auth`].
pub fn plan_auth_full_ex(
    project_root: &Path,
    name: &str,
    timestamp: &str,
    oauth: &AuthOAuthOptions,
    totp: bool,
    passkeys: bool,
) -> Result<Plan, GenerateError> {
    plan_auth_options_impl(
        project_root,
        name,
        timestamp,
        oauth,
        totp,
        passkeys,
        false,
        false,
    )
}

/// Compute the file actions for
/// `autumn generate auth [--oauth …] [--totp] [--passkeys] [--magic-link]`.
///
/// Extended version of [`plan_auth_full_ex`] that additionally supports
/// passwordless email magic-link login (issue #1328). The magic-link scaffold
/// is fully composable with `--oauth`, `--totp`, and `--passkeys`.
///
/// # Errors
/// Same as [`plan_auth`].
pub fn plan_auth_full_ex2(
    project_root: &Path,
    name: &str,
    timestamp: &str,
    oauth: &AuthOAuthOptions,
    totp: bool,
    passkeys: bool,
    magic_link: bool,
) -> Result<Plan, GenerateError> {
    plan_auth_options_impl(
        project_root,
        name,
        timestamp,
        oauth,
        totp,
        passkeys,
        magic_link,
        false,
    )
}

/// Compute the file actions for `autumn destroy auth …`.
///
/// Identical to [`plan_auth_full_ex2`] except it recomputes the plan for the
/// revert path: it skips the generate-only shared-layout preflight so cleanup
/// still succeeds in a project whose shared `pub fn layout` is missing or
/// renamed (e.g. one scaffolded by an older CLI). `autumn destroy auth` reverts
/// the returned plan; the preflight would otherwise hard-fail the destroy
/// before any generated file is removed (issue #1353 follow-up).
///
/// # Errors
/// Same as [`plan_auth_full_ex2`], minus the shared-layout preflight.
pub fn plan_auth_full_ex2_for_revert(
    project_root: &Path,
    name: &str,
    timestamp: &str,
    oauth: &AuthOAuthOptions,
    totp: bool,
    passkeys: bool,
    magic_link: bool,
) -> Result<Plan, GenerateError> {
    plan_auth_options_impl(
        project_root,
        name,
        timestamp,
        oauth,
        totp,
        passkeys,
        magic_link,
        true,
    )
}

/// Shared implementation: base (optionally TOTP-aware, optionally passkey-aware,
/// optionally magic-link-aware) scaffold plus, when providers are supplied, the
/// OAuth artifacts.
// The three feature flags (`totp`/`passkeys`/`magic_link`) already saturate the
// bool/arg budget; the fourth (`for_revert`) is an internal generate-vs-destroy
// toggle threaded only from this crate's two public wrappers, so keep the flat
// signature rather than wrap it in a one-off options struct.
#[allow(
    clippy::too_many_lines,
    clippy::too_many_arguments,
    clippy::fn_params_excessive_bools
)]
fn plan_auth_options_impl(
    project_root: &Path,
    name: &str,
    timestamp: &str,
    oauth: &AuthOAuthOptions,
    totp: bool,
    passkeys: bool,
    magic_link: bool,
    for_revert: bool,
) -> Result<Plan, GenerateError> {
    // Start with the base auth plan with providers (and optional TOTP, and
    // optional magic-link) applied. `for_revert` threads through to suppress the
    // generate-only shared-layout preflight on the `autumn destroy auth` path.
    let mut plan = plan_auth_with_providers_ex_impl(
        project_root,
        name,
        timestamp,
        &oauth.providers,
        totp,
        magic_link,
        for_revert,
    )?;

    // Determine the target app's database backend so the scaffolded migrations
    // emit backend-aware DDL (issue #1927), matching the base auth plan above.
    let backend = super::detect_backend(project_root);
    let pascal_name = pascal(name);
    let snake_name = snake(name);
    let user_table = pluralize(&snake_name);

    if !oauth.providers.is_empty() {
        // ── oauth_identities migration ─────────────────────────────────────────
        // Increment the timestamp by one second so Diesel never sees two migrations
        // with the same version number.
        let oauth_ts_str: String = timestamp
            .parse::<i64>()
            .map_or_else(|_| format!("{timestamp}1"), |t| (t + 1).to_string());
        let mig_dir = project_root
            .join("migrations")
            .join(format!("{oauth_ts_str}_create_oauth_identities"));
        plan.create(
            mig_dir.join("up.sql"),
            render_oauth_migration_up(backend, &user_table),
        );
        plan.create(mig_dir.join("down.sql"), render_oauth_migration_down());

        // ── src/schema.rs entry for oauth_identities ───────────────────────────
        let schema_path = project_root.join("src").join("schema.rs");
        let schema_base = find_plan_content_for_path(&plan, &schema_path)
            .unwrap_or_else(|| read_or_empty(&schema_path));
        let oauth_fields: Vec<super::dsl::Field> = [
            "provider:String",
            "subject:String",
            "user_id:i64",
            "email:Option<String>",
            "name:Option<String>",
        ]
        .iter()
        .map(|t| super::dsl::parse_field(t).expect("oauth field tokens are always valid"))
        .collect();
        let updated_schema = append_schema_table(&schema_base, "oauth_identities", &oauth_fields);
        plan.modify(schema_path.clone(), updated_schema);
        plan.push_revert(crate::generate::emit::Revert::SchemaTable {
            path: schema_path,
            table: "oauth_identities".to_owned(),
            expected_block: append_schema_table("", "oauth_identities", &oauth_fields),
        });

        // ── oauth routes ───────────────────────────────────────────────────────
        let routes_dir = project_root.join("src").join("routes");
        plan.create(
            routes_dir.join("oauth.rs"),
            render_oauth_routes_file(
                &pascal_name,
                &snake_name,
                &user_table,
                &oauth.providers,
                totp,
            ),
        );

        // Add `pub mod oauth;` to src/routes/mod.rs — use the base plan's already-modified
        // content so the base `pub mod auth;` declaration is not overwritten.
        let route_mod_path = routes_dir.join("mod.rs");
        let route_mod_base = find_plan_content_for_path(&plan, &route_mod_path)
            .unwrap_or_else(|| read_or_empty(&route_mod_path));
        let updated_route_mod = add_mod_declaration(&route_mod_base, "oauth");
        plan.modify(route_mod_path.clone(), updated_route_mod);
        plan.push_revert(crate::generate::emit::Revert::ModDecl {
            path: route_mod_path,
            name: "oauth".to_owned(),
        });

        // ── Register oauth routes in src/main.rs ───────────────────────────────
        let main_path = project_root.join("src").join("main.rs");
        let main_existing = std::fs::read_to_string(&main_path).map_err(|_| {
            GenerateError::Io(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("missing {}", main_path.display()),
            ))
        })?;
        let oauth_entries = oauth_route_entries();
        // The base plan has already modified main.rs; find current state in plan or use existing.
        let base_main =
            find_plan_content_for_path(&plan, &main_path).unwrap_or_else(|| main_existing.clone());
        let updated_main = super::schema_edit::update_main_rs(
            &base_main,
            &["models", "routes", "schema"],
            &oauth_entries,
        );
        plan.modify(main_path.clone(), updated_main);
        plan.push_revert(crate::generate::emit::Revert::RoutesEntries {
            path: main_path,
            entries: oauth_entries,
        });

        // ── docs/guide/oauth.md ────────────────────────────────────────────────
        let docs_dir = project_root.join("docs").join("guide");
        plan.create(
            docs_dir.join("oauth.md"),
            render_oauth_docs_file(backend, &oauth.providers, &user_table),
        );

        // ── Cargo.toml: add oauth2 feature to autumn-web ─────────────────────
        let cargo_toml_path = project_root.join("Cargo.toml");
        let cargo_existing = read_or_empty(&cargo_toml_path);
        // The base plan may have already updated Cargo.toml; use its content if present.
        let base_cargo = find_plan_content_for_path(&plan, &cargo_toml_path)
            .unwrap_or_else(|| cargo_existing.clone());
        let with_oauth2 = ensure_autumn_web_oauth2_feature(&base_cargo);
        if with_oauth2 != base_cargo {
            plan.modify(cargo_toml_path.clone(), with_oauth2);
        }
        plan.push_revert(crate::generate::emit::Revert::CargoAutumnWebFeature {
            path: cargo_toml_path,
            feature: "oauth2".to_owned(),
            owner_dir: Some(project_root.join("src").join("models")),
        });

        // ── autumn.toml OAuth provider stubs ───────────────────────────────────
        let autumn_toml_path = project_root.join("autumn.toml");
        if autumn_toml_path.exists() {
            let toml_existing = read_or_empty(&autumn_toml_path);
            let updated_toml = append_oauth_stubs_to_toml(&toml_existing, &oauth.providers);
            if updated_toml != toml_existing {
                plan.modify(autumn_toml_path.clone(), updated_toml);
            }
            plan.push_revert(crate::generate::emit::Revert::AuthOAuthProviderStubs {
                path: autumn_toml_path,
                providers: oauth.providers.clone(),
            });
        }
    }

    if passkeys {
        // ── webauthn_credentials collision check ───────────────────────────────
        // If the project already has webauthn_credentials in schema.rs, the
        // migration below would fail at `diesel migration run`. Reject upfront.
        //
        // Only reject a *foreign* `webauthn_credentials` table: when the auth
        // user table itself is also already present, this is a re-run over
        // our own output (`--force`, or `autumn destroy` recomputing this
        // same plan against already-generated files — issue #1048), where
        // the schema append below is an idempotent no-op.
        let schema_for_check = project_root.join("src").join("schema.rs");
        let schema_existing_for_passkey = find_plan_content_for_path(&plan, &schema_for_check)
            .unwrap_or_else(|| read_or_empty(&schema_for_check));
        if schema_has_table(&schema_existing_for_passkey, "webauthn_credentials")
            && !schema_has_table(&schema_existing_for_passkey, &user_table)
        {
            return Err(GenerateError::InvalidName(
                name.to_owned(),
                "this project already defines a `webauthn_credentials` table, which \
                 `--passkeys` needs; rename or remove the existing table first."
                    .to_owned(),
            ));
        }

        // ── webauthn_credentials migration ─────────────────────────────────────
        // Use timestamp+2 when oauth is also requested (oauth uses timestamp+1),
        // so both migrations get unique Diesel version numbers.
        let passkey_offset: i64 = if oauth.providers.is_empty() { 1 } else { 2 };
        let passkey_ts_str: String = timestamp.parse::<i64>().map_or_else(
            |_| format!("{timestamp}{passkey_offset}"),
            |t| (t + passkey_offset).to_string(),
        );
        let mig_dir = project_root
            .join("migrations")
            .join(format!("{passkey_ts_str}_create_webauthn_credentials"));
        plan.create(
            mig_dir.join("up.sql"),
            render_passkey_migration_up(backend, &user_table),
        );
        plan.create(mig_dir.join("down.sql"), render_passkey_migration_down());

        // ── src/models/webauthn_credential.rs ─────────────────────────────────
        let models_dir = project_root.join("src").join("models");
        plan.create(
            models_dir.join("webauthn_credential.rs"),
            render_webauthn_credential_model_file(&user_table),
        );
        let model_mod_path = models_dir.join("mod.rs");
        let model_mod_base = find_plan_content_for_path(&plan, &model_mod_path)
            .unwrap_or_else(|| read_or_empty(&model_mod_path));
        plan.modify(
            model_mod_path.clone(),
            add_mod_declaration(&model_mod_base, "webauthn_credential"),
        );
        plan.push_revert(crate::generate::emit::Revert::ModDecl {
            path: model_mod_path,
            name: "webauthn_credential".to_owned(),
        });

        // ── src/schema.rs: webauthn_credentials table ─────────────────────────
        let schema_path = project_root.join("src").join("schema.rs");
        let schema_base = find_plan_content_for_path(&plan, &schema_path)
            .unwrap_or_else(|| read_or_empty(&schema_path));
        let wc_fields: Vec<super::dsl::Field> = [
            "user_id:i64",
            "credential_id:String",
            "credential_json:String",
            "name:String",
            "last_used_at:Option<NaiveDateTime>",
        ]
        .iter()
        .map(|t| super::dsl::parse_field(t).expect("webauthn credential field tokens are valid"))
        .collect();
        let updated_schema = append_schema_table(&schema_base, "webauthn_credentials", &wc_fields);
        plan.modify(schema_path.clone(), updated_schema);
        plan.push_revert(crate::generate::emit::Revert::SchemaTable {
            path: schema_path,
            table: "webauthn_credentials".to_owned(),
            expected_block: append_schema_table("", "webauthn_credentials", &wc_fields),
        });

        // ── src/routes/passkeys.rs ─────────────────────────────────────────────
        let routes_dir = project_root.join("src").join("routes");
        plan.create(
            routes_dir.join("passkeys.rs"),
            render_passkeys_routes_file(&pascal_name, &snake_name, &user_table),
        );
        let route_mod_path = routes_dir.join("mod.rs");
        let route_mod_base = find_plan_content_for_path(&plan, &route_mod_path)
            .unwrap_or_else(|| read_or_empty(&route_mod_path));
        plan.modify(
            route_mod_path.clone(),
            add_mod_declaration(&route_mod_base, "passkeys"),
        );
        plan.push_revert(crate::generate::emit::Revert::ModDecl {
            path: route_mod_path,
            name: "passkeys".to_owned(),
        });

        // ── Register passkey routes in src/main.rs ─────────────────────────────
        let main_path = project_root.join("src").join("main.rs");
        let main_existing = std::fs::read_to_string(&main_path).map_err(|_| {
            GenerateError::Io(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("missing {}", main_path.display()),
            ))
        })?;
        let pk_entries = passkey_route_entries();
        let base_main =
            find_plan_content_for_path(&plan, &main_path).unwrap_or_else(|| main_existing.clone());
        let updated_main = super::schema_edit::update_main_rs(
            &base_main,
            &["models", "routes", "schema"],
            &pk_entries,
        );
        plan.modify(main_path.clone(), updated_main);
        plan.push_revert(crate::generate::emit::Revert::RoutesEntries {
            path: main_path,
            entries: pk_entries,
        });

        // ── tests/auth_passkeys.rs ─────────────────────────────────────────────
        let tests_dir = project_root.join("tests");
        plan.create(
            tests_dir.join("auth_passkeys.rs"),
            render_passkeys_tests_file(&pascal_name, &snake_name),
        );

        // ── docs/guide/passkeys.md ─────────────────────────────────────────────
        let docs_dir = project_root.join("docs").join("guide");
        plan.create(docs_dir.join("passkeys.md"), render_passkeys_docs_file());

        // ── autumn.toml: [auth.webauthn] stub ─────────────────────────────────
        let autumn_toml_path = project_root.join("autumn.toml");
        if autumn_toml_path.exists() {
            let toml_existing = find_plan_content_for_path(&plan, &autumn_toml_path)
                .unwrap_or_else(|| read_or_empty(&autumn_toml_path));
            let updated_toml = append_webauthn_stub_to_toml(
                &toml_existing,
                "localhost",
                "My App",
                "http://localhost:3000",
            );
            if updated_toml != toml_existing {
                plan.modify(autumn_toml_path.clone(), updated_toml);
            }
            plan.push_revert(crate::generate::emit::Revert::AuthWebauthnStub {
                path: autumn_toml_path,
            });
        }

        // ── Cargo.toml: add webauthn-rs dep + webauthn feature on autumn-web ───
        let cargo_toml_path = project_root.join("Cargo.toml");
        let base_cargo = find_plan_content_for_path(&plan, &cargo_toml_path)
            .unwrap_or_else(|| read_or_empty(&cargo_toml_path));
        let all_passkey_deps: Vec<(&str, &str)> = PASSKEY_EXTRA_DEPS.to_vec();
        // `ensure_cargo_dependencies` is name-only, so an app that already pins
        // an older `base64` keeps it and never gets `0.23`; the emitted
        // `encode_cred_id` needs the 0.21+ `Engine` API, so warn if it's too old.
        super::model::warn_if_existing_dep_below_version(&mut plan, &base_cargo, "base64", 0, 22);
        // The emitted passkey code uses the `webauthn-rs` 0.6 API.
        super::model::warn_if_existing_dep_below_version(
            &mut plan,
            &base_cargo,
            "webauthn-rs",
            0,
            6,
        );
        let with_deps = super::model::ensure_cargo_dependencies(&base_cargo, &all_passkey_deps);
        // If the project already declared webauthn-rs without the required features,
        // ensure_cargo_dependencies would have skipped it; merge them here.
        let with_deps = ensure_webauthn_rs_features(&with_deps);
        let with_webauthn = ensure_autumn_web_webauthn_feature(&with_deps);
        if with_webauthn != base_cargo {
            plan.modify(cargo_toml_path.clone(), with_webauthn);
        }
        let passkey_models_owner_dir = project_root.join("src").join("models");
        let passkey_dep_names: Vec<String> = all_passkey_deps
            .iter()
            .map(|(name, _)| *name)
            .filter(|name| !super::model::TEMPLATE_SHIPPED_CARGO_DEPS.contains(name))
            .map(str::to_owned)
            .collect();
        if !passkey_dep_names.is_empty() {
            plan.push_revert(crate::generate::emit::Revert::CargoDeps {
                path: cargo_toml_path.clone(),
                names: passkey_dep_names,
                owner_dir: passkey_models_owner_dir.clone(),
            });
        }
        plan.push_revert(crate::generate::emit::Revert::CargoAutumnWebFeature {
            path: cargo_toml_path,
            feature: "webauthn".to_owned(),
            owner_dir: Some(passkey_models_owner_dir),
        });
    }

    Ok(plan)
}

/// Extract the planned output content for a given path from the plan (last modify/create wins).
fn find_plan_content_for_path(plan: &Plan, path: &std::path::Path) -> Option<String> {
    use super::emit::Action;
    plan.actions
        .iter()
        .rev()
        .find(|a| a.path() == path)
        .and_then(|a| match a {
            Action::Create { contents, .. }
            | Action::Modify { contents, .. }
            | Action::CreateIfAbsent { contents, .. } => Some(contents.clone()),
            // Binary/verbatim files have no textual content to inspect.
            Action::CreateBytes { .. } => None,
        })
}

/// Ensure `autumn-web` in `[dependencies]` carries `features = ["<feature_name>"]`.
///
/// Handles the three common forms a fresh Autumn project may use:
/// - `autumn-web = "x.y"` (simple string)
/// - `autumn-web = { version = "x.y", ... }` (inline table)
/// - `[dependencies.autumn-web]` subtable (hyphenated spelling, or the
///   underscore-normalized `[dependencies.autumn_web]` spelling — but only when
///   its body renames the package back with `package = "autumn-web"`; without
///   that rename Cargo resolves the table to a different package literally
///   named `autumn_web`, which must be left untouched)
///
/// Shared by the `oauth2`/`mail`/`webauthn` feature injectors below. The only
/// thing that ever varied between those three copies (once #2752/#2771 closed
/// the underscore-subtable soundness gap and #2948/#3084 closed the multiline-
/// array gaps in all three) was which feature string to require — see the
/// clone-class history in issue #2753.
#[allow(clippy::too_many_lines)]
fn ensure_autumn_web_feature(toml: &str, feature_name: &str) -> String {
    const CRATE: &str = "autumn-web";
    let feature_lit = format!("\"{feature_name}\"");
    let feature: &str = &feature_lit;

    let mut lines: Vec<String> = toml.lines().map(str::to_owned).collect();
    let trailing_newline = toml.ends_with('\n');

    let simple_prefix = format!("{CRATE} = \"");
    let table_prefix = format!("{CRATE} = {{");
    let subtable_header = format!("[dependencies.{CRATE}]");
    let subtable_header_underscore = format!("[dependencies.{}]", CRATE.replace('-', "_"));

    let mut i = 0;
    while i < lines.len() {
        let trimmed = lines[i].trim().to_owned();
        let indent: String = lines[i]
            .chars()
            .take_while(char::is_ascii_whitespace)
            .collect();

        if let Some(rest) = trimmed.strip_prefix(&simple_prefix) {
            let version = rest.trim_end_matches('"');
            lines[i] =
                format!("{indent}{CRATE} = {{ version = \"{version}\", features = [{feature}] }}");
            break;
        }

        if trimmed.starts_with(&table_prefix) {
            // A trailing `# comment` mentioning the feature is not TOML —
            // check only the code portion of the line, the same guard the
            // subtable branch below needs against a commented-out mention.
            if strip_line_comment(&trimmed).contains(feature) {
                break; // already present
            }
            if let Some(feat_bracket) =
                find_unquoted_str(strip_line_comment(&trimmed), "features = [")
            {
                let list_start = feat_bracket + "features = [".len();
                if let Some(close_bracket) = find_unquoted(&trimmed[list_start..], ']') {
                    let list_end = close_bracket + list_start;
                    let existing = trimmed[list_start..list_end].trim();
                    let new_list = if existing.is_empty() {
                        feature.to_owned()
                    } else {
                        format!("{existing}, {feature}")
                    };
                    lines[i] = format!(
                        "{indent}{}{}{}",
                        &trimmed[..list_start],
                        new_list,
                        &trimmed[list_end..]
                    );
                } else {
                    // Multiline `features = [` … `]` array inside the
                    // inline-table form (legal TOML since 1.0): mirror the
                    // subtable branch's own multiline handling below rather
                    // than a same-line-only scan. Codex review on #3084
                    // found this thinner version could both lose the
                    // separator before a feature appended after an entry
                    // with no trailing comma, and miss an already-merged
                    // feature sitting on a continuation line — the same two
                    // defects #2948 already fixed once for the subtable
                    // form.
                    let mut k = i + 1;
                    let mut already_present = false;
                    let mut close_line = None;
                    while k < lines.len() {
                        let tk = lines[k].trim();
                        if tk.starts_with('[') {
                            break;
                        }
                        let code = strip_line_comment(tk);
                        if let Some(close_idx) = find_unquoted(code, ']') {
                            // Unlike the subtable form, an inline table's `}`
                            // can carry more comma-separated fields after the
                            // array's `]` on this same line (`], path = "…" }`)
                            // — Codex review on #3084 found a field whose own
                            // string value happened to equal the feature name
                            // (`path = "<feature>"`) made this look merged
                            // already when the array itself was not. Only the
                            // portion before `]` is the array.
                            if code[..close_idx].contains(feature) {
                                already_present = true;
                            }
                            close_line = Some(k);
                            break;
                        }
                        if code.contains(feature) {
                            already_present = true;
                        }
                        k += 1;
                    }
                    if !already_present && let Some(k) = close_line {
                        let tk = lines[k].trim().to_owned();
                        let close_idx = find_unquoted(&tk, ']').unwrap_or(tk.len());
                        let before_close = tk[..close_idx].trim();
                        // The closing bracket's own line may have no entry
                        // before it, in which case the last real entry is on
                        // an earlier line — including possibly the opener
                        // line itself, past `features = [`.
                        let last_entry = (i..=k).rev().find_map(|idx| {
                            let raw: &str = if idx == k {
                                before_close
                            } else if idx == i {
                                &trimmed[list_start..]
                            } else {
                                &lines[idx]
                            };
                            let raw = strip_line_comment(raw).trim();
                            (!raw.is_empty()).then(|| raw.to_owned())
                        });
                        let sep = if last_entry.is_some_and(|e| !e.ends_with(',')) {
                            ", "
                        } else {
                            ""
                        };
                        let indent_k: String = lines[k]
                            .chars()
                            .take_while(char::is_ascii_whitespace)
                            .collect();
                        lines[k] =
                            format!("{indent_k}{before_close}{sep}{feature}{}", &tk[close_idx..]);
                    }
                }
            } else {
                let close = trimmed.rfind('}').unwrap();
                let before_close = trimmed[..close].trim_end();
                let sep = if before_close.ends_with('{') {
                    ""
                } else {
                    ", "
                };
                lines[i] = format!(
                    "{indent}{}{sep}features = [{feature}]{}",
                    &trimmed[..close],
                    &trimmed[close..]
                );
            }
            break;
        }

        // Cargo does not normalize `-`/`_` in a dependency table key: unlike
        // `[dependencies.autumn-web]`, `[dependencies.autumn_web]` names an
        // unrelated package `autumn_web` unless its body renames it back with
        // `package = "autumn-web"` (confirmed via `cargo metadata`). Require
        // that declaration before treating the underscore form as a match, the
        // same way `find_section_start_with_autumn_web_package` does.
        let underscore_aliases_autumn_web = trimmed == subtable_header_underscore && {
            let body_end = lines[i + 1..]
                .iter()
                .position(|l| l.trim_start().starts_with('['))
                .map_or(lines.len(), |p| i + 1 + p);
            lines[i + 1..body_end].iter().any(|l| {
                let code = l.split_once('#').map_or(l.as_str(), |(before, _)| before);
                declares_package(code, CRATE)
            })
        };

        if trimmed == subtable_header || underscore_aliases_autumn_web {
            let mut j = i + 1;
            let mut found_features = false;
            while j < lines.len() {
                let t = lines[j].trim().to_owned();
                if t.starts_with('[') {
                    break;
                }
                if t.starts_with("features") {
                    found_features = true;
                    // A trailing `# comment` on the opener line is not TOML —
                    // check only the code portion, both for "is the feature
                    // already mentioned" and for locating a real closing `]`
                    // (a `]` inside the comment would misclassify a genuinely
                    // multiline array as single-line and merge into dead text
                    // past the `#`).
                    if strip_line_comment(&t).contains(feature) {
                        break;
                    }
                    if let Some(open) = t.find('[') {
                        if let Some(close) = find_unquoted(strip_line_comment(&t), ']') {
                            let inner = t[open + 1..close].trim();
                            let new_inner = if inner.is_empty() {
                                feature.to_owned()
                            } else {
                                format!("{inner}, {feature}")
                            };
                            let indent_j: String = lines[j]
                                .chars()
                                .take_while(char::is_ascii_whitespace)
                                .collect();
                            lines[j] = format!("{indent_j}features = [{new_inner}]");
                        } else {
                            // Multiline `features = [` … `]` array: scan every
                            // line up to the closing bracket. The feature may
                            // already be merged on a line other than the
                            // opener, in which case nothing should be
                            // appended (it would otherwise be duplicated on
                            // every re-run of the generator).
                            let mut k = j + 1;
                            let mut already_present = false;
                            let mut close_line = None;
                            while k < lines.len() {
                                let tk = lines[k].trim();
                                if tk.starts_with('[') {
                                    break;
                                }
                                // A `#`-commented-out mention of the feature or
                                // a stray `]` inside a comment is not TOML —
                                // check only the code portion of the line.
                                let code = strip_line_comment(tk);
                                if code.contains(feature) {
                                    already_present = true;
                                }
                                if find_unquoted(code, ']').is_some() {
                                    close_line = Some(k);
                                    break;
                                }
                                k += 1;
                            }
                            if !already_present && let Some(k) = close_line {
                                let tk = lines[k].trim().to_owned();
                                let close_idx = find_unquoted(&tk, ']').unwrap_or(tk.len());
                                let before_close = tk[..close_idx].trim();
                                // The closing bracket's own line may have no
                                // entry before it (just `]`, or just a
                                // comment), in which case the last real entry
                                // — needed to know whether a comma must be
                                // inserted — is on an earlier line. A trailing
                                // `# comment` never counts as the entry: strip
                                // it before checking, or a commented `"ws", #
                                // note` line reads as not ending in ',' and
                                // gets a second, invalid comma inserted ahead
                                // of it.
                                let last_entry = (j..=k).rev().find_map(|idx| {
                                    let raw: &str = if idx == k {
                                        before_close
                                    } else if idx == j {
                                        lines[idx].split_once('[').map_or("", |(_, rest)| rest)
                                    } else {
                                        &lines[idx]
                                    };
                                    let raw = strip_line_comment(raw).trim();
                                    (!raw.is_empty()).then(|| raw.to_owned())
                                });
                                let sep = if last_entry.is_some_and(|e| !e.ends_with(',')) {
                                    ", "
                                } else {
                                    ""
                                };
                                let indent_k: String = lines[k]
                                    .chars()
                                    .take_while(char::is_ascii_whitespace)
                                    .collect();
                                lines[k] = format!(
                                    "{indent_k}{before_close}{sep}{feature}{}",
                                    &tk[close_idx..]
                                );
                            }
                        }
                    }
                    break;
                }
                j += 1;
            }
            if !found_features {
                lines.insert(i + 1, format!("features = [{feature}]"));
            }
            break;
        }

        i += 1;
    }

    let mut out = lines.join("\n");
    if trailing_newline && !out.ends_with('\n') {
        out.push('\n');
    }
    out
}

/// Ensure `autumn-web` in `[dependencies]` has `features = ["oauth2"]`.
fn ensure_autumn_web_oauth2_feature(toml: &str) -> String {
    ensure_autumn_web_feature(toml, "oauth2")
}

/// CLI entry point for `autumn generate auth <Name>` (no OAuth providers).
#[allow(dead_code)]
pub fn run(name: &str, flags: Flags) {
    run_with_options(name, flags, &AuthOAuthOptions::default(), false, false);
}

/// CLI entry point for `autumn generate auth <Name> --oauth <providers> [--totp] [--passkeys]`.
pub fn run_with_options(
    name: &str,
    flags: Flags,
    oauth: &AuthOAuthOptions,
    totp: bool,
    passkeys: bool,
) {
    let cwd = match std::env::current_dir() {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Error: cannot determine current directory: {e}");
            std::process::exit(1);
        }
    };
    let timestamp = timestamp_now();
    let plan = plan_auth_full_ex(&cwd, name, &timestamp, oauth, totp, passkeys);
    match plan.and_then(|p| p.execute(flags)) {
        Ok(()) => {}
        Err(e) => {
            eprintln!("Error: {e}");
            std::process::exit(1);
        }
    }
}

/// Ensure `autumn-web` in `[dependencies]` has `features = ["mail"]`.
fn ensure_autumn_web_mail_feature(toml: &str) -> String {
    ensure_autumn_web_feature(toml, "mail")
}

fn append_oauth_stubs_to_toml(existing: &str, providers: &[String]) -> String {
    let mut out = existing.trim_end().to_owned();
    for name in providers {
        let header = format!("[auth.oauth2.{name}]");
        if out.contains(&header) {
            continue;
        }
        out.push('\n');
        out.push_str(&oauth_provider_stub_block(name));
    }
    out.push('\n');
    out
}

/// The exact `[auth.oauth2.<name>]` stub block [`append_oauth_stubs_to_toml`]
/// inserts for a known or unknown provider name. Shared with
/// `remove_oauth_provider_stubs` (via [`toml_table_block_matches`]) so
/// `autumn destroy` can verify a block is still byte-identical to this stub
/// — never hand-filled with real credentials, and never a pre-existing
/// block `generate` left untouched — before removing it.
fn oauth_provider_stub_block(name: &str) -> String {
    match name {
        "github" => r#"[auth.oauth2.github]
client_id = ""
client_secret = ""
authorize_url = "https://github.com/login/oauth/authorize"
token_url = "https://github.com/login/oauth/access_token"
userinfo_url = "https://api.github.com/user"
redirect_uri = "http://localhost:3000/auth/github/callback"
scope = "read:user user:email"
"#
        .to_owned(),
        "google" => r#"[auth.oauth2.google]
client_id = ""
client_secret = ""
authorize_url = "https://accounts.google.com/o/oauth2/v2/auth"
token_url = "https://oauth2.googleapis.com/token"
userinfo_url = "https://openidconnect.googleapis.com/v1/userinfo"
redirect_uri = "http://localhost:3000/auth/google/callback"
scope = "openid profile email"
issuer = "https://accounts.google.com"
jwks_url = "https://www.googleapis.com/oauth2/v3/certs"
discovery_url = "https://accounts.google.com"
"#
        .to_owned(),
        "microsoft" => r#"[auth.oauth2.microsoft]
client_id = ""
client_secret = ""
authorize_url = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
token_url = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
redirect_uri = "http://localhost:3000/auth/microsoft/callback"
scope = "openid profile email"
issuer = "https://login.microsoftonline.com/common/v2.0"
jwks_url = "https://login.microsoftonline.com/common/discovery/v2.0/keys"
discovery_url = "https://login.microsoftonline.com/common/v2.0"
"#
        .to_owned(),
        _ => format!(
            r#"[auth.oauth2.{name}]
client_id = ""
client_secret = ""
authorize_url = "https://example.com/oauth/authorize"
token_url = "https://example.com/oauth/token"
redirect_uri = "http://localhost:3000/auth/{name}/callback"
scope = "openid profile email"
"#
        ),
    }
}

// ── Template rendering ────────────────────────────────────────────────────────

/// Backend-specific SQL fragments for the hand-written auth migration DDL
/// (issue #1927).
///
/// The auth generator scaffolds several tables (users, sessions, remember
/// tokens, recovery codes, magic-link tokens, OAuth identities, `WebAuthn`
/// credentials) via hand-written `CREATE TABLE` strings. This carries the small
/// set of column-type fragments that differ between backends so the Postgres
/// output stays byte-for-byte identical while a `SQLite` app gets valid DDL:
/// `INTEGER PRIMARY KEY AUTOINCREMENT` for auto-increment ids (`SQLite` has no
/// `BIGSERIAL`), plain `INTEGER` for `BIGINT`/`INT`, and ISO-8601 `TEXT`
/// timestamps defaulted to `CURRENT_TIMESTAMP` (`SQLite` has no dedicated
/// timestamp type nor `NOW()`). Portable pieces (`TEXT`, `REFERENCES`, `UNIQUE`,
/// `CREATE INDEX`) are shared and unchanged. Mirrors the dialect mapping the
/// backend-aware model/migration generators use
/// (`super::dsl::IdType::pk_sql_for` / `FieldKind::sqlite_sql_type`).
#[derive(Clone, Copy)]
struct AuthDdl {
    /// Auto-increment primary-key column definition (the SQL after `id `).
    pk: &'static str,
    /// A `BIGINT` foreign-key / integer column type.
    big_int: &'static str,
    /// A nullable timestamp column type (used as `{ts} NULL`).
    ts: &'static str,
    /// A `NOT NULL` timestamp column defaulted to the creation time.
    ts_not_null_default_now: &'static str,
    /// A `BOOLEAN NOT NULL DEFAULT FALSE` column.
    bool_not_null_false: &'static str,
    /// A small-integer `NOT NULL DEFAULT 0` column (`failed_attempts`).
    int_not_null_zero: &'static str,
}

impl AuthDdl {
    const fn for_backend(backend: autumn_web::config::DatabaseBackend) -> Self {
        match backend {
            autumn_web::config::DatabaseBackend::Postgres => Self {
                pk: "BIGSERIAL PRIMARY KEY",
                big_int: "BIGINT",
                ts: "TIMESTAMP",
                ts_not_null_default_now: "TIMESTAMP NOT NULL DEFAULT NOW()",
                bool_not_null_false: "BOOLEAN NOT NULL DEFAULT FALSE",
                int_not_null_zero: "INT NOT NULL DEFAULT 0",
            },
            autumn_web::config::DatabaseBackend::Sqlite => Self {
                pk: "INTEGER PRIMARY KEY AUTOINCREMENT",
                big_int: "INTEGER",
                ts: "TEXT",
                ts_not_null_default_now: "TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP",
                bool_not_null_false: "INTEGER NOT NULL DEFAULT 0",
                int_not_null_zero: "INTEGER NOT NULL DEFAULT 0",
            },
        }
    }
}

/// Name of the per-login session-tracking table (issue #819), derived from
/// the auth resource: `User` → `user_sessions`, `Account` → `account_sessions`.
fn sessions_table_name(snake_name: &str) -> String {
    format!("{snake_name}_sessions")
}

/// Table backing persistent "remember-me" login chains (issue #1397).
fn remember_table_name(snake_name: &str) -> String {
    format!("{snake_name}_remember_tokens")
}

/// DDL for the tracked-sessions table, in the app's own dialect.
///
/// Shared by the scaffolded migration and the generated session-management
/// guide (issue #1908) so a `SQLite` app is never handed Postgres-only
/// `BIGSERIAL` / `NOW()` DDL, and the two copies cannot drift.
fn render_sessions_table_ddl(
    backend: autumn_web::config::DatabaseBackend,
    snake_name: &str,
    user_table: &str,
) -> String {
    let d = AuthDdl::for_backend(backend);
    let sess_table = sessions_table_name(snake_name);
    format!(
        "CREATE TABLE {sess_table} (\n\
         \x20   id {pk},\n\
         \x20   user_id {big_int} NOT NULL REFERENCES {user_table}(id) ON DELETE CASCADE,\n\
         \x20   token_digest TEXT NOT NULL UNIQUE,\n\
         \x20   ip TEXT NOT NULL DEFAULT '',\n\
         \x20   user_agent TEXT NOT NULL DEFAULT '',\n\
         \x20   ua_family TEXT NOT NULL DEFAULT '',\n\
         \x20   ua_os TEXT NOT NULL DEFAULT '',\n\
         \x20   ua_device TEXT NOT NULL DEFAULT '',\n\
         \x20   label TEXT NULL,\n\
         \x20   last_seen_at {created_at},\n\
         \x20   created_at {created_at}\n\
         );\n\
         \n\
         CREATE INDEX {sess_table}_user_id_idx ON {sess_table} (user_id);\n",
        pk = d.pk,
        big_int = d.big_int,
        created_at = d.ts_not_null_default_now,
    )
}

#[allow(clippy::too_many_lines)]
fn render_migration_up(
    backend: autumn_web::config::DatabaseBackend,
    snake_name: &str,
    table: &str,
    totp: bool,
    magic_link: bool,
) -> String {
    let d = AuthDdl::for_backend(backend);
    // TOTP columns are inserted after password_digest so the column order
    // matches the generated model struct and `schema.rs` block.
    let totp_columns = if totp {
        format!(
            "\x20   totp_secret_encrypted TEXT NULL,\n\
             \x20   totp_enabled {bool_default_false},\n\
             \x20   totp_last_used_step {big_int} NULL,\n",
            bool_default_false = d.bool_not_null_false,
            big_int = d.big_int,
        )
    } else {
        String::new()
    };
    let mut out = format!(
        "CREATE TABLE {table} (\n\
         \x20   id {pk},\n\
         \x20   email TEXT NOT NULL,\n\
         \x20   time_zone TEXT NULL,\n\
         \x20   password_digest TEXT NOT NULL,\n\
         {totp_columns}\
         \x20   failed_attempts {int_zero},\n\
         \x20   locked_at {ts} NULL,\n\
         \x20   reset_token_digest TEXT NULL,\n\
         \x20   reset_token_expires_at {ts} NULL,\n\
         \x20   confirm_token_digest TEXT NULL,\n\
         \x20   confirm_token_expires_at {ts} NULL,\n\
         \x20   email_confirmed_at {ts} NULL,\n\
         \x20   pending_email TEXT NULL,\n\
         \x20   export_requested_at {ts} NULL,\n\
         \x20   delete_requested_at {ts} NULL,\n\
         \x20   delete_scheduled_at {ts} NULL,\n\
         \x20   created_at {created_at}\n\
         );\n",
        pk = d.pk,
        int_zero = d.int_not_null_zero,
        ts = d.ts,
        created_at = d.ts_not_null_default_now,
    );
    // `email`'s uniqueness is expressed through the same shared primitive
    // `field:String:unique` scaffolds elsewhere (issue #1032), rather than a
    // parallel hand-rolled `UNIQUE` column constraint.
    out.push_str(&unique_index_sql(table, "email", &[]));
    if totp {
        let _ = write!(
            out,
            "\n\
             CREATE TABLE recovery_codes (\n\
             \x20   id {pk},\n\
             \x20   user_id {big_int} NOT NULL REFERENCES {table}(id) ON DELETE CASCADE,\n\
             \x20   code_digest TEXT NOT NULL,\n\
             \x20   used_at {ts} NULL,\n\
             \x20   created_at {created_at}\n\
             );\n\
             \n\
             CREATE INDEX recovery_codes_user_id_idx ON recovery_codes (user_id);\n",
            pk = d.pk,
            big_int = d.big_int,
            ts = d.ts,
            created_at = d.ts_not_null_default_now,
        );
    }
    // Active login sessions (issue #819): one row per login, keyed by the
    // SHA-256 digest of the opaque server-side session id. Only the digest
    // is stored so a database leak cannot be replayed as a session cookie.
    let _ = write!(
        out,
        "\n{ddl}",
        ddl = render_sessions_table_ddl(backend, snake_name, table),
    );
    // Persistent "remember-me" login chains (issue #1397): one row per device
    // login-chain, keyed by the stable opaque `series`. `token_hash` rotates on
    // every use so a replayed rotated-out cookie is detected as theft. Only the
    // SHA-256 hash of the current token is stored — never the raw token — so a
    // database leak cannot be replayed as a remember cookie.
    let rem_table = remember_table_name(snake_name);
    let _ = write!(
        out,
        "\n\
         CREATE TABLE {rem_table} (\n\
         \x20   id {pk},\n\
         \x20   series TEXT NOT NULL UNIQUE,\n\
         \x20   user_id {big_int} NOT NULL REFERENCES {table}(id) ON DELETE CASCADE,\n\
         \x20   token_hash TEXT NOT NULL,\n\
         \x20   previous_token_hash TEXT NULL,\n\
         \x20   rotated_at {ts} NULL,\n\
         \x20   expires_at {ts} NOT NULL,\n\
         \x20   ip TEXT NOT NULL DEFAULT '',\n\
         \x20   user_agent TEXT NOT NULL DEFAULT '',\n\
         \x20   ua_family TEXT NOT NULL DEFAULT '',\n\
         \x20   ua_os TEXT NOT NULL DEFAULT '',\n\
         \x20   ua_device TEXT NOT NULL DEFAULT '',\n\
         \x20   label TEXT NULL,\n\
         \x20   last_used_at {ts} NULL,\n\
         \x20   created_at {created_at}\n\
         );\n\
         \n\
         CREATE INDEX {rem_table}_user_id_idx ON {rem_table} (user_id);\n",
        pk = d.pk,
        big_int = d.big_int,
        ts = d.ts,
        created_at = d.ts_not_null_default_now,
    );
    // Passwordless magic-link tokens (issue #1328): one row per issued link,
    // keyed by the SHA-256 digest of the raw token. Only the digest is stored —
    // the raw token appears only in the emailed link. `consumed_at` is the
    // single-use marker; `expires_at` enforces the configurable TTL.
    if magic_link {
        let _ = write!(
            out,
            "\n\
             CREATE TABLE magic_link_tokens (\n\
             \x20   id {pk},\n\
             \x20   user_id {big_int} NOT NULL REFERENCES {table}(id) ON DELETE CASCADE,\n\
             \x20   token_digest TEXT NOT NULL UNIQUE,\n\
             \x20   expires_at {ts} NOT NULL,\n\
             \x20   consumed_at {ts} NULL,\n\
             \x20   created_at {created_at}\n\
             );\n\
             \n\
             CREATE INDEX magic_link_tokens_user_id_idx ON magic_link_tokens (user_id);\n",
            pk = d.pk,
            big_int = d.big_int,
            ts = d.ts,
            created_at = d.ts_not_null_default_now,
        );
    }
    out
}

fn render_migration_down(snake_name: &str, table: &str, totp: bool, magic_link: bool) -> String {
    // Drop the dependent tables first so the FK constraints are satisfied.
    let sess_table = sessions_table_name(snake_name);
    let rem_table = remember_table_name(snake_name);
    // Magic-link tokens FK the user table, so drop them before it (issue #1328).
    let magic_drop = if magic_link {
        "DROP TABLE magic_link_tokens;\n"
    } else {
        ""
    };
    if totp {
        format!(
            "{magic_drop}DROP TABLE {rem_table};\nDROP TABLE {sess_table};\nDROP TABLE recovery_codes;\nDROP TABLE {table};\n"
        )
    } else {
        format!(
            "{magic_drop}DROP TABLE {rem_table};\nDROP TABLE {sess_table};\nDROP TABLE {table};\n"
        )
    }
}

fn render_model_file(pascal_name: &str, _snake_name: &str, table: &str, totp: bool) -> String {
    // TOTP columns mirror the migration/schema order (after password_digest).
    // TOTP columns mirror the migration/schema order (after password_digest).
    // `totp_secret_encrypted` holds the AES-GCM-encrypted secret (never plaintext),
    // and `totp_last_used_step` is the replay guard. All three are `#[default]`
    // so they are excluded from `NewUser` and fall back to their DB defaults
    // (disabled / NULL) on signup.
    let totp_fields = if totp {
        "    #[default]\n\
         \x20   pub totp_secret_encrypted: Option<String>,\n\
         \x20   #[default]\n\
         \x20   pub totp_enabled: bool,\n\
         \x20   #[default]\n\
         \x20   pub totp_last_used_step: Option<i64>,\n"
    } else {
        ""
    };
    format!(
        r"//! Generated by `autumn generate auth`.
//!
//! Edit freely — once generated, this is ordinary user code.
//! Security note: never store raw passwords, reset tokens, or TOTP secrets
//! here in the clear — only digests and encrypted blobs.

use crate::schema::{table};

#[autumn_web::model]
pub struct {pascal_name} {{
    pub id: i64,
    pub email: String,
    pub time_zone: Option<String>,
    pub password_digest: String,
{totp_fields}    #[default]
    pub failed_attempts: i32,
    #[default]
    pub locked_at: Option<chrono::NaiveDateTime>,
    pub reset_token_digest: Option<String>,
    pub reset_token_expires_at: Option<chrono::NaiveDateTime>,
    pub confirm_token_digest: Option<String>,
    pub confirm_token_expires_at: Option<chrono::NaiveDateTime>,
    #[default]
    pub email_confirmed_at: Option<chrono::NaiveDateTime>,
    // Pending email-change target (issue #1396). Nullable: set when a change is
    // requested, cleared when the new-address token is confirmed. The old
    // `email` stays valid for sign-in until confirmation swaps it.
    #[default]
    pub pending_email: Option<String>,
    #[default]
    pub export_requested_at: Option<chrono::NaiveDateTime>,
    #[default]
    pub delete_requested_at: Option<chrono::NaiveDateTime>,
    #[default]
    pub delete_scheduled_at: Option<chrono::NaiveDateTime>,
    #[default]
    pub created_at: chrono::NaiveDateTime,
}}
"
    )
}

/// Render `src/models/recovery_code.rs` (only emitted with `--totp`).
///
/// Recovery codes are single-use: only the bcrypt `code_digest` is stored, and
/// `used_at` is stamped when a code is consumed so it can never be replayed.
fn render_recovery_code_model_file(user_pascal: &str, user_table: &str) -> String {
    format!(
        r"//! Generated by `autumn generate auth --totp`.
//!
//! Single-use TOTP recovery codes for {user_pascal}. Edit freely.
//! Security note: only the bcrypt digest of each code is stored — never the
//! raw code. `used_at` marks a code as consumed so it cannot be reused.

use crate::schema::recovery_codes;

#[autumn_web::model]
pub struct RecoveryCode {{
    pub id: i64,
    // References {user_table}(id).
    pub user_id: i64,
    pub code_digest: String,
    // Kept in `NewRecoveryCode` so inserts set it explicitly to `None`.
    pub used_at: Option<chrono::NaiveDateTime>,
    #[default]
    pub created_at: chrono::NaiveDateTime,
}}
"
    )
}

/// Render `src/models/{snake}_session.rs` — the active-login-session row and
/// the revocation APIs on the user model (issue #819).
///
/// Only the SHA-256 digest of the opaque session id is stored, so a database
/// leak cannot be replayed as a session cookie. Revocation deletes the row;
/// the per-request gate in `routes/auth.rs` treats a missing row as a revoked
/// session and 401s immediately.
#[allow(clippy::too_many_lines)]
fn render_session_model_file(user_pascal: &str, user_snake: &str, user_table: &str) -> String {
    let sess_table = sessions_table_name(user_snake);
    format!(
        r#"//! Generated by `autumn generate auth`.
//!
//! Active login sessions for {user_pascal} — one row per logged-in device.
//! Edit freely — once generated, this is ordinary user code.
//!
//! Security notes:
//! - `token_digest` is the SHA-256 of the opaque server-side session id;
//!   the raw id is never stored, so a database leak cannot be replayed as
//!   a session cookie.
//! - Revocation deletes the row. The per-request gate in `routes/auth.rs`
//!   (`require_tracked_session`) treats a missing row as revoked and
//!   responds 401 immediately, even if the cookie is replayed.

use diesel::prelude::*;
use diesel_async::RunQueryDsl;

use crate::models::{user_snake}::{user_pascal};
use crate::schema::{sess_table};

#[autumn_web::model]
pub struct {user_pascal}Session {{
    pub id: i64,
    // References {user_table}(id).
    pub user_id: i64,
    pub token_digest: String,
    pub ip: String,
    pub user_agent: String,
    pub ua_family: String,
    pub ua_os: String,
    pub ua_device: String,
    #[default]
    pub label: Option<String>,
    #[default]
    pub last_seen_at: chrono::NaiveDateTime,
    #[default]
    pub created_at: chrono::NaiveDateTime,
}}

impl {user_pascal}Session {{
    /// Human-readable device line for the sessions page, preferring the
    /// user-set label over the parsed User-Agent.
    #[must_use]
    pub fn device_description(&self) -> String {{
        if let Some(label) = self.label.as_deref().filter(|l| !l.trim().is_empty()) {{
            return label.to_owned();
        }}
        match (self.ua_family.as_str(), self.ua_os.as_str()) {{
            ("" | "Unknown", "" | "Unknown") => "Unknown device".to_owned(),
            (family, "" | "Unknown") => family.to_owned(),
            ("" | "Unknown", os) => os.to_owned(),
            (family, os) => format!("{{family}} on {{os}}"),
        }}
    }}
}}

/// Active-session APIs available from any request handler that has loaded
/// the current user (issue #819).
impl {user_pascal} {{
    /// All active login sessions for this account, most recently seen first.
    pub async fn sessions(
        &self,
        conn: &mut impl diesel_async::AsyncConnection<Backend = ::autumn_web::RuntimeBackend>,
    ) -> autumn_web::AutumnResult<Vec<{user_pascal}Session>> {{
        {sess_table}::table
            .filter({sess_table}::user_id.eq(self.id))
            .order({sess_table}::last_seen_at.desc())
            .select({user_pascal}Session::as_select())
            .load(conn)
            .await
            .map_err(|e| {{
                autumn_web::AutumnError::internal_server_error_msg(format!(
                    "Failed to load sessions: {{e}}"
                ))
            }})
    }}

    /// Revoke a single session by row id. Scoped to this account — revoking
    /// another user's session id is a no-op. Returns `true` when a session
    /// was actually revoked.
    pub async fn revoke_session(
        &self,
        conn: &mut impl diesel_async::AsyncConnection<Backend = ::autumn_web::RuntimeBackend>,
        session_id: i64,
    ) -> autumn_web::AutumnResult<bool> {{
        let rows = diesel::delete(
            {sess_table}::table
                .filter({sess_table}::id.eq(session_id))
                .filter({sess_table}::user_id.eq(self.id)),
        )
        .execute(conn)
        .await
        .map_err(|e| {{
            autumn_web::AutumnError::internal_server_error_msg(format!(
                "Failed to revoke session: {{e}}"
            ))
        }})?;
        Ok(rows == 1)
    }}

    /// Revoke every session except the one identified by
    /// `current_token_digest` ("sign out everywhere else"). Returns the
    /// number of sessions revoked.
    pub async fn revoke_other_sessions(
        &self,
        conn: &mut impl diesel_async::AsyncConnection<Backend = ::autumn_web::RuntimeBackend>,
        current_token_digest: &str,
    ) -> autumn_web::AutumnResult<usize> {{
        diesel::delete(
            {sess_table}::table
                .filter({sess_table}::user_id.eq(self.id))
                .filter({sess_table}::token_digest.ne(current_token_digest)),
        )
        .execute(conn)
        .await
        .map_err(|e| {{
            autumn_web::AutumnError::internal_server_error_msg(format!(
                "Failed to revoke sessions: {{e}}"
            ))
        }})
    }}

    /// Revoke every session for this account, including the current one.
    /// Used on password change, where all existing sessions are suspect.
    pub async fn revoke_all_sessions(
        &self,
        conn: &mut impl diesel_async::AsyncConnection<Backend = ::autumn_web::RuntimeBackend>,
    ) -> autumn_web::AutumnResult<usize> {{
        diesel::delete({sess_table}::table.filter({sess_table}::user_id.eq(self.id)))
            .execute(conn)
            .await
            .map_err(|e| {{
                autumn_web::AutumnError::internal_server_error_msg(format!(
                    "Failed to revoke sessions: {{e}}"
                ))
            }})
    }}
}}
"#
    )
}

/// Render `src/models/{snake}_remember_token.rs` — the persistent remember-me
/// chain row and its CRUD, plus a bulk-revocation method on the user model
/// (issue #1397).
///
/// Only the SHA-256 hash of the current token is stored; the raw token lives
/// only in the cookie. `series` is the stable per-device lookup key and
/// `token_hash` rotates on every use so a replayed rotated-out cookie is
/// detected as theft (see `routes/auth.rs::remember_me`).
#[allow(clippy::too_many_lines)]
fn render_remember_model_file(user_pascal: &str, user_snake: &str, user_table: &str) -> String {
    let rem_table = remember_table_name(user_snake);
    format!(
        r#"//! Generated by `autumn generate auth`.
//!
//! Persistent "remember-me" login chains for {user_pascal} (issue #1397).
//! Edit freely — once generated, this is ordinary user code.
//!
//! Security notes:
//! - `token_hash` is the SHA-256 of the current rotating token; the raw token
//!   is never stored, so a database leak cannot be replayed as a cookie.
//! - `series` is stable across rotations for one device chain; `token_hash`
//!   rotates on every use. Replaying a rotated-out token for a known series is
//!   detected as theft and nukes the whole chain — see `routes/auth.rs`.

use diesel::prelude::*;
use diesel_async::RunQueryDsl;

use crate::models::{user_snake}::{user_pascal};
use crate::schema::{rem_table};

#[autumn_web::model]
pub struct {user_pascal}RememberToken {{
    pub id: i64,
    /// Stable, opaque per-device lookup key.
    pub series: String,
    // References {user_table}(id).
    pub user_id: i64,
    /// SHA-256 hash of the current rotating token (never the raw token).
    pub token_hash: String,
    /// SHA-256 hash of the token that was just rotated out, accepted during the
    /// grace window so benign concurrent requests do not false-fire theft
    /// detection (issue #1397).
    #[default]
    pub previous_token_hash: Option<String>,
    /// When the current token was minted (the last rotation); bounds how long
    /// `previous_token_hash` stays acceptable.
    #[default]
    pub rotated_at: Option<chrono::NaiveDateTime>,
    pub expires_at: chrono::NaiveDateTime,
    pub ip: String,
    pub user_agent: String,
    pub ua_family: String,
    pub ua_os: String,
    pub ua_device: String,
    #[default]
    pub label: Option<String>,
    #[default]
    pub last_used_at: Option<chrono::NaiveDateTime>,
    #[default]
    pub created_at: chrono::NaiveDateTime,
}}

impl {user_pascal}RememberToken {{
    /// Absolute expiry as a UTC datetime, for `autumn_web::auth::evaluate_remember`.
    #[must_use]
    pub fn expires_at_utc(&self) -> chrono::DateTime<chrono::Utc> {{
        self.expires_at.and_utc()
    }}

    /// Human-readable device line for the sessions page, preferring the
    /// user-set label over the parsed User-Agent (mirrors the active-session
    /// row's `device_description`).
    #[must_use]
    pub fn device_description(&self) -> String {{
        if let Some(label) = self.label.as_deref().filter(|l| !l.trim().is_empty()) {{
            return label.to_owned();
        }}
        match (self.ua_family.as_str(), self.ua_os.as_str()) {{
            ("" | "Unknown", "" | "Unknown") => "Unknown device".to_owned(),
            (family, "" | "Unknown") => family.to_owned(),
            ("" | "Unknown", os) => os.to_owned(),
            (family, os) => format!("{{family}} on {{os}}"),
        }}
    }}
}}

/// Persist a new remember chain for a successful "remember me" login.
pub async fn insert_remember_token(
    conn: &mut impl diesel_async::AsyncConnection<Backend = ::autumn_web::RuntimeBackend>,
    row: &New{user_pascal}RememberToken,
) -> autumn_web::AutumnResult<()> {{
    diesel::insert_into({rem_table}::table)
        .values(row)
        .execute(conn)
        .await
        .map_err(|e| {{
            autumn_web::AutumnError::internal_server_error_msg(format!(
                "Failed to persist remember token: {{e}}"
            ))
        }})?;
    Ok(())
}}

/// Look a chain up by its stable series id.
pub async fn find_remember_token(
    conn: &mut impl diesel_async::AsyncConnection<Backend = ::autumn_web::RuntimeBackend>,
    series: &str,
) -> autumn_web::AutumnResult<Option<{user_pascal}RememberToken>> {{
    {rem_table}::table
        .filter({rem_table}::series.eq(series))
        .select({user_pascal}RememberToken::as_select())
        .first(conn)
        .await
        .optional()
        .map_err(|e| {{
            autumn_web::AutumnError::internal_server_error_msg(format!(
                "Failed to load remember token: {{e}}"
            ))
        }})
}}

/// Atomically rotate a chain (compare-and-swap): move the current `token_hash`
/// into `previous_token_hash`, install `new_hash`, stamp `rotated_at`/
/// `last_used_at`, and extend the sliding expiry — but ONLY if the row still
/// carries `old_hash`. Returns the number of rows affected (0 when a sibling
/// request already rotated the chain, 1 on success), so the caller can detect a
/// lost race and re-evaluate rather than silently double-rotating (issue #1397).
pub async fn rotate_remember_token(
    conn: &mut impl diesel_async::AsyncConnection<Backend = ::autumn_web::RuntimeBackend>,
    series: &str,
    old_hash: &str,
    new_hash: &str,
    new_expiry: chrono::NaiveDateTime,
    now: chrono::NaiveDateTime,
) -> autumn_web::AutumnResult<usize> {{
    diesel::update(
        {rem_table}::table
            .filter({rem_table}::series.eq(series))
            .filter({rem_table}::token_hash.eq(old_hash)),
    )
    .set((
        {rem_table}::previous_token_hash.eq(Some(old_hash)),
        {rem_table}::token_hash.eq(new_hash),
        {rem_table}::rotated_at.eq(Some(now)),
        {rem_table}::expires_at.eq(new_expiry),
        {rem_table}::last_used_at.eq(Some(now)),
    ))
    .execute(conn)
    .await
    .map_err(|e| {{
        autumn_web::AutumnError::internal_server_error_msg(format!(
            "Failed to rotate remember token: {{e}}"
        ))
    }})
}}

/// Delete a single chain by series (theft / this-device logout revocation).
pub async fn delete_remember_series(
    conn: &mut impl diesel_async::AsyncConnection<Backend = ::autumn_web::RuntimeBackend>,
    series: &str,
) -> autumn_web::AutumnResult<usize> {{
    diesel::delete({rem_table}::table.filter({rem_table}::series.eq(series)))
        .execute(conn)
        .await
        .map_err(|e| {{
            autumn_web::AutumnError::internal_server_error_msg(format!(
                "Failed to delete remember token: {{e}}"
            ))
        }})
}}

impl {user_pascal} {{
    /// All persistent remember-me chains for this account, most recently used
    /// first, so they can be listed as their own entries on the device page and
    /// revoked individually (issue #1397.6).
    pub async fn remember_tokens(
        &self,
        conn: &mut impl diesel_async::AsyncConnection<Backend = ::autumn_web::RuntimeBackend>,
    ) -> autumn_web::AutumnResult<Vec<{user_pascal}RememberToken>> {{
        {rem_table}::table
            .filter({rem_table}::user_id.eq(self.id))
            .order({rem_table}::created_at.desc())
            .select({user_pascal}RememberToken::as_select())
            .load(conn)
            .await
            .map_err(|e| {{
                autumn_web::AutumnError::internal_server_error_msg(format!(
                    "Failed to load remember tokens: {{e}}"
                ))
            }})
    }}

    /// Revoke a single remember chain by `series`, scoped to this account so a
    /// user can never revoke another account's chain. Returns `true` when a
    /// chain was actually revoked (issue #1397.6).
    pub async fn revoke_remember_series(
        &self,
        conn: &mut impl diesel_async::AsyncConnection<Backend = ::autumn_web::RuntimeBackend>,
        series: &str,
    ) -> autumn_web::AutumnResult<bool> {{
        let rows = diesel::delete(
            {rem_table}::table
                .filter({rem_table}::series.eq(series))
                .filter({rem_table}::user_id.eq(self.id)),
        )
        .execute(conn)
        .await
        .map_err(|e| {{
            autumn_web::AutumnError::internal_server_error_msg(format!(
                "Failed to revoke remember chain: {{e}}"
            ))
        }})?;
        Ok(rows == 1)
    }}

    /// Revoke every remember chain for this account. Used on "sign out
    /// everywhere else" and on credential change, where every persistent login
    /// is suspect — a replayed remember cookie afterwards finds no row and is
    /// rejected. Returns the number of chains revoked.
    pub async fn revoke_all_remember_tokens(
        &self,
        conn: &mut impl diesel_async::AsyncConnection<Backend = ::autumn_web::RuntimeBackend>,
    ) -> autumn_web::AutumnResult<usize> {{
        diesel::delete({rem_table}::table.filter({rem_table}::user_id.eq(self.id)))
            .execute(conn)
            .await
            .map_err(|e| {{
                autumn_web::AutumnError::internal_server_error_msg(format!(
                    "Failed to revoke remember tokens: {{e}}"
                ))
            }})
    }}
}}
"#
    )
}

/// Field tokens for the `magic_link_tokens` table (issue #1328), shared by the
/// schema append and its destroy revert so they stay byte-identical. `id` and
/// `created_at` are added automatically by `append_schema_table`.
fn magic_link_token_fields() -> Vec<super::dsl::Field> {
    [
        "user_id:i64",
        "token_digest:String",
        "expires_at:NaiveDateTime",
        "consumed_at:Option<NaiveDateTime>",
    ]
    .iter()
    .map(|t| super::dsl::parse_field(t).expect("magic-link field tokens are always valid"))
    .collect()
}

/// Render `src/models/magic_link_token.rs` — the passwordless login-token row
/// (issue #1328).
///
/// Mirrors the reset-token invariants: only the SHA-256 digest of the raw
/// token is stored (`token_digest`), never the raw token. `consumed_at` is the
/// single-use marker (set on the first successful verify), and `expires_at`
/// enforces the configurable TTL. Unknown/expired/consumed tokens are all
/// rejected with the same generic failure — see `routes/auth.rs`.
fn render_magic_link_token_model_file(user_pascal: &str, user_table: &str) -> String {
    format!(
        r"//! Generated by `autumn generate auth --magic-link`.
//!
//! Passwordless magic-link login tokens for {user_pascal}. Edit freely.
//! Security note: only the SHA-256 digest of each raw token is stored — never
//! the raw token, which appears only in the emailed link. `consumed_at` marks a
//! token as used so it cannot be replayed; `expires_at` enforces the TTL.

use crate::schema::magic_link_tokens;

#[autumn_web::model]
pub struct MagicLinkToken {{
    pub id: i64,
    // References {user_table}(id).
    pub user_id: i64,
    pub token_digest: String,
    pub expires_at: chrono::NaiveDateTime,
    // Single-use marker: set to `now` on the first successful verify. A second
    // verify of the same token finds it non-NULL and is rejected.
    pub consumed_at: Option<chrono::NaiveDateTime>,
    #[default]
    pub created_at: chrono::NaiveDateTime,
}}
"
    )
}

/// Magic-link cleanup injected into a credential-change transaction (issues
/// #1328 hardening): when the account's password or email is changed, delete the
/// user's outstanding `magic_link_tokens` in the SAME transaction so a link
/// minted/intercepted before the change cannot sign the account in afterwards
/// (magic-link auth matches an unconsumed, unexpired token, keyed by user id and
/// independent of the changed credential). Emitted only under `--magic-link` —
/// the table exists only then — and empty otherwise. Assumes a `user_id` binding
/// (`let {snake}_id = {snake}.id;`) and a `conn` transaction handle are in scope,
/// matching the `change_password` / `confirm_email_change` transactions.
fn magic_link_credential_clear_txn_src(snake_name: &str) -> String {
    const TPL: &str = r"            // Invalidate any outstanding magic-link login tokens in the SAME
            // transaction: a link minted before this credential change must not
            // sign the account in afterwards (magic-link auth matches an
            // unconsumed, unexpired token, keyed by user id and independent of
            // the changed credential).
            diesel::delete(
                magic_link_tokens::table.filter(magic_link_tokens::user_id.eq(__SNAKE___id)),
            )
            .execute(conn)
            .await?;
";
    TPL.replace("__SNAKE__", snake_name)
}

#[allow(
    clippy::too_many_lines,
    reason = "Single auth-routes template — splitting fragments makes the template harder to read."
)]
fn render_routes_file(
    pascal_name: &str,
    snake_name: &str,
    table: &str,
    providers: &[String],
    totp: bool,
    magic_link: bool,
) -> String {
    let sess_table = sessions_table_name(snake_name);
    let rem_table = remember_table_name(snake_name);
    // Passwordless magic-link login (issue #1328). All output is gated on the
    // `--magic-link` flag so the flow composes with `--oauth`/`--totp`/`--passkeys`.
    let (magic_link_imports, magic_link_section, magic_link_login_link) = if magic_link {
        (
            "use crate::models::magic_link_token::{MagicLinkToken, NewMagicLinkToken};\n\
             use crate::schema::magic_link_tokens;\n"
                .to_owned(),
            magic_link_routes_section_src(pascal_name, snake_name, table, totp),
            "        p { a href=\"/login/magic\" { \"Email me a magic sign-in link\" } }\n"
                .to_owned(),
        )
    } else {
        (String::new(), String::new(), String::new())
    };
    // Magic-link token cleanup spliced into the `change_password` (#7),
    // `confirm_email_change` (#10) and `reset_password` (#11) credential-change
    // transactions. Gated on `--magic-link` so the `magic_link_tokens` reference
    // only appears when the table (and its import) exist. (For 2FA-enabled users
    // the reset commit is deferred to `login_verify`, which carries its own gated
    // cleanup — see `magic_link_reset_commit_clear_txn_src`.)
    let (
        magic_link_change_password_clear,
        magic_link_email_change_clear,
        magic_link_reset_password_clear,
    ) = if magic_link {
        (
            magic_link_credential_clear_txn_src(snake_name),
            magic_link_credential_clear_txn_src(snake_name),
            magic_link_credential_clear_txn_src(snake_name),
        )
    } else {
        (String::new(), String::new(), String::new())
    };
    let oauth_buttons = if providers.is_empty() {
        String::new()
    } else {
        let mut btn_html = String::with_capacity(256);
        btn_html.push_str("hr;\n        h3 { \"Or sign in with:\" }\n        div style=\"display: flex; gap: 0.5rem;\" {\n");
        for p in providers {
            let label = match p.as_str() {
                "github" => "GitHub",
                "google" => "Google",
                "microsoft" => "Microsoft",
                _ => p,
            };
            btn_html.push_str("            a href=\"/auth/");
            btn_html.push_str(p);
            btn_html.push_str("/redirect\" { button type=\"button\" { \"Sign in with ");
            btn_html.push_str(label);
            btn_html.push_str("\" } }\n");
        }
        btn_html.push_str("        }\n");
        btn_html
    };

    let (
        totp_imports,
        totp_login_branch,
        totp_reset_branch,
        totp_clear_pending,
        totp_confirm_branch,
        totp_section,
        totp_reauth_field,
        totp_reauth_check,
    ) = if totp {
        (
            totp_imports_src().to_owned(),
            totp_login_branch_src(snake_name),
            totp_reset_branch_src(snake_name),
            totp_clear_pending_src().to_owned(),
            totp_confirm_branch_src(snake_name),
            totp_routes_section_src(pascal_name, snake_name, table, magic_link),
            totp_reauth_field_src(),
            totp_reauth_check_src(snake_name, table),
        )
    } else {
        (
            String::new(),
            String::new(),
            String::new(),
            String::new(),
            String::new(),
            String::new(),
            String::new(),
            String::new(),
        )
    };

    format!(
        r##"//! Generated by `autumn generate auth`.
//!
//! Complete browser authentication flow. Edit freely — once generated,
//! this is ordinary user code.
//!
//! Security properties:
//! - Passwords are hashed with bcrypt via `autumn_web::auth`.
//! - Reset tokens are 32-byte random values; only the SHA-256 digest is stored.
//! - Duplicate signup and failed login return identical non-enumerating errors.
//! - Login and reset-password rotate the session ID to prevent fixation.
//! - Logout clears + rotates the session, invalidating the old session (the old
//!   cookie cannot be replayed) while carrying a one-shot "logged out" notice.
//! - Every login is tracked as a `{sess_table}` row (digest of the opaque
//!   session id + device attribution); revoking the row signs that device out
//!   immediately — see `require_tracked_session` and
//!   docs/guide/session-management.md.

use autumn_web::auth::{{
    RememberConfig, RememberDecision, RememberRecord, build_remember_clear_cookie,
    build_remember_cookie, evaluate_remember, generate_remember_credential, generate_token,
    hash_password, hash_remember_token, parse_remember_cookie_value, verify_password,
}};
use autumn_web::extract::Query;
use autumn_web::form::{{FieldOptions, password_input_with}};
use autumn_web::prelude::*;
use axum::extract::Path;
use axum::response::{{IntoResponse, Response}};
use diesel::prelude::*;
use diesel_async::AsyncConnection as _;
use diesel_async::RunQueryDsl;
use serde::Deserialize;

use crate::models::{snake_name}::{{New{pascal_name}, {pascal_name}}};
use crate::models::{snake_name}_session::{{New{pascal_name}Session, {pascal_name}Session}};
use crate::models::{snake_name}_remember_token::{{
    New{pascal_name}RememberToken, {pascal_name}RememberToken, delete_remember_series,
    find_remember_token, insert_remember_token, rotate_remember_token,
}};
use crate::schema::{sess_table};
use crate::schema::{rem_table};
use crate::schema::{table};
{totp_imports}{magic_link_imports}

// ── Layout helpers ────────────────────────────────────────────────────────────

fn redirect_to(url: &str) -> Response {{
    axum::response::Redirect::to(url).into_response()
}}

/// A password field from `autumn_web::form`. The page shows the error
/// itself, so the changeset is empty.
fn password_field(field: &str, label: &str, options: FieldOptions<'_>) -> Markup {{
    password_input_with(&Changeset::new(()), field, label, &options)
}}

// ── Persistent "remember-me" login (issue #1397) ─────────────────────────────
//
// A remember credential is a `(series, token)` pair (the Barry Jaspan rotating
// scheme). On login-with-remember, `issue_remember_cookie` persists a
// `{rem_table}` row (storing only the SHA-256 hash of the token) and sets the
// cookie. On any request WITHOUT a session but WITH a remember cookie,
// `remember_me` rotates the token, establishes a session, and re-sets the
// cookie — or, on a replayed rotated-out token, trips theft detection and nukes
// the chain. See docs/guide/session-management.md.
//
// The middleware and its startup hook are AUTO-WIRED into `src/main.rs` by the
// generator: `.layer(axum::middleware::from_fn(routes::auth::remember_me))`
// plus `.on_startup(routes::auth::remember_me_startup)`. `remember_me` runs as a
// plain Tower layer with no `AppState`, so the startup hook stashes the shared
// pool AND the resolved `[auth.remember]` config in a process-wide handle it
// reads from.

/// The process-wide state the remember middleware needs: the pool it checks
/// connections out of plus the resolved `[auth.remember]` config, so
/// `cookie_name`/`duration_secs`/`enabled` overrides in `autumn.toml` (or
/// `AUTUMN_AUTH__REMEMBER__*`) are honoured instead of the compiled defaults
/// (issue #1397.2).
struct RememberMiddlewareState {{
    pool: diesel_async::pooled_connection::deadpool::Pool<::autumn_web::RuntimeConnection>,
    config: RememberConfig,
    // The configured `[auth].session_key` (default `"user_id"`), captured at
    // startup so a remember-me restore writes the SAME identity key that
    // `#[secured]` / `#[authorize]` authenticate against — the middleware has
    // no `AppState` to call `state.auth_session_key()` on at request time.
    auth_session_key: String,
}}

static REMEMBER_STATE: std::sync::OnceLock<RememberMiddlewareState> = std::sync::OnceLock::new();

/// Install the shared pool, resolved config, and configured auth session key the
/// remember middleware uses. Idempotent — a second call is ignored. Called by
/// `remember_me_startup`.
pub fn init_remember_pool(
    pool: diesel_async::pooled_connection::deadpool::Pool<::autumn_web::RuntimeConnection>,
    config: RememberConfig,
    auth_session_key: String,
) {{
    let _ = REMEMBER_STATE.set(RememberMiddlewareState {{
        pool,
        config,
        auth_session_key,
    }});
}}

/// Startup hook (auto-wired into `main` via `.on_startup(...)`) that hands the
/// remember middleware the shared pool, the resolved `[auth.remember]` config,
/// and the configured `[auth].session_key`.
pub async fn remember_me_startup(state: AppState) -> AutumnResult<()> {{
    if let Some(pool) = state.pool() {{
        init_remember_pool(
            pool.clone(),
            state.config().auth.remember.clone(),
            state.auth_session_key().to_string(),
        );
        // Re-point the tracked row after ANY session-id rotation (impersonation,
        // idle rotation, app code), so the next request does not 401.
        let pool = pool.clone();
        state
            .session_rotation_hooks()
            .register(move |rotation| {{
                let pool = pool.clone();
                async move {{
                    rebind_tracked_session_on_rotation(&pool, &rotation)
                        .await
                        .map_err(|e| e.to_string().into())
                }}
            }});
    }}
    Ok(())
}}

/// Move the tracked row from the old session id's digest to the new one.
///
/// No row matches when the flow already rebound it, so a repeat is harmless.
async fn rebind_tracked_session_on_rotation(
    pool: &diesel_async::pooled_connection::deadpool::Pool<::autumn_web::RuntimeConnection>,
    rotation: &::autumn_web::session::SessionRotation,
) -> AutumnResult<()> {{
    let mut db = pool.get().await.map_err(|e| {{
        AutumnError::internal_server_error_msg(format!("Failed to rebind tracked session: {{e}}"))
    }})?;
    // The row sits under any earlier id of this request: a flow may have moved
    // it by hand after a first rotation.
    let earlier: Vec<String> = rotation.earlier_ids.iter().map(|id| sha256_hex(id)).collect();
    diesel::update({sess_table}::table.filter({sess_table}::token_digest.eq_any(earlier)))
    .set({sess_table}::token_digest.eq(sha256_hex(&rotation.new_id)))
    .execute(&mut *db)
    .await
    .map_err(|e| {{
        AutumnError::internal_server_error_msg(format!("Failed to rebind tracked session: {{e}}"))
    }})?;
    Ok(())
}}

/// The sliding expiry `duration_secs` in the future, as a naive UTC timestamp
/// (the column type), guarding the `u64 → i64` cast and saturating (rather than
/// panicking) on an absurd configured duration.
fn remember_expiry(config: &RememberConfig, now: chrono::DateTime<chrono::Utc>) -> chrono::NaiveDateTime {{
    let secs = i64::try_from(config.duration_secs).unwrap_or(2_592_000);
    now.checked_add_signed(chrono::Duration::seconds(secs))
        .unwrap_or(chrono::DateTime::<chrono::Utc>::MAX_UTC)
        .naive_utc()
}}

/// Whether to set the `Secure` cookie attribute — mirrors the session cookie by
/// keying off the forwarded scheme (HTTPS in production behind a TLS proxy).
fn remember_secure(headers: &axum::http::HeaderMap) -> bool {{
    headers
        .get("x-forwarded-proto")
        .and_then(|v| v.to_str().ok())
        .is_some_and(|proto| proto.eq_ignore_ascii_case("https"))
}}

/// Read a single cookie value by name out of the request `Cookie` header.
fn read_cookie(headers: &axum::http::HeaderMap, name: &str) -> Option<String> {{
    let cookies = headers.get(axum::http::header::COOKIE)?.to_str().ok()?;
    for pair in cookies.split(';') {{
        if let Some((k, v)) = pair.trim().split_once('=')
            && k.trim() == name
        {{
            return Some(v.trim().to_owned());
        }}
    }}
    None
}}

/// Append a `Set-Cookie` header (never replaces an existing one, so the rotated
/// session cookie and the rotated remember cookie coexist on one response).
fn append_set_cookie(response: &mut Response, value: &str) {{
    if let Ok(header_value) = axum::http::HeaderValue::from_str(value) {{
        response
            .headers_mut()
            .append(axum::http::header::SET_COOKIE, header_value);
    }}
}}

/// Mint and persist a remember chain for a just-authenticated {snake_name},
/// returning the `Set-Cookie` header the login handler attaches. Only the hash
/// of the rotating token is stored.
pub async fn issue_remember_cookie(
    db: &mut Db,
    config: &RememberConfig,
    {snake_name}_id: i64,
    ip: std::net::IpAddr,
    headers: &axum::http::HeaderMap,
) -> AutumnResult<String> {{
    let cred = generate_remember_credential();
    let user_agent = headers
        .get(axum::http::header::USER_AGENT)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .chars()
        .take(512)
        .collect::<String>();
    let parsed = autumn_web::user_agent::parse_user_agent(&user_agent);
    let row = New{pascal_name}RememberToken {{
        series: cred.series.clone(),
        user_id: {snake_name}_id,
        token_hash: hash_remember_token(&cred.token),
        expires_at: remember_expiry(config, chrono::Utc::now()),
        ip: ip.to_string(),
        user_agent,
        ua_family: parsed.family,
        ua_os: parsed.os,
        ua_device: parsed.device_class.to_string(),
    }};
    insert_remember_token(&mut **db, &row).await?;
    Ok(build_remember_cookie(
        config,
        &cred.series,
        &cred.token,
        remember_secure(headers),
    ))
}}

/// Revoke the remember chain named by the request's remember cookie (used by
/// logout). Does nothing when the cookie is absent or malformed. Returns the
/// delete error on failure: the remember cookie is a long-lived credential,
/// so the caller must not report logout as successful when revocation fails.
async fn revoke_remember_from_cookie(
    db: &mut Db,
    config: &RememberConfig,
    headers: &axum::http::HeaderMap,
) -> autumn_web::AutumnResult<()> {{
    if let Some(value) = read_cookie(headers, &config.cookie_name)
        && let Some((series, _token)) = parse_remember_cookie_value(&value)
    {{
        delete_remember_series(&mut **db, &series).await?;
    }}
    Ok(())
}}

/// Project a stored row into the pure [`RememberRecord`] the decision function
/// evaluates.
fn to_remember_record(r: &{pascal_name}RememberToken) -> RememberRecord {{
    RememberRecord {{
        series: r.series.clone(),
        token_hash: r.token_hash.clone(),
        previous_token_hash: r.previous_token_hash.clone(),
        rotated_at: r.rotated_at.map(|t| t.and_utc()),
        expires_at: r.expires_at_utc(),
    }}
}}

/// Establish a real session for the chain's owner — the same shape the login
/// handler writes, so `require_tracked_session` accepts it — and track it as an
/// active session so it shows in the device list and can be revoked (issue #819
/// + #1397).
async fn establish_remember_login(
    session: &Session,
    pool: &diesel_async::pooled_connection::deadpool::Pool<::autumn_web::RuntimeConnection>,
    auth_session_key: &str,
    {snake_name}_id: i64,
    ip: std::net::IpAddr,
    headers: &axum::http::HeaderMap,
) {{
    session.rotate_id().await;
    // `rotate_id()` PRESERVES existing session data, so ANY stale step-up /
    // reauth elevation marker from a prior authenticated state in this browser
    // could survive into the restored session. Actively CLEAR them ALL before
    // writing identity keys — a remember-cookie restore must never inherit a
    // prior session's "sudo mode", nor resume a mid-step-up elevated state.
    // Two markers grant/advance elevation and must be dropped:
    //   * `last_strong_auth_at` (STEP_UP_SESSION_KEY) — the "recently did strong
    //     auth" claim that `#[step_up]` routes check.
    //   * `reauth_pw_ok` — the reauth flow's "password already verified, awaiting
    //     TOTP code" marker (valid ~10 min). Left behind, a restored session
    //     could POST /reauth with only a TOTP/recovery code and mint a fresh
    //     `last_strong_auth_at` WITHOUT re-entering the password, defeating this
    //     downgrade. `rotate_id()` preserves it too, so clear it here as well.
    // (issue #833/#1397).
    session.remove(autumn_web::step_up::STEP_UP_SESSION_KEY).await;
    session.remove("reauth_pw_ok").await;
    // A remembered request must be fully authenticated for protected routes:
    // write the SAME identity keys login writes. `{snake_name}_id` powers the
    // identity extractors / tracked-session lookup, and the configured
    // `auth_session_key` is the key `#[secured]` / `#[authorize]` check — without
    // it a remember-cookie restore would rotate the token but still 401.
    session.insert("{snake_name}_id", {snake_name}_id.to_string()).await;
    session.insert(auth_session_key, {snake_name}_id.to_string()).await;
    // Intentionally do NOT stamp `set_last_strong_auth_at` here: a long-lived
    // remember cookie is *not* strong authentication. Restoring a session from
    // it must not satisfy step-up "sudo mode" — otherwise a stolen/unattended
    // persistent cookie would silently pass `#[step_up]` routes (e.g. account
    // deletion) with no password reauth. Because `rotate_id()` preserves data we
    // additionally CLEAR any pre-existing claim above (defense against a prior
    // fresh step-up surviving the restore), forcing those routes to redirect to
    // `/reauth` until the user re-enters their password (issue #833).
    if let Ok(mut db) = pool.get().await {{
        let session_row = build_session_row(session, {snake_name}_id, ip, headers).await;
        let _ = diesel::insert_into({sess_table}::table)
            .values(&session_row)
            .execute(&mut *db)
            .await;
    }}
}}

/// Global middleware: upgrade a request that carries a valid remember cookie but
/// no session into an authenticated one (rotating the token), or trip theft
/// detection on a replayed rotated-out cookie. Auto-wired into `src/main.rs` by
/// the generator (see the module header above).
pub async fn remember_me(
    session: Session,
    request: axum::extract::Request,
    next: axum::middleware::Next,
) -> Response {{
    // The resolved config + pool are stashed at startup; without them the
    // middleware is inert.
    let Some(mw_state) = REMEMBER_STATE.get() else {{
        return next.run(request).await;
    }};
    let config = &mw_state.config;

    // Already authenticated or remember disabled: the existing session wins.
    if !config.enabled || session.get("{snake_name}_id").await.is_some() {{
        return next.run(request).await;
    }}

    let Some(cookie_value) = read_cookie(request.headers(), &config.cookie_name) else {{
        return next.run(request).await;
    }};
    // A malformed cookie is ignored (proceed unauthenticated) rather than 400.
    let Some((series, token)) = parse_remember_cookie_value(&cookie_value) else {{
        return next.run(request).await;
    }};

    let Ok(mut conn) = mw_state.pool.get().await else {{
        return next.run(request).await;
    }};

    let record = match find_remember_token(&mut *conn, &series).await {{
        Ok(record) => record,
        // A transient DB error must not authenticate — proceed unauthenticated.
        // Release the checked-out connection first so a downstream `Db` route
        // can't self-starve a small/exhausted pool while `next.run` awaits.
        Err(_) => {{
            drop(conn);
            return next.run(request).await;
        }}
    }};

    let now = chrono::Utc::now();
    let secure = remember_secure(request.headers());
    let grace = autumn_web::auth::default_rotation_grace();
    let ip = request
        .extensions()
        .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
        .map(|c| c.0.ip())
        .unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED));
    let evaluated = record.as_ref().map(to_remember_record);

    match evaluate_remember(&token, evaluated.as_ref(), now, grace) {{
        RememberDecision::Rotate => {{
            let row = record.expect("Rotate is only returned for a present record");

            // Atomic compare-and-swap rotation: only the request that still sees
            // the current token wins. Extend the sliding expiry at the same time,
            // BEFORE establishing the session, so the old cookie value can never
            // be replayed.
            let new_token = generate_token();
            let new_hash = hash_remember_token(&new_token);
            let new_expiry = remember_expiry(config, now);
            let affected = match rotate_remember_token(
                &mut *conn,
                &series,
                &row.token_hash,
                &new_hash,
                new_expiry,
                now.naive_utc(),
            )
            .await
            {{
                Ok(n) => n,
                // A transient DB error must not authenticate. Release the
                // connection before yielding so a downstream `Db` route can't
                // self-starve a small/exhausted pool while `next.run` awaits.
                Err(_) => {{
                    drop(conn);
                    return next.run(request).await;
                }}
            }};

            if affected == 1 {{
                drop(conn);
                establish_remember_login(&session, &mw_state.pool, &mw_state.auth_session_key, row.user_id, ip, request.headers())
                    .await;
                let mut response = next.run(request).await;
                append_set_cookie(
                    &mut response,
                    &build_remember_cookie(config, &series, &new_token, secure),
                );
                response
            }} else {{
                // Lost the race: a sibling request already rotated the chain.
                // Re-select and re-evaluate the presented token against the new
                // state before deciding.
                let record2 = find_remember_token(&mut *conn, &series).await.ok().flatten();
                let evaluated2 = record2.as_ref().map(to_remember_record);
                match evaluate_remember(&token, evaluated2.as_ref(), now, grace) {{
                    RememberDecision::Accept | RememberDecision::Rotate => {{
                        // Within grace (or somehow still current): authenticate
                        // WITHOUT rotating again or re-cookieing.
                        drop(conn);
                        establish_remember_login(
                            &session,
                            &mw_state.pool,
                            &mw_state.auth_session_key,
                            row.user_id,
                            ip,
                            request.headers(),
                        )
                        .await;
                        next.run(request).await
                    }}
                    RememberDecision::Theft => {{
                        let _ = delete_remember_series(&mut *conn, &series).await;
                        drop(conn);
                        let mut response = next.run(request).await;
                        append_set_cookie(&mut response, &build_remember_clear_cookie(config));
                        response
                    }}
                    RememberDecision::Reject => {{
                        drop(conn);
                        let mut response = next.run(request).await;
                        append_set_cookie(&mut response, &build_remember_clear_cookie(config));
                        response
                    }}
                }}
            }}
        }}
        RememberDecision::Accept => {{
            // A benign concurrent request presenting the just-rotated-out token
            // within the grace window: authenticate without rotating or setting a
            // new cookie.
            let row = record.expect("Accept is only returned for a present record");
            drop(conn);
            establish_remember_login(&session, &mw_state.pool, &mw_state.auth_session_key, row.user_id, ip, request.headers())
                .await;
            next.run(request).await
        }}
        RememberDecision::Theft => {{
            // Replayed, rotated-out token for a known series → an attacker holds a
            // stale cookie. Nuke the whole chain and stay unauthenticated.
            let _ = delete_remember_series(&mut *conn, &series).await;
            drop(conn);
            let mut response = next.run(request).await;
            append_set_cookie(&mut response, &build_remember_clear_cookie(config));
            response
        }}
        RememberDecision::Reject => {{
            drop(conn);
            let mut response = next.run(request).await;
            append_set_cookie(&mut response, &build_remember_clear_cookie(config));
            response
        }}
    }}
}}

// ── Active session tracking (issue #819) ─────────────────────────────────────
//
// Every login persists a `{sess_table}` row keyed by the SHA-256 digest of the
// opaque session id. Authenticated handlers call `require_tracked_session`,
// which (1) 401s — and destroys the cookie session — when the row has been
// revoked, even if the cookie is replayed, and (2) updates `last_seen_at` at
// most once per `[auth.sessions].last_seen_update_secs` to bound write
// amplification. See docs/guide/session-management.md.

/// SHA-256 digest of the current opaque session id. Only the digest is ever
/// stored server-side, so a database leak cannot be replayed as a cookie.
pub async fn session_token_digest(session: &Session) -> String {{
    sha256_hex(&session.id().await)
}}

/// Build the tracked-session row for the current session id and device.
///
/// To plug in a custom User-Agent parser, replace the
/// `autumn_web::user_agent::parse_user_agent` call below — this is the only
/// parse site. See docs/guide/session-management.md.
pub async fn build_session_row(
    session: &Session,
    {snake_name}_id: i64,
    ip: std::net::IpAddr,
    headers: &axum::http::HeaderMap,
) -> New{pascal_name}Session {{
    let user_agent = headers
        .get(axum::http::header::USER_AGENT)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .chars()
        .take(512)
        .collect::<String>();
    let parsed = autumn_web::user_agent::parse_user_agent(&user_agent);
    New{pascal_name}Session {{
        user_id: {snake_name}_id,
        token_digest: session_token_digest(session).await,
        ip: ip.to_string(),
        user_agent,
        ua_family: parsed.family,
        ua_os: parsed.os,
        ua_device: parsed.device_class.to_string(),
    }}
}}

/// Persist a `{sess_table}` row for a successful login on this device.
pub async fn record_login_session(
    db: &mut Db,
    session: &Session,
    {snake_name}_id: i64,
    ip: std::net::IpAddr,
    headers: &axum::http::HeaderMap,
) -> AutumnResult<()> {{
    let row = build_session_row(session, {snake_name}_id, ip, headers).await;
    diesel::insert_into({sess_table}::table)
        .values(&row)
        .execute(&mut **db)
        .await
        .map_err(|e| {{
            AutumnError::internal_server_error_msg(format!(
                "Failed to record login session: {{e}}"
            ))
        }})?;
    Ok(())
}}

/// Re-point the tracked session row at the current (rotated) session id.
///
/// `session.rotate_id()` changes the opaque id, and with it the digest the
/// row is keyed by. Any flow that rotates while *staying logged in* (e.g.
/// step-up reauth) must call this with the digest captured before the
/// rotation, or the very next request would look up a missing row, be
/// treated as revoked, and 401.
pub async fn rebind_tracked_session(
    db: &mut Db,
    session: &Session,
    old_token_digest: &str,
) -> AutumnResult<()> {{
    let new_digest = session_token_digest(session).await;
    diesel::update(
        {sess_table}::table.filter({sess_table}::token_digest.eq(old_token_digest)),
    )
    .set({sess_table}::token_digest.eq(&new_digest))
    .execute(&mut **db)
    .await
    .map_err(|e| {{
        AutumnError::internal_server_error_msg(format!(
            "Failed to rebind tracked session: {{e}}"
        ))
    }})?;
    Ok(())
}}

/// Delete the tracked row for the *current* session id, if any.
///
/// Login flows call this before `session.rotate_id()`: the rotation
/// destroys the old server-side session, so a row keyed to its digest
/// could never authenticate again and would linger as a phantom device on
/// the previous account's sessions page. Logout uses it too.
pub async fn untrack_current_session(db: &mut Db, session: &Session) -> AutumnResult<()> {{
    let token_digest = session_token_digest(session).await;
    diesel::delete(
        {sess_table}::table.filter({sess_table}::token_digest.eq(&token_digest)),
    )
    .execute(&mut **db)
    .await
    .map_err(|e| {{
        AutumnError::internal_server_error_msg(format!(
            "Failed to clean up tracked session: {{e}}"
        ))
    }})?;
    Ok(())
}}

/// Validate the tracked session row for the authenticated user and return
/// the current {pascal_name}.
///
/// The `{sess_table}` row is the source of truth: deleting it signs the
/// device out *immediately* — the next request 401s and the cookie session
/// is destroyed, so a replayed cookie cannot resurrect it. `last_seen_at`
/// is refreshed at most once per `[auth.sessions].last_seen_update_secs`
/// per session, bounding write amplification.
///
/// Call this at the top of every handler that requires authentication.
pub async fn require_tracked_session(
    session: &Session,
    db: &mut Db,
    state: &AppState,
) -> AutumnResult<{pascal_name}> {{
    let {snake_name}_id: i64 = session
        .get("{snake_name}_id")
        .await
        .and_then(|s| s.parse().ok())
        .ok_or_else(|| AutumnError::unauthorized_msg("Not authenticated."))?;

    // While an operator impersonates, `{snake_name}_id` is the target but the row
    // still belongs to the operator who signed in. Match the row by its owner.
    let row_owner_id: i64 = ::autumn_web::auth::impersonation::audit_actor_id(
        session,
        &{snake_name}_id.to_string(),
    )
    .await
    .parse()
    .unwrap_or({snake_name}_id);

    let token_digest = session_token_digest(session).await;
    let tracked: Option<{pascal_name}Session> = {sess_table}::table
        .filter({sess_table}::token_digest.eq(&token_digest))
        .filter({sess_table}::user_id.eq(row_owner_id))
        .select({pascal_name}Session::as_select())
        .first(&mut **db)
        .await
        .optional()
        .map_err(|e| {{
            AutumnError::internal_server_error_msg(format!("Failed to load session: {{e}}"))
        }})?;

    let Some(tracked) = tracked else {{
        // Revoked (or never recorded): destroy the cookie session so a
        // replayed cookie cannot resurrect it, then reject.
        session.destroy().await;
        return Err(AutumnError::unauthorized_msg("Session revoked."));
    }};

    // Bounded write amplification: skip the UPDATE inside the window.
    // `config_arc` shares the resolved config behind an `Arc`; `config()`
    // would deep-clone every section to read one field on a request path.
    let config = state.config_arc();
    let sessions_cfg = &config.auth.sessions;
    let now = chrono::Utc::now().naive_utc();
    let window =
        chrono::Duration::seconds(i64::try_from(sessions_cfg.last_seen_update_secs).unwrap_or(60));
    if now.signed_duration_since(tracked.last_seen_at) >= window {{
        let _ = diesel::update({sess_table}::table.find(tracked.id))
            .set({sess_table}::last_seen_at.eq(now))
            .execute(&mut **db)
            .await;
    }}

    {table}::table
        .find({snake_name}_id)
        .select({pascal_name}::as_select())
        .first(&mut **db)
        .await
        .map_err(|_| AutumnError::unauthorized_msg("Account not found."))
}}

/// Render the device list. Shared by the full page and the htmx partial.
///
/// Persistent "remember-me" chains (issue #1397.6) are surfaced as their own
/// entries alongside active sessions, each with its own Revoke control, so a
/// dormant chain (browser closed, no active session) is still listed and
/// revocable — otherwise a "revoked" device could silently re-authenticate via
/// its surviving remember cookie.
fn sessions_list_fragment(
    sessions: &[{pascal_name}Session],
    remember_chains: &[{pascal_name}RememberToken],
    current_digest: &str,
    csrf: Option<&CsrfToken>,
    csrf_field: Option<&CsrfFormField>,
) -> Markup {{
    let csrf_name = csrf_field.map_or("_csrf", |f| f.0.as_str());
    html! {{
        div id="session-list" {{
            @if sessions.is_empty() && remember_chains.is_empty() {{
                p {{ "No active sessions." }}
            }}
            ul style="list-style:none;padding:0;" {{
                @for s in sessions {{
                    @let current = s.token_digest == current_digest;
                    li style="border:1px solid #ccc;padding:0.75rem;margin-bottom:0.5rem;" {{
                        p {{
                            strong {{ (s.device_description()) }}
                            @if current {{ " — this device" }}
                        }}
                        p {{
                            "Signed in " (s.created_at.format("%Y-%m-%d %H:%M UTC").to_string())
                            " from " (s.ip)
                            " · last seen " (s.last_seen_at.format("%Y-%m-%d %H:%M UTC").to_string())
                        }}
                        @if !current {{
                            // Real form so revocation works without JavaScript;
                            // htmx intercepts the submit for an in-place swap.
                            form method="post" action={{ "/account/sessions/" (s.id) "/revoke" }}
                                hx-post={{ "/account/sessions/" (s.id) "/revoke" }}
                                hx-target="#session-list" hx-swap="outerHTML"
                                style="display:inline" {{
                                @if let Some(csrf) = csrf {{
                                    input type="hidden" name=(csrf_name) value=(csrf.token());
                                }}
                                button type="submit" {{ "Revoke" }}
                            }}
                        }}
                        form action={{ "/account/sessions/" (s.id) "/label" }} method="post"
                            style="margin-top:0.25rem;" {{
                            @if let Some(csrf) = csrf {{
                                input type="hidden" name=(csrf_name) value=(csrf.token());
                            }}
                            label for={{ "device-label-" (s.id) }} {{ "Device label" }}
                            input type="text" id={{ "device-label-" (s.id) }} name="label"
                                value=[s.label.as_deref()];
                            button type="submit" {{ "Save label" }}
                        }}
                    }}
                }}
                // Persistent remember-me chains as their own revocable entries
                // (issue #1397.6). A chain can outlive any active session, so it
                // is listed even when its device has no live session row.
                @for r in remember_chains {{
                    li style="border:1px solid #ccc;padding:0.75rem;margin-bottom:0.5rem;" {{
                        p {{
                            strong {{ (r.device_description()) }}
                            " — Persistent login (Remember me)"
                        }}
                        p {{
                            "Created " (r.created_at.format("%Y-%m-%d %H:%M UTC").to_string())
                            " from " (r.ip)
                            @if let Some(last) = r.last_used_at {{
                                " · last used " (last.format("%Y-%m-%d %H:%M UTC").to_string())
                            }}
                        }}
                        // Revoke this persistent chain by its stable series id,
                        // scoped to the current account.
                        form method="post" action={{ "/account/remember/" (r.series) "/revoke" }}
                            hx-post={{ "/account/remember/" (r.series) "/revoke" }}
                            hx-target="#session-list" hx-swap="outerHTML"
                            style="display:inline" {{
                            @if let Some(csrf) = csrf {{
                                input type="hidden" name=(csrf_name) value=(csrf.token());
                            }}
                            button type="submit" {{ "Revoke" }}
                        }}
                    }}
                }}
            }}
            // Real form so bulk revocation works without JavaScript; htmx
            // intercepts the submit for an in-place swap.
            form method="post" action="/account/sessions/revoke-others"
                hx-post="/account/sessions/revoke-others"
                hx-target="#session-list" hx-swap="outerHTML" {{
                @if let Some(csrf) = csrf {{
                    input type="hidden" name=(csrf_name) value=(csrf.token());
                }}
                button type="submit" {{ "Sign out everywhere else" }}
            }}
        }}
    }}
}}

/// Re-render after a mutation: htmx requests get the refreshed partial,
/// plain form posts get a redirect back to the page.
async fn sessions_after_mutation(
    session: &Session,
    db: &mut Db,
    state: &AppState,
    hx: HxRequest,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Response> {{
    if !hx.is_htmx {{
        return Ok(redirect_to("/account/sessions"));
    }}
    let {snake_name} = require_tracked_session(session, db, state).await?;
    let current_digest = session_token_digest(session).await;
    let sessions = {snake_name}.sessions(&mut **db).await?;
    let remember_chains = {snake_name}.remember_tokens(&mut **db).await?;
    Ok(sessions_list_fragment(
        &sessions,
        &remember_chains,
        &current_digest,
        csrf.as_ref(),
        csrf_field.as_ref(),
    )
    .into_response())
}}

/// `GET /account/sessions` — list active sessions with revocation controls.
/// Requires authentication.
#[secured]
#[get("/account/sessions")]
pub async fn sessions_page(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    hx: HxRequest,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Response> {{
    let {snake_name} = require_tracked_session(&session, &mut db, &state).await?;
    let current_digest = session_token_digest(&session).await;
    let sessions = {snake_name}.sessions(&mut *db).await?;
    let remember_chains = {snake_name}.remember_tokens(&mut *db).await?;
    let fragment = sessions_list_fragment(
        &sessions,
        &remember_chains,
        &current_digest,
        csrf.as_ref(),
        csrf_field.as_ref(),
    );
    if hx.is_htmx {{
        return Ok(fragment.into_response());
    }}
    Ok(crate::layout("Active Sessions", "/account/sessions", html! {{}}, html! {{
        @if let Some(ref csrf) = csrf {{ meta name="csrf-token" content=(csrf.token()); }}
        script src=(HTMX_JS_PATH) {{}}
        script src=(HTMX_CSRF_JS_PATH) {{}}
        h1 {{ "Active Sessions" }}
        p {{
            "These are the devices currently signed in to your account, plus any \
             persistent \"remember me\" logins. Revoke anything you don't \
             recognise — that device is signed out immediately and can no longer \
             auto-login."
        }}
        (fragment)
        p {{ a href="/account" {{ "← Back to account" }} }}
    }}).into_response())
}}

/// `POST /account/sessions/{{id}}/revoke` — sign a single device out.
/// The revoked device's next request 401s. Requires authentication.
#[secured]
#[post("/account/sessions/{{id}}/revoke")]
pub async fn sessions_revoke(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    hx: HxRequest,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
    Path(id): Path<i64>,
) -> AutumnResult<Response> {{
    let {snake_name} = require_tracked_session(&session, &mut db, &state).await?;
    {snake_name}.revoke_session(&mut *db, id).await?;
    sessions_after_mutation(&session, &mut db, &state, hx, csrf, csrf_field).await
}}

/// `POST /account/remember/{{series}}/revoke` — revoke a single persistent
/// remember-me chain (issue #1397.6). Scoped to the current account, so a
/// dormant chain listed on the device page can be signed out even when its
/// device has no active session. Requires authentication.
#[secured]
#[post("/account/remember/{{series}}/revoke")]
pub async fn sessions_revoke_remember(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    hx: HxRequest,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
    Path(series): Path<String>,
) -> AutumnResult<Response> {{
    let {snake_name} = require_tracked_session(&session, &mut db, &state).await?;
    {snake_name}.revoke_remember_series(&mut *db, &series).await?;
    sessions_after_mutation(&session, &mut db, &state, hx, csrf, csrf_field).await
}}

/// `POST /account/sessions/revoke-others` — "Sign out everywhere else":
/// revoke every session except the current one. Requires authentication.
#[secured]
#[post("/account/sessions/revoke-others")]
pub async fn sessions_revoke_others(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    hx: HxRequest,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Response> {{
    let {snake_name} = require_tracked_session(&session, &mut db, &state).await?;
    let current_digest = session_token_digest(&session).await;
    {snake_name}
        .revoke_other_sessions(&mut *db, &current_digest)
        .await?;
    // Also revoke every persistent remember-me chain for this account (issue
    // #1397): a "sign out everywhere" that left a live remember cookie behind
    // would let a signed-out device silently auto-login again.
    {snake_name}.revoke_all_remember_tokens(&mut *db).await?;
    sessions_after_mutation(&session, &mut db, &state, hx, csrf, csrf_field).await
}}

#[derive(Deserialize)]
pub struct SessionLabelForm {{
    pub label: String,
}}

/// `POST /account/sessions/{{id}}/label` — set a human-readable device label
/// (e.g. "Work laptop"). An empty label clears it. Requires authentication.
#[secured]
#[post("/account/sessions/{{id}}/label")]
pub async fn sessions_label(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    hx: HxRequest,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
    Path(id): Path<i64>,
    Form(form): Form<SessionLabelForm>,
) -> AutumnResult<Response> {{
    let {snake_name} = require_tracked_session(&session, &mut db, &state).await?;
    let label = form.label.trim().chars().take(100).collect::<String>();
    let label = if label.is_empty() {{ None }} else {{ Some(label) }};
    diesel::update(
        {sess_table}::table
            .filter({sess_table}::id.eq(id))
            .filter({sess_table}::user_id.eq({snake_name}.id)),
    )
    .set({sess_table}::label.eq(label))
    .execute(&mut *db)
    .await
    .map_err(|e| {{
        AutumnError::internal_server_error_msg(format!("Failed to set label: {{e}}"))
    }})?;
    sessions_after_mutation(&session, &mut db, &state, hx, csrf, csrf_field).await
}}

// ── Signup ────────────────────────────────────────────────────────────────────

/// Render the signup form, optionally with a validation error. The minimum
/// password length is read from `[auth.password]` so the copy always matches
/// the active policy.
fn render_signup_form(
    min_len: usize,
    error: Option<&str>,
    csrf: Option<&CsrfToken>,
    csrf_field: Option<&CsrfFormField>,
) -> Markup {{
    crate::layout("Sign Up", "/signup", html! {{}}, html! {{
        h1 {{ "Create an Account" }}
        @if let Some(error) = error {{
            p role="alert" {{ (error) }}
        }}
        form action="/signup" method="post" {{
            @if let Some(csrf) = csrf {{ input type="hidden" name=(csrf_field.map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }}
            div {{
                label for="email" {{ "Email" }}
                input type="email" id="email" name="email" required autocomplete="email";
            }}
            (password_field("password", &format!("Password ({{min_len}}+ characters)"),
                FieldOptions::new().required().new_password().minlength(min_len).strength_hint().reveal()))
            button type="submit" {{ "Sign Up" }}
        }}
        p {{ a href="/login" {{ "Already have an account? Log in" }} }}
    }})
}}

/// `GET /signup` — render the signup form.
#[get("/signup")]
pub async fn signup_form(
    State(state): State<AppState>,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Markup> {{
    let min_len = state.config_arc().auth.password.min_length;
    Ok(render_signup_form(min_len, None, csrf.as_ref(), csrf_field.as_ref()))
}}

#[derive(Deserialize)]
pub struct SignupForm {{
    pub email: String,
    pub password: String,
}}

/// `POST /signup` — create a new account in an unconfirmed state and
/// immediately dispatch a confirmation email.
///
/// The user is NOT logged in by signup; they must confirm their email first.
/// Non-enumerating: returns the same error whether the email is taken or invalid
/// so callers cannot learn which addresses are registered.
/// Fails fast when mail is not configured so the "check your email" page is
/// never shown when no mail will actually be sent.
#[post("/signup")]
pub async fn signup(
    State(state): State<AppState>,
    mut db: Db,
    mailer: Mailer,
    session: Session,
    flash: Flash,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
    Form(form): Form<SignupForm>,
) -> AutumnResult<Response> {{
    // Fail fast: confirmation requires mail. Check before any DB work so the
    // response does not depend on whether the email address already exists.
    if mailer.is_disabled() {{
        return Err(AutumnError::internal_server_error_msg(
            "Signup requires email confirmation, but mail is not configured. \
             Set [mail] transport in autumn.toml (e.g. transport = \"log\" for dev). \
             The signup feature is unavailable until mail is set up.",
        ));
    }}

    let email = form.email.trim().to_lowercase();
    // Same message for invalid format and duplicate email — non-enumerating.
    let account_err = || AutumnError::unprocessable_msg("Unable to create account. Please try a different email.");
    if let Some((_, domain)) = email.split_once('@') {{
        if !domain.contains('.') {{
            return Err(account_err());
        }}
    }} else {{
        return Err(account_err());
    }}
    // Enforce the configured password policy (length, weak-list, similarity to
    // the supplied email, and optional HIBP breach check) instead of a bare
    // length gate. On failure, re-render the form with the specific message at
    // HTTP 200 rather than accepting a weak credential or returning an error page.
    // `config_arc` shares the resolved config behind an `Arc`; `config()`
    // would deep-clone every section to read one field on a request path.
    let config = state.config_arc();
    let password_cfg = &config.auth.password;
    let mut policy = password_cfg.policy();
    if password_cfg.breach_check != autumn_web::auth::BreachCheck::Off {{
        // Breach checking needs an HTTP client for the HIBP k-anonymity lookup;
        // the default-off path never constructs one.
        policy = policy.with_client(autumn_web::http_client::Client::new());
    }}
    let ctx = [email.as_str()];
    let validation = autumn_web::auth::validate_password(&form.password, &policy, &ctx).await;
    if !validation.is_valid() {{
        // Show EVERY failure (e.g. both "too short" and "too common"), not just
        // the first, so the user can fix all problems at once (issue #1345.6).
        let messages = validation.messages();
        let message = if messages.is_empty() {{
            "Invalid password.".to_owned()
        }} else {{
            messages.join("\n")
        }};
        return Ok(render_signup_form(
            password_cfg.min_length,
            Some(&message),
            csrf.as_ref(),
            csrf_field.as_ref(),
        )
        .into_response());
    }}

    let raw_confirm_token = generate_confirmation_token();
    let confirm_digest = sha256_hex(&raw_confirm_token);
    let confirm_expires_at = chrono::Utc::now().naive_utc() + chrono::Duration::hours(24);

    let password_digest = hash_password(&form.password).await?;
    let new_{snake_name} = New{pascal_name} {{
        email: email.clone(),
        time_zone: None,
        password_digest,
        reset_token_digest: None,
        reset_token_expires_at: None,
        confirm_token_digest: Some(confirm_digest),
        confirm_token_expires_at: Some(confirm_expires_at),
    }};

    let result: Result<{pascal_name}, _> = diesel::insert_into({table}::table)
        .values(&new_{snake_name})
        .returning({pascal_name}::as_returning())
        .get_result(&mut *db)
        .await;

    let {snake_name} = result.map_err(|_| account_err())?;

    // Rotate session to prevent any pending 2FA or enrollment state from a
    // previous flow in this browser from being resumed under the new account.
    // The rotation preserves any existing login's keys, so re-point that
    // login's tracked row at the new session id — otherwise the next
    // authenticated request would miss the row (treated as revoked) and the
    // old row would linger as a phantom device.
    let pre_rotation_digest = session_token_digest(&session).await;
    session.rotate_id().await;
    rebind_tracked_session(&mut db, &session, &pre_rotation_digest).await?;
    session.remove("totp_pending_id").await;
    session.remove("totp_pending_reset_digest").await;
    session.remove("totp_pending_reset_token").await;
    session.remove("totp_pending_secret").await;

    // Propagate mail failures: login is gated on email_confirmed_at, so an
    // account whose confirmation link was never delivered is unusable.
    // Roll back the insert so the address is free to retry signup.
    if let Err(e) = send_confirmation_email(&mailer, &{snake_name}.email, &raw_confirm_token).await {{
        let _ = diesel::delete({table}::table.find({snake_name}.id))
            .execute(&mut *db)
            .await;
        tracing::error!("confirmation email failed on signup — rolled back: {{e}}");
        return Err(AutumnError::internal_server_error_msg(
            "Failed to send confirmation email. Please try again later.",
        ));
    }}

    flash.info("Account created — check your email to confirm.").await;
    Ok(redirect_to("/check-your-email"))
}}

// ── Login ─────────────────────────────────────────────────────────────────────

/// `GET /login` — render the login form.
#[get("/login")]
pub async fn login_form(flash: Flash, csrf: Option<CsrfToken>, csrf_field: Option<CsrfFormField>) -> AutumnResult<Markup> {{
    Ok(crate::layout("Log In", "/login", flash_messages(&flash.consume().await), html! {{
        h1 {{ "Log In" }}
        form action="/login" method="post" {{
            @if let Some(ref csrf) = csrf {{ input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }}
            div {{
                label for="email" {{ "Email" }}
                input type="email" id="email" name="email" required autocomplete="email";
            }}
            (password_field("password", "Password", FieldOptions::new().required().current_password().reveal()))
            label {{
                input type="checkbox" name="remember" value="on";
                " Remember me on this device"
            }}
            button type="submit" {{ "Log In" }}
        }}
        {oauth_buttons}
        p {{ a href="/signup" {{ "New here? Create an account" }} }}
        p {{ a href="/forgot-password" {{ "Forgot your password?" }} }}
{magic_link_login_link}        p {{ a href="/auth/confirm/resend" {{ "Resend confirmation email" }} }}
    }}))
}}

#[derive(Deserialize)]
pub struct LoginForm {{
    pub email: String,
    pub password: String,
    /// Present (`Some("on")`) when the "Remember me" checkbox is ticked; an
    /// unchecked box posts nothing, so this stays `None` (issue #1397).
    #[serde(default)]
    pub remember: Option<String>,
}}

/// Extracts the client IP from `ConnectInfo` when present, or falls back to
/// `UNSPECIFIED` so the handler compiles and runs correctly in both production
/// (where `into_make_service_with_connect_info` injects the extension) and
/// in test environments where it is absent.
pub struct MaybeClientIp(pub std::net::IpAddr);

impl<S: Send + Sync> axum::extract::FromRequestParts<S> for MaybeClientIp {{
    type Rejection = std::convert::Infallible;
    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {{
        let ip = parts
            .extensions
            .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
            .map(|c| c.0.ip())
            .unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED));
        Ok(MaybeClientIp(ip))
    }}
}}

/// Stamp `locked_at` when the failure count reaches the threshold.
///
/// The UPDATE needs `failed_attempts >= threshold` and `locked_at IS NULL`.
/// So only one concurrent caller changes the row, and a reset by a good login
/// is never undone (#2500). The clock is read here, just before the write,
/// so a slow caller cannot save an old time (#2531).
///
/// Returns `true` only when this call set the lock. Log only on `true`.
async fn stamp_lockout(db: &mut Db, id: i64, threshold: i32) -> AutumnResult<bool> {{
    let locked_rows = diesel::update(
        {table}::table
            .find(id)
            .filter({table}::failed_attempts.ge(threshold))
            .filter({table}::locked_at.is_null()),
    )
    .set({table}::locked_at.eq(Some(chrono::Utc::now().naive_utc())))
    .execute(&mut **db)
    .await
    .map_err(|e| AutumnError::internal_server_error_msg(&format!("Failed to lock account: {{e}}")))?;
    Ok(locked_rows > 0)
}}

/// `POST /login` — verify credentials and start a session.
///
/// Non-enumerating: returns the same error for unknown email, wrong password,
/// and a locked account so callers cannot learn which accounts are registered
/// or which are currently locked.
///
/// Account lockout policy is read from `[auth.lockout]` in `autumn.toml`.
/// Safe defaults: threshold = 10 failures, cooloff = 900 s.
/// Disable with `enabled = false` or `threshold = 0` to restore pre-lockout behaviour.
#[post("/login")]
pub async fn login(
    mut db: Db,
    State(state): State<AppState>,
    session: Session,
    flash: Flash,
    MaybeClientIp(addr_ip): MaybeClientIp,
    headers: axum::http::HeaderMap,
    Form(form): Form<LoginForm>,
) -> AutumnResult<Response> {{
    let email = form.email.trim().to_lowercase();
    let auth_err = || AutumnError::unprocessable_msg("Invalid email or password.");

    let found_{snake_name}: Option<{pascal_name}> = {table}::table
        .filter({table}::email.eq(&email))
        .select({pascal_name}::as_select())
        .first(&mut *db)
        .await
        .ok();

    // Always run bcrypt to equalise timing: a miss uses a dummy hash so
    // response latency is indistinguishable from a wrong-password attempt
    // on a real account.
    const DUMMY_HASH: &str = "$2b$12$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    let password_hash = found_{snake_name}
        .as_ref()
        .map(|u| u.password_digest.as_str())
        .unwrap_or(DUMMY_HASH);
    let password_ok = verify_password(&form.password, password_hash).await.unwrap_or(false);

    // ── Account lockout policy ────────────────────────────────────────────────
    // Read lockout config from the standard Autumn config surface.
    // `config_arc` shares the resolved config behind an `Arc`; `config()`
    // would deep-clone every section to read one field on a request path.
    let config = state.config_arc();
    let lockout_cfg = &config.auth.lockout;
    let lockout_enabled = lockout_cfg.enabled && lockout_cfg.threshold > 0;

    if let Some(ref {snake_name}) = found_{snake_name} {{
        if lockout_enabled {{
            let now = chrono::Utc::now().naive_utc();
            let cooloff = chrono::Duration::seconds(lockout_cfg.cooloff_secs as i64);

            // Track local state; reset if cool-off has elapsed so the first new
            // failure after expiry is counted as attempt #1, not a re-lock.
            let mut current_attempts = {snake_name}.failed_attempts;
            let mut current_locked_at = {snake_name}.locked_at;

            // Check if the account is currently locked: locked_at is set and
            // cool-off period has not elapsed. Non-enumerating: return the same
            // auth_err as wrong password so the response does not reveal lock state.
            if let Some(locked_at) = {snake_name}.locked_at {{
                if now < locked_at + cooloff {{
                    return Err(auth_err());
                }}
                // Cool-off elapsed — treat the account as unlocked. Reset local
                // counters so the next failure starts from 1, not from threshold.
                current_attempts = 0;
                current_locked_at = None;
            }}

            if !password_ok {{
                // Atomically increment the failure counter so concurrent bad-password
                // requests each count as distinct failures rather than collapsing into
                // one. Use two separate update paths (different Diesel expression types)
                // rather than an if expression inside `.eq(...)`.
                let new_attempts: i32 = if current_attempts == {snake_name}.failed_attempts {{
                    // Normal path: DB atomically computes `failed_attempts + 1`.
                    // Propagate write errors — silently absorbing a failure here
                    // would let repeated bad-password attempts bypass the threshold.
                    diesel::update({table}::table.find({snake_name}.id))
                        .set({table}::failed_attempts.eq({table}::failed_attempts + 1))
                        .returning({table}::failed_attempts)
                        .get_result::<i32>(&mut *db)
                        .await
                        .map_err(|e| AutumnError::internal_server_error_msg(&format!("Failed to record failed login: {{e}}")))?
                }} else {{
                    // Cool-off reset path: atomically reset counter to 1 and clear
                    // locked_at in a single UPDATE. Concurrent requests hitting this
                    // branch all write the same values so races are benign (all still
                    // count 1 failure each, not zero). Propagate write errors so that
                    // DB permission failures don't silently bypass the lockout threshold.
                    diesel::update({table}::table.find({snake_name}.id))
                        .set((
                            {table}::failed_attempts.eq(1i32),
                            {table}::locked_at.eq(None::<chrono::NaiveDateTime>),
                        ))
                        .execute(&mut *db)
                        .await
                        .map_err(|e| AutumnError::internal_server_error_msg(&format!("Failed to reset lockout counter: {{e}}")))?;
                    1i32
                }};

                if new_attempts >= lockout_cfg.threshold && current_locked_at.is_none() {{
                    // The account reaches the threshold. `current_locked_at` is an
                    // old read, so the helper checks the row again in the database.
                    // Propagate errors: a failed write leaves the account unlocked.
                    let newly_locked =
                        stamp_lockout(&mut db, {snake_name}.id, lockout_cfg.threshold).await?;

                    // Log only when this call set the lock. A concurrent call or a
                    // good login can win the race, and then nothing is logged.
                    if newly_locked {{
                        // Truncate to a coarse IP prefix (IPv4 /24, IPv6 /64) so
                        // the telemetry event enables incident response without
                        // logging a precise user identifier.
                        let ip_prefix = match addr_ip {{
                            std::net::IpAddr::V4(ip) => {{
                                let [a, b, c, _] = ip.octets();
                                format!("{{a}}.{{b}}.{{c}}.0/24")
                            }}
                            std::net::IpAddr::V6(ip) => {{
                                let s = ip.segments();
                                format!("{{:x}}:{{:x}}:{{:x}}:{{:x}}::/64", s[0], s[1], s[2], s[3])
                            }}
                        }};
                        // Salt the digest with the app's signing secret. This
                        // stops recovery of the account ID from small integers.
                        // Production always has this secret set (see
                        // fail_fast_on_invalid_signing_secret). Dev and test may
                        // not; the fallback salt below only affects those local,
                        // process-only logs.
                        let account_id_digest = {{
                            use sha2::{{Digest, Sha256}};
                            let salt = config.security.signing_secret.secret.as_deref()
                                .unwrap_or_else(|| {{
                                    tracing::warn!(
                                        "account_locked digest is salted with a public \
                                         constant: set AUTUMN_SECURITY__SIGNING_SECRET so \
                                         it cannot be reversed to an account id"
                                    );
                                    "autumn-lockout-fallback-salt"
                                }});
                            let hash = Sha256::digest(
                                format!("{{}}:{{}}", salt, {snake_name}.id).as_bytes(),
                            );
                            hex::encode(&hash[..8])
                        }};
                        tracing::warn!(
                            event = "account_locked",
                            account_id_digest = %account_id_digest,
                            ip_prefix = %ip_prefix,
                            failed_attempts = new_attempts,
                            "account locked after repeated failed login attempts"
                        );
                    }}
                }}
                return Err(auth_err());
            }}
        }} else if !password_ok {{
            return Err(auth_err());
        }}
    }} else {{
        // Unknown email — bcrypt ran on DUMMY_HASH above for timing safety.
        if !password_ok {{
            return Err(auth_err());
        }}
    }}

    let {snake_name} = found_{snake_name}.ok_or_else(auth_err)?;

    // Successful login: reset lockout counter only when the account is not
    // currently locked. The WHERE clause accepts both:
    //   - locked_at IS NULL (no lock ever set), and
    //   - locked_at <= now - cooloff (lock expired via cool-off),
    // so that a user who waited out the cool-off can log in with a correct
    // password without requiring an operator unlock.
    // If zero rows match after excluding active (non-expired) locks, the
    // account was just locked concurrently — reject the login.
    if lockout_enabled {{
        let cooloff = chrono::Duration::seconds(lockout_cfg.cooloff_secs as i64);
        let lock_expired_before = chrono::Utc::now().naive_utc() - cooloff;
        let rows_cleared = diesel::update(
            {table}::table
                .find({snake_name}.id)
                .filter(
                    {table}::locked_at.is_null().or(
                        {table}::locked_at.le(lock_expired_before)
                    )
                ),
        )
        .set((
            {table}::failed_attempts.eq(0),
            {table}::locked_at.eq(None::<chrono::NaiveDateTime>),
        ))
        .execute(&mut *db)
        .await
        .map_err(|e| AutumnError::internal_server_error_msg(&format!("Failed to reset lockout on login: {{e}}")))?;
        if rows_cleared == 0 {{
            return Err(auth_err());
        }}
    }}

    // AC5: Reject unconfirmed accounts with the same non-enumerating response
    // as a wrong-password attempt so the endpoint does not reveal whether the
    // address is registered or merely unconfirmed.
    if {snake_name}.email_confirmed_at.is_none() {{
        return Err(auth_err());
    }}

    // This browser may already hold a tracked session (re-login or account
    // switch). The rotation below destroys that session id, so drop its row
    // now — otherwise it would linger as a phantom device.
    untrack_current_session(&mut db, &session).await?;
{totp_login_branch}
    session.rotate_id().await;
{totp_clear_pending}    session.insert("{snake_name}_id", {snake_name}.id.to_string()).await;
    session.insert("{snake_name}_email", &{snake_name}.email).await;
    // Use the same session key checked by `#[secured]` / `#[authorize]`.
    session.insert(state.auth_session_key(), {snake_name}.id.to_string()).await;
    // Stamp the step-up claim so `#[step_up]` routes are immediately accessible.
    autumn_web::step_up::set_last_strong_auth_at(&session).await;
    // Track this login as an active session (device list + revocation).
    record_login_session(&mut db, &session, {snake_name}.id, addr_ip, &headers).await?;
    flash.success("Logged in.").await;

    let mut response = redirect_to("/account");
    // Persistent "remember-me" opt-in (issue #1397): when the box is ticked and
    // policy allows it, mint a rotating remember chain and attach its cookie
    // alongside the session cookie. Unticked → behaviour is unchanged.
    // One shared read of the config serves both the opt-in check and the
    // resolved `[auth.remember]` section — `config()` would deep-clone every
    // config section twice per login.
    let config = state.config_arc();
    if form.remember.is_some() && config.auth.remember.enabled {{
        // Thread the resolved `[auth.remember]` config so cookie_name/duration
        // overrides are honoured (issue #1397.2).
        let remember_cfg = &config.auth.remember;
        let cookie =
            issue_remember_cookie(&mut db, remember_cfg, {snake_name}.id, addr_ip, &headers).await?;
        append_set_cookie(&mut response, &cookie);
    }}
    Ok(response)
}}

// ── Logout ────────────────────────────────────────────────────────────────────

/// `POST /logout` — destroy the session and redirect to the login page.
///
/// Destroying (not just clearing) the session ensures an old session cookie
/// cannot be replayed after logout. The tracked `{sess_table}` row is removed
/// too so the device disappears from the active-sessions list.
#[post("/logout")]
pub async fn logout(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    headers: axum::http::HeaderMap,
    flash: Flash,
) -> AutumnResult<Response> {{
    // Thread the resolved `[auth.remember]` config so an overridden cookie name
    // is the one we revoke and clear (issue #1397.2). Read through the shared
    // `Arc` — a logout must not deep-clone every config section.
    let config = state.config_arc();
    let remember_cfg = &config.auth.remember;
    // Best-effort: the device must sign out even if the row delete hiccups.
    let _ = untrack_current_session(&mut db, &session).await;
    // Revoke this device's remember chain (issue #1397) so a stolen remember
    // cookie cannot re-establish a login after logout. No-op when absent.
    // Hold the result rather than propagating it here: the session below is
    // the primary credential and must be invalidated even if this failed.
    let revoke_result = revoke_remember_from_cookie(&mut db, remember_cfg, &headers).await;
    // Invalidate the session: clear all data (drops the auth keys) and rotate
    // the id so the pre-logout cookie can no longer be replayed — the old id is
    // destroyed in the session store on save. This is equivalent to `destroy()`
    // for replay safety while letting a one-shot logout notice ride the freshly
    // rotated session through to the login page. Unconditional: it must not
    // be skipped by a remember-chain delete failure propagated below.
    session.clear().await;
    session.rotate_id().await;
    // Fail the logout if the remember chain survived: it is a long-lived
    // bearer credential and reporting success would be false. Still clear the
    // cookie on THIS browser even on failure — otherwise it keeps presenting
    // a still-valid remember cookie, and once the database recovers,
    // `remember_me` would silently re-establish a session on the next
    // request, undoing this logout.
    if let Err(error) = revoke_result {{
        let mut response = error.into_response();
        append_set_cookie(&mut response, &build_remember_clear_cookie(remember_cfg));
        return Ok(response);
    }}
    flash.info("You have been logged out.").await;
    let mut response = redirect_to("/login");
    append_set_cookie(&mut response, &build_remember_clear_cookie(remember_cfg));
    Ok(response)
}}

// ── Operator unlock ───────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct UnlockAccountForm {{
    pub email: String,
}}

/// `POST /auth/admin/unlock` — clear the lockout for a single account.
///
/// Requires the `X-Admin-Secret` header to match the `AUTUMN_ADMIN_SECRET`
/// environment variable. Returns the same 422 as a wrong-password attempt on
/// both wrong secret and unknown email so the response does not reveal which
/// accounts exist or are locked.
///
/// Protect this endpoint with network-level access controls (VPN, internal
/// load-balancer allowlist) in production in addition to the secret header.
///
/// **CSRF exemption required.** Autumn enables CSRF by default on all non-safe
/// routes. Add this path to the exempt list in `autumn.toml`:
/// ```toml
/// [security.csrf]
/// exempt_paths = ["/auth/admin/unlock"]
/// ```
///
/// Usage:
/// ```sh
/// curl -s -X POST https://example.com/auth/admin/unlock \
///   -H "Content-Type: application/x-www-form-urlencoded" \
///   -H "X-Admin-Secret: $AUTUMN_ADMIN_SECRET" \
///   -d "email=user%40example.com"
/// ```
#[post("/auth/admin/unlock")]
pub async fn unlock_account(
    mut db: Db,
    headers: axum::http::HeaderMap,
    Form(form): Form<UnlockAccountForm>,
) -> AutumnResult<Markup> {{
    let admin_secret = std::env::var("AUTUMN_ADMIN_SECRET").unwrap_or_default();
    let provided = headers
        .get("x-admin-secret")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    if admin_secret.is_empty() || provided != admin_secret {{
        return Err(AutumnError::unprocessable_msg("Invalid email or password."));
    }}
    let email = form.email.trim().to_lowercase();
    diesel::update({table}::table.filter({table}::email.eq(&email)))
        .set((
            {table}::failed_attempts.eq(0),
            {table}::locked_at.eq(None::<chrono::NaiveDateTime>),
        ))
        .execute(&mut *db)
        .await
        .map_err(|e| AutumnError::internal_server_error_msg(&format!("Failed to unlock account: {{e}}")))?;
    Ok(crate::layout("Account Unlocked", "/account", html! {{}}, html! {{
        h1 {{ "Account Unlocked" }}
        p {{ "The lockout for " (email) " has been cleared if it existed." }}
    }}))
}}

// ── Account (protected example route) ────────────────────────────────────────

/// `GET /account` — current-account profile placeholder. Requires authentication.
///
/// This is a protected-route example: the `#[secured]` attribute rejects
/// anonymous requests before the handler body runs.
#[secured]
#[get("/account")]
pub async fn account(session: Session, State(state): State<AppState>, mut db: Db, flash: Flash, csrf: Option<CsrfToken>, csrf_field: Option<CsrfFormField>) -> AutumnResult<Response> {{
    // Validates the tracked session row (401s immediately if revoked) and
    // refreshes `last_seen_at` with bounded write amplification.
    let {snake_name} = require_tracked_session(&session, &mut db, &state).await?;

    // Email-confirmed gate: demonstrates how to require a confirmed address on
    // any route. Remove this block to allow unconfirmed users to access the
    // route, or replicate it on other routes that should require confirmation.
    // See docs/guide/authentication.md for the full pattern.
    if {snake_name}.email_confirmed_at.is_none() {{
        return Ok(redirect_to("/check-your-email").into_response());
    }}

    Ok(crate::layout("Your Account", "/account", flash_messages(&flash.consume().await), html! {{
        h1 {{ "Your Account" }}
        @if let Some(scheduled) = {snake_name}.delete_scheduled_at {{
            div style="border:1px solid #c00;padding:0.75rem;margin-bottom:1rem;" {{
                p {{
                    "⚠️ Your account is scheduled for deletion on "
                    (scheduled.format("%Y-%m-%d").to_string())
                    ". Log in before then to cancel."
                }}
                form action="/account/delete/cancel" method="post" {{
                    @if let Some(ref csrf) = csrf {{
                        input type="hidden"
                            name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str()))
                            value=(csrf.token());
                    }}
                    button type="submit" {{ "Cancel Deletion" }}
                }}
            }}
        }}
        p {{ "Email: " ({snake_name}.email) }}
        p {{
            "Email confirmed: "
            @if {snake_name}.email_confirmed_at.is_some() {{ "Yes" }} @else {{ "No" }}
        }}
        form action="/logout" method="post" {{
            @if let Some(ref csrf) = csrf {{ input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }}
            button type="submit" {{ "Log Out" }}
        }}
        p {{ a href="/account/password" {{ "Change password" }} }}
        p {{ a href="/account/email" {{ "Change email address" }} }}
        p {{ a href="/account/sessions" {{ "Manage active sessions" }} }}
        p {{
            a href="/account/delete" {{ "Delete my account" }}
            " (30-day grace period — GDPR Article 17)"
        }}
    }}).into_response())
}}

/// `POST /account/destroy` — permanently delete the authenticated user's account.
///
/// Requires both a valid session (`#[secured]`) and a fresh step-up claim
/// (`#[step_up]`), so a hijacked or unattended session cannot silently delete
/// the account. CSRF protection is provided by the CsrfLayer middleware; no
/// manual token check is needed here. After deletion the session is destroyed
/// and the user is redirected to the home page.
#[secured]
#[step_up]
#[post("/account/destroy")]
pub async fn account_destroy(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
) -> AutumnResult<Response> {{
    let {snake_name}_id: i64 = require_tracked_session(&session, &mut db, &state).await?.id;

    // Deleting the account cascades to {sess_table} (FK ON DELETE CASCADE),
    // signing every device out immediately.
    diesel::delete({table}::table.find({snake_name}_id))
        .execute(&mut *db)
        .await
        .map_err(|_| AutumnError::internal_server_error_msg("Failed to delete account."))?;

    session.destroy().await;
    Ok(redirect_to("/").into_response())
}}

// ── Change Password (issue #1396) ─────────────────────────────────────────────

/// Wrap a re-rendered form in a `422 Unprocessable Entity` response.
///
/// The account settings forms re-render themselves on a rejected submission
/// (wrong current password, weak/ mismatched new password, invalid address) with
/// a `422` status so the failure is machine-detectable and never mistaken for a
/// success — while still returning the human-readable form body.
fn form_unprocessable(body: Markup) -> Response {{
    let mut response = body.into_response();
    *response.status_mut() = axum::http::StatusCode::UNPROCESSABLE_ENTITY;
    response
}}

/// Render the authenticated change-password form, optionally with an error.
fn render_change_password_form(
    error: Option<&str>,
    csrf: Option<&CsrfToken>,
    csrf_field: Option<&CsrfFormField>,
) -> Markup {{
    crate::layout("Change Password", "/account/password", html! {{}}, html! {{
        h1 {{ "Change Password" }}
        @if let Some(error) = error {{
            p role="alert" {{ (error) }}
        }}
        form action="/account/password" method="post" {{
            @if let Some(csrf) = csrf {{ input type="hidden" name=(csrf_field.map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }}
            (password_field("current_password", "Current password",
                FieldOptions::new().required().current_password().reveal_label("Show current password")))
            (password_field("new_password", "New password",
                FieldOptions::new().required().new_password().strength_hint().reveal_label("Show new password")))
            (password_field("new_password_confirmation", "Confirm new password",
                FieldOptions::new().required().new_password().reveal_label("Show confirmation")))
            button type="submit" {{ "Change Password" }}
        }}
        p {{ a href="/account" {{ "← Back to account" }} }}
    }})
}}

/// `GET /account/password` — render the change-password form. Requires auth.
#[secured]
#[get("/account/password")]
pub async fn change_password_form(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Response> {{
    // Validates the tracked session row (401s immediately if revoked).
    let _ = require_tracked_session(&session, &mut db, &state).await?;
    Ok(render_change_password_form(None, csrf.as_ref(), csrf_field.as_ref()).into_response())
}}

#[derive(Deserialize)]
pub struct ChangePasswordForm {{
    pub current_password: String,
    pub new_password: String,
    pub new_password_confirmation: String,
}}

/// `POST /account/password` — verify the current password and set a new one.
///
/// Requires a valid session (`#[secured]`) and a fresh step-up claim
/// (`#[step_up]`). On success the password policy is applied, the new password
/// is hashed with `hash_password`, the session id is rotated (fixation defence
/// on a credential change), every OTHER tracked session and remember-me chain is
/// revoked, and the step-up claim is re-stamped. The current device stays signed
/// in. A wrong current password re-renders the form with a `422` and never
/// partially updates. The response never reveals whether any address exists.
#[secured]
#[step_up]
#[post("/account/password")]
pub async fn change_password(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    flash: Flash,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
    Form(form): Form<ChangePasswordForm>,
) -> AutumnResult<Response> {{
    let {snake_name} = require_tracked_session(&session, &mut db, &state).await?;

    // Verify the CURRENT password before anything else. A wrong current password
    // re-renders the form at 422 and makes no change (AC2).
    let current_ok = verify_password(&form.current_password, &{snake_name}.password_digest)
        .await
        .unwrap_or(false);
    if !current_ok {{
        return Ok(form_unprocessable(render_change_password_form(
            Some("Current password is incorrect."),
            csrf.as_ref(),
            csrf_field.as_ref(),
        )));
    }}

    // The confirmation field must match so a typo cannot lock the user out.
    if form.new_password != form.new_password_confirmation {{
        return Ok(form_unprocessable(render_change_password_form(
            Some("New password and confirmation do not match."),
            csrf.as_ref(),
            csrf_field.as_ref(),
        )));
    }}

    // Enforce the configured password policy, passing the account email as
    // similarity context (matches the signup path).
    // `config_arc` shares the resolved config behind an `Arc`; `config()`
    // would deep-clone every section to read one field on a request path.
    let config = state.config_arc();
    let password_cfg = &config.auth.password;
    let mut policy = password_cfg.policy();
    if password_cfg.breach_check != autumn_web::auth::BreachCheck::Off {{
        policy = policy.with_client(autumn_web::http_client::Client::new());
    }}
    let ctx = [{snake_name}.email.as_str()];
    let validation = autumn_web::auth::validate_password(&form.new_password, &policy, &ctx).await;
    if !validation.is_valid() {{
        let messages = validation.messages();
        let message = if messages.is_empty() {{
            "Invalid password.".to_owned()
        }} else {{
            messages.join("\n")
        }};
        return Ok(form_unprocessable(render_change_password_form(
            Some(&message),
            csrf.as_ref(),
            csrf_field.as_ref(),
        )));
    }}

    let new_digest = hash_password(&form.new_password).await?;

    // Rotate the session id (fixation defence on a credential change), then
    // atomically: persist the new digest, revoke every OTHER tracked session,
    // rebind the CURRENT device's row onto the rotated id so it stays signed in,
    // and revoke every persistent remember-me chain (the old password is now
    // suspect). If any step fails the whole change rolls back.
    //
    // FAIL-CLOSED TRADEOFF: rotation happens BEFORE the transaction so both the
    // pre- and post-rotation digests are known and the row rebind is atomic with
    // the password write. The cost is that on a rolled-back change the cookie
    // already holds the rotated id, which no longer matches any `user_sessions`
    // row — so a FAILED change logs the acting device out. This is fail-closed
    // (a security-neutral logout, never an unintended stay-signed-in), so it is
    // left as-is: moving the rotate/rebind after commit would only relocate the
    // same window and risks the "rotate before auth writes" fixation invariant.
    //
    // Revoking every OTHER tracked session is the standard response to a
    // credential change, but it honours the same opt-out the reset/TOTP/passkey
    // credential-change paths read ([auth.sessions].revoke_on_credential_change).
    // When that flag is false we still rotate + rebind the CURRENT session (so
    // this device stays signed in on a fresh id) and still clear reset/magic-link
    // tokens — only the other-device sign-out is skipped.
    let revoke_other_sessions_in_txn = state.config_arc().auth.sessions.revoke_on_credential_change;
    let pre_rotation_digest = session_token_digest(&session).await;
    session.rotate_id().await;
    let post_rotation_digest = session_token_digest(&session).await;
    let {snake_name}_id = {snake_name}.id;
    (*db)
        .transaction::<_, diesel::result::Error, _>(async move |conn| {{
            diesel::update({table}::table.find({snake_name}_id))
                .set((
                    {table}::password_digest.eq(&new_digest),
                    // Invalidate any outstanding forgot-password token in the SAME
                    // transaction: reset_password authenticates SOLELY by matching
                    // an unexpired reset_token_digest, so a link minted before this
                    // change could otherwise overwrite the just-secured password.
                    {table}::reset_token_digest.eq(None::<String>),
                    {table}::reset_token_expires_at.eq(None::<chrono::NaiveDateTime>),
                ))
                .execute(conn)
                .await?;
            // Revoke every OTHER session (all rows whose digest is not this
            // device's pre-rotation digest) unless the opt-out is set, then
            // always rebind this device onto the rotated id below.
            if revoke_other_sessions_in_txn {{
                diesel::delete(
                    {sess_table}::table
                        .filter({sess_table}::user_id.eq({snake_name}_id))
                        .filter({sess_table}::token_digest.ne(&pre_rotation_digest)),
                )
                .execute(conn)
                .await?;
            }}
            diesel::update(
                {sess_table}::table.filter({sess_table}::token_digest.eq(&pre_rotation_digest)),
            )
            .set({sess_table}::token_digest.eq(&post_rotation_digest))
            .execute(conn)
            .await?;
            diesel::delete(
                {rem_table}::table.filter({rem_table}::user_id.eq({snake_name}_id)),
            )
            .execute(conn)
            .await?;
{magic_link_change_password_clear}            Ok(())
        }})
        .await
        .map_err(|e| {{
            AutumnError::internal_server_error_msg(format!("Failed to change password: {{e}}"))
        }})?;

    // Re-stamp the step-up claim so the freshly rotated session keeps sudo-mode
    // freshness (consistent with reauth / reset-password).
    autumn_web::step_up::set_last_strong_auth_at(&session).await;
    flash.success("Your password has been changed.").await;
    Ok(redirect_to("/account"))
}}

// ── Change Email (issue #1396) ────────────────────────────────────────────────

/// Render the authenticated change-email form, optionally with an error.
fn render_change_email_form(
    error: Option<&str>,
    csrf: Option<&CsrfToken>,
    csrf_field: Option<&CsrfFormField>,
) -> Markup {{
    crate::layout("Change Email Address", "/account/email", html! {{}}, html! {{
        h1 {{ "Change Email Address" }}
        p {{ "We'll send a confirmation link to the new address. Your current \
              address keeps working until you confirm the change." }}
        @if let Some(error) = error {{
            p role="alert" {{ (error) }}
        }}
        form action="/account/email" method="post" {{
            @if let Some(csrf) = csrf {{ input type="hidden" name=(csrf_field.map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }}
            div {{
                label for="new-email" {{ "New email address" }}
                input type="email" id="new-email" name="new_email" autocomplete="email" required;
            }}
            (password_field("current_password", "Current password", FieldOptions::new().required().current_password().reveal()))
            button type="submit" {{ "Send Confirmation Link" }}
        }}
        p {{ a href="/account" {{ "← Back to account" }} }}
    }})
}}

/// `GET /account/email` — render the change-email form. Requires auth.
#[secured]
#[get("/account/email")]
pub async fn change_email_form(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Response> {{
    // Validates the tracked session row (401s immediately if revoked).
    let _ = require_tracked_session(&session, &mut db, &state).await?;
    Ok(render_change_email_form(None, csrf.as_ref(), csrf_field.as_ref()).into_response())
}}

#[derive(Deserialize)]
pub struct ChangeEmailForm {{
    pub new_email: String,
    pub current_password: String,
}}

/// `POST /account/email` — start an email-address change.
///
/// Requires a valid session (`#[secured]`) and a fresh step-up claim
/// (`#[step_up]`). Verifies the current password, then stores the new address as
/// `pending_email` (re-using the `confirm_token_digest` machinery) and sends a
/// confirmation link to the NEW address plus a change-notice to the OLD address.
/// The OLD address stays valid for sign-in until the new-address token is
/// confirmed. A second request supersedes the prior pending token. Mail must be
/// configured; the disabled-transport guard runs first.
#[secured]
#[step_up]
#[post("/account/email")]
pub async fn change_email(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    mailer: Mailer,
    flash: Flash,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
    Form(form): Form<ChangeEmailForm>,
) -> AutumnResult<Response> {{
    // Guard disabled mail FIRST — the flow is unusable without a confirmation
    // email, so fail loudly rather than store a pending change no one can confirm.
    if mailer.is_disabled() {{
        return Err(AutumnError::internal_server_error_msg(
            "Changing your email requires mail to be configured. \
             Set [mail] transport in autumn.toml (e.g. transport = \"log\" for dev). \
             The change-email feature is unavailable until mail is set up.",
        ));
    }}

    let {snake_name} = require_tracked_session(&session, &mut db, &state).await?;

    // Verify the current password before accepting the change (AC3). A wrong
    // password re-renders the form at 422 and makes no change.
    let current_ok = verify_password(&form.current_password, &{snake_name}.password_digest)
        .await
        .unwrap_or(false);
    if !current_ok {{
        return Ok(form_unprocessable(render_change_email_form(
            Some("Current password is incorrect."),
            csrf.as_ref(),
            csrf_field.as_ref(),
        )));
    }}

    let new_email = form.new_email.trim().to_lowercase();
    // Basic format check, mirroring signup. Same message for every rejection so
    // the endpoint never reveals whether the address is already registered.
    let invalid = || {{
        Ok(form_unprocessable(render_change_email_form(
            Some("Please enter a valid email address."),
            csrf.as_ref(),
            csrf_field.as_ref(),
        )))
    }};
    match new_email.split_once('@') {{
        Some((_, domain)) if domain.contains('.') => {{}}
        _ => return invalid(),
    }}
    if new_email == {snake_name}.email {{
        return invalid();
    }}

    // Reserve availability BEFORE minting a token, sending mail, or storing any
    // pending state. If the address already belongs to ANOTHER account (we already
    // excluded the caller's own address above), short-circuit to the SAME generic
    // "check your email" response: do NOT email that third party a confirmation
    // link, and do NOT persist a pending change the later confirm could never apply
    // (it would collide on `email`'s unique index). Non-enumerating — the caller
    // cannot tell a taken address from an available one. Swallow lookup errors like
    // the reset flow so a transient DB error never becomes an existence oracle.
    let already_taken = {table}::table
        .filter({table}::email.eq(&new_email))
        .select({pascal_name}::as_select())
        .first::<{pascal_name}>(&mut *db)
        .await
        .ok()
        .is_some();
    if already_taken {{
        flash
            .info("Check your new email address for a confirmation link.")
            .await;
        return Ok(redirect_to("/account"));
    }}

    // Mint a fresh single-use token; only the SHA-256 digest is stored. A second
    // change request overwrites `pending_email` and re-mints the token, so the
    // prior pending change is superseded (AC4).
    let raw_token = generate_confirmation_token();
    let confirm_digest = sha256_hex(&raw_token);
    let confirm_expires_at = chrono::Utc::now().naive_utc() + chrono::Duration::hours(24);

    // Send the confirmation link to the NEW address first; only persist the
    // pending change on success, so a transient mail failure leaves the account
    // untouched (the old address keeps working, no stale pending token).
    send_email_change_confirmation(&mailer, &new_email, &raw_token).await?;

    diesel::update({table}::table.find({snake_name}.id))
        .set((
            {table}::pending_email.eq(Some(&new_email)),
            {table}::confirm_token_digest.eq(Some(&confirm_digest)),
            {table}::confirm_token_expires_at.eq(Some(confirm_expires_at)),
        ))
        .execute(&mut *db)
        .await
        .map_err(|e| {{
            AutumnError::internal_server_error_msg(format!("Failed to record email change: {{e}}"))
        }})?;

    // Notify the OLD address so the account owner is alerted to the change even
    // if it was initiated by someone else. Best-effort: a failure here must not
    // roll back the (already-confirmed-deliverable) pending change.
    if let Err(e) = send_email_change_notice(&mailer, &{snake_name}.email, &new_email).await {{
        tracing::warn!("email-change notice to old address failed: {{e}}");
    }}

    flash
        .info("Check your new email address for a confirmation link.")
        .await;
    Ok(redirect_to("/account"))
}}

/// `GET /account/email/confirm/{{token}}` — confirm a pending email change.
///
/// On a valid unexpired token whose account still has a `pending_email`: swaps
/// `email` to the pending address, clears `pending_email` and the token, and
/// stamps `email_confirmed_at`. Single-use — the token is consumed atomically so
/// a replay matches zero rows. Any invalid/expired/unknown/already-consumed
/// token returns the SAME non-revealing 422 (no oracle). Only the SHA-256 digest
/// is ever stored; the raw token lives only in the emailed URL.
#[get("/account/email/confirm/{{token}}")]
pub async fn confirm_email_change(
    mut db: Db,
    Path(params): Path<ConfirmEmailPath>,
) -> AutumnResult<Response> {{
    let token_digest = sha256_hex(&params.token);
    let now = chrono::Utc::now().naive_utc();
    let generic = || {{
        AutumnError::unprocessable_msg(
            "This email-change link is invalid or has expired. \
             Please request a new email change from your account settings.",
        )
    }};

    // Load the pending row by token digest. `pending_email IS NOT NULL` keeps
    // this path from colliding with the signup email-confirmation flow, which
    // shares the `confirm_token_digest` column but never sets `pending_email`.
    let {snake_name}: {pascal_name} = {table}::table
        .filter({table}::confirm_token_digest.eq(Some(&token_digest)))
        .filter({table}::confirm_token_expires_at.gt(now))
        .filter({table}::pending_email.is_not_null())
        .select({pascal_name}::as_select())
        .first(&mut *db)
        .await
        .map_err(|_| generic())?;

    let Some(new_email) = {snake_name}.pending_email.clone() else {{
        return Err(generic());
    }};

    // Consume atomically: the UPDATE re-filters on the digest so two concurrent
    // requests with the same token cannot both apply (the second matches zero
    // rows). Swapping the address here also enforces email uniqueness — a
    // collision surfaces as the same generic error, revealing nothing. The whole
    // mutation runs in one transaction so the magic-link cleanup below commits
    // atomically with the address swap (or rolls back together on any failure).
    let {snake_name}_id = {snake_name}.id;
    // Keep a copy for the success page; the original is moved into the txn.
    let new_email_display = new_email.clone();
    let rows = (*db)
        .transaction::<_, diesel::result::Error, _>(async move |conn| {{
            let rows = diesel::update(
                {table}::table
                    .find({snake_name}_id)
                    .filter({table}::confirm_token_digest.eq(Some(&token_digest))),
            )
            .set((
                {table}::email.eq(&new_email),
                {table}::pending_email.eq(None::<String>),
                {table}::confirm_token_digest.eq(None::<String>),
                {table}::confirm_token_expires_at.eq(None::<chrono::NaiveDateTime>),
                {table}::email_confirmed_at.eq(Some(now)),
                // Invalidate any outstanding reset token: a link sent to the OLD
                // mailbox before this change must not be usable to reset the
                // account after it has moved to the new address.
                {table}::reset_token_digest.eq(None::<String>),
                {table}::reset_token_expires_at.eq(None::<chrono::NaiveDateTime>),
            ))
            .execute(conn)
            .await?;
            // Lost single-use race (token already consumed): nothing matched, so
            // commit the no-op and leave the winner's magic-link cleanup intact.
            // The same generic error is surfaced below.
            if rows == 0 {{
                return Ok(0);
            }}
{magic_link_email_change_clear}            Ok(rows)
        }})
        .await
        .map_err(|_| generic())?;
    if rows == 0 {{
        return Err(generic());
    }}

    Ok(crate::layout("Email Address Updated", "/account/email", html! {{}}, html! {{
        h1 {{ "Email Address Updated" }}
        p {{ "Your email address has been changed to " (new_email_display) "." }}
        p {{ a href="/account" {{ "← Back to account" }} }}
    }})
    .into_response())
}}

/// Send the email-change confirmation link to the NEW address.
async fn send_email_change_confirmation(
    mailer: &Mailer,
    to: &str,
    token: &str,
) -> AutumnResult<()> {{
    if mailer.is_disabled() {{
        return Err(AutumnError::internal_server_error_msg(
            "Changing your email requires mail to be configured.",
        ));
    }}
    let base_url = std::env::var("APP_BASE_URL")
        .unwrap_or_else(|_| "http://localhost:3000".to_owned());
    let confirm_url = format!("{{base_url}}/account/email/confirm/{{token}}");
    let mail = Mail::builder()
        .to(to.to_owned())
        .subject("Confirm your new email address")
        .html(html! {{
            p {{ "Click the link below to confirm this as the new email address for your account." }}
            p {{ "This link expires in 24 hours." }}
            p {{ a href=(&confirm_url) {{ "Confirm New Email Address" }} }}
            p {{ "If you did not request this change, you can safely ignore this email." }}
        }})
        .text(format!(
            "Confirm your new email address: {{confirm_url}}\n\
             This link expires in 24 hours.\n\
             If you did not request this change, you can safely ignore this email."
        ))
        .build()
        .map_err(|e| {{
            AutumnError::internal_server_error_msg(format!(
                "Failed to build email-change confirmation: {{e}}"
            ))
        }})?;
    mailer.send(mail).await.map_err(|e| {{
        AutumnError::internal_server_error_msg(format!(
            "Failed to send email-change confirmation: {{e}}"
        ))
    }})
}}

/// Send a change-notice to the OLD address so the owner is alerted.
async fn send_email_change_notice(
    mailer: &Mailer,
    to: &str,
    new_email: &str,
) -> AutumnResult<()> {{
    let mail = Mail::builder()
        .to(to.to_owned())
        .subject("Email address change requested")
        .html(html! {{
            p {{ "Someone requested changing the email address on your account to " (new_email) "." }}
            p {{ "The change only takes effect once the new address is confirmed. \
                  Your current address stays active until then." }}
            p {{ "If you did not request this, change your password immediately — \
                  your account may be compromised." }}
        }})
        .text(format!(
            "Someone requested changing the email address on your account to {{new_email}}.\n\
             The change only takes effect once the new address is confirmed.\n\
             If you did not request this, change your password immediately."
        ))
        .build()
        .map_err(|e| {{
            AutumnError::internal_server_error_msg(format!(
                "Failed to build email-change notice: {{e}}"
            ))
        }})?;
    mailer.send(mail).await.map_err(|e| {{
        AutumnError::internal_server_error_msg(format!(
            "Failed to send email-change notice: {{e}}"
        ))
    }})
}}

// ── Step-Up Reauth ────────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct ReauthForm {{
    // The TOTP retry form omits the password field and relies on the
    // `reauth_pw_ok` session marker, so `password` must be optional here.
    #[serde(default)]
    pub password: String,
    #[serde(default)]
    pub return_to: String,
    #[serde(default)]
    pub totp_code: String,
}}

/// `GET /reauth` — prompt for password to refresh the step-up claim.
///
/// Redirects unauthenticated users to `/login`. Renders a minimal password
/// form that posts back to `POST /reauth`. The `return_to` query parameter
/// is forwarded as a hidden field so it survives the form submit.
#[get("/reauth")]
pub async fn reauth_form(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    Query(params): Query<std::collections::HashMap<String, String>>,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Response> {{
    if session.get("{snake_name}_id").await.is_none() {{
        return Ok(redirect_to("/login").into_response());
    }}
    // Validates the tracked session row (401s immediately if revoked).
    let _ = require_tracked_session(&session, &mut db, &state).await?;
    let return_to = params.get("return_to").cloned().unwrap_or_default();
    Ok(crate::layout("Confirm your identity", "/reauth", html! {{}}, html! {{
        h1 {{ "Confirm your identity" }}
        p {{ "For security, please re-enter your password to continue." }}
        form action="/reauth" method="post" {{
            @if let Some(ref csrf) = csrf {{ input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }}
            input type="hidden" name="return_to" value=(return_to);
            (password_field("password", "Password", FieldOptions::new().required().current_password().reveal()))
            {totp_reauth_field}
            button type="submit" {{ "Confirm" }}
        }}
    }}).into_response())
}}

/// `POST /reauth` — verify current password and refresh the step-up claim.
///
/// On success, sets `last_strong_auth_at` in the session and redirects to
/// `return_to` (same-origin validated). On failure, renders the form again
/// with an error message. Unauthenticated requests are redirected to `/login`.
#[post("/reauth")]
pub async fn reauth(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
    Form(form): Form<ReauthForm>,
) -> AutumnResult<Response> {{
    if session.get("{snake_name}_id").await.is_none() {{
        return Ok(redirect_to("/login").into_response());
    }}

    // Validates the tracked session row (401s immediately if revoked).
    let {snake_name} = require_tracked_session(&session, &mut db, &state).await?;

    // In the TOTP multi-step flow, the password is verified in one request and the
    // TOTP code in the next. Rather than echoing the password into a hidden DOM
    // field (which would expose it to any script on the page), we store a short-
    // lived session marker after a successful password check and rely on that marker
    // on subsequent submissions so the password never leaves the server.
    // The marker stores "<timestamp>:<account_id>" so it is both time-limited
    // (10-minute window) and bound to the specific account — if the session is
    // reused by a different account the stored id will not match and the marker
    // is ignored, requiring the new account's password to be re-entered.
    const REAUTH_PW_VALID_SECS: i64 = 600;
    let pw_verified_recently = session
        .get("reauth_pw_ok")
        .await
        .and_then(|s| {{
            let mut parts = s.splitn(2, ':');
            let ts = parts.next()?.parse::<i64>().ok()?;
            let id = parts.next()?.parse::<i64>().ok()?;
            Some((ts, id))
        }})
        .is_some_and(|(ts, id)| {{
            id == {snake_name}.id
                && chrono::Utc::now().timestamp() - ts < REAUTH_PW_VALID_SECS
        }});
    if !pw_verified_recently {{
        // Helper to render the reauth error form without duplicating markup.
        let reauth_form_err = |ret: &str| {{
            crate::layout("Confirm your identity", "/reauth", html! {{}}, html! {{
                h1 {{ "Confirm your identity" }}
                p style="color:red" {{ "Incorrect password. Please try again." }}
                form action="/reauth" method="post" {{
                    @if let Some(ref csrf) = csrf {{ input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }}
                    input type="hidden" name="return_to" value=(ret);
                    (password_field("password", "Password", FieldOptions::new().required().current_password().reveal()))
                    {totp_reauth_field}
                    button type="submit" {{ "Confirm" }}
                }}
            }}).into_response()
        }};

        // ── Account lockout policy ──────────────────────────────────────────
        // `config_arc` shares the resolved config behind an `Arc`; `config()`
        // would deep-clone every section to read one field on a request path.
        let config = state.config_arc();
        let lockout_cfg = &config.auth.lockout;
        let lockout_enabled = lockout_cfg.enabled && lockout_cfg.threshold > 0;

        if lockout_enabled {{
            let now = chrono::Utc::now().naive_utc();
            let cooloff = chrono::Duration::seconds(lockout_cfg.cooloff_secs as i64);

            // Local mutable counters reset when cool-off has elapsed.
            let mut current_attempts = {snake_name}.failed_attempts;
            let mut current_locked_at = {snake_name}.locked_at;

            if let Some(locked_at) = {snake_name}.locked_at {{
                if now < locked_at + cooloff {{
                    // Non-enumerating: same form as wrong password.
                    session.remove("reauth_pw_ok").await;
                    return Ok(reauth_form_err(&form.return_to));
                }}
                // Cool-off elapsed — treat as unlocked.
                current_attempts = 0;
                current_locked_at = None;
            }}

            let password_ok = verify_password(&form.password, &{snake_name}.password_digest)
                .await
                .unwrap_or(false);

            if !password_ok {{
                // Atomically increment (or reset to 1 if cool-off just elapsed).
                let new_attempts: i32 = if current_attempts == {snake_name}.failed_attempts {{
                    diesel::update({table}::table.find({snake_name}.id))
                        .set({table}::failed_attempts.eq({table}::failed_attempts + 1))
                        .returning({table}::failed_attempts)
                        .get_result::<i32>(&mut *db)
                        .await
                        .map_err(|e| AutumnError::internal_server_error_msg(&format!("Failed to record failed reauth: {{e}}")))?
                }} else {{
                    diesel::update({table}::table.find({snake_name}.id))
                        .set((
                            {table}::failed_attempts.eq(1i32),
                            {table}::locked_at.eq(None::<chrono::NaiveDateTime>),
                        ))
                        .execute(&mut *db)
                        .await
                        .map_err(|e| AutumnError::internal_server_error_msg(&format!("Failed to reset lockout counter: {{e}}")))?;
                    1i32
                }};
                if new_attempts >= lockout_cfg.threshold && current_locked_at.is_none() {{
                    // Same guarded stamp as `login` (#2500, #2531). This path does not log.
                    stamp_lockout(&mut db, {snake_name}.id, lockout_cfg.threshold).await?;
                }}
                session.remove("reauth_pw_ok").await;
                return Ok(reauth_form_err(&form.return_to));
            }}

            // Correct password — reset lockout counters. The WHERE guard
            // excludes accounts locked by a concurrent bad-password request
            // between our check and now, treating that race as auth failure.
            let lock_expired_before = chrono::Utc::now().naive_utc() - cooloff;
            let rows_cleared = diesel::update(
                {table}::table
                    .find({snake_name}.id)
                    .filter(
                        {table}::locked_at.is_null().or(
                            {table}::locked_at.le(lock_expired_before)
                        ),
                    ),
            )
            .set((
                {table}::failed_attempts.eq(0i32),
                {table}::locked_at.eq(None::<chrono::NaiveDateTime>),
            ))
            .execute(&mut *db)
            .await
            .map_err(|e| AutumnError::internal_server_error_msg(&format!("Failed to reset lockout on reauth: {{e}}")))?;
            if rows_cleared == 0 {{
                // Concurrently locked — treat as authentication failure.
                session.remove("reauth_pw_ok").await;
                return Ok(reauth_form_err(&form.return_to));
            }}
        }} else {{
            let password_ok = verify_password(&form.password, &{snake_name}.password_digest)
                .await
                .unwrap_or(false);
            if !password_ok {{
                session.remove("reauth_pw_ok").await;
                return Ok(reauth_form_err(&form.return_to));
            }}
        }}

        session
            .insert(
                "reauth_pw_ok",
                format!("{{}}:{{}}", chrono::Utc::now().timestamp(), {snake_name}.id),
            )
            .await;
    }}
    {totp_reauth_check}
    // Rotate session ID before elevating privileges to prevent session fixation
    // attacks where a stolen cookie is used to benefit from a legitimate reauth.
    // The tracked session row is keyed by the digest of the id, so capture the
    // pre-rotation digest and re-point the row at the new id — otherwise the
    // redirected step-up request would find no row and be treated as revoked.
    let pre_rotation_digest = session_token_digest(&session).await;
    session.rotate_id().await;
    rebind_tracked_session(&mut db, &session, &pre_rotation_digest).await?;
    session.remove("reauth_pw_ok").await;
    // Refresh the step-up claim.
    autumn_web::step_up::set_last_strong_auth_at(&session).await;

    // Redirect to the validated same-origin destination.
    let dest = autumn_web::step_up::validate_return_to(&form.return_to)
        .ok()
        .filter(|_| !form.return_to.is_empty())
        .map(|_| form.return_to.as_str())
        .unwrap_or("/account")
        .to_owned();

    // Suppress unused warning when state.auth_session_key() is not used here.
    let _ = &state;
    Ok(redirect_to(&dest).into_response())
}}

// ── Forgot Password ───────────────────────────────────────────────────────────

/// `GET /forgot-password` — render the forgot-password form.
#[get("/forgot-password")]
pub async fn forgot_password_form(csrf: Option<CsrfToken>, csrf_field: Option<CsrfFormField>) -> AutumnResult<Markup> {{
    Ok(crate::layout("Forgot Password", "/forgot-password", html! {{}}, html! {{
        h1 {{ "Forgot Your Password?" }}
        form action="/forgot-password" method="post" {{
            @if let Some(ref csrf) = csrf {{ input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }}
            div {{
                label for="email" {{ "Email" }}
                input type="email" id="email" name="email" required autocomplete="email";
            }}
            button type="submit" {{ "Send Reset Link" }}
        }}
    }}))
}}

#[derive(Deserialize)]
pub struct ForgotPasswordForm {{
    pub email: String,
}}

/// `POST /forgot-password` — generate a reset token and email a reset link.
///
/// Non-enumerating: always returns the same confirmation page whether or not
/// the email address is registered, so callers cannot learn which addresses
/// exist. Requires Autumn mail to be configured; fails with a clear message
/// identifying the missing mail configuration if it is not.
#[post("/forgot-password")]
pub async fn forgot_password(
    mut db: Db,
    mailer: Mailer,
    Form(form): Form<ForgotPasswordForm>,
) -> AutumnResult<Markup> {{
    // Fail fast when mail is not configured — safe because this check is
    // independent of the email address lookup and does not leak whether an
    // address is registered.
    if mailer.is_disabled() {{
        return Err(AutumnError::internal_server_error_msg(
            "Password reset requires mail to be configured. \
             Set [mail] transport in autumn.toml (e.g. transport = \"smtp\"). \
             The forgot-password feature is unavailable until mail is set up.",
        ));
    }}

    let email = form.email.trim().to_lowercase();

    // Record start time; the response is padded to a constant minimum below
    // so an attacker cannot infer whether an address is registered by
    // measuring response latency.
    let t0 = std::time::Instant::now();

    // Non-enumerating: silently skip unknown addresses.
    let maybe_{snake_name}: Option<{pascal_name}> = {table}::table
        .filter({table}::email.eq(&email))
        .select({pascal_name}::as_select())
        .first(&mut *db)
        .await
        .ok();

    if let Some({snake_name}) = maybe_{snake_name} {{
        let raw_token = generate_reset_token();
        let token_digest = sha256_hex(&raw_token);
        let expires_at =
            chrono::Utc::now().naive_utc() + chrono::Duration::hours(2);

        diesel::update({table}::table.find({snake_name}.id))
            .set((
                {table}::reset_token_digest.eq(Some(&token_digest)),
                {table}::reset_token_expires_at.eq(Some(expires_at)),
            ))
            .execute(&mut *db)
            .await?;

        // Non-enumerating: log send failures but do not surface them to the
        // caller — the response is always the same "check your email" page.
        if let Err(e) = send_reset_email(&mailer, &{snake_name}.email, &raw_token).await {{
            tracing::error!("password-reset email failed: {{e}}");
        }}
    }}

    // Pad to a constant minimum so hit and miss paths take indistinguishable
    // wall-clock time.
    if let Some(remaining) = std::time::Duration::from_secs(1).checked_sub(t0.elapsed()) {{
        tokio::time::sleep(remaining).await;
    }}

    Ok(crate::layout("Check Your Email", "/forgot-password", html! {{}}, html! {{
        h1 {{ "Check Your Email" }}
        p {{
            "If that address is registered you'll receive a reset link shortly."
        }}
        p {{ a href="/login" {{ "Back to login" }} }}
    }}))
}}

// ── Reset Password ────────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct ResetPasswordQuery {{
    pub token: String,
}}

/// Render the reset-password form, optionally with a validation error. The
/// minimum length reflects the active `[auth.password]` policy.
fn render_reset_password_form(
    token: &str,
    min_len: usize,
    error: Option<&str>,
    csrf: Option<&CsrfToken>,
    csrf_field: Option<&CsrfFormField>,
) -> Markup {{
    crate::layout("Reset Password", "/reset-password", html! {{}}, html! {{
        h1 {{ "Set a New Password" }}
        @if let Some(error) = error {{
            p role="alert" {{ (error) }}
        }}
        form action="/reset-password" method="post" {{
            @if let Some(csrf) = csrf {{ input type="hidden" name=(csrf_field.map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }}
            input type="hidden" name="token" value=(token);
            (password_field("password", &format!("New Password ({{min_len}}+ characters)"),
                FieldOptions::new().required().new_password().minlength(min_len).strength_hint().reveal()))
            button type="submit" {{ "Set New Password" }}
        }}
    }})
}}

/// `GET /reset-password?token=<raw>` — render the reset-password form.
#[get("/reset-password")]
pub async fn reset_password_form(
    State(state): State<AppState>,
    Query(query): Query<ResetPasswordQuery>,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Markup> {{
    let min_len = state.config_arc().auth.password.min_length;
    Ok(render_reset_password_form(
        &query.token,
        min_len,
        None,
        csrf.as_ref(),
        csrf_field.as_ref(),
    ))
}}

#[derive(Deserialize)]
pub struct ResetPasswordForm {{
    pub token: String,
    pub password: String,
}}

/// `POST /reset-password` — verify the reset token and update the password.
///
/// The token is compared via its stored digest (constant-time via `sha2`).
/// On success the session is rotated, invalidating any prior authenticated
/// state.
#[post("/reset-password")]
pub async fn reset_password(
    mut db: Db,
    State(state): State<AppState>,
    session: Session,
    MaybeClientIp(addr_ip): MaybeClientIp,
    headers: axum::http::HeaderMap,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
    Form(form): Form<ResetPasswordForm>,
) -> AutumnResult<Response> {{
    // Enforce the configured password policy. The reset flow has no verified
    // user identifier in scope at this point (the token is validated below), so
    // no similarity context is supplied. On failure, re-render the form with the
    // specific message at HTTP 200 rather than accepting a weak credential.
    // `config_arc` shares the resolved config behind an `Arc`; `config()`
    // would deep-clone every section to read one field on a request path.
    let config = state.config_arc();
    let password_cfg = &config.auth.password;
    let mut policy = password_cfg.policy();
    if password_cfg.breach_check != autumn_web::auth::BreachCheck::Off {{
        policy = policy.with_client(autumn_web::http_client::Client::new());
    }}
    let validation = autumn_web::auth::validate_password(&form.password, &policy, &[]).await;
    if !validation.is_valid() {{
        // Show EVERY failure (e.g. both "too short" and "too common"), not just
        // the first, so the user can fix all problems at once (issue #1345.6).
        let messages = validation.messages();
        let message = if messages.is_empty() {{
            "Invalid password.".to_owned()
        }} else {{
            messages.join("\n")
        }};
        return Ok(render_reset_password_form(
            &form.token,
            password_cfg.min_length,
            Some(&message),
            csrf.as_ref(),
            csrf_field.as_ref(),
        )
        .into_response());
    }}

    let token_digest = sha256_hex(&form.token);
    let now = chrono::Utc::now().naive_utc();

    let {snake_name}: {pascal_name} = {table}::table
        .filter({table}::reset_token_digest.eq(Some(&token_digest)))
        .filter({table}::reset_token_expires_at.gt(now))
        .select({pascal_name}::as_select())
        .first(&mut *db)
        .await
        .map_err(|_| {{
            AutumnError::unprocessable_msg("Invalid or expired reset link.")
        }})?;

    let new_digest = hash_password(&form.password).await?;

    // Password reset and email confirmation are independent state transitions (AC8).
    // Resetting a password does NOT implicitly confirm the email address.
    // Check BEFORE the TOTP interstitial so both TOTP and non-TOTP accounts are
    // gated — without this, a TOTP-enabled unconfirmed user could complete the
    // reset via /login/verify without ever confirming their email.
    if {snake_name}.email_confirmed_at.is_none() {{
        return Ok(redirect_to("/check-your-email"));
    }}

    // This browser may already hold a tracked session. The rotation below
    // (or inside the 2FA branch) destroys that session id, so drop its row
    // now — otherwise it would linger as a phantom device.
    untrack_current_session(&mut db, &session).await?;
{totp_reset_branch}
    // Rotate before the commit so the fresh session's row can be inserted
    // in the same transaction (the rotation itself is in-memory until the
    // response is sent, so a rollback leaves no half-applied state).
    session.rotate_id().await;
    let new_session_row = build_session_row(&session, {snake_name}.id, addr_ip, &headers).await;

    // Commit the password change, the reset-token consumption, the session
    // revocation, and the new session row atomically: if any part fails
    // everything rolls back, so the reset link stays usable and no state is
    // half-applied. Revoking every existing session is the standard
    // response to credential theft (defaulted on, configurable via
    // [auth.sessions].revoke_on_credential_change).
    let revoke_existing_sessions = state.config_arc().auth.sessions.revoke_on_credential_change;
    let {snake_name}_id = {snake_name}.id;
    (*db)
        .transaction::<_, diesel::result::Error, _>(async move |conn| {{
            diesel::update({table}::table.find({snake_name}_id))
                .set((
                    {table}::password_digest.eq(&new_digest),
                    {table}::reset_token_digest.eq(None::<String>),
                    {table}::reset_token_expires_at.eq(None::<chrono::NaiveDateTime>),
                ))
                .execute(conn)
                .await?;
            // Revoke before inserting so the bulk delete cannot eat the
            // fresh row.
            if revoke_existing_sessions {{
                diesel::delete(
                    {sess_table}::table.filter({sess_table}::user_id.eq({snake_name}_id)),
                )
                .execute(conn)
                .await?;
            }}
            // Persistent remember-me chains are ALWAYS revoked on a credential
            // change (issue #1397): the old password is compromised, so a
            // replayed remember cookie must not re-establish a session — it will
            // find no row and be rejected.
            diesel::delete(
                {rem_table}::table.filter({rem_table}::user_id.eq({snake_name}_id)),
            )
            .execute(conn)
            .await?;
            diesel::insert_into({sess_table}::table)
                .values(&new_session_row)
                .execute(conn)
                .await?;
{magic_link_reset_password_clear}            Ok(())
        }})
        .await
        .map_err(|e| {{
            AutumnError::internal_server_error_msg(format!("Failed to reset password: {{e}}"))
        }})?;

{totp_clear_pending}    session.insert("{snake_name}_id", {snake_name}.id.to_string()).await;
    session.insert("{snake_name}_email", &{snake_name}.email).await;
    // Use the same session key checked by `#[secured]` / `#[authorize]`.
    session.insert(state.auth_session_key(), {snake_name}.id.to_string()).await;
    // Stamp the step-up claim so `#[step_up]` routes are immediately accessible.
    autumn_web::step_up::set_last_strong_auth_at(&session).await;
    Ok(redirect_to("/account"))
}}

// ── Helpers ───────────────────────────────────────────────────────────────────

/// Generate a 32-byte cryptographically-random reset token, hex-encoded.
fn generate_reset_token() -> String {{
    use rand::TryRng;
    let mut bytes = [0u8; 32];
    rand::rngs::SysRng
        .try_fill_bytes(&mut bytes)
        .expect("OS RNG failed");
    hex::encode(bytes)
}}

/// SHA-256 hex digest of `input` using the `sha2` crate.
fn sha256_hex(input: &str) -> String {{
    use sha2::{{Digest, Sha256}};
    let hash = Sha256::digest(input.as_bytes());
    hex::encode(hash)
}}

/// Send a password-reset email via the Autumn mailer.
///
/// # Errors
/// Returns a clear `AutumnError::internal` message when mail is not configured
/// (`transport = "disabled"`) or when the send itself fails.
async fn send_reset_email(mailer: &Mailer, to: &str, token: &str) -> AutumnResult<()> {{
    if mailer.is_disabled() {{
        return Err(AutumnError::internal_server_error_msg(
            "Password reset requires mail to be configured. \
             Set [mail] transport in autumn.toml (e.g. transport = \"smtp\"). \
             The forgot-password feature is unavailable until mail is set up.",
        ));
    }}
    // APP_BASE_URL must be set to the public URL of your app (e.g. https://example.com).
    let base_url = std::env::var("APP_BASE_URL")
        .unwrap_or_else(|_| "http://localhost:3000".to_owned());
    let reset_url = format!("{{base_url}}/reset-password?token={{token}}");
    let mail = Mail::builder()
        .to(to.to_owned())
        .subject("Reset your password")
        .html(html! {{
            p {{ "Click the link below to reset your password." }}
            p {{ "This link expires in 2 hours." }}
            p {{ a href=(&reset_url) {{ "Reset Password" }} }}
            p {{ "If you did not request this, you can safely ignore this email." }}
        }})
        .text(format!(
            "Reset your password: {{reset_url}}\n\
             This link expires in 2 hours.\n\
             If you did not request this you can safely ignore this email."
        ))
        .build()
        .map_err(|e| {{
            AutumnError::internal_server_error_msg(format!(
                "Failed to build password-reset email: {{e}}"
            ))
        }})?;
    mailer.send(mail).await.map_err(|e| {{
        AutumnError::internal_server_error_msg(format!(
            "Failed to send password-reset email: {{e}}"
        ))
    }})
}}

// ── Email Confirmation ────────────────────────────────────────────────────────

/// `GET /check-your-email` — shown after signup while awaiting email confirmation.
#[get("/check-your-email")]
pub async fn check_your_email(flash: Flash) -> AutumnResult<Markup> {{
    Ok(crate::layout("Check Your Email", "/check-your-email", flash_messages(&flash.consume().await), html! {{
        h1 {{ "Check Your Email" }}
        p {{ "We've sent a confirmation link to your email address." }}
        p {{ "Please click the link in the email to activate your account. The link expires in 24 hours." }}
        p {{ a href="/auth/confirm/resend" {{ "Didn't receive it? Resend confirmation email" }} }}
        p {{ a href="/login" {{ "Back to login" }} }}
    }}))
}}

#[derive(Deserialize)]
pub struct ConfirmEmailPath {{
    pub token: String,
}}

/// `GET /auth/confirm/{{token}}` — validate the confirmation token and mark the
/// account as confirmed.
///
/// On a valid unexpired token: stamps `email_confirmed_at`, invalidates the
/// token (single-use), and grants an authenticated session.
/// On an invalid or expired token: returns a non-revealing 422 with a
/// "request a new confirmation email" page.
///
/// Only the SHA-256 digest is stored; the raw token only exists in the email
/// and the user's URL bar — never in the database, logs, or error reports.
#[get("/auth/confirm/{{token}}")]
pub async fn confirm_email(
    mut db: Db,
    State(state): State<AppState>,
    session: Session,
    MaybeClientIp(addr_ip): MaybeClientIp,
    headers: axum::http::HeaderMap,
    Path(params): Path<ConfirmEmailPath>,
) -> AutumnResult<Response> {{
    let token_digest = sha256_hex(&params.token);
    let now = chrono::Utc::now().naive_utc();

    // Atomic UPDATE…RETURNING: filter, stamp, and invalidate in a single
    // statement so concurrent requests with the same token cannot both
    // succeed — the second UPDATE matches zero rows and returns an error.
    let {snake_name}: {pascal_name} = diesel::update(
        {table}::table
            .filter({table}::confirm_token_digest.eq(Some(&token_digest)))
            .filter({table}::confirm_token_expires_at.gt(now))
            // Disambiguate from an email-CHANGE token, which shares the
            // `confirm_token_digest` column but sets `pending_email`. Without this
            // reverse guard a change-email token could satisfy this signup-confirm
            // UPDATE — consuming it, stamping `email_confirmed_at`, orphaning
            // `pending_email`, and minting an unintended session (mirror of the
            // `pending_email.is_not_null()` guard in `confirm_email_change`).
            .filter({table}::pending_email.is_null()),
    )
    .set((
        {table}::email_confirmed_at.eq(Some(now)),
        {table}::confirm_token_digest.eq(None::<String>),
        {table}::confirm_token_expires_at.eq(None::<chrono::NaiveDateTime>),
    ))
    .returning({pascal_name}::as_returning())
    .get_result(&mut *db)
    .await
    .map_err(|_| {{
        AutumnError::unprocessable_msg(
            "This confirmation link is invalid or has expired. \
             Please request a new confirmation email.",
        )
    }})?;

    // This browser may already hold a tracked session for another account.
    // The rotation below (or inside the 2FA branch) destroys that session
    // id, so drop its row now — otherwise it would linger as a phantom device.
    untrack_current_session(&mut db, &session).await?;

    // For 2FA-enabled accounts, redirect to /login/verify before granting a
    // full session — email confirmation proves address ownership, not TOTP possession.
{totp_confirm_branch}    // Grant an authenticated session on confirmation.
    session.rotate_id().await;
    // Discard any step-up claim that may have carried over from a previous
    // login in this browser — email confirmation proves inbox access, not
    // password knowledge, so it must not inherit sudo-mode freshness.
    session.remove(autumn_web::step_up::STEP_UP_SESSION_KEY).await;
{totp_clear_pending}    session.insert("{snake_name}_id", {snake_name}.id.to_string()).await;
    session.insert("{snake_name}_email", &{snake_name}.email).await;
    // Use the same session key checked by `#[secured]` / `#[authorize]`.
    session.insert(state.auth_session_key(), {snake_name}.id.to_string()).await;
    // Track this login as an active session (device list + revocation).
    record_login_session(&mut db, &session, {snake_name}.id, addr_ip, &headers).await?;
    // Step-up protected routes will redirect to /reauth as designed.
    Ok(redirect_to("/account"))
}}

/// `GET /auth/confirm/resend` — render the resend-confirmation form.
#[get("/auth/confirm/resend")]
pub async fn resend_confirmation_form(
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Markup> {{
    Ok(crate::layout("Resend Confirmation Email", "/auth/confirm/resend", html! {{}}, html! {{
        h1 {{ "Resend Confirmation Email" }}
        form action="/auth/confirm/resend" method="post" {{
            @if let Some(ref csrf) = csrf {{ input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }}
            div {{
                label for="email" {{ "Email" }}
                input type="email" id="email" name="email" required autocomplete="email";
            }}
            button type="submit" {{ "Resend Confirmation Email" }}
        }}
        p {{ a href="/login" {{ "Back to login" }} }}
    }}))
}}

#[derive(Deserialize)]
pub struct ResendConfirmationForm {{
    pub email: String,
}}

/// `POST /auth/confirm/resend` — generate a new confirmation token and email it.
///
/// Non-enumerating: always returns the same "check your email" page regardless
/// of whether the address is registered or already confirmed, so callers cannot
/// learn which addresses exist. Resending invalidates the previous outstanding
/// token for the account (single-outstanding-token invariant).
/// Rate-limited per-account via Autumn's existing rate limiter.
#[post("/auth/confirm/resend")]
pub async fn resend_confirmation(
    mut db: Db,
    mailer: Mailer,
    Form(form): Form<ResendConfirmationForm>,
) -> AutumnResult<Markup> {{
    if mailer.is_disabled() {{
        return Err(AutumnError::internal_server_error_msg(
            "Email confirmation requires mail to be configured. \
             Set [mail] transport in autumn.toml (e.g. transport = \"log\" for dev). \
             The confirmation feature is unavailable until mail is set up.",
        ));
    }}

    let email = form.email.trim().to_lowercase();
    let t0 = std::time::Instant::now();

    // Throttle: skip re-issue if a token was minted in the last 5 minutes
    // (expires_at would still be > 23h55m from now).  Non-enumerating.
    let throttle_threshold = chrono::Utc::now().naive_utc() + chrono::Duration::minutes(23 * 60 + 55);

    // Check eligibility before generating a new token.  We send the email
    // FIRST and only overwrite the stored token on success — so a transient
    // mail failure leaves the previous (still-valid) token intact rather than
    // invalidating it without delivering a replacement.
    let eligible: bool = {table}::table
        .filter({table}::email.eq(&email))
        .filter({table}::email_confirmed_at.is_null())
        .filter(
            {table}::confirm_token_expires_at
                .is_null()
                .or({table}::confirm_token_expires_at.le(throttle_threshold)),
        )
        .count()
        .get_result::<i64>(&mut *db)
        .await
        .unwrap_or(0)
        > 0;

    if eligible {{
        let raw_confirm_token = generate_confirmation_token();
        let confirm_digest = sha256_hex(&raw_confirm_token);
        let confirm_expires_at = chrono::Utc::now().naive_utc() + chrono::Duration::hours(24);

        match send_confirmation_email(&mailer, &email, &raw_confirm_token).await {{
            Ok(()) => {{
                // Email delivered — now atomically overwrite the stored token.
                let _ = diesel::update(
                    {table}::table
                        .filter({table}::email.eq(&email))
                        .filter({table}::email_confirmed_at.is_null()),
                )
                .set((
                    {table}::confirm_token_digest.eq(Some(&confirm_digest)),
                    {table}::confirm_token_expires_at.eq(Some(confirm_expires_at)),
                ))
                .execute(&mut *db)
                .await;
            }}
            Err(e) => {{
                // Previous token is preserved — warn but remain non-enumerating.
                tracing::warn!("confirmation email failed on resend: {{e}}");
            }}
        }}
    }}

    // Pad to a constant minimum so hit and miss paths take indistinguishable time.
    if let Some(remaining) = std::time::Duration::from_secs(1).checked_sub(t0.elapsed()) {{
        tokio::time::sleep(remaining).await;
    }}

    Ok(crate::layout("Confirmation Email Sent", "/auth/confirm/resend", html! {{}}, html! {{
        h1 {{ "Check Your Email" }}
        p {{
            "If that address has a pending unconfirmed account, you'll receive a new \
             confirmation link shortly."
        }}
        p {{ a href="/login" {{ "Back to login" }} }}
    }}))
}}

/// Generate a 32-byte cryptographically-random confirmation token, hex-encoded.
fn generate_confirmation_token() -> String {{
    use rand::TryRng;
    let mut bytes = [0u8; 32];
    rand::rngs::SysRng
        .try_fill_bytes(&mut bytes)
        .expect("OS RNG failed");
    hex::encode(bytes)
}}

/// Send a confirmation email via the Autumn mailer.
async fn send_confirmation_email(mailer: &Mailer, to: &str, token: &str) -> AutumnResult<()> {{
    let base_url = std::env::var("APP_BASE_URL")
        .unwrap_or_else(|_| "http://localhost:3000".to_owned());
    let confirm_url = format!("{{base_url}}/auth/confirm/{{token}}");
    let mail = Mail::builder()
        .to(to.to_owned())
        .subject("Confirm your email address")
        .html(html! {{
            p {{ "Click the link below to confirm your email address and activate your account." }}
            p {{ "This link expires in 24 hours." }}
            p {{ a href=(&confirm_url) {{ "Confirm Email Address" }} }}
            p {{ "If you did not create an account, you can safely ignore this email." }}
        }})
        .text(format!(
            "Confirm your email address: {{confirm_url}}\n\
             This link expires in 24 hours.\n\
             If you did not create an account, you can safely ignore this email."
        ))
        .build()
        .map_err(|e| {{
            AutumnError::internal_server_error_msg(format!(
                "Failed to build confirmation email: {{e}}"
            ))
        }})?;
    mailer.send(mail).await.map_err(|e| {{
        AutumnError::internal_server_error_msg(format!(
            "Failed to send confirmation email: {{e}}"
        ))
    }})
}}

// ── GDPR: Data Export & Account Deletion (Issue #820) ─────────────────────────
//
// These routes satisfy GDPR Article 15 (right of access) and Article 17
// (right to erasure) obligations. Edit freely — all logic is app code.

/// `GET /account/data-export` — "Download my data" request form.
///
/// The authenticated user may request a full data archive. The request is
/// recorded and a background job is enqueued to build the archive and email
/// a signed download link.
#[get("/account/data-export")]
pub async fn data_export_form(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Response> {{
    // Validates the tracked session row (401s immediately if revoked).
    let _ = require_tracked_session(&session, &mut db, &state).await?;
    Ok(crate::layout("Download My Data", "/account/data-export", html! {{}}, html! {{
        h1 {{ "Download My Data" }}
        p {{
            "Request a copy of all data we hold about you. You will receive an email \
             with a secure download link when the archive is ready (usually within a few minutes)."
        }}
        form action="/account/data-export" method="post" {{
            @if let Some(ref csrf) = csrf {{
                input type="hidden"
                    name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str()))
                    value=(csrf.token());
            }}
            button type="submit" {{ "Request My Data Archive" }}
        }}
        p {{ a href="/account" {{ "← Back to account" }} }}
    }}).into_response())
}}

/// `POST /account/data-export` — enqueue the export job (GDPR Article 15).
///
/// Stamps `export_requested_at` and enqueues a `data_export_job` that builds
/// a JSON archive and emails a signed download link via the configured mailer.
/// The job is idempotent: a second request within the same hour is a no-op.
#[post("/account/data-export")]
pub async fn data_export(
    session: Session,
    mut db: Db,
    State(state): State<AppState>,
) -> AutumnResult<Response> {{
    let {snake_name}_id: i64 = require_tracked_session(&session, &mut db, &state).await?.id;

    let mailer = state.extension::<Mailer>();
    let now = chrono::Utc::now().naive_utc();
    let one_hour_ago = now - chrono::Duration::hours(1);

    // Idempotency: only update (and enqueue) if no export was requested in the last hour.
    let updated = diesel::update({table}::table.find({snake_name}_id))
        .filter(
            {table}::export_requested_at
                .is_null()
                .or({table}::export_requested_at.lt(Some(one_hour_ago))),
        )
        .set({table}::export_requested_at.eq(Some(now)))
        .execute(&mut *db)
        .await
        .map_err(|_| AutumnError::internal_server_error_msg("Failed to record export request."))?;

    if updated == 0 {{
        return Ok(crate::layout("Export Already Pending", "/account/data-export", html! {{}}, html! {{
            h1 {{ "Export Already Pending" }}
            p {{
                "A data export was already requested within the last hour. \
                 Please check your email or try again later."
            }}
            p {{ a href="/account" {{ "← Back to account" }} }}
        }}).into_response());
    }}

    // Enqueue the background export job.
    enqueue_data_export_job(&state, {snake_name}_id, mailer.as_deref()).await;

    autumn_web::audit::write_from_state(
        &state,
        autumn_web::audit::AuditEvent::new(
            {snake_name}_id.to_string(),
            "gdpr.export.requested",
            {snake_name}_id.to_string(),
            None,
            autumn_web::audit::AuditStatus::Success,
        ),
    )
    .await
    .ok();

    Ok(crate::layout("Export Requested", "/account/data-export", html! {{}}, html! {{
        h1 {{ "Export Requested" }}
        p {{
            "Your data export is being prepared. You will receive an email with a \
             secure download link when it is ready."
        }}
        p {{ a href="/account" {{ "← Back to account" }} }}
    }}).into_response())
}}

/// Background export job: build the JSON archive and email a signed link.
///
/// In production, move this to a dedicated `src/jobs/data_export.rs` file and
/// register it with `autumn_web::job::JobClient`. For now it is a plain async
/// function invoked inline so the starter compiles without a job backend.
async fn enqueue_data_export_job(
    state: &AppState,
    {snake_name}_id: i64,
    mailer: Option<&Mailer>,
) {{
    // TODO: Replace with state.jobs().enqueue("data_export_job", payload).await
    // when a job backend is configured. This inline stub satisfies the starter
    // without requiring a running Redis/Postgres job queue.
    let _ = (state, {snake_name}_id, mailer);
    tracing::info!(
        user_id = {snake_name}_id,
        "data_export_job enqueued (stub — wire up JobClient for production)"
    );
}}

#[derive(Deserialize)]
pub struct DeleteAccountForm {{
    /// User must type "DELETE" to confirm the irreversible operation.
    pub confirmation: String,
}}

/// `GET /account/delete` — account deletion confirmation form.
///
/// Requires a confirmation step: the user types "DELETE" before submitting,
/// reducing accidental deletions.
#[get("/account/delete")]
pub async fn delete_account_form(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Response> {{
    // Validates the tracked session row (401s immediately if revoked).
    let _ = require_tracked_session(&session, &mut db, &state).await?;
    Ok(crate::layout("Delete My Account", "/account/delete", html! {{}}, html! {{
        h1 {{ "Delete My Account" }}
        p class="warning" {{
            "⚠️ This action schedules your account for permanent deletion after a \
             30-day grace period. You may cancel during the grace period by logging in."
        }}
        p {{
            "All data we hold about you will be erased. Data we are legally required \
             to retain (e.g. financial records) will be anonymized or held under legal-hold \
             with the reason documented in our audit log."
        }}
        form action="/account/delete" method="post" {{
            @if let Some(ref csrf) = csrf {{
                input type="hidden"
                    name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str()))
                    value=(csrf.token());
            }}
            div {{
                label for="confirmation" {{ "Type DELETE to confirm:" }}
                input type="text" id="confirmation" name="confirmation"
                    placeholder="DELETE" autocomplete="off" required;
            }}
            button type="submit" {{ "Schedule Account Deletion" }}
        }}
        p {{ a href="/account" {{ "← Back to account" }} }}
    }}).into_response())
}}

/// `POST /account/delete` — schedule account for deletion (GDPR Article 17).
///
/// Records `delete_requested_at` and `delete_scheduled_at` (30-day grace period)
/// then writes an audit log entry. A background sweeper handles the hard-delete
/// once the grace period expires. The user is logged out immediately.
#[secured]
#[step_up]
#[post("/account/delete")]
pub async fn delete_account(
    session: Session,
    mut db: Db,
    State(state): State<AppState>,
    axum::Form(form): axum::Form<DeleteAccountForm>,
) -> AutumnResult<Response> {{
    let {snake_name}_id: i64 = require_tracked_session(&session, &mut db, &state).await?.id;

    // Require the user to type DELETE as a confirmation step.
    if form.confirmation.trim() != "DELETE" {{
        return Ok(crate::layout("Delete My Account", "/account/delete", html! {{}}, html! {{
            h1 {{ "Delete My Account" }}
            p class="error" {{ "You must type DELETE (in uppercase) to confirm." }}
            p {{ a href="/account/delete" {{ "← Back" }} }}
        }}).into_response());
    }}

    let now = chrono::Utc::now().naive_utc();
    let grace_until = now + chrono::Duration::days(30);

    diesel::update({table}::table.find({snake_name}_id))
        .set((
            {table}::delete_requested_at.eq(Some(now)),
            {table}::delete_scheduled_at.eq(Some(grace_until)),
        ))
        .execute(&mut *db)
        .await
        .map_err(|_| AutumnError::internal_server_error_msg("Failed to schedule deletion."))?;

    autumn_web::audit::write_from_state(
        &state,
        autumn_web::audit::AuditEvent::new(
            {snake_name}_id.to_string(),
            "gdpr.erasure.requested",
            {snake_name}_id.to_string(),
            None,
            autumn_web::audit::AuditStatus::Success,
        ),
    )
    .await
    .ok();

    session.destroy().await;

    Ok(crate::layout("Deletion Scheduled", "/account/delete", html! {{}}, html! {{
        h1 {{ "Account Deletion Scheduled" }}
        p {{
            "Your account has been scheduled for deletion in 30 days. \
             You will receive a confirmation email."
        }}
        p {{
            "If you change your mind, log in within 30 days and visit \
             your account settings to cancel."
        }}
    }}).into_response())
}}

/// `POST /account/delete/cancel` — cancel a pending account deletion.
///
/// Clears the `delete_requested_at` / `delete_scheduled_at` columns and writes
/// an audit log entry. Returns an error if no deletion is pending or the grace
/// period has already elapsed.
#[secured]
#[post("/account/delete/cancel")]
pub async fn cancel_delete_account(
    session: Session,
    mut db: Db,
    State(state): State<AppState>,
) -> AutumnResult<Response> {{
    let {snake_name}_id: i64 = require_tracked_session(&session, &mut db, &state).await?.id;

    // Only cancel if a future deletion is scheduled; reject once the deadline has passed.
    let rows = diesel::update({table}::table.find({snake_name}_id))
        .filter({table}::delete_scheduled_at.gt(Some(chrono::Utc::now().naive_utc())))
        .set((
            {table}::delete_requested_at.eq(None::<chrono::NaiveDateTime>),
            {table}::delete_scheduled_at.eq(None::<chrono::NaiveDateTime>),
        ))
        .execute(&mut *db)
        .await
        .map_err(|_| AutumnError::internal_server_error_msg("Failed to cancel deletion."))?;

    if rows == 0 {{
        return Err(AutumnError::unprocessable_msg(
            "No pending deletion found, or the grace period has already elapsed.",
        ));
    }}

    autumn_web::audit::write_from_state(
        &state,
        autumn_web::audit::AuditEvent::new(
            {snake_name}_id.to_string(),
            "gdpr.erasure.cancelled",
            {snake_name}_id.to_string(),
            None,
            autumn_web::audit::AuditStatus::Success,
        ),
    )
    .await
    .ok();

    Ok(redirect_to("/account").into_response())
}}

// ── Admin GDPR Operations (Issue #820 AC#6) ───────────────────────────────────
//
// These routes allow an admin operator to trigger export or erasure on behalf
// of a user. All operations are fully audited with actor, reason, and timestamp.
// Mount behind your admin authentication middleware.

#[derive(Deserialize)]
pub struct AdminGdprActionForm {{
    /// Free-text reason recorded in the audit log (required for compliance).
    pub reason: String,
}}

/// `POST /admin/{table}/{{id}}/data-export` — admin triggers data export for a user.
///
/// Stamps `export_requested_at` and enqueues the export job.
/// Records `actor_id` (the operator) + `reason` in the audit log.
/// Requires the caller to have the `"admin"` role in their session.
#[secured("admin")]
#[post("/admin/{table}/{{id}}/data-export")]
pub async fn admin_data_export(
    Path(user_id): Path<i64>,
    session: Session,
    mut db: Db,
    State(state): State<AppState>,
    axum::Form(form): axum::Form<AdminGdprActionForm>,
) -> AutumnResult<Response> {{
    let operator_id: String = session
        .get("{snake_name}_id")
        .await
        .ok_or_else(|| AutumnError::unauthorized_msg("Admin access required."))?;

    if form.reason.trim().is_empty() {{
        return Err(AutumnError::unprocessable_msg("Reason is required for admin GDPR actions."));
    }}

    let mailer = state.extension::<Mailer>();

    let now = chrono::Utc::now().naive_utc();
    let updated = diesel::update({table}::table.find(user_id))
        .set({table}::export_requested_at.eq(Some(now)))
        .execute(&mut *db)
        .await
        .map_err(|_| AutumnError::internal_server_error_msg("Failed to record export request."))?;

    if updated == 0 {{
        return Err(AutumnError::not_found_msg("User not found."));
    }}

    enqueue_data_export_job(&state, user_id, mailer.as_deref()).await;

    autumn_web::audit::write_from_state(
        &state,
        autumn_web::audit::AuditEvent::new(
            operator_id,
            format!("gdpr.export.admin_triggered reason={{}}", form.reason),
            user_id.to_string(),
            None,
            autumn_web::audit::AuditStatus::Success,
        ),
    )
    .await
    .ok();

    Ok(redirect_to(&format!("/admin/{table}/{{user_id}}")).into_response())
}}

/// `POST /admin/{table}/{{id}}/delete` — admin triggers account erasure for a user.
///
/// Schedules the account for deletion (30-day grace period).
/// Records `actor_id` (the operator), `reason`, and timestamp in the audit log.
/// Requires the caller to have the `"admin"` role in their session.
#[secured("admin")]
#[post("/admin/{table}/{{id}}/delete")]
pub async fn admin_delete_account(
    Path(user_id): Path<i64>,
    session: Session,
    mut db: Db,
    State(state): State<AppState>,
    axum::Form(form): axum::Form<AdminGdprActionForm>,
) -> AutumnResult<Response> {{
    let operator_id: String = session
        .get("{snake_name}_id")
        .await
        .ok_or_else(|| AutumnError::unauthorized_msg("Admin access required."))?;

    if form.reason.trim().is_empty() {{
        return Err(AutumnError::unprocessable_msg("Reason is required for admin GDPR actions."));
    }}

    let now = chrono::Utc::now().naive_utc();
    let grace_until = now + chrono::Duration::days(30);

    let updated = diesel::update({table}::table.find(user_id))
        .set((
            {table}::delete_requested_at.eq(Some(now)),
            {table}::delete_scheduled_at.eq(Some(grace_until)),
        ))
        .execute(&mut *db)
        .await
        .map_err(|_| AutumnError::internal_server_error_msg("Failed to schedule deletion."))?;

    if updated == 0 {{
        return Err(AutumnError::not_found_msg("User not found."));
    }}

    autumn_web::audit::write_from_state(
        &state,
        autumn_web::audit::AuditEvent::new(
            operator_id,
            format!("gdpr.erasure.admin_triggered reason={{}}", form.reason),
            user_id.to_string(),
            None,
            autumn_web::audit::AuditStatus::Success,
        ),
    )
    .await
    .ok();

    Ok(redirect_to(&format!("/admin/{table}/{{user_id}}")).into_response())
}}
{totp_section}{magic_link_section}"##
    )
}

#[allow(clippy::too_many_lines)]
fn render_tests_file(pascal_name: &str, _snake_name: &str, magic_link: bool) -> String {
    // Passwordless magic-link live-DB integration test (issue #1328, AC7).
    // Emitted only under `--magic-link`; `#[ignore]`d so it compiles and passes
    // out of the box, like the sibling live-DB tests in this file.
    let magic_link_tests = if magic_link {
        MAGIC_LINK_TESTS_SECTION
    } else {
        ""
    };
    format!(
        r#"//! Request-level smoke tests for {pascal_name} auth, generated by `autumn generate auth`.
//!
//! These tests run against a live server started with `AUTUMN_TEST_BASE_URL`.
//! In CI, start the app, set the env var, and run `cargo test`.
//!
//! Each test uses a raw TCP connection to avoid adding an HTTP client dep;
//! replace with your preferred HTTP client once it is in `Cargo.toml`.

use std::io::{{Read, Write}};
use std::net::TcpStream;

fn base_url() -> Option<String> {{
    std::env::var("AUTUMN_TEST_BASE_URL").ok()
}}

fn host_port(base: &str) -> String {{
    base.trim_start_matches("http://")
        .trim_start_matches("https://")
        .to_owned()
}}

fn get(base: &str, path: &str) -> String {{
    let hp = host_port(base);
    let mut stream =
        TcpStream::connect(&hp).unwrap_or_else(|_| panic!("cannot connect to {{base}}"));
    let req = format!("GET {{path}} HTTP/1.1\r\nHost: {{hp}}\r\nConnection: close\r\n\r\n");
    stream.write_all(req.as_bytes()).expect("write failed");
    let mut resp = String::new();
    stream.read_to_string(&mut resp).expect("read failed");
    resp
}}

fn post_form(base: &str, path: &str, body: &str, cookie: &str) -> String {{
    let hp = host_port(base);
    let mut stream =
        TcpStream::connect(&hp).unwrap_or_else(|_| panic!("cannot connect to {{base}}"));
    let req = format!(
        "POST {{path}} HTTP/1.1\r\n\
         Host: {{hp}}\r\n\
         Content-Type: application/x-www-form-urlencoded\r\n\
         Content-Length: {{}}\r\n\
         Cookie: {{cookie}}\r\n\
         Connection: close\r\n\r\n\
         {{body}}",
        body.len()
    );
    stream.write_all(req.as_bytes()).expect("write failed");
    let mut resp = String::new();
    stream.read_to_string(&mut resp).expect("read failed");
    resp
}}

/// Cookie-aware GET (the bare `get` above sends no `Cookie` header). Used by the
/// live-DB end-to-end tests that must replay an authenticated session.
fn get_auth(base: &str, path: &str, cookie: &str) -> String {{
    let hp = host_port(base);
    let mut stream =
        TcpStream::connect(&hp).unwrap_or_else(|_| panic!("cannot connect to {{base}}"));
    let req = format!(
        "GET {{path}} HTTP/1.1\r\n\
         Host: {{hp}}\r\n\
         Cookie: {{cookie}}\r\n\
         Connection: close\r\n\r\n"
    );
    stream.write_all(req.as_bytes()).expect("write failed");
    let mut resp = String::new();
    stream.read_to_string(&mut resp).expect("read failed");
    resp
}}

/// Extract the session cookie (`name=value`) from a `Set-Cookie` header.
fn session_cookie(resp: &str) -> Option<String> {{
    resp.lines()
        .filter(|l| l.to_ascii_lowercase().starts_with("set-cookie:"))
        .filter_map(|l| l.splitn(2, ':').nth(1))
        .map(|v| v.split(';').next().unwrap_or("").trim().to_owned())
        .find(|c| !c.is_empty())
}}

/// A process-unique suffix so each live-DB test operates on a fresh account.
fn unique_suffix() -> String {{
    use std::time::{{SystemTime, UNIX_EPOCH}};
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    format!("{{nanos}}")
}}

/// Strip `scheme://host` from a URL, returning just the path (plus any query).
fn url_path(url: &str) -> String {{
    if let Some(idx) = url.find("://") {{
        let after = &url[idx + 3..];
        match after.find('/') {{
            Some(p) => after[p..].to_owned(),
            None => "/".to_owned(),
        }}
    }} else {{
        url.to_owned()
    }}
}}

/// Read captured mail from a file-based transport and return the first URL
/// containing `marker` (newest message first). Point `AUTUMN_TEST_MAILDIR` at the
/// transport's output directory (e.g. `[mail] transport = "file"`); returns
/// `None` when unset or no match is found.
fn mail_link(marker: &str) -> Option<String> {{
    let dir = std::env::var("AUTUMN_TEST_MAILDIR").ok()?;
    let mut entries: Vec<_> = std::fs::read_dir(&dir).ok()?.filter_map(Result::ok).collect();
    // Scan newest file first so we pick up the most recently delivered message.
    entries.sort_by_key(|e| e.metadata().and_then(|m| m.modified()).ok());
    entries.reverse();
    for entry in entries {{
        let Ok(body) = std::fs::read_to_string(entry.path()) else {{
            continue;
        }};
        if let Some(idx) = body.find(marker) {{
            let start = body[..idx].rfind("http").unwrap_or(idx);
            let tail = &body[start..];
            let end = tail
                .find(|c: char| c.is_whitespace() || c == '"' || c == '<' || c == '\'')
                .unwrap_or(tail.len());
            return Some(tail[..end].to_owned());
        }}
    }}
    None
}}

/// Sign up an account and confirm it by GETting the confirmation link captured
/// from the file mail transport, leaving it ready to sign in.
fn signup_and_confirm(base: &str, email: &str, password: &str) {{
    let body = format!("email={{email}}&password={{password}}");
    post_form(base, "/signup", &body, "");
    if let Some(url) = mail_link("/auth/confirm/") {{
        let _ = get(base, &url_path(&url));
    }}
}}

/// Log in and return the authenticated session cookie. Panics on failure.
fn login(base: &str, email: &str, password: &str) -> String {{
    let body = format!("email={{email}}&password={{password}}");
    let resp = post_form(base, "/login", &body, "");
    assert!(
        resp.contains("HTTP/1.1 30") || resp.contains("HTTP/1.0 30"),
        "login did not redirect — is the account confirmed?\n{{resp}}"
    );
    session_cookie(&resp).expect("login response missing Set-Cookie")
}}

#[test]
fn auth_signup_returns_200() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let resp = get(&base, "/signup");
    assert!(
        resp.starts_with("HTTP/1.1 200") || resp.starts_with("HTTP/1.0 200"),
        "GET /signup did not return 200:\n{{resp}}"
    );
}}

#[test]
fn auth_login_returns_200() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let resp = get(&base, "/login");
    assert!(
        resp.starts_with("HTTP/1.1 200") || resp.starts_with("HTTP/1.0 200"),
        "GET /login did not return 200:\n{{resp}}"
    );
}}

#[test]
fn auth_logout_redirects() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let resp = post_form(&base, "/logout", "", "");
    assert!(
        resp.contains("HTTP/1.1 30") || resp.contains("HTTP/1.0 30"),
        "POST /logout did not redirect:\n{{resp}}"
    );
}}

#[test]
fn auth_forgot_password_returns_200() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let resp = get(&base, "/forgot-password");
    assert!(
        resp.starts_with("HTTP/1.1 200") || resp.starts_with("HTTP/1.0 200"),
        "GET /forgot-password did not return 200:\n{{resp}}"
    );
}}

#[test]
fn auth_reset_password_returns_200() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let resp = get(&base, "/reset-password?token=dummy");
    assert!(
        resp.starts_with("HTTP/1.1 200") || resp.starts_with("HTTP/1.0 200"),
        "GET /reset-password did not return 200:\n{{resp}}"
    );
}}

#[test]
fn auth_account_rejects_anonymous() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    // Without a session cookie, /account must reject with 401 or redirect.
    let resp = get(&base, "/account");
    let is_rejected = resp.contains("HTTP/1.1 401")
        || resp.contains("HTTP/1.0 401")
        || resp.contains("HTTP/1.1 30")
        || resp.contains("HTTP/1.0 30");
    assert!(
        is_rejected,
        "GET /account should reject anonymous requests (expected 401 or redirect):\n{{resp}}"
    );
}}

// ── Account lockout tests ─────────────────────────────────────────────────────
//
// These tests verify the lockout policy required by issue #814.
// They run against a live server like the tests above; set AUTUMN_TEST_BASE_URL.
//
// Each lockout test creates its own account via POST /signup before running
// so the tests are self-contained against a fresh database — no pre-seeding needed.

/// Sign up an account and confirm it, making it ready for login in lockout tests.
///
/// Email confirmation is required before login. This helper creates the account
/// and then confirms it by reading the confirmation URL from the mail log (requires
/// `[mail] transport = "log"` in `autumn.toml` and access to the server's stdout).
///
/// For CI: run the server with `transport = "log"`, capture stdout, extract the
/// `/auth/confirm/...` URL from the log, and GET it before running lockout tests.
/// Alternatively seed the DB directly (replace `users` with your table name):
/// ```sql
/// UPDATE users SET email_confirmed_at = NOW() WHERE email = 'your-test@example.com';
/// ```
fn ensure_account(base: &str, email: &str, password: &str) {{
    let body = format!("email={{email}}&password={{password}}");
    // Creates the account (unconfirmed). The test must also confirm the account
    // before exercising login — see the doc comment above for options.
    post_form(base, "/signup", &body, "");
}}

/// AC8a — N+1 failed attempts within the window cause the next attempt with
/// correct credentials to be rejected.
///
/// Scenario: sign up an account, submit threshold bad-password POSTs, then
/// submit one more POST with the correct password. The final attempt must be
/// rejected (same 422 body as wrong password) because the account is now locked.
///
/// Set `AUTUMN_AUTH__LOCKOUT__THRESHOLD=10` (the default) to run against the
/// standard policy.
#[test]
fn auth_lockout_rejects_correct_credentials() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let email = "lockout-test@example.com";
    let password = "correct-password-L0ck";
    ensure_account(&base, email, password);
    let bad_body = format!("email={{email}}&password=wrong-password");
    // Exhaust the threshold (default 10) with wrong passwords.
    for _ in 0..10 {{
        post_form(&base, "/login", &bad_body, "");
    }}
    // The next attempt with the CORRECT password must still be rejected.
    let correct_body = format!("email={{email}}&password={{password}}");
    let resp = post_form(&base, "/login", &correct_body, "");
    assert!(
        resp.contains("HTTP/1.1 422") || resp.contains("HTTP/1.0 422"),
        "locked account must reject correct credentials with 422:\n{{resp}}"
    );
}}

/// AC8b — a successful login before the threshold resets the failure counter.
///
/// Scenario: sign up an account, submit (threshold-1) bad-password POSTs, then
/// 1 correct-password POST (which succeeds and resets the counter), then
/// (threshold-1) more bad-password POSTs. The account must remain unlocked.
#[test]
fn auth_successful_login_resets_lockout_counter() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let email = "lockout-reset-test@example.com";
    let password = "correct-password-R3set";
    ensure_account(&base, email, password);
    let bad_body = format!("email={{email}}&password=wrong-password");
    let good_body = format!("email={{email}}&password={{password}}");
    // 5 failures (below default threshold of 10).
    for _ in 0..5 {{
        post_form(&base, "/login", &bad_body, "");
    }}
    // Successful login resets the counter.
    let good_resp = post_form(&base, "/login", &good_body, "");
    assert!(
        good_resp.contains("HTTP/1.1 302") || good_resp.contains("HTTP/1.0 302"),
        "correct credentials must succeed before lockout threshold:\n{{good_resp}}"
    );
    // 5 more failures (counter was reset, so still below threshold).
    for _ in 0..5 {{
        post_form(&base, "/login", &bad_body, "");
    }}
    // Should still be able to log in with correct credentials.
    let after_resp = post_form(&base, "/login", &good_body, "");
    assert!(
        after_resp.contains("HTTP/1.1 302") || after_resp.contains("HTTP/1.0 302"),
        "account must remain unlocked after counter was reset by successful login:\n{{after_resp}}"
    );
}}

/// AC8c — the locked-state response is byte-identical at the response-body
/// level to a wrong-password response (non-enumerating lockout).
#[test]
fn auth_lockout_response_identical_to_wrong_password() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let email_locked = "lockout-body-test@example.com";
    let password = "correct-password-B0dy";
    ensure_account(&base, email_locked, password);
    // Wrong-password response body for a non-locked known account.
    let wrong_resp = post_form(
        &base,
        "/login",
        &format!("email={{email_locked}}&password=wrong"),
        "",
    );
    let wrong_body = wrong_resp.splitn(2, "\r\n\r\n").nth(1).unwrap_or("");
    // Exhaust threshold to lock the target account.
    for _ in 0..9 {{
        post_form(
            &base,
            "/login",
            &format!("email={{email_locked}}&password=bad"),
            "",
        );
    }}
    // Locked-account response with correct password.
    let locked_resp = post_form(
        &base,
        "/login",
        &format!("email={{email_locked}}&password={{password}}"),
        "",
    );
    let locked_body = locked_resp.splitn(2, "\r\n\r\n").nth(1).unwrap_or("");
    assert_eq!(
        wrong_body, locked_body,
        "locked-state response body must be byte-identical to wrong-password response body\n\
         wrong:  {{wrong_body:?}}\n\
         locked: {{locked_body:?}}"
    );
}}

// ── Email confirmation tests (issue #823) ─────────────────────────────────────
//
// These tests verify the confirmation flow introduced alongside the signup
// changes. They run against a live server (set AUTUMN_TEST_BASE_URL).

/// AC1/AC5 — signing up creates an unconfirmed account; the user cannot log in
/// until they have clicked the confirmation link.
#[test]
fn signup_without_confirm_cannot_login() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let email = "unconfirmed-test@example.com";
    let password = "UnconfirmedPass1!";
    let signup_body = format!("email={{email}}&password={{password}}");
    let signup_resp = post_form(&base, "/signup", &signup_body, "");
    // Signup redirects to check-your-email, not to /account.
    assert!(
        signup_resp.contains("HTTP/1.1 30") || signup_resp.contains("HTTP/1.0 30"),
        "signup must redirect after account creation:\n{{signup_resp}}"
    );
    // Attempting to log in before confirming must fail.
    let login_body = format!("email={{email}}&password={{password}}");
    let login_resp = post_form(&base, "/login", &login_body, "");
    assert!(
        login_resp.contains("HTTP/1.1 422") || login_resp.contains("HTTP/1.0 422"),
        "unconfirmed account must be rejected on login with 422:\n{{login_resp}}"
    );
}}

/// AC2 — clicking a valid confirmation token marks the account confirmed and
/// grants an authenticated session.
#[test]
fn confirm_with_valid_token_can_login() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    // This test requires a real mail transport (e.g. transport = "log" or "file")
    // that captures outgoing messages so the confirmation URL can be extracted.
    //
    // Suggested implementation:
    //   1. POST /signup to create an unconfirmed account.
    //   2. Read the confirmation URL from the mail log / .eml file.
    //   3. GET /auth/confirm/<token> and assert HTTP 302 → /account.
    //   4. Assert the session is authenticated (e.g. GET /account → 200).
    //
    // See docs/guide/authentication.md for a full walkthrough.
    let _ = base;
    todo!(
        "implement confirm_with_valid_token_can_login: \
         capture the token from the mail transport log, \
         GET /auth/confirm/<token>, and assert 302 → /account"
    )
}}

/// AC4 — an expired confirmation token returns a non-revealing 422 and the
/// "request a new confirmation" page.
#[test]
fn confirm_with_expired_token_fails() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let resp = get(&base, "/auth/confirm/this-token-does-not-exist");
    assert!(
        resp.contains("HTTP/1.1 422") || resp.contains("HTTP/1.0 422"),
        "expired/invalid confirmation token must return 422:\n{{resp}}"
    );
}}

/// AC4 — replaying a used confirmation token returns a non-revealing failure
/// (the token is cleared on first use so the digest no longer exists).
#[test]
fn confirm_with_replayed_token_fails() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    // Use an obviously fake token — the handler must return 422, not 500 or 200.
    let resp = get(&base, "/auth/confirm/replayed-fake-token-that-was-used");
    assert!(
        resp.contains("HTTP/1.1 422") || resp.contains("HTTP/1.0 422"),
        "replayed confirmation token must return 422:\n{{resp}}"
    );
}}

/// AC6 — the resend-confirmation endpoint returns the same page regardless of
/// whether the address is known (non-enumerating); rate limiting is enforced
/// per-account by the framework's rate limiter.
#[test]
fn resend_confirmation_rate_limit() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let body = "email=noone%40example.com";
    // Unknown address — must return same 200 "check your email" page (non-enumerating).
    let resp = post_form(&base, "/auth/confirm/resend", body, "");
    assert!(
        resp.contains("HTTP/1.1 200") || resp.contains("HTTP/1.0 200"),
        "resend-confirmation must return 200 for unknown address:\n{{resp}}"
    );
}}

// ── Change password / change email (issue #1396) ──────────────────────────────

/// The authenticated change-password page is `#[secured]`, so an anonymous
/// request must be rejected (401) or redirected to sign in.
#[test]
fn change_password_page_requires_auth() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let resp = get(&base, "/account/password");
    let rejected = resp.contains("HTTP/1.1 401")
        || resp.contains("HTTP/1.0 401")
        || resp.contains("HTTP/1.1 30")
        || resp.contains("HTTP/1.0 30");
    assert!(rejected, "GET /account/password must reject anonymous requests:\n{{resp}}");
}}

/// The authenticated change-email page is `#[secured]`, so an anonymous request
/// must be rejected (401) or redirected to sign in.
#[test]
fn change_email_page_requires_auth() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let resp = get(&base, "/account/email");
    let rejected = resp.contains("HTTP/1.1 401")
        || resp.contains("HTTP/1.0 401")
        || resp.contains("HTTP/1.1 30")
        || resp.contains("HTTP/1.0 30");
    assert!(rejected, "GET /account/email must reject anonymous requests:\n{{resp}}");
}}

/// AC4 — an invalid/expired/unknown email-change token returns the same
/// non-revealing 422 (no oracle).
#[test]
fn email_change_confirm_invalid_token_fails() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let resp = get(&base, "/account/email/confirm/this-token-does-not-exist");
    assert!(
        resp.contains("HTTP/1.1 422") || resp.contains("HTTP/1.0 422"),
        "invalid email-change token must return 422:\n{{resp}}"
    );
}}

/// AC — end-to-end behaviour that requires a live database (start the app
/// against Postgres, set `AUTUMN_TEST_BASE_URL`, and a mail transport that
/// captures messages such as `transport = "log"` or `"file"`). Ignored by
/// default so `cargo test` is green out of the box; run with `-- --ignored`.
///
/// Full coverage of issue #1396's acceptance criteria:
///   1. Sign up + confirm + sign in on two browsers (two session cookies).
///   2. POST /account/password with the correct current password + a strong new
///      password (through /reauth for the step-up claim). Assert the OTHER
///      browser's session is now revoked (its next request 401s / redirects),
///      while the acting browser stays signed in.
///   3. POST /account/password with a WRONG current password → 422, and the
///      password is unchanged (the old one still signs in).
///   4. POST /account/email with a new address → the OLD address still signs in;
///      GET the confirmation link from the captured mail; after confirming, the
///      NEW address signs in and the old one no longer does.
///
/// See docs/guide/authentication.md for a full walkthrough.
#[test]
#[ignore = "requires a live database and a capturing mail transport"]
fn password_and_email_change_end_to_end() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};

    // A fresh, confirmed account (sign up, then GET the confirm link from mail).
    let suffix = unique_suffix();
    let email = format!("pw-change-{{suffix}}@example.com");
    let password = "correct-horse-Battery-1";
    signup_and_confirm(&base, &email, password);

    // ── (a) A successful password change invalidates OTHER sessions ──────────
    let cookie_a = login(&base, &email, password);
    let cookie_b = login(&base, &email, password);
    assert!(
        get_auth(&base, "/account", &cookie_a).contains(" 200"),
        "client A should start signed in"
    );
    assert!(
        get_auth(&base, "/account", &cookie_b).contains(" 200"),
        "client B should start signed in"
    );

    let new_password = "different-Zebra-2-quux";
    let change_body = format!(
        "current_password={{password}}\
         &new_password={{new_password}}\
         &new_password_confirmation={{new_password}}"
    );
    let change_resp = post_form(&base, "/account/password", &change_body, &cookie_a);
    assert!(
        change_resp.contains("HTTP/1.1 30") || change_resp.contains("HTTP/1.0 30"),
        "password change should redirect on success:\n{{change_resp}}"
    );
    // The acting client's session id is rotated on change; follow the new cookie.
    let cookie_a = session_cookie(&change_resp).unwrap_or(cookie_a);
    assert!(
        get_auth(&base, "/account", &cookie_a).contains(" 200"),
        "the acting client must stay signed in after the change"
    );
    // The OTHER client's next request is now unauthenticated (session revoked).
    let resp_b = get_auth(&base, "/account", &cookie_b);
    assert!(
        resp_b.contains("HTTP/1.1 401")
            || resp_b.contains("HTTP/1.0 401")
            || resp_b.contains("HTTP/1.1 30")
            || resp_b.contains("HTTP/1.0 30"),
        "the other session must be revoked by the password change:\n{{resp_b}}"
    );

    // ── (b) Wrong current password → 422, and the password is unchanged ──────
    let wrong_body = format!(
        "current_password=totally-wrong\
         &new_password=Another-Pass-3-xyz\
         &new_password_confirmation=Another-Pass-3-xyz"
    );
    let wrong_resp = post_form(&base, "/account/password", &wrong_body, &cookie_a);
    assert!(
        wrong_resp.contains("HTTP/1.1 422") || wrong_resp.contains("HTTP/1.0 422"),
        "a wrong current password must be rejected with 422:\n{{wrong_resp}}"
    );
    // The CURRENT password still authenticates → the failed attempt changed nothing.
    let relogin = post_form(
        &base,
        "/login",
        &format!("email={{email}}&password={{new_password}}"),
        "",
    );
    assert!(
        relogin.contains("HTTP/1.1 30") || relogin.contains("HTTP/1.0 30"),
        "the failed change must not have altered the password:\n{{relogin}}"
    );

    // ── (c) A pending email change keeps the OLD address usable until confirmed ─
    let new_email = format!("pw-change-new-{{suffix}}@example.com");
    let cookie = login(&base, &email, new_password);
    let email_body = format!("new_email={{new_email}}&current_password={{new_password}}");
    let start_resp = post_form(&base, "/account/email", &email_body, &cookie);
    assert!(
        start_resp.contains("HTTP/1.1 30")
            || start_resp.contains("HTTP/1.0 30")
            || start_resp.contains(" 200"),
        "starting an email change should succeed:\n{{start_resp}}"
    );
    // The OLD address still signs in while the change is pending.
    let old_still = post_form(
        &base,
        "/login",
        &format!("email={{email}}&password={{new_password}}"),
        "",
    );
    assert!(
        old_still.contains("HTTP/1.1 30") || old_still.contains("HTTP/1.0 30"),
        "the old address must remain usable until the new-address token is confirmed:\n{{old_still}}"
    );
    // Confirm the change via the link mailed to the NEW address.
    let confirm_url = mail_link("/account/email/confirm/")
        .expect("captured mail should contain the email-change confirm link");
    let confirmed = get(&base, &url_path(&confirm_url));
    assert!(
        confirmed.contains(" 200") || confirmed.contains(" 30"),
        "confirming the email change should succeed:\n{{confirmed}}"
    );
    // The NEW address now signs in.
    let new_login = post_form(
        &base,
        "/login",
        &format!("email={{new_email}}&password={{new_password}}"),
        "",
    );
    assert!(
        new_login.contains("HTTP/1.1 30") || new_login.contains("HTTP/1.0 30"),
        "the new address must sign in after confirmation:\n{{new_login}}"
    );
}}
{magic_link_tests}"#
    )
}

/// Live-DB magic-link integration test appended to `tests/auth.rs` under
/// `--magic-link` (issue #1328, AC7). Uses plain single braces — it is inserted
/// verbatim into the `render_tests_file` output, not re-formatted.
const MAGIC_LINK_TESTS_SECTION: &str = r#"
/// Magic-link end-to-end (issue #1328, AC7). Against a live DB with a capturing
/// mail transport, this asserts the request endpoint sends a link and that
/// consuming that link logs the user in.
///
/// Outline (fill in with your HTTP client + mail capture once wired):
///   1. POST /login/magic with a registered, confirmed email → 200
///      "check your email", and the capturing mail transport receives one
///      message whose body contains a `/login/magic/verify?token=…` URL.
///   2. POST /login/magic with an UNREGISTERED email → the SAME 200 response
///      and NO email is sent (non-enumerating).
///   3. GET the captured verify URL → a 200 "Confirm sign-in" page (the token is
///      NOT consumed on GET, so scanners/prefetch bots can't burn the link).
///   4. POST /login/magic/verify with that token → redirect to /account with a
///      session cookie; a follow-up GET /account with that cookie returns 200.
///   5. POST /login/magic/verify with the SAME token again → generic failure
///      (single-use).
///   6. POST /login/magic/verify?token=deadbeef (unknown) → the SAME generic
///      failure page (no oracle).
#[test]
#[ignore = "requires a live database and a capturing mail transport"]
fn magic_link_request_and_consume_logs_in() {
    let Some(base) = base_url() else {
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    };

    // A confirmed account is eligible for a magic link.
    let suffix = unique_suffix();
    let email = format!("magic-{suffix}@example.com");
    let password = "magic-Passw0rd-link";
    signup_and_confirm(&base, &email, password);

    // (1) Requesting a link for the confirmed account emails a verify URL.
    let resp = post_form(&base, "/login/magic", &format!("email={email}"), "");
    assert!(
        resp.contains(" 200"),
        "POST /login/magic should return the check-your-email page:\n{resp}"
    );
    let verify_url = mail_link("/login/magic/verify?token=")
        .expect("the magic-link email must contain a /login/magic/verify?token= URL");
    let verify_path = url_path(&verify_url);
    // The raw token from the emailed link; the confirm form POSTs it back.
    let token = verify_url
        .rsplit("token=")
        .next()
        .expect("verify URL must carry a token= query")
        .to_owned();

    // (3) GETting the link renders a "Confirm sign-in" page and does NOT consume
    //     the token — a scanner that only follows the GET can't burn the link.
    let confirm = get(&base, &verify_path);
    assert!(
        confirm.contains(" 200"),
        "GET verify must render the confirm page, not redirect/consume:\n{confirm}"
    );

    // (4) POSTing the confirmation consumes the token and logs the user in: the
    //     redirect carries a session cookie that authenticates a follow-up
    //     /account request.
    let consume = post_form(&base, "/login/magic/verify", &format!("token={token}"), "");
    assert!(
        consume.contains("HTTP/1.1 30") || consume.contains("HTTP/1.0 30"),
        "POSTing the magic-link confirmation should redirect to /account:\n{consume}"
    );
    let cookie = session_cookie(&consume).expect("the verify redirect must set a session cookie");
    assert!(
        get_auth(&base, "/account", &cookie).contains(" 200"),
        "the magic-link session must authenticate /account"
    );

    // (5) A SECOND POST of the same token fails generically (single-use).
    let second = post_form(&base, "/login/magic/verify", &format!("token={token}"), "");
    assert!(
        !second.contains("HTTP/1.1 30") && !second.contains("HTTP/1.0 30"),
        "a consumed magic link must not log in again:\n{second}"
    );
    assert!(
        second.contains("invalid or has expired"),
        "a re-used token must render the generic failure page:\n{second}"
    );

    // (6) An unknown token yields the SAME generic failure (no oracle).
    let unknown = post_form(
        &base,
        "/login/magic/verify",
        "token=deadbeefdeadbeef",
        "",
    );
    assert!(
        unknown.contains("invalid or has expired"),
        "an unknown token must render the same generic failure page:\n{unknown}"
    );
}
"#;

#[allow(clippy::too_many_lines)]
/// Render `tests/auth_sessions.rs` — integration tests for active-session
/// management (issue #819), including the two-client revocation flow.
fn render_sessions_tests_file(pascal_name: &str, _snake_name: &str) -> String {
    format!(
        r#"//! Active-session management integration tests for {pascal_name},
//! generated by `autumn generate auth` (issue #819).
//!
//! These tests run against a live server started with `AUTUMN_TEST_BASE_URL`.
//! They skip when the env var is unset, so they compile and pass out of the box.
//!
//! The revocation tests additionally need a *confirmed* account because login
//! is gated on email confirmation. Provide one via:
//!
//! ```sh
//! export AUTUMN_TEST_CONFIRMED_EMAIL=tester@example.com
//! export AUTUMN_TEST_CONFIRMED_PASSWORD=some-password-123
//! ```
//!
//! Seed it directly if needed (replace `users` with your table name):
//!
//! ```sql
//! UPDATE users SET email_confirmed_at = NOW() WHERE email = 'tester@example.com';
//! ```

use std::io::{{Read, Write}};
use std::net::TcpStream;

fn base_url() -> Option<String> {{
    std::env::var("AUTUMN_TEST_BASE_URL").ok()
}}

fn confirmed_account() -> Option<(String, String)> {{
    let email = std::env::var("AUTUMN_TEST_CONFIRMED_EMAIL").ok()?;
    let password = std::env::var("AUTUMN_TEST_CONFIRMED_PASSWORD").ok()?;
    Some((email, password))
}}

fn host_port(base: &str) -> String {{
    base.trim_start_matches("http://")
        .trim_start_matches("https://")
        .to_owned()
}}

fn request(base: &str, method: &str, path: &str, body: &str, cookie: &str) -> String {{
    let hp = host_port(base);
    let mut stream =
        TcpStream::connect(&hp).unwrap_or_else(|_| panic!("cannot connect to {{base}}"));
    let req = format!(
        "{{method}} {{path}} HTTP/1.1\r\n\
         Host: {{hp}}\r\n\
         Content-Type: application/x-www-form-urlencoded\r\n\
         Content-Length: {{}}\r\n\
         Cookie: {{cookie}}\r\n\
         User-Agent: auth-sessions-integration-test\r\n\
         Connection: close\r\n\r\n\
         {{body}}",
        body.len()
    );
    stream.write_all(req.as_bytes()).expect("write failed");
    let mut resp = String::new();
    stream.read_to_string(&mut resp).expect("read failed");
    resp
}}

fn get(base: &str, path: &str, cookie: &str) -> String {{
    request(base, "GET", path, "", cookie)
}}

fn post_form(base: &str, path: &str, body: &str, cookie: &str) -> String {{
    request(base, "POST", path, body, cookie)
}}

/// Extract the session cookie (`name=value`) from a `Set-Cookie` header.
fn session_cookie(resp: &str) -> Option<String> {{
    resp.lines()
        .filter(|l| l.to_ascii_lowercase().starts_with("set-cookie:"))
        .filter_map(|l| l.splitn(2, ':').nth(1))
        .map(|v| v.split(';').next().unwrap_or("").trim().to_owned())
        .find(|c| !c.is_empty())
}}

/// Log in and return the authenticated session cookie. Panics on failure.
fn login(base: &str, email: &str, password: &str) -> String {{
    let body = format!("email={{email}}&password={{password}}");
    let resp = post_form(base, "/login", &body, "");
    assert!(
        resp.contains("HTTP/1.1 30") || resp.contains("HTTP/1.0 30"),
        "login did not redirect — is the account confirmed?\n{{resp}}"
    );
    session_cookie(&resp).expect("login response missing Set-Cookie")
}}

/// The revocation tests share one confirmed account, so a concurrent
/// `revoke-others` from one test would tear down another test's sessions.
/// Serialize them.
static REVOKE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

#[test]
fn sessions_page_rejects_anonymous() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let resp = get(&base, "/account/sessions", "");
    let is_rejected = resp.contains("HTTP/1.1 401")
        || resp.contains("HTTP/1.0 401")
        || resp.contains("HTTP/1.1 30")
        || resp.contains("HTTP/1.0 30");
    assert!(
        is_rejected,
        "GET /account/sessions should reject anonymous requests:\n{{resp}}"
    );
}}

/// AC — log in on two clients, revoke from one, and the revoked client's
/// next request 401s even though it replays the same (still-valid-looking)
/// cookie. No reliance on cookie expiry.
#[test]
fn revoked_session_next_request_401s() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let Some((email, password)) = confirmed_account() else {{
        eprintln!("skipping: AUTUMN_TEST_CONFIRMED_EMAIL/PASSWORD not set");
        return;
    }};
    let _serial = REVOKE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);

    // Two independent clients (e.g. laptop + phone).
    let cookie_a = login(&base, &email, &password);
    let cookie_b = login(&base, &email, &password);

    // Both sessions work.
    assert!(
        get(&base, "/account", &cookie_a).contains(" 200"),
        "client A should be signed in"
    );
    assert!(
        get(&base, "/account", &cookie_b).contains(" 200"),
        "client B should be signed in"
    );

    // Client A signs everything else out — one click.
    let resp = post_form(&base, "/account/sessions/revoke-others", "", &cookie_a);
    assert!(
        resp.contains(" 200") || resp.contains(" 30"),
        "revoke-others failed:\n{{resp}}"
    );

    // Client B's replayed cookie must 401 on its very next request.
    let resp_b = get(&base, "/account", &cookie_b);
    assert!(
        resp_b.contains("HTTP/1.1 401") || resp_b.contains("HTTP/1.0 401"),
        "revoked client's next request must 401:\n{{resp_b}}"
    );
}}

/// "Sign out everywhere else" must never revoke the session that asked.
#[test]
fn revoke_other_sessions_keeps_current_session_alive() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    let Some((email, password)) = confirmed_account() else {{
        eprintln!("skipping: AUTUMN_TEST_CONFIRMED_EMAIL/PASSWORD not set");
        return;
    }};
    let _serial = REVOKE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);

    let cookie_a = login(&base, &email, &password);
    let _cookie_b = login(&base, &email, &password);

    post_form(&base, "/account/sessions/revoke-others", "", &cookie_a);

    let resp_a = get(&base, "/account", &cookie_a);
    assert!(
        resp_a.contains(" 200"),
        "current session must survive revoke-others:\n{{resp_a}}"
    );
    let resp_page = get(&base, "/account/sessions", &cookie_a);
    assert!(
        resp_page.contains(" 200"),
        "sessions page must render for the surviving session:\n{{resp_page}}"
    );
}}
"#
    )
}

/// Render `docs/guide/session-management.md` — covers the data model, the
/// handler APIs, the auto-revocation policy, the privacy posture for stored
/// IP / User-Agent data, and how to plug in a custom UA parser (issue #819).
#[allow(clippy::too_many_lines)]
fn render_sessions_docs_file(
    backend: autumn_web::config::DatabaseBackend,
    pascal_name: &str,
    snake_name: &str,
    user_table: &str,
) -> String {
    let sess_table = sessions_table_name(snake_name);
    // The stale-row sweep and the retrofit DDL are copy-paste SQL for the
    // operator, so both must be in the app's own dialect (issue #1908).
    let stale_cutoff = match backend {
        autumn_web::config::DatabaseBackend::Postgres => "NOW() - INTERVAL '90 days'",
        autumn_web::config::DatabaseBackend::Sqlite => "datetime('now', '-90 days')",
    };
    let sessions_ddl = render_sessions_table_ddl(backend, snake_name, user_table);
    format!(
        r#"# Active Session Management

Generated by `autumn generate auth`. Every login persists a `{sess_table}`
row so users can answer "where am I signed in?" and revoke any device —
per-session or all-at-once — from `/account/sessions`.

## How it works

- **One row per login.** A successful login (password, email confirmation,
  TOTP verify, or passkey) inserts a `{sess_table}` row holding the SHA-256
  digest of the opaque server-side session id, the {pascal_name} id, the IP
  at login, the raw and parsed User-Agent, an optional user-set device
  label, `created_at`, and `last_seen_at`.
- **The row is the source of truth.** Authenticated handlers call
  `require_tracked_session(&session, &mut db, &state)`, which loads the row
  by digest. If the row is gone the request is rejected with `401` and the
  cookie session is destroyed — a revoked session dies on its *next*
  request, even if the cookie is replayed. There is no reliance on cookie
  expiry.
- **Bounded write amplification.** `last_seen_at` is refreshed at most once
  per `[auth.sessions].last_seen_update_secs` (default 60 s) per session,
  so a busy session costs one `UPDATE` per window, not one per request.
- **Only the digest is stored.** The raw session id never touches the
  database, so a database leak cannot be replayed as a session cookie.

## Handler APIs

From any request handler that has loaded the current {pascal_name}:

```rust
// List active sessions, most recently seen first.
let sessions = current_{snake_name}.sessions(&mut *db).await?;

// Revoke one session by row id (scoped to this account).
current_{snake_name}.revoke_session(&mut *db, session_id).await?;

// "Sign out everywhere else."
let digest = session_token_digest(&session).await;
current_{snake_name}.revoke_other_sessions(&mut *db, &digest).await?;

// Revoke everything, including the current session (password change).
current_{snake_name}.revoke_all_sessions(&mut *db).await?;
```

Protect your own routes the same way the generated ones are protected:

```rust
let current_{snake_name} = require_tracked_session(&session, &mut db, &state).await?;
```

## The /account/sessions page

`GET /account/sessions` lists every active session with device description
(parsed from the User-Agent), IP, sign-in and last-seen times, a per-row
**Revoke** button, a device-label form, and a one-click **Sign out
everywhere else** button. The page is Maud + htmx: revocations swap the
list in place without a full reload, and fall back to normal form posts
when JavaScript is unavailable.

## Automatic revocation on credential change

Password change (reset flow), TOTP enrollment, TOTP disable, and passkey
add/remove revoke all *other* sessions by default — the standard response
to credential theft. Disable or tune it in `autumn.toml`:

```toml
[auth.sessions]
revoke_on_credential_change = true  # default
last_seen_update_secs = 60          # default
```

## Privacy posture for stored IP and User-Agent

The session row stores the login IP and User-Agent so a person can
recognise their own devices. Treat both as personal data:

- **Purpose limitation.** The data exists for device recognition and
  incident response only. Don't repurpose it for analytics.
- **Retention.** Rows are deleted on logout, revocation, and account
  deletion (`ON DELETE CASCADE`). Sessions that simply go stale keep their
  rows until revoked — pick a retention window and scrub on a schedule:

  ```sql
  DELETE FROM {sess_table} WHERE last_seen_at < {stale_cutoff};
  ```

  Pair this with your session cookie `max_age_secs` so rows do not outlive
  the cookies that reference them.
- **Scrubbing/minimisation.** If full IPs are more than you need, truncate
  before storing (e.g. zero the last IPv4 octet) in `build_session_row`,
  or store only the parsed UA fields and set `user_agent` to `""`.
- **No geolocation.** The framework stores the IP only; GeoIP lookups are
  deliberately left to userland.
- **Data export.** Include `{sess_table}` in your GDPR export job — see
  docs/guide/gdpr-compliance.md.

## Plugging in a custom User-Agent parser

The default parser (`autumn_web::user_agent::parse_user_agent`) is a small
heuristic covering the major browser/OS families. Every parse goes through
one call site — `build_session_row` in `src/routes/auth.rs` — so
swapping in a dedicated crate is a one-line change:

```rust
// In build_session_row, replace:
let parsed = autumn_web::user_agent::parse_user_agent(&user_agent);
// with your parser of choice, mapping into the same three fields:
let ua = my_ua_crate::parse(&user_agent);
let parsed = autumn_web::user_agent::ParsedUserAgent {{
    family: ua.browser_name,
    os: ua.os_name,
    device_class: autumn_web::user_agent::DeviceClass::Unknown,
}};
```

The parsed fields are stored denormalised (`ua_family`, `ua_os`,
`ua_device`), so changing the parser only affects *new* sessions.

## Migration path for existing apps

Already generated the auth starter before session management existed? The
upgrade is one additive table:

```sql
{sessions_ddl}```

Existing logged-in sessions have no row, so `require_tracked_session`
treats them as revoked: every user re-authenticates once after the
deploy. That is the safe default after introducing revocation.

## Integration tests

`tests/auth_sessions.rs` covers the two-client flow: log in on two
clients, revoke from one, and assert the revoked client's next request
401s while the surviving client keeps working. Set `AUTUMN_TEST_BASE_URL`
plus `AUTUMN_TEST_CONFIRMED_EMAIL`/`AUTUMN_TEST_CONFIRMED_PASSWORD` to run
them against a live server.
"#
    )
}

#[allow(clippy::too_many_lines)]
fn render_docs_file(
    backend: autumn_web::config::DatabaseBackend,
    pascal_name: &str,
    totp: bool,
    magic_link: bool,
) -> String {
    let totp_docs = if totp { TOTP_DOCS_SECTION } else { "" };
    let magic_link_docs = if magic_link {
        MAGIC_LINK_DOCS_SECTION
    } else {
        ""
    };
    // The lockout retrofit DDL and the confirm-existing-accounts statement are
    // copy-paste SQL for the operator, so both must be in the app's own dialect
    // (issue #1927), matching `render_sessions_docs_file` /
    // `render_oauth_docs_file`. `SQLite` takes one `ADD COLUMN` per `ALTER
    // TABLE`, has no `IF NOT EXISTS` / `IF EXISTS` on either, and no `NOW()`.
    let (lockout_up, lockout_down, confirmed_now, confirm_up, confirm_down) = match backend {
        // `{table}` stays a literal placeholder for the reader, exactly as the
        // template emitted it before this fork — these fragments are inserted
        // as data, so they are NOT format-escaped the way `{{table}}` was.
        autumn_web::config::DatabaseBackend::Postgres => (
            "ALTER TABLE {table}\n  \
             ADD COLUMN IF NOT EXISTS failed_attempts INT NOT NULL DEFAULT 0,\n  \
             ADD COLUMN IF NOT EXISTS locked_at TIMESTAMP NULL;",
            "ALTER TABLE {table}\n  \
             DROP COLUMN IF EXISTS failed_attempts,\n  \
             DROP COLUMN IF EXISTS locked_at;",
            "NOW()",
            "ALTER TABLE {table}\n  \
             ADD COLUMN IF NOT EXISTS confirm_token_digest TEXT NULL,\n  \
             ADD COLUMN IF NOT EXISTS confirm_token_expires_at TIMESTAMP NULL,\n  \
             ADD COLUMN IF NOT EXISTS email_confirmed_at TIMESTAMP NULL,\n  \
             ADD COLUMN IF NOT EXISTS pending_email TEXT NULL;",
            "ALTER TABLE {table}\n  \
             DROP COLUMN IF EXISTS confirm_token_digest,\n  \
             DROP COLUMN IF EXISTS confirm_token_expires_at,\n  \
             DROP COLUMN IF EXISTS email_confirmed_at,\n  \
             DROP COLUMN IF EXISTS pending_email;",
        ),
        // `SQLite` takes one `ADD COLUMN` per `ALTER TABLE`, has no
        // `IF NOT EXISTS` / `IF EXISTS` on either, and no `NOW()`.
        autumn_web::config::DatabaseBackend::Sqlite => (
            "ALTER TABLE {table} ADD COLUMN failed_attempts INTEGER NOT NULL DEFAULT 0;\n\
             ALTER TABLE {table} ADD COLUMN locked_at TEXT NULL;",
            "ALTER TABLE {table} DROP COLUMN failed_attempts;\n\
             ALTER TABLE {table} DROP COLUMN locked_at;",
            "CURRENT_TIMESTAMP",
            "ALTER TABLE {table} ADD COLUMN confirm_token_digest TEXT NULL;\n\
             ALTER TABLE {table} ADD COLUMN confirm_token_expires_at TEXT NULL;\n\
             ALTER TABLE {table} ADD COLUMN email_confirmed_at TEXT NULL;\n\
             ALTER TABLE {table} ADD COLUMN pending_email TEXT NULL;",
            "ALTER TABLE {table} DROP COLUMN confirm_token_digest;\n\
             ALTER TABLE {table} DROP COLUMN confirm_token_expires_at;\n\
             ALTER TABLE {table} DROP COLUMN email_confirmed_at;\n\
             ALTER TABLE {table} DROP COLUMN pending_email;",
        ),
    };

    format!(
        r#"# Authentication Guide

Generated by `autumn generate auth`. Edit freely.

## Overview

This guide documents the browser-session authentication flow generated for
your Autumn application. The generated code handles signup, login, logout,
account profile, and password reset using Autumn's built-in session, CSRF,
password hashing, and mail primitives.

## Generated Routes

| Method | Path | Handler | Auth |
|--------|------|---------|------|
| GET | `/signup` | `signup_form` | Public |
| POST | `/signup` | `signup` | Public |
| GET | `/check-your-email` | `check_your_email` | Public |
| GET | `/login` | `login_form` | Public |
| POST | `/login` | `login` | Public |
| POST | `/logout` | `logout` | Any |
| GET | `/account` | `account` | **Required** + Confirmed |
| POST | `/account/destroy` | `account_destroy` | **Required** + Step-up |
| GET | `/reauth` | `reauth_form` | Any (redirects if unauthed) |
| POST | `/reauth` | `reauth` | Any (redirects if unauthed) |
| GET | `/forgot-password` | `forgot_password_form` | Public |
| POST | `/forgot-password` | `forgot_password` | Public |
| GET | `/reset-password` | `reset_password_form` | Public |
| POST | `/reset-password` | `reset_password` | Public |
| GET | `/auth/confirm/:token` | `confirm_email` | Public |
| GET | `/auth/confirm/resend` | `resend_confirmation_form` | Public |
| POST | `/auth/confirm/resend` | `resend_confirmation` | Public |

## Security Properties

- **Passwords**: Hashed with bcrypt (cost 12) via `autumn_web::auth::hash_password`.
  Raw passwords are never logged or stored.
- **Reset tokens**: 32-byte random values generated with `SysRng`; only the
  SHA-256 digest is stored in `reset_token_digest`. The raw token is sent by
  email only and expires after 2 hours.
- **Non-enumeration**: Duplicate signup, failed login, unconfirmed-login,
  and forgot-password submissions for unknown addresses all return responses
  that do not reveal whether an email address is registered.
- **Email confirmation**: Signup creates the account in an unconfirmed state
  and sends a confirmation link. Users cannot log in until they confirm their
  email. Only the SHA-256 digest of the confirmation token is stored
  (`confirm_token_digest`); the raw token lives only in the email and URL bar.
- **Session fixation**: Login and password-reset rotate the session ID
  (`session.rotate_id()`).
- **Session invalidation**: Logout clears the session data and rotates the ID,
  destroying the old server-side session so the pre-logout cookie cannot be
  replayed (equivalent to `destroy()` for replay safety) while still carrying a
  one-shot "logged out" flash notice to the login page.
- **Protected routes**: The `/account` route uses `#[secured]` to reject
  unauthenticated requests before the handler runs.
- **Account lockout**: After the configured threshold of failed login attempts,
  the account is locked for the cool-off period. Lockout responses are
  indistinguishable from wrong-password responses (same status, same body) so
  the endpoint does not reveal which accounts are locked. Lockout state is
  stored in Postgres so all app replicas agree. See [Account Lockout Policy](#account-lockout-policy) below.

## Account Lockout Policy

The generated login endpoint includes account-level lockout to protect against
credential-stuffing attacks that rotate source IPs to bypass IP-rate limiting.

### How It Works

1. Each failed login increments `failed_attempts` on the account row.
2. When `failed_attempts` reaches `threshold`, `locked_at` is stamped with the
   current time and a structured telemetry event fires (see below). Only the
   request that sets `locked_at` logs, so each lock logs once.
3. While the account is locked (`locked_at + cooloff_secs > now`), every login
   attempt — correct password or not — returns the same `422 Invalid email or
   password` response as a wrong-password attempt (non-enumerating).
4. A successful login resets `failed_attempts` to `0` and clears `locked_at`.
5. After `cooloff_secs` elapses without a login attempt, the account auto-unlocks
   on the next successful login.

### Configuration (`autumn.toml`)

```toml
[auth.lockout]
enabled      = true  # false → disable lockout entirely (e.g. external policy in place)
threshold    = 10    # consecutive failures before lockout
window_secs  = 60    # reserved for future sliding-window counting; not yet enforced —
                     # failures currently accumulate since the last successful login
cooloff_secs = 900   # lock duration in seconds (default 15 minutes)
```

Override at deploy time via environment variables:

| Variable | Description |
|----------|-------------|
| `AUTUMN_AUTH__LOCKOUT__ENABLED` | `true` / `false` |
| `AUTUMN_AUTH__LOCKOUT__THRESHOLD` | integer (0 = disabled) |
| `AUTUMN_AUTH__LOCKOUT__WINDOW_SECS` | integer |
| `AUTUMN_AUTH__LOCKOUT__COOLOFF_SECS` | integer |

Set `threshold = 0` or `enabled = false` to restore the pre-lockout login
behaviour for apps that use a stronger external policy.

### Telemetry

When an account transitions into the locked state the handler emits a
`tracing::warn!` event with:

| Field | Value |
|-------|-------|
| `event` | `"account_locked"` |
| `account_id_digest` | First 8 bytes of SHA-256(account ID) — stable but not reversible |
| `ip_prefix` | IPv4 /24 prefix (`a.b.c.0/24`) or IPv6 /64 prefix (`x:x:x:x::/64`) |
| `failed_attempts` | Counter value at lock time |

This event flows through the standard Autumn tracing/metrics surface
(OTLP, structured JSON, or console pretty-print depending on config).

### Operator Unlock

The generated auth routes include a `POST /auth/admin/unlock` endpoint that
clears the lockout for a single account. It is protected by the
`X-Admin-Secret` header matching the `AUTUMN_ADMIN_SECRET` environment
variable. Set this variable to a strong random value in production:

```sh
# Generate and store a secret (do this once, store in your .env or deployment
# secrets manager — NOT in autumn credentials, which are not consulted here).
export AUTUMN_ADMIN_SECRET="$(openssl rand -hex 32)"

# Unlock an account
curl -s -X POST https://example.com/auth/admin/unlock \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -H "X-Admin-Secret: $AUTUMN_ADMIN_SECRET" \
  -d "email=user%40example.com"
```

Protect this endpoint with network-level access controls (VPN, internal
load-balancer allowlist) in production in addition to the secret header.
If `AUTUMN_ADMIN_SECRET` is not set, the endpoint always returns 422.

### Existing Apps — Adoption Path

Apps that ran `autumn generate auth` before this feature was introduced need
one additional migration to add the lockout columns. Because `generate migration`
does not carry column defaults, write the SQL directly:

```sh
# 1. Create an empty migration
autumn generate migration add_lockout_to_{{table}}

# 2. Edit the generated up.sql to add the columns with correct defaults:
```

```sql
-- migrations/<timestamp>_add_lockout_to_{{table}}/up.sql
{lockout_up}
```

```sql
-- migrations/<timestamp>_add_lockout_to_{{table}}/down.sql
{lockout_down}
```

```sh
# 3. Apply the migration
autumn migrate

# 4. Re-generate auth templates to pick up the lockout handler and unlock route
autumn generate auth {pascal_name} --force
```

No behaviour changes for existing apps until the migration is applied and
the generator re-run — the framework does not silently change behaviour.

## Mail Configuration

Password-reset emails contain an absolute link built from `APP_BASE_URL`.
Set this environment variable to your application's public URL:

```sh
# .env or shell
APP_BASE_URL=https://example.com
```

In development, configure file-based mail capture in `autumn.toml` so reset
links land in `target/mail/` instead of hitting an SMTP server:

```toml
[mail]
transport = "file"
from = "Your App <noreply@yourapp.dev>"
```

Open the `.eml` files with any email client to click the reset link.

If `[mail]` is not configured (`transport = "disabled"`), the forgot-password
handler returns an immediate HTTP 500 with a clear configuration message
rather than silently showing "Check Your Email" when no mail will be sent.

## Email Confirmation

Signup creates the account in an **unconfirmed** state and immediately sends a
confirmation link. The user is **not** logged in until they click the link.
Attempting to log in with an unconfirmed address returns the same
`422 Invalid email or password` response as a wrong-password attempt
(non-enumerating — does not reveal that the address exists but is unconfirmed).

### Generated Routes

| Method | Path | Handler | Auth |
|--------|------|---------|------|
| GET | `/check-your-email` | `check_your_email` | Public |
| GET | `/auth/confirm/:token` | `confirm_email` | Public |
| GET | `/auth/confirm/resend` | `resend_confirmation_form` | Public |
| POST | `/auth/confirm/resend` | `resend_confirmation` | Public |

### Security Properties

- **Digest-only storage**: The raw confirmation token is never stored in the
  database, logs, traces, or error reports. Only its SHA-256 digest is
  persisted in `confirm_token_digest`. The raw token lives only in the email
  body and the user's URL bar.
- **Single-use tokens**: `confirm_email` clears `confirm_token_digest` and
  `confirm_token_expires_at` on first use. Replaying the token returns a 422.
- **Token expiry**: Tokens expire after 24 hours (`confirm_token_expires_at`).
  An expired token returns a non-revealing 422 with a "request a new
  confirmation" page.
- **Non-enumeration**: Resend-confirmation always returns the same "Check Your
  Email" page regardless of whether the address is registered or already
  confirmed, so the endpoint does not reveal which addresses exist.
- **Resend invalidates old token**: Each resend overwrites
  `confirm_token_digest` / `confirm_token_expires_at`, so old links stop
  working immediately.

### Confirmed-Only Gate

The generated `/account` route demonstrates how to require a confirmed email
address on any route. After fetching the user record, check
`email_confirmed_at`:

```rust
// In any #[secured] handler that requires email confirmation:
if {snake_name}.email_confirmed_at.is_none() {{
    return Ok(redirect_to("/check-your-email"));
}}
```

Replicate this block on any route that should be gated behind confirmation.

### Confirmation vs. Password Reset

Password reset and email confirmation are **independent state transitions**.
Completing a password reset does **not** confirm the email address. This is
intentional: an attacker who controls a reset link (e.g., via a compromised
inbox) should not also gain a confirmed account status. After a successful
password reset, an unconfirmed user is redirected to `/check-your-email`
rather than `/account`.

### Email-Change Flow

When an existing user changes their email address, the new address must be
re-confirmed before it becomes the active sign-in address. The generated
scaffolding supports this via the following pattern:

1. On email-change form submission, generate a new confirmation token and store
   its digest in `confirm_token_digest`.
2. Set `email_confirmed_at = NULL` for the *new* address column (or keep the
   old address in a `pending_email` column until confirmed).
3. Send a confirmation email to the *new* address.
4. Keep the *old* address valid for sign-in until confirmation succeeds.
5. On confirmation, swap the address and stamp `email_confirmed_at`.
6. Send a notice email to the *old* address.

The starter scaffolds the token/confirmation machinery; the email-change form
and address-swap logic are left as a documented customization point in
`src/routes/auth.rs` because the exact data model depends on your application's
requirements. See `resend_confirmation` for the token-generation pattern to
reuse.

### Configuration

Confirmation token expiry is 24 hours by default. To change it, edit the
`hours(24)` call in `signup` and `resend_confirmation` in `src/routes/auth.rs`.

### Development Setup

In development, set `transport = "log"` or `transport = "file"` in
`autumn.toml` so confirmation links are visible without an SMTP provider:

```toml
[mail]
transport = "log"          # prints the confirmation URL to the console
# transport = "file"       # writes .eml files to target/mail/
from = "noreply@yourapp.dev"
```

If `transport = "disabled"` (the default when `[mail]` is absent), the signup
handler fails immediately with a clear HTTP 500 message naming the missing mail
configuration rather than silently creating an account that can never be confirmed.

### Existing Apps — Adoption Path (email confirmation columns)

Apps that ran `autumn generate auth` before email confirmation was added need
an additional migration to add the new columns:

```sh
# 1. Create an empty migration
autumn generate migration add_email_confirmation_to_{{table}}

# 2. Edit the generated up.sql:
```

```sql
-- migrations/<timestamp>_add_email_confirmation_to_{{table}}/up.sql
{confirm_up}
```

```sql
-- migrations/<timestamp>_add_email_confirmation_to_{{table}}/down.sql
{confirm_down}
```

```sh
# 3. Apply the migration
autumn migrate

# 4. Regenerate src/schema.rs so Diesel knows about the new columns.
#    (autumn generate auth only adds the table when it is absent; it cannot
#    add columns to an existing table entry in schema.rs.)
diesel print-schema > src/schema.rs

# 5. Re-generate auth templates to pick up the confirmation handlers
autumn generate auth {pascal_name} --force
```

After the migration, existing (pre-confirmation) accounts will have
`email_confirmed_at = NULL`. To mark all existing accounts as confirmed so
they can log in immediately (opt-in migration), run:

```sql
-- Only run this if you trust all existing accounts (no spam/abuse backlog).
UPDATE {{table}} SET email_confirmed_at = {confirmed_now} WHERE email_confirmed_at IS NULL;
```

No behaviour changes for existing accounts until the migration is applied and
the generator re-run — the framework does not silently change behaviour.

## Customization Points

- **Validation**: Add stricter email / password rules to `signup` and
  `reset_password` in `src/routes/auth.rs`.
- **Session keys**: Change the session key names (`{snake_name}_id`,
  `{snake_name}_email`) to match your application's conventions.
- **Redirect targets**: Adjust `redirect_to("/account")` calls to send users
  to the right page after login/signup/reset.
- **Email templates**: Customise the `send_reset_email` function to match your
  brand.
- **{pascal_name} fields**: Add display-name, avatar, or role fields to the
  `{pascal_name}` model and a new migration.

{totp_docs}{magic_link_docs}## When to Choose This Flow vs. Alternatives

| Scenario | Recommendation |
|----------|---------------|
| Browser-based web app | ✅ This generated flow |
| Mobile / CLI / third-party API clients | API tokens (`autumn generate token` — see [#520]) |
| Social login (Google, GitHub, …) | OAuth2/OIDC (S-059) |
| Enterprise / SSO | SAML / enterprise IdP (future) |

## Quick Start

```sh
autumn new myapp
cd myapp
autumn generate auth {pascal_name}
autumn migrate
autumn dev
```

Then open <http://localhost:3000/signup> to create your first account.
"#,
        snake_name = pascal_name.to_lowercase(),
        pascal_name = pascal_name,
    )
}

/// Render `docs/guide/gdpr-compliance.md` — GDPR/CCPA compliance checklist.
///
/// Documents exactly which generated artifacts satisfy Article 15 (right of
/// access) and Article 17 (right to erasure), and which obligations remain the
/// application developer's responsibility.
fn render_gdpr_docs_file() -> String {
    r#"# GDPR & CCPA Compliance Checklist

This document describes the data-privacy obligations covered by the generated
auth starter and those that remain the application developer's responsibility.

## What the Auth Starter Provides

### Article 15 — Right of Access (`GET /account/data-export`)

| Artifact | Location |
|---|---|
| Self-service "Download my data" form | `GET /account/data-export` |
| Export-request POST handler | `POST /account/data-export` |
| `export_requested_at` column on the users table | Migration + model |
| Audit log entry on request (`gdpr.export.requested`) | `src/routes/auth.rs` |
| Background export job stub (wire up `JobClient` for production) | `src/routes/auth.rs` |

### Article 17 — Right to Erasure (`POST /account/delete`)

| Artifact | Location |
|---|---|
| Self-service "Delete my account" confirmation form | `GET /account/delete` |
| 30-day grace period with `delete_scheduled_at` column | Migration + model |
| Typed confirmation step (user must type "DELETE") | `src/routes/auth.rs` |
| Audit log entry on request (`gdpr.erasure.requested`) | `src/routes/auth.rs` |
| Cancellation route during grace period | `POST /account/delete/cancel` |
| Audit log entry on cancellation (`gdpr.erasure.cancelled`) | `src/routes/auth.rs` |

## What the Application Developer Must Provide

The following obligations are **not** automated by the framework and require
per-application implementation:

### Hard-Delete / Anonymize Sweeper

The grace-period sweeper that reads `delete_scheduled_at` and performs the
actual erasure is the application's responsibility. Implement it as a scheduled
job or a cron task:

1. Query for `WHERE delete_scheduled_at < NOW()`.
2. For each model, apply the registered erasure strategy:
   - `hard_delete` — `DELETE FROM <table> WHERE user_id = $1`.
   - `anonymize` — replace PII columns with tombstone values (e.g. `DELETED_<hash>`).
   - `retain` — keep the row, record the retention reason in your audit log.
3. Finally, hard-delete the user row.

### Third-Party Processor Erasure

GDPR requires erasure from third-party processors (Stripe, SendGrid, analytics
services, etc.). This is out of scope for the auth starter. Document your
processor list and erasure API calls in a separate runbook.

### Admin-Triggered Export and Erasure

For Subject Access Requests (SARs) initiated by your legal/ops team, add admin
routes that call the same export/erasure logic with the operator's identity
recorded as the `actor_id` in the audit log.

## Compliance Status Summary

| Obligation | Status |
|---|---|
| Article 15 — right of access route | ✅ Generated |
| Article 15 — audit log | ✅ Generated |
| Article 17 — erasure request route | ✅ Generated |
| Article 17 — grace period + cancellation | ✅ Generated |
| Article 17 — audit log | ✅ Generated |
| Article 17 — actual row deletion sweeper | ⚠️ Application responsibility |
| Article 17 — third-party processor erasure | ⚠️ Application responsibility |
| CCPA §1798.105 — deletion right | ✅ Covered by Article 17 routes |
| Admin/operator SAR tooling | ⚠️ Application responsibility |

## Running `autumn doctor`

After registering your application's models, run:

```bash
autumn doctor
```

The `gdpr_export_registration` check will warn if any `#[repository]`-annotated
models are not registered for export/erasure. Register models via `GdprRegistry`
in your application state.
"#
    .to_owned()
}

fn auth_route_entries(totp: bool, magic_link: bool) -> Vec<String> {
    let mut entries = vec![
        "routes::auth::signup_form".to_owned(),
        "routes::auth::signup".to_owned(),
        "routes::auth::login_form".to_owned(),
        "routes::auth::login".to_owned(),
        "routes::auth::logout".to_owned(),
        "routes::auth::unlock_account".to_owned(),
        "routes::auth::account".to_owned(),
        "routes::auth::account_destroy".to_owned(),
        "routes::auth::change_password_form".to_owned(),
        "routes::auth::change_password".to_owned(),
        "routes::auth::change_email_form".to_owned(),
        "routes::auth::change_email".to_owned(),
        "routes::auth::confirm_email_change".to_owned(),
        "routes::auth::sessions_page".to_owned(),
        "routes::auth::sessions_revoke".to_owned(),
        "routes::auth::sessions_revoke_remember".to_owned(),
        "routes::auth::sessions_revoke_others".to_owned(),
        "routes::auth::sessions_label".to_owned(),
        "routes::auth::reauth_form".to_owned(),
        "routes::auth::reauth".to_owned(),
        "routes::auth::forgot_password_form".to_owned(),
        "routes::auth::forgot_password".to_owned(),
        "routes::auth::reset_password_form".to_owned(),
        "routes::auth::reset_password".to_owned(),
        "routes::auth::check_your_email".to_owned(),
        "routes::auth::resend_confirmation_form".to_owned(),
        "routes::auth::resend_confirmation".to_owned(),
        "routes::auth::confirm_email".to_owned(),
        "routes::auth::data_export_form".to_owned(),
        "routes::auth::data_export".to_owned(),
        "routes::auth::delete_account_form".to_owned(),
        "routes::auth::delete_account".to_owned(),
        "routes::auth::cancel_delete_account".to_owned(),
        "routes::auth::admin_data_export".to_owned(),
        "routes::auth::admin_delete_account".to_owned(),
    ];
    if totp {
        entries.extend([
            "routes::auth::login_verify_form".to_owned(),
            "routes::auth::login_verify".to_owned(),
            "routes::auth::two_factor_status".to_owned(),
            "routes::auth::two_factor_enable".to_owned(),
            "routes::auth::two_factor_confirm".to_owned(),
            "routes::auth::two_factor_disable".to_owned(),
        ]);
    }
    if magic_link {
        entries.extend([
            "routes::auth::magic_link_request_form".to_owned(),
            "routes::auth::magic_link_request".to_owned(),
            "routes::auth::magic_link_verify_form".to_owned(),
            "routes::auth::magic_link_verify".to_owned(),
        ]);
    }
    entries
}

fn oauth_route_entries() -> Vec<String> {
    vec![
        "routes::oauth::oauth_redirect".to_owned(),
        "routes::oauth::oauth_callback".to_owned(),
    ]
}

fn render_oauth_migration_up(
    backend: autumn_web::config::DatabaseBackend,
    user_table: &str,
) -> String {
    let d = AuthDdl::for_backend(backend);
    format!(
        "CREATE TABLE oauth_identities (\n\
         \x20   id {pk},\n\
         \x20   provider TEXT NOT NULL,\n\
         \x20   subject TEXT NOT NULL,\n\
         \x20   user_id {big_int} NOT NULL REFERENCES {user_table}(id) ON DELETE CASCADE,\n\
         \x20   email TEXT NULL,\n\
         \x20   name TEXT NULL,\n\
         \x20   created_at {created_at},\n\
         \x20   UNIQUE (provider, subject)\n\
         );\n\
         \n\
         CREATE INDEX oauth_identities_user_id_idx ON oauth_identities (user_id);\n",
        pk = d.pk,
        big_int = d.big_int,
        created_at = d.ts_not_null_default_now,
    )
}

fn render_oauth_migration_down() -> String {
    "DROP TABLE oauth_identities;\n".to_owned()
}

#[allow(clippy::too_many_lines)]
fn render_oauth_routes_file(
    pascal_name: &str,
    snake_name: &str,
    user_table: &str,
    providers: &[String],
    totp: bool,
) -> String {
    let provider_list = providers
        .iter()
        .map(|p| format!("\"{p}\""))
        .collect::<Vec<_>>()
        .join(", ");

    // When TOTP is also generated, the callback guidance must NOT set the secured
    // session key directly for a 2FA-enabled account — it has to route through
    // `/login/verify` exactly like password login, or OAuth would bypass 2FA.
    let totp_callback_note = if totp {
        "    //\n\
         \x20   // ⚠️ TWO-FACTOR: this app was generated with `--totp`. If the resolved\n\
         \x20   // local account has `totp_enabled == true`, do NOT set the secured\n\
         \x20   // session key here. Instead mark the session pending and redirect to\n\
         \x20   // the second-factor form, mirroring the password-login flow:\n\
         \x20   //\n\
         \x20   //   if local_user.totp_enabled {\n\
         \x20   //       // Refuse if [auth].session_key collides with a reserved pending\n\
         \x20   //       // key — otherwise parking `totp_pending_id` would write the very\n\
         \x20   //       // key `#[secured]` trusts, authenticating before /login/verify:\n\
         \x20   //       if crate::routes::auth::is_reserved_totp_pending_key(&auth_cfg.session_key) {\n\
         \x20   //           return Redirect::to(\"/login?error=totp_key_collision\").into_response();\n\
         \x20   //       }\n\
         \x20   //       session.rotate_id().await;\n\
         \x20   //       // rotate_id() keeps session data, so drop any live auth from a\n\
         \x20   //       // prior login in this browser before parking the pending handoff:\n\
         \x20   //       session.remove(&auth_cfg.session_key).await;\n\
         \x20   //       session.remove(\"__SNAKE___id\").await;\n\
         \x20   //       session.remove(\"__SNAKE___email\").await;\n\
         \x20   //       session.remove(\"totp_pending_reset_digest\").await;\n\
         \x20   //       session.remove(\"totp_pending_reset_token\").await;\n\
         \x20   //       session.remove(\"totp_pending_secret\").await;\n\
         \x20   //       session.insert(\"totp_pending_id\", local_user.id.to_string()).await;\n\
         \x20   //       return Redirect::to(\"/login/verify\").into_response();\n\
         \x20   //   }\n\
         \x20   //   // otherwise, fully authenticate. Rotate the session id first — like\n\
         \x20   //   // the password-login/reset paths — so a pre-login (possibly fixated)\n\
         \x20   //   // session id is never promoted unchanged:\n\
         \x20   //   session.rotate_id().await;\n\
         \x20   //   // Then clear any abandoned pending-2FA / deferred-reset / enrollment\n\
         \x20   //   // state, and set BOTH the model-specific identity keys the generated\n\
         \x20   //   // handlers read (`__SNAKE___id` / `_email`) and the configured auth key\n\
         \x20   //   // — clearing stale model keys first so a prior login in this browser\n\
         \x20   //   // can't leave a mismatched identity:\n\
         \x20   //   session.remove(\"totp_pending_id\").await;\n\
         \x20   //   session.remove(\"totp_pending_reset_digest\").await;\n\
         \x20   //   session.remove(\"totp_pending_reset_token\").await;\n\
         \x20   //   session.remove(\"totp_pending_secret\").await;\n\
         \x20   //   session.insert(\"__SNAKE___id\", local_user.id.to_string()).await;\n\
         \x20   //   session.insert(\"__SNAKE___email\", &local_user.email).await;\n\
         \x20   //   session.insert(&auth_cfg.session_key, local_user.id.to_string()).await;\n"
            .replace("__SNAKE__", snake_name)
    } else {
        String::new()
    };

    format!(
        r#"//! OAuth2/OIDC redirect and callback handlers.
//!
//! Generated by `autumn generate auth --oauth`.
//! Edit freely — once generated this is ordinary user code.
//!
//! Routes:
//!   GET  /auth/:provider/redirect  → redirects the browser to the provider
//!   GET  /auth/:provider/callback  → exchanges the code and logs the user in

use autumn_web::auth::{{OAuth2Callback, OidcIdentity, oauth2_authorize_url, oauth2_finish_login}};
use autumn_web::prelude::*;
use autumn_web::{{get, oauth2_callback, AppState, State}};
use axum::extract::{{Path, Query}};
use axum::response::{{IntoResponse, Redirect}};
use tracing::warn;

/// Supported OAuth2/OIDC providers.
const SUPPORTED_PROVIDERS: &[&str] = &[{provider_list}];

/// Redirect the browser to the provider's authorization endpoint.
///
/// State and nonce are stored in the session for CSRF protection.
/// PKCE (S256) code_challenge is appended automatically by the framework.
#[get("/auth/{{provider}}/redirect")]
pub async fn oauth_redirect(
    Path(provider_name): Path<String>,
    State(state): State<AppState>,
    session: Session,
) -> impl IntoResponse {{
    if !SUPPORTED_PROVIDERS.contains(&provider_name.as_str()) {{
        return Redirect::to("/login?error=unknown_provider").into_response();
    }}

    // `config_arc` shares the resolved config behind an `Arc`; `config()`
    // would deep-clone every section to read one field on a request path.
    let config = state.config_arc();
    let auth_cfg = &config.auth;
    let Some(provider) = auth_cfg.oauth2.providers.get(&provider_name) else {{
        warn!(provider = %provider_name, "oauth provider not configured in autumn.toml");
        return Redirect::to("/login?error=provider_not_configured").into_response();
    }};

    match oauth2_authorize_url(&session, &provider_name, provider).await {{
        Ok(url) => Redirect::to(&url).into_response(),
        Err(e) => {{
            warn!(error = %e, "oauth2_authorize_url failed");
            Redirect::to("/login?error=oauth_error").into_response()
        }}
    }}
}}

/// Handle the OAuth2 callback: exchange the code, create or link a local account.
///
/// On success the user is redirected to `/account`. A missing or mismatched state
/// returns a non-revealing error redirect without logging the offending values.
///
/// **Important:** `oauth2_finish_login` does NOT set the application session key.
/// You must resolve (or create) the local {pascal_name} row and call
/// `session.insert(&auth_cfg.session_key, local_user_id.to_string())` before redirecting.
#[oauth2_callback("/auth/{{provider}}/callback")]
pub async fn oauth_callback(
    Path(provider_name): Path<String>,
    Query(callback): Query<OAuth2Callback>,
    State(state): State<AppState>,
    session: Session,
) -> impl IntoResponse {{
    if !SUPPORTED_PROVIDERS.contains(&provider_name.as_str()) {{
        return Redirect::to("/login?error=unknown_provider").into_response();
    }}

    // `config_arc` shares the resolved config behind an `Arc`; `config()`
    // would deep-clone every section to read one field on a request path.
    let config = state.config_arc();
    let auth_cfg = &config.auth;
    let Some(provider) = auth_cfg.oauth2.providers.get(&provider_name) else {{
        warn!(provider = %provider_name, "oauth provider not configured in autumn.toml");
        return Redirect::to("/login?error=provider_not_configured").into_response();
    }};

    let identity: OidcIdentity = match oauth2_finish_login(
        &session,
        &provider_name,
        provider,
        &callback,
    )
    .await
    {{
        Ok(id) => id,
        Err(_) => {{
            // Do not log the offending state or code to avoid leaking sensitive values.
            return Redirect::to("/login?error=oauth_failed").into_response();
        }}
    }};

    // TODO: resolve or create a local {pascal_name} record, then set the session.
    //
    // Example (fill in your actual DB query):
    //
    //   let local_user_id: i64 = link_or_create_{snake_name}(
    //       &mut db,
    //       &identity,          // OidcIdentity {{ subject, email, name, … }}
    //       &provider_name,     // e.g. "github"
    //       &auth_cfg,          // carries oauth_linking_policy
    //   ).await?;
    //
    //   session.insert(&auth_cfg.session_key, local_user_id.to_string()).await;
    //
    //   // Track the OAuth login as an active session (device list + revocation,
    //   // issue #819) — add `MaybeClientIp(addr_ip)` and `headers: HeaderMap`
    //   // extractors to this handler, then:
    //   crate::routes::auth::record_login_session(&mut db, &session, local_user_id, addr_ip, &headers).await?;
    //
    // Until the above is implemented the user will NOT be logged in after the OAuth
    // callback — that is intentional to avoid authenticating without a local account.
{totp_callback_note}    let _ = identity;
    let _ = user_table_placeholder_{snake_name}();

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

#[allow(dead_code)]
fn user_table_placeholder_{snake_name}() -> &'static str {{
    "{user_table}"
}}
"#,
    )
}

#[allow(clippy::too_many_lines)]
fn render_oauth_docs_file(
    backend: autumn_web::config::DatabaseBackend,
    providers: &[String],
    user_table: &str,
) -> String {
    // The documented schema must match the migration this same run writes, so
    // it takes its column types from the same dialect table (issue #1908).
    let d = AuthDdl::for_backend(backend);
    let provider_list = providers.join(", ");
    let provider_config_examples = providers
        .iter()
        .map(|p| match p.as_str() {
            "github" => concat!(
                "[auth.oauth2.github]\n",
                "client_id     = \"\"\n",
                "client_secret = \"\"\n",
                "authorize_url = \"https://github.com/login/oauth/authorize\"\n",
                "token_url     = \"https://github.com/login/oauth/access_token\"\n",
                "userinfo_url  = \"https://api.github.com/user\"\n",
                "redirect_uri  = \"https://your-app.example.com/auth/github/callback\"\n",
                "scope         = \"read:user user:email\"\n",
            )
            .to_owned(),
            "google" => concat!(
                "[auth.oauth2.google]\n",
                "client_id     = \"\"\n",
                "client_secret = \"\"\n",
                "authorize_url = \"https://accounts.google.com/o/oauth2/v2/auth\"\n",
                "token_url     = \"https://oauth2.googleapis.com/token\"\n",
                "userinfo_url  = \"https://openidconnect.googleapis.com/v1/userinfo\"\n",
                "redirect_uri  = \"https://your-app.example.com/auth/google/callback\"\n",
                "scope         = \"openid email profile\"\n",
                "issuer        = \"https://accounts.google.com\"\n",
                "jwks_url      = \"https://www.googleapis.com/oauth2/v3/certs\"\n",
                "discovery_url = \"https://accounts.google.com\"\n",
            )
            .to_owned(),
            "microsoft" => concat!(
                "[auth.oauth2.microsoft]\n",
                "client_id     = \"\"\n",
                "client_secret = \"\"\n",
                "authorize_url = \"https://login.microsoftonline.com/{YOUR_TENANT_ID}/oauth2/v2.0/authorize\"\n",
                "token_url     = \"https://login.microsoftonline.com/{YOUR_TENANT_ID}/oauth2/v2.0/token\"\n",
                "redirect_uri  = \"https://your-app.example.com/auth/microsoft/callback\"\n",
                "scope         = \"openid email profile\"\n",
                "# Single-tenant: replace {YOUR_TENANT_ID} with your Directory (tenant) ID.\n",
                "# Multi-tenant (common endpoint): ID-token issuer varies per user — see docs/guide/oauth.md.\n",
                "issuer        = \"https://login.microsoftonline.com/{YOUR_TENANT_ID}/v2.0\"\n",
                "jwks_url      = \"https://login.microsoftonline.com/{YOUR_TENANT_ID}/discovery/v2.0/keys\"\n",
            )
            .to_owned(),
            p => {
                format!(
                    r#"[auth.oauth2.{p}]
client_id     = ""
client_secret = ""
authorize_url = "https://{p}.example.com/oauth2/authorize"
token_url     = "https://{p}.example.com/oauth2/token"
redirect_uri  = "https://your-app.example.com/auth/{p}/callback"
scope         = "openid profile email"
"#
                )
            }
        })
        .collect::<Vec<_>>()
        .join("\n");

    format!(
        r#"# OAuth2 / OIDC Authentication

Generated by `autumn generate auth --oauth {provider_list}`.

## Quick start

### 1. Register redirect URIs with each provider

Before the app will work you must register each redirect URI with the provider's
developer console:

| Provider | Console URL | Redirect URI path |
|----------|-------------|-------------------|
| Google   | <https://console.cloud.google.com/> | `/auth/google/callback` |
| GitHub   | <https://github.com/settings/developers> | `/auth/github/callback` |
| Microsoft | <https://portal.azure.com/> | `/auth/microsoft/callback` |

### 2. Add provider credentials to `autumn.toml`

```toml
{provider_config_examples}
```

Keep `client_secret` out of source control — use environment variables or
`autumn credentials edit` to inject secrets at runtime.

### 3. Run the generator command

```sh
autumn generate auth User --oauth {provider_list}
autumn migrate
autumn dev
```

Open <http://localhost:3000/auth/{first_provider}/redirect> to test the flow.

## Security properties

| Property | Status |
|----------|---------|
| PKCE (S256) | ✅ enabled for every provider by default |
| State (anti-CSRF) | ✅ constant-time validated on every callback |
| Nonce (replay protection) | ✅ validated for OIDC ID-token flows |
| ID-token signature | ✅ verified against provider JWKS |
| Session fixation prevention | ✅ session ID rotated on login |
| `client_secret` in logs | ✅ never logged |

## Account-linking policy

Configure in `autumn.toml`:

```toml
[auth]
oauth_linking_policy = "create_account"           # default: create a new account on first sign-in
# oauth_linking_policy = "require_local_signup_first"  # link only to existing accounts
```

## OIDC discovery

Providers that support OIDC discovery (`discovery_url` in preset) have their
endpoints populated automatically from `{{discovery_url}}/.well-known/openid-configuration`.
GitHub uses explicit endpoints (it is pure OAuth2, not OIDC).

## Troubleshooting

**`redirect_uri_mismatch`** — The `redirect_uri` in `autumn.toml` must match
exactly what is registered in the provider console, including scheme and path.

**`invalid_client`** — Check that `client_id` and `client_secret` are correct
and that the app is not in a restricted mode in the provider console.

**`state mismatch` on callback** — The session may have expired between the
redirect and callback. Increase `[session] ttl` or check for load-balancer
sticky-session misconfiguration.

## Generated database schema

```sql
CREATE TABLE oauth_identities (
    id         {pk},
    provider   TEXT NOT NULL,
    subject    TEXT NOT NULL,         -- provider's user identifier (sub / id)
    user_id    {big_int} NOT NULL REFERENCES {user_table}(id) ON DELETE CASCADE,
    email      TEXT NULL,
    name       TEXT NULL,
    created_at {created_at},
    UNIQUE (provider, subject)        -- collision guard: one local account per identity
);
```

Re-authentication with the same `(provider, subject)` pair links to the existing
account. A second local user trying to claim the same identity returns an error and
never silently merges accounts.
"#,
        first_provider = providers.first().map_or("github", String::as_str),
        pk = d.pk,
        big_int = d.big_int,
        created_at = d.ts_not_null_default_now,
    )
}

// ── TOTP (two-factor) template fragments ────────────────────────────────────────
//
// These helpers return generated *application* source as plain Strings, so the
// braces inside are literal (never processed by this generator's `format!`).

/// Extra `use` lines added to the generated `src/routes/auth.rs` under `--totp`.
const fn totp_imports_src() -> &'static str {
    "use aes_gcm::aead::{Aead, KeyInit};\n\
     use aes_gcm::{Aes256Gcm, Key, Nonce};\n\
     use base64::Engine as _;\n\
     use base64::engine::general_purpose::STANDARD as B64;\n\
     use autumn_web::form::{OtpFormat, otp_input_with};\n\
     use totp_rs::{Algorithm, Secret, TOTP};\n\
     use crate::models::recovery_code::{NewRecoveryCode, RecoveryCode};\n\
     use crate::schema::recovery_codes;\n"
}

/// The interstitial branch injected into `login` after password verification.
///
/// A password login starts a *fresh* pending-2FA handoff, so it first clears any
/// stale pending markers left by an abandoned earlier flow (a different account's
/// pending login, or a parked reset) before parking this account.
fn totp_login_branch_src(snake_name: &str) -> String {
    const TPL: &str = r#"
    // ── 2FA interstitial ────────────────────────────────────────────────────
    // If the account has TOTP enabled, do NOT set the `#[secured]` auth key yet.
    // Mark the session `totp_pending` and redirect to the second-factor form.
    if __SNAKE__.totp_enabled {
        // A pending (pre-2FA) session must never write the `#[secured]` auth key.
        // If the app configured `[auth].session_key` to collide with one of the
        // reserved `totp_pending_*` keys, parking the pending marker would set the
        // trusted auth key and let a half-authenticated session pass `#[secured]`.
        // Refuse rather than risk a 2FA bypass.
        if is_reserved_totp_pending_key(state.auth_session_key()) {
            return Err(AutumnError::internal_server_error_msg(
                "[auth].session_key collides with a reserved TOTP pending key (totp_pending_*). \
                 Choose a different [auth].session_key.",
            ));
        }
        session.rotate_id().await;
        // `rotate_id()` keeps existing session data, so if this browser was
        // already authenticated as another account, drop those *live* auth keys
        // before parking the pending handoff — otherwise `#[secured]` routes
        // would still treat the pre-2FA session as the previous account.
        session.remove("__SNAKE___id").await;
        session.remove("__SNAKE___email").await;
        session.remove(state.auth_session_key()).await;
        // Drop any abandoned pending state from a previous flow too, so a stale
        // parked reset, enrollment secret, or a different account's pending login
        // can never be resumed under this login.
        session.remove("totp_pending_reset_digest").await;
        session.remove("totp_pending_reset_token").await;
        session.remove("totp_pending_secret").await;
        session.remove("totp_pending_confirmation").await;
        session
            .insert("totp_pending_id", __SNAKE__.id.to_string())
            .await;
        return Ok(redirect_to("/login/verify"));
    }
"#;
    TPL.replace("__SNAKE__", snake_name)
}

/// Lines injected into every *direct* full-authentication path (password login,
/// password reset, and signup for non-2FA accounts) right after
/// `session.rotate_id()`. They clear any leftover pending-2FA / parked-reset
/// markers — and any half-finished enrollment secret — so an abandoned
/// `/login/verify` or `/account/2fa/enable` for another account can't be
/// resumed against this freshly established session.
const fn totp_clear_pending_src() -> &'static str {
    "    // Clear any abandoned pending-2FA / deferred-reset / enrollment state so it\n\
     \x20   // cannot be resumed under this freshly authenticated session.\n\
     \x20   session.remove(\"totp_pending_id\").await;\n\
     \x20   session.remove(\"totp_pending_reset_digest\").await;\n\
     \x20   session.remove(\"totp_pending_reset_token\").await;\n\
     \x20   session.remove(\"totp_pending_secret\").await;\n\
     \x20   session.remove(\"totp_pending_confirmation\").await;\n"
}

/// The interstitial branch injected into `reset_password` *before* the password
/// is written. A correct reset token proves control of the email, not possession
/// of the second factor — so for a 2FA-enabled account we DEFER the password
/// change: stash the new digest in the session and require `/login/verify` to
/// pass before committing it. Someone with only the emailed link therefore can't
/// change the password (lockout/DoS) without the second factor.
fn totp_reset_branch_src(snake_name: &str) -> String {
    const TPL: &str = r#"
    // ── 2FA interstitial ────────────────────────────────────────────────────
    if __SNAKE__.totp_enabled {
        // A pending (pre-2FA) session must never write the `#[secured]` auth key
        // (see the login interstitial). Refuse a colliding `[auth].session_key`.
        if is_reserved_totp_pending_key(state.auth_session_key()) {
            return Err(AutumnError::internal_server_error_msg(
                "[auth].session_key collides with a reserved TOTP pending key (totp_pending_*). \
                 Choose a different [auth].session_key.",
            ));
        }
        // Do NOT write the new password yet. Park it in the session and finish
        // the reset in `login_verify` only after the second factor is proven.
        session.rotate_id().await;
        // `rotate_id()` keeps existing session data, so drop any live auth keys
        // from a prior login in this browser before parking the pending handoff
        // (see the login interstitial), and any half-finished enrollment secret.
        session.remove("__SNAKE___id").await;
        session.remove("__SNAKE___email").await;
        session.remove(state.auth_session_key()).await;
        session.remove("totp_pending_secret").await;
        session.remove("totp_pending_confirmation").await;
        session
            .insert("totp_pending_id", __SNAKE__.id.to_string())
            .await;
        session.insert("totp_pending_reset_digest", &new_digest).await;
        session.insert("totp_pending_reset_token", &token_digest).await;
        return Ok(redirect_to("/login/verify"));
    }
"#;
    TPL.replace("__SNAKE__", snake_name)
}

/// The interstitial branch injected into `confirm_email` after the token is
/// validated.  Email confirmation proves address ownership, not TOTP possession —
/// so a 2FA-enabled account is parked in pending state and sent to /login/verify
/// rather than immediately receiving a full authenticated session.
fn totp_confirm_branch_src(snake_name: &str) -> String {
    const TPL: &str = r#"
    // ── 2FA interstitial ────────────────────────────────────────────────────
    // Confirming the email proves address ownership but not possession of the
    // second factor.  For a 2FA-enabled account, park the session and redirect
    // to /login/verify so TOTP is still required to complete authentication.
    if __SNAKE__.totp_enabled {
        if is_reserved_totp_pending_key(state.auth_session_key()) {
            return Err(AutumnError::internal_server_error_msg(
                "[auth].session_key collides with a reserved TOTP pending key (totp_pending_*). \
                 Choose a different [auth].session_key.",
            ));
        }
        session.rotate_id().await;
        // rotate_id() preserves session data; drop the step-up claim so a
        // prior password-authenticated session cannot piggyback step-up
        // privileges into this email-confirmation-only pending session.
        session.remove(autumn_web::step_up::STEP_UP_SESSION_KEY).await;
        session.remove("__SNAKE___id").await;
        session.remove("__SNAKE___email").await;
        session.remove(state.auth_session_key()).await;
        session.remove("totp_pending_reset_digest").await;
        session.remove("totp_pending_reset_token").await;
        session.remove("totp_pending_secret").await;
        session
            .insert("totp_pending_id", __SNAKE__.id.to_string())
            .await;
        // Mark that this pending login originated from email confirmation (not a
        // password login). login_verify checks this to skip the step-up stamp:
        // email + TOTP proves address & second-factor but NOT password knowledge.
        session.insert("totp_pending_confirmation", "1").await;
        return Ok(redirect_to("/login/verify"));
    }
"#;
    TPL.replace("__SNAKE__", snake_name)
}

/// HTML fragment injected into the reauth form for TOTP-enabled projects.
///
/// Shown as an optional field; the handler enforces it for accounts that have
/// `totp_enabled = true` and ignores it for accounts that don't.
fn totp_reauth_field_src() -> String {
    "            div {{\n\
     \x20               label for=\"totp-code\" {{ \"Authenticator code\" }}\n\
     \x20               input type=\"text\" id=\"totp-code\" name=\"totp_code\" autocomplete=\"one-time-code\"\n\
     \x20                   inputmode=\"text\" pattern=\"[0-9a-fA-F \\\\-]*\" aria-describedby=\"totp-hint\";\n\
     \x20               small id=\"totp-hint\" {{ \"Enter the 6-digit code or a recovery code. Required if your account uses two-factor authentication.\" }}\n\
     \x20           }}\n"
        .to_owned()
}

/// Verification block injected into the `reauth` handler after the password
/// check when TOTP is enabled.  For accounts with `totp_enabled = true` the
/// user must also supply a valid TOTP code or recovery code; other accounts
/// pass through without any second-factor check.
#[allow(clippy::too_many_lines)]
fn totp_reauth_check_src(snake_name: &str, table: &str) -> String {
    // This string is substituted verbatim into the outer format!() as a named argument.
    // format!() does NOT further process the substituted value, so {{ and }} in this
    // template appear literally in the output. Use single { } for Rust control flow,
    // and {{ }} only inside maud html! invocations.
    const TPL: &str = r#"    // If the account uses TOTP, also require the second factor.
    if __SNAKE__.totp_enabled {
        let code = form.totp_code.trim().to_owned();
        if code.is_empty() {
            let return_to = form.return_to.clone();
            return Ok(crate::layout("Confirm your identity", "/reauth", html! {}, html! {{
                h1 {{ "Confirm your identity" }}
                p style="color:red" {{ "Your account uses two-factor authentication. Please also enter your authenticator code." }}
                form action="/reauth" method="post" {{
                    @if let Some(ref csrf) = csrf {{ input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }}
                    input type="hidden" name="return_to" value=(return_to);
                    div {{
                        label for="totp-code" {{ "Authenticator code" }}
                        input type="text" id="totp-code" name="totp_code" autocomplete="one-time-code"
                            inputmode="text" pattern="[0-9a-fA-F \\-]*" required
                            aria-describedby="totp-hint";
                        small id="totp-hint" {{ "Enter the 6-digit code or a recovery code. Required if your account uses two-factor authentication." }}
                    }}
                    button type="submit" {{ "Confirm" }}
                }}
            }}).into_response());
        }
        let mut totp_verified = false;
        if let Some(stored) = __SNAKE__.totp_secret_encrypted.as_deref() {
            if let Some(step) = decrypt_secret(stored)
                .ok()
                .and_then(|secret| build_totp(secret, &__SNAKE__.email).ok())
                .and_then(|totp| verify_totp_code(&totp, &code))
            {
                let affected = diesel::update(
                    __TABLE__::table.find(__SNAKE__.id).filter(
                        __TABLE__::totp_last_used_step
                            .is_null()
                            .or(__TABLE__::totp_last_used_step.lt(step)),
                    ),
                )
                .set(__TABLE__::totp_last_used_step.eq(Some(step)))
                .execute(&mut *db)
                .await?;
                if affected == 1 {
                    totp_verified = true;
                }
            }
        }
        if !totp_verified {
            let unused: Vec<RecoveryCode> = recovery_codes::table
                .filter(recovery_codes::user_id.eq(__SNAKE__.id))
                .filter(recovery_codes::used_at.is_null())
                .select(RecoveryCode::as_select())
                .load(&mut *db)
                .await
                .unwrap_or_default();
            for rc in &unused {
                if verify_password(&code, &rc.code_digest).await.unwrap_or(false) {
                    let affected = diesel::update(
                        recovery_codes::table
                            .find(rc.id)
                            .filter(recovery_codes::used_at.is_null()),
                    )
                    .set(recovery_codes::used_at.eq(Some(chrono::Utc::now().naive_utc())))
                    .execute(&mut *db)
                    .await?;
                    if affected == 1 {
                        totp_verified = true;
                        break;
                    }
                }
            }
        }
        if !totp_verified {
            let return_to = form.return_to.clone();
            return Ok(crate::layout("Confirm your identity", "/reauth", html! {}, html! {{
                h1 {{ "Confirm your identity" }}
                p style="color:red" {{ "Invalid authenticator code. Please try again." }}
                form action="/reauth" method="post" {{
                    @if let Some(ref csrf) = csrf {{ input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }}
                    input type="hidden" name="return_to" value=(return_to);
                    div {{
                        label for="totp-code" {{ "Authenticator code" }}
                        input type="text" id="totp-code" name="totp_code" autocomplete="one-time-code"
                            inputmode="text" pattern="[0-9a-fA-F \\-]*" required
                            aria-describedby="totp-hint";
                        small id="totp-hint" {{ "Enter the 6-digit code or a recovery code. Required if your account uses two-factor authentication." }}
                    }}
                    button type="submit" {{ "Confirm" }}
                }}
            }}).into_response());
        }
    }
"#;
    TPL.replace("__SNAKE__", snake_name)
        .replace("__TABLE__", table)
}

#[allow(clippy::too_many_lines)]
fn totp_routes_section_src(
    pascal_name: &str,
    snake_name: &str,
    table: &str,
    magic_link: bool,
) -> String {
    const TPL: &str = r#"
// ── Two-factor authentication (TOTP) ────────────────────────────────────────────
//
// Generated by `autumn generate auth --totp`. Edit freely.
//
// Security properties:
// - TOTP secrets are encrypted at rest with AES-256-GCM (never stored plaintext).
// - Verification accepts a ±1 time-step window and refuses to replay a step that
//   was already consumed (`totp_last_used_step`).
// - Recovery codes are single-use; only their bcrypt digest is stored and each is
//   marked `used_at` when consumed.
// - NOTE: rate-limiting / lockout on repeated failed second-factor attempts is a
//   follow-up (see docs) — add it before exposing this to untrusted traffic.

/// Number of single-use recovery codes generated on enrollment.
const RECOVERY_CODE_COUNT: usize = 10;

/// TOTP time step in seconds (RFC 6238 default).
const TOTP_STEP: u64 = 30;

/// Session keys reserved by the two-factor flow for transient pre-auth state.
/// `[auth].session_key` must not collide with any of these, or a pending
/// (pre-2FA) session could be mistaken for a fully authenticated one.
const RESERVED_TOTP_PENDING_KEYS: &[&str] = &[
    "totp_pending_id",
    "totp_pending_reset_digest",
    "totp_pending_reset_token",
    "totp_pending_secret",
    "totp_pending_confirmation",
];

/// Whether `key` (typically the configured `[auth].session_key`) collides with a
/// reserved `totp_pending_*` key. Used to refuse a config that would let a
/// pending second-factor session write the trusted `#[secured]` auth key.
///
/// `pub(crate)` so the OAuth callback handler (a separate module) can apply the
/// same guard before parking a pending 2FA session.
pub(crate) fn is_reserved_totp_pending_key(key: &str) -> bool {
    RESERVED_TOTP_PENDING_KEYS.contains(&key)
}

#[derive(Deserialize)]
pub struct TotpCodeForm {
    pub code: String,
}

#[derive(Deserialize)]
pub struct TotpEnableForm {
    pub password: String,
}

#[derive(Deserialize)]
pub struct TotpDisableForm {
    pub password: Option<String>,
    pub code: Option<String>,
}

/// Load the 32-byte AES-256-GCM key used to encrypt TOTP secrets at rest.
///
/// Read from the `TOTP_ENC_KEY` env var (base64 of 32 bytes). Manage it like any
/// other secret (e.g. `autumn credentials`); never commit it.
fn totp_enc_key() -> AutumnResult<[u8; 32]> {
    let raw = std::env::var("TOTP_ENC_KEY").map_err(|_| {
        AutumnError::internal_server_error_msg(
            "TOTP_ENC_KEY is not set. Generate 32 random bytes, base64-encode them, \
             and set TOTP_ENC_KEY before enabling two-factor auth.",
        )
    })?;
    let bytes = B64
        .decode(raw.trim())
        .map_err(|_| AutumnError::internal_server_error_msg("TOTP_ENC_KEY must be valid base64."))?;
    let arr: [u8; 32] = bytes.as_slice().try_into().map_err(|_| {
        AutumnError::internal_server_error_msg("TOTP_ENC_KEY must decode to exactly 32 bytes.")
    })?;
    Ok(arr)
}

/// Encrypt a TOTP secret for storage. Output is base64(nonce ‖ ciphertext).
fn encrypt_secret(plaintext: &[u8]) -> AutumnResult<String> {
    use rand::TryRng;
    let key = totp_enc_key()?;
    let cipher = Aes256Gcm::new(<&Key<Aes256Gcm>>::from(&key));
    let mut nonce_bytes = [0u8; 12];
    rand::rngs::SysRng
        .try_fill_bytes(&mut nonce_bytes)
        .map_err(|_| AutumnError::internal_server_error_msg("RNG failure generating nonce"))?;
    let nonce = <&Nonce<_>>::from(&nonce_bytes);
    let ct = cipher
        .encrypt(nonce, plaintext)
        .map_err(|_| AutumnError::internal_server_error_msg("failed to encrypt TOTP secret"))?;
    let mut combined = nonce_bytes.to_vec();
    combined.extend_from_slice(&ct);
    Ok(B64.encode(combined))
}

/// Decrypt a stored TOTP secret produced by [`encrypt_secret`].
fn decrypt_secret(stored: &str) -> AutumnResult<Vec<u8>> {
    let key = totp_enc_key()?;
    let cipher = Aes256Gcm::new(<&Key<Aes256Gcm>>::from(&key));
    let raw = B64
        .decode(stored.trim())
        .map_err(|_| AutumnError::internal_server_error_msg("stored TOTP secret is not valid base64"))?;
    if raw.len() < 12 {
        return Err(AutumnError::internal_server_error_msg(
            "stored TOTP secret is malformed",
        ));
    }
    let (nonce_bytes, ct) = raw.split_at(12);
    let nonce = <&Nonce<_>>::try_from(nonce_bytes)
        .map_err(|_| AutumnError::internal_server_error_msg("stored TOTP secret is malformed"))?;
    cipher
        .decrypt(nonce, ct)
        .map_err(|_| AutumnError::internal_server_error_msg("failed to decrypt TOTP secret"))
}

/// Build a `TOTP` (SHA1, 6 digits, ±1 step skew) from raw secret bytes.
///
/// `get_url()` yields the standard `otpauth://` provisioning URI used for the QR.
fn build_totp(secret: Vec<u8>, account: &str) -> AutumnResult<TOTP> {
    // `totp-rs` rejects issuer/account labels containing a colon. The account
    // label is only a display hint in the `otpauth://` URI (it doesn't affect
    // code generation/verification), so strip colons defensively — otherwise an
    // address like `a:b@example.com` would 500 on enrollment.
    let account = account.replace(':', "_");
    TOTP::new(
        Algorithm::SHA1,
        6,
        1,
        TOTP_STEP,
        secret,
        Some("__PASCAL__".to_owned()),
        account,
    )
    .map_err(|_| AutumnError::internal_server_error_msg("invalid TOTP secret"))
}

/// Current RFC 6238 time step.
fn current_step() -> i64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    (secs / TOTP_STEP) as i64
}

/// Verify a TOTP code within a ±1 step window, returning the matched step.
///
/// The caller compares the returned step against `totp_last_used_step` to reject
/// replay of an already-consumed step.
fn verify_totp_code(totp: &TOTP, code: &str) -> Option<i64> {
    let step = current_step();
    let candidate = code.trim();
    for delta in [-1i64, 0, 1] {
        let s = step + delta;
        if s < 0 {
            continue;
        }
        let expected = totp.generate(s as u64 * TOTP_STEP);
        if expected == candidate {
            return Some(s);
        }
    }
    None
}

/// Generate one human-friendly single-use recovery code (10 hex chars, grouped).
fn generate_recovery_code() -> String {
    use rand::TryRng;
    let mut bytes = [0u8; 5];
    rand::rngs::SysRng
        .try_fill_bytes(&mut bytes)
        .expect("OS RNG failed");
    let hexs = hex::encode(bytes);
    format!("{}-{}", &hexs[..5], &hexs[5..])
}

/// `GET /account/2fa` — show current two-factor state. Requires authentication.
#[secured]
#[get("/account/2fa")]
pub async fn two_factor_status(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Markup> {
    // Validates the tracked session row (401s immediately if revoked).
    let __SNAKE__ = require_tracked_session(&session, &mut db, &state).await?;

    let remaining: i64 = if __SNAKE__.totp_enabled {
        recovery_codes::table
            .filter(recovery_codes::user_id.eq(__SNAKE__.id))
            .filter(recovery_codes::used_at.is_null())
            .count()
            .get_result(&mut *db)
            .await
            .unwrap_or(0)
    } else {
        0
    };

    Ok(crate::layout("Two-Factor Authentication", "/account/2fa", html! {}, html! {
        h1 { "Two-Factor Authentication" }
        @if __SNAKE__.totp_enabled {
            p { "Two-factor authentication is " strong { "enabled" } "." }
            p { "You have " (remaining) " recovery codes remaining." }
            form action="/account/2fa/disable" method="post" {
                @if let Some(ref csrf) = csrf { input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }
                (password_field("password", "Confirm with your password", FieldOptions::new().current_password().reveal()))
                // One input: paste and SMS autofill fill all six boxes.
                (otp_input_with(&Changeset::new(()), "code", "or a current 6-digit code", OtpFormat::digits(6), &FieldOptions::new()))
                button type="submit" { "Disable two-factor" }
            }
        } @else {
            p { "Two-factor authentication is " strong { "disabled" } "." }
            form action="/account/2fa/enable" method="post" {
                @if let Some(ref csrf) = csrf { input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }
                (password_field("password", "Confirm your password to begin enrollment:", FieldOptions::new().required().current_password().reveal()))
                button type="submit" { "Enable two-factor" }
            }
        }
    }))
}

/// `POST /account/2fa/enable` — generate a secret, render the QR + manual key,
/// and ask the user to confirm with a valid code before enabling. Requires auth.
///
/// The pending secret is held in the session (encrypted) and is NOT written to
/// the account until `two_factor_confirm` succeeds. This means starting (and
/// abandoning) re-enrollment never disturbs an already-active second factor.
#[secured]
#[post("/account/2fa/enable")]
pub async fn two_factor_enable(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
    Form(form): Form<TotpEnableForm>,
) -> AutumnResult<Markup> {
    // Enrollment stashes `totp_pending_secret` in the session. If the app
    // configured `[auth].session_key` to a reserved `totp_pending_*` name, that
    // write would clobber the live auth key and the account would later be
    // locked out by the reserved-key guard in the login interstitial. Refuse the
    // misconfiguration up front (the login/reset handoffs reject it too).
    if is_reserved_totp_pending_key(state.auth_session_key()) {
        return Err(AutumnError::internal_server_error_msg(
            "[auth].session_key collides with a reserved TOTP pending key (totp_pending_*). \
             Choose a different [auth].session_key.",
        ));
    }
    // Validates the tracked session row (401s immediately if revoked).
    let __SNAKE__ = require_tracked_session(&session, &mut db, &state).await?;

    // Step-up re-auth: a logged-in but unattended/hijacked session must not be
    // able to enroll an attacker's authenticator. Require the account password
    // before starting enrollment (matches GitHub/Google behaviour).
    if !verify_password(&form.password, &__SNAKE__.password_digest)
        .await
        .unwrap_or(false)
    {
        return Err(AutumnError::unprocessable_msg(
            "Password confirmation failed.",
        ));
    }

    // Re-enrollment guard: if 2FA is already active, a hijacked (already-past-2FA)
    // session must not be able to swap in a new authenticator without re-proving
    // the current factor. Disabling first goes through `/account/2fa/disable`,
    // which requires a current code or the password.
    if __SNAKE__.totp_enabled {
        return Err(AutumnError::unprocessable_msg(
            "Two-factor is already enabled. Disable it first (which requires your \
             current code or password) before enrolling a new authenticator.",
        ));
    }

    let secret = Secret::generate_secret();
    let secret_bytes = secret
        .to_bytes()
        .map_err(|_| AutumnError::internal_server_error_msg("failed to generate TOTP secret"))?;
    let manual_key = secret.to_encoded().to_string();
    let totp = build_totp(secret_bytes.clone(), &__SNAKE__.email)?;
    // The provisioning URI (otpauth://…) drives the QR and manual entry.
    let provisioning_uri = totp.get_url();
    let qr = totp
        .get_qr_base64()
        .map_err(|_| AutumnError::internal_server_error_msg("failed to render QR code"))?;

    // Stash the pending secret in the session only — the live account row is
    // untouched until the user proves possession in `two_factor_confirm`.
    let encrypted = encrypt_secret(&secret_bytes)?;
    session.insert("totp_pending_secret", &encrypted).await;

    Ok(crate::layout("Enable Two-Factor", "/account/2fa", html! {}, html! {
        h1 { "Scan this QR code" }
        p { "Scan with Google Authenticator, 1Password, or any RFC 6238 app." }
        img src=(format!("data:image/png;base64,{}", qr)) alt="TOTP QR code";
        p { "Or enter this key manually: " code { (manual_key) } }
        p { small { "Provisioning URI: " code { (provisioning_uri) } } }
        h2 { "Confirm" }
        p { "Enter the 6-digit code shown in your app to finish enabling 2FA." }
        form action="/account/2fa/confirm" method="post" {
            @if let Some(ref csrf) = csrf { input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }
            (otp_input_with(&Changeset::new(()), "code", "6-digit code", OtpFormat::digits(6), &FieldOptions::new().required()))
            button type="submit" { "Confirm and enable" }
        }
    }))
}

/// `POST /account/2fa/confirm` — verify a code against the pending secret, flip
/// `totp_enabled`, and generate single-use recovery codes (shown once). Requires auth.
#[secured]
#[post("/account/2fa/confirm")]
pub async fn two_factor_confirm(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    Form(form): Form<TotpCodeForm>,
) -> AutumnResult<Markup> {
    // Validates the tracked session row (401s immediately if revoked).
    let __SNAKE__ = require_tracked_session(&session, &mut db, &state).await?;

    // Re-enrollment guard (defense in depth — `two_factor_enable` blocks this too):
    // never replace an active factor without first disabling (which re-authenticates).
    if __SNAKE__.totp_enabled {
        return Err(AutumnError::unprocessable_msg(
            "Two-factor is already enabled. Disable it first before confirming a \
             new authenticator.",
        ));
    }

    // The pending secret lives in the session (set by `two_factor_enable`), so
    // an unconfirmed enrollment never touched the live account row.
    let pending = session
        .get("totp_pending_secret")
        .await
        .ok_or_else(|| AutumnError::unprocessable_msg("Start enrollment first."))?;
    let secret = decrypt_secret(&pending)?;
    let totp = build_totp(secret, &__SNAKE__.email)?;
    let Some(step) = verify_totp_code(&totp, &form.code) else {
        return Err(AutumnError::unprocessable_msg("Invalid code. Try again."));
    };

    // Persist the new secret and a fresh single-use recovery-code set BEFORE
    // flipping `totp_enabled`, so a failure mid-way leaves the account in its
    // prior state rather than locked behind a secret whose codes were never
    // shown. Run it all in one transaction for atomicity.
    let pending_secret = pending.clone();
    let user_id = __SNAKE__.id;
    let mut plaintext_codes: Vec<String> = Vec::with_capacity(RECOVERY_CODE_COUNT);
    let mut hashed_codes: Vec<String> = Vec::with_capacity(RECOVERY_CODE_COUNT);
    for _ in 0..RECOVERY_CODE_COUNT {
        let code = generate_recovery_code();
        hashed_codes.push(hash_password(&code).await?);
        plaintext_codes.push(code);
    }

    // Capture the revocation policy up front so the delete can run inside
    // the same transaction as the enablement (a post-commit failure here
    // would 500 before the one-time recovery codes are ever shown).
    let revoke_other_sessions_in_txn = state.config_arc().auth.sessions.revoke_on_credential_change;
    let current_token_digest = session_token_digest(&session).await;
    let txn_result = (*db)
        .transaction::<_, diesel::result::Error, _>(async move |conn| {
            diesel::update(__TABLE__::table.find(user_id))
                .set((
                    __TABLE__::totp_secret_encrypted.eq(Some(pending_secret)),
                    __TABLE__::totp_last_used_step.eq(Some(step)),
                ))
                .execute(conn)
                .await?;
            diesel::delete(recovery_codes::table.filter(recovery_codes::user_id.eq(user_id)))
                .execute(conn)
                .await?;
            for digest in hashed_codes {
                diesel::insert_into(recovery_codes::table)
                    .values(NewRecoveryCode {
                        user_id,
                        code_digest: digest,
                        used_at: None,
                    })
                    .execute(conn)
                    .await?;
            }
            // Flip the flag last, conditional on it still being false. This is
            // both the durability gate (the account is only "2FA-enabled" once
            // the new secret + recovery codes are stored) and the race gate: if
            // a concurrent confirm already enabled 2FA, this matches zero rows
            // and we roll back, discarding this request's recovery codes so the
            // stored set always matches the plaintext the winner displayed.
            let claimed = diesel::update(
                __TABLE__::table
                    .find(user_id)
                    .filter(__TABLE__::totp_enabled.eq(false)),
            )
            .set(__TABLE__::totp_enabled.eq(true))
            .execute(conn)
            .await?;
            if claimed != 1 {
                return Err(diesel::result::Error::RollbackTransaction);
            }
            // Credential change (second factor enrolled): sign out every
            // *other* device in the same transaction (defaulted on,
            // configurable via [auth.sessions].revoke_on_credential_change).
            if revoke_other_sessions_in_txn {
                diesel::delete(
                    __SESSTABLE__::table
                        .filter(__SESSTABLE__::user_id.eq(user_id))
                        .filter(__SESSTABLE__::token_digest.ne(current_token_digest)),
                )
                .execute(conn)
                .await?;
            }
            Ok(())
        })
        .await;
    match txn_result {
        Ok(()) => {}
        Err(diesel::result::Error::RollbackTransaction) => {
            return Err(AutumnError::unprocessable_msg(
                "Two-factor was just enabled by another request. Reload /account/2fa.",
            ));
        }
        Err(_) => {
            return Err(AutumnError::internal_server_error_msg(
                "Failed to enable two-factor.",
            ));
        }
    }

    session.remove("totp_pending_secret").await;

    Ok(crate::layout("Save Your Recovery Codes", "/account/2fa", html! {}, html! {
        h1 { "Two-factor authentication enabled" }
        p { strong { "Save these recovery codes now." } " Each can be used once if you lose your device. They will not be shown again." }
        ul {
            @for code in &plaintext_codes {
                li { code { (code) } }
            }
        }
        p { a href="/account/2fa" { "Done" } }
    }))
}

/// `POST /account/2fa/disable` — require re-auth (current code OR password), then
/// clear the secret and all recovery codes. Requires authentication.
///
/// The handler itself verifies the user's current TOTP code or password before
/// disabling the factor, providing its own re-authentication guarantee. A
/// separate `#[step_up]` is therefore not added here to avoid double-prompting.
#[secured]
#[post("/account/2fa/disable")]
pub async fn two_factor_disable(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    Form(form): Form<TotpDisableForm>,
) -> AutumnResult<Response> {
    // Validates the tracked session row (401s immediately if revoked).
    let __SNAKE__ = require_tracked_session(&session, &mut db, &state).await?;

    // Re-authenticate: accept a current TOTP code or the account password.
    // A TOTP code used here is consumed with the same atomic replay guard as
    // `/login/verify`, so a code already spent on login cannot be replayed to
    // disable the factor.
    let mut ok = false;
    if let Some(code) = form.code.as_deref().filter(|c| !c.trim().is_empty()) {
        if let Some(stored) = __SNAKE__.totp_secret_encrypted.as_deref() {
            // A decrypt/build failure (e.g. rotated TOTP_ENC_KEY) must not abort:
            // the password fallback below is the escape from that lockout.
            if let Some(step) = decrypt_secret(stored)
                .ok()
                .and_then(|secret| build_totp(secret, &__SNAKE__.email).ok())
                .and_then(|totp| verify_totp_code(&totp, code))
            {
                let affected = diesel::update(
                    __TABLE__::table.find(__SNAKE__.id).filter(
                        __TABLE__::totp_last_used_step
                            .is_null()
                            .or(__TABLE__::totp_last_used_step.lt(step)),
                    ),
                )
                .set(__TABLE__::totp_last_used_step.eq(Some(step)))
                .execute(&mut *db)
                .await?;
                ok = affected == 1;
            }
        }
    }
    if !ok {
        if let Some(password) = form.password.as_deref().filter(|p| !p.is_empty()) {
            ok = verify_password(password, &__SNAKE__.password_digest)
                .await
                .unwrap_or(false);
        }
    }
    if !ok {
        return Err(AutumnError::unprocessable_msg(
            "Re-authentication failed. Provide a valid code or your password.",
        ));
    }

    // Disable the factor, delete the recovery codes, and revoke every
    // *other* session in one transaction so a mid-operation failure can't
    // leave the account half-changed — and so a revocation failure can't
    // 500 after the factor was already removed. Revocation is defaulted on,
    // configurable via [auth.sessions].revoke_on_credential_change.
    let user_id = __SNAKE__.id;
    let revoke_other_sessions_in_txn = state.config_arc().auth.sessions.revoke_on_credential_change;
    let current_token_digest = session_token_digest(&session).await;
    (*db)
        .transaction::<_, diesel::result::Error, _>(async move |conn| {
            diesel::update(__TABLE__::table.find(user_id))
                .set((
                    __TABLE__::totp_enabled.eq(false),
                    __TABLE__::totp_secret_encrypted.eq(None::<String>),
                    __TABLE__::totp_last_used_step.eq(None::<i64>),
                ))
                .execute(conn)
                .await?;
            diesel::delete(recovery_codes::table.filter(recovery_codes::user_id.eq(user_id)))
                .execute(conn)
                .await?;
__MAGIC_LINK_TOTP_DISABLE_CLEAR__            if revoke_other_sessions_in_txn {
                diesel::delete(
                    __SESSTABLE__::table
                        .filter(__SESSTABLE__::user_id.eq(user_id))
                        .filter(__SESSTABLE__::token_digest.ne(current_token_digest)),
                )
                .execute(conn)
                .await?;
            }
            Ok(())
        })
        .await
        .map_err(|_| AutumnError::internal_server_error_msg("Failed to disable two-factor."))?;

    Ok(redirect_to("/account/2fa"))
}

/// `GET /login/verify` — second-factor prompt shown after a correct password
/// when the account has 2FA enabled (the session is `totp_pending`).
#[get("/login/verify")]
pub async fn login_verify_form(
    session: Session,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Response> {
    if session.get("totp_pending_id").await.is_none() {
        return Ok(redirect_to("/login"));
    }
    Ok(crate::layout("Two-Factor Verification", "/login/verify", html! {}, html! {
        h1 { "Two-Factor Verification" }
        form action="/login/verify" method="post" {
            @if let Some(ref csrf) = csrf { input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }
            div {
                label for="code" { "Authentication code or recovery code" }
                input type="text" id="code" name="code" inputmode="numeric" autocomplete="one-time-code" required;
            }
            button type="submit" { "Verify" }
        }
    })
    .into_response())
}

/// `POST /login/verify` — accept a TOTP code OR a single-use recovery code.
///
/// Only on success is the `#[secured]` auth key set. A consumed recovery code is
/// marked `used_at`; a used TOTP step cannot be replayed.
#[post("/login/verify")]
pub async fn login_verify(
    mut db: Db,
    State(state): State<AppState>,
    session: Session,
    MaybeClientIp(addr_ip): MaybeClientIp,
    headers: axum::http::HeaderMap,
    Form(form): Form<TotpCodeForm>,
) -> AutumnResult<Response> {
    let pending_id: i64 = session
        .get("totp_pending_id")
        .await
        .and_then(|s| s.parse().ok())
        .ok_or_else(|| AutumnError::unauthorized_msg("No pending login."))?;
    let __SNAKE__: __PASCAL__ = __TABLE__::table
        .find(pending_id)
        .select(__PASCAL__::as_select())
        .first(&mut *db)
        .await
        .map_err(|_| AutumnError::unauthorized_msg("No pending login."))?;

    let submitted = form.code.trim().to_owned();
    let mut verified = false;

    // 1) Try TOTP within the ±1 window, rejecting an already-used step (replay).
    //    Consumption is atomic: the UPDATE only matches rows whose stored step is
    //    still below this one, and we require exactly one row to be changed. Two
    //    concurrent requests with the same code therefore cannot both win — the
    //    second sees `affected == 0`.
    //
    //    A decrypt/build failure here (e.g. TOTP_ENC_KEY rotated/missing, or a
    //    corrupt blob) is treated like a non-matching code rather than aborting,
    //    so the user can still fall back to a recovery code below — recovery
    //    codes are stored independently and are the only escape from that lockout.
    if let Some(stored) = __SNAKE__.totp_secret_encrypted.as_deref() {
        if let Some(step) = decrypt_secret(stored)
            .ok()
            .and_then(|secret| build_totp(secret, &__SNAKE__.email).ok())
            .and_then(|totp| verify_totp_code(&totp, &submitted))
        {
            let affected = diesel::update(
                __TABLE__::table.find(__SNAKE__.id).filter(
                    __TABLE__::totp_last_used_step
                        .is_null()
                        .or(__TABLE__::totp_last_used_step.lt(step)),
                ),
            )
            .set(__TABLE__::totp_last_used_step.eq(Some(step)))
            .execute(&mut *db)
            .await?;
            if affected == 1 {
                verified = true;
            }
        }
    }

    // 2) Otherwise, try an unused recovery code (single-use). Marking it used is
    //    a conditional UPDATE guarded by `used_at IS NULL`; the code is only
    //    accepted when this request is the one that flips it, so a code can never
    //    be redeemed twice even under concurrent submissions.
    if !verified {
        let unused: Vec<RecoveryCode> = recovery_codes::table
            .filter(recovery_codes::user_id.eq(__SNAKE__.id))
            .filter(recovery_codes::used_at.is_null())
            .select(RecoveryCode::as_select())
            .load(&mut *db)
            .await
            .unwrap_or_default();
        for rc in &unused {
            if verify_password(&submitted, &rc.code_digest).await.unwrap_or(false) {
                let affected = diesel::update(
                    recovery_codes::table
                        .find(rc.id)
                        .filter(recovery_codes::used_at.is_null()),
                )
                .set(recovery_codes::used_at.eq(Some(chrono::Utc::now().naive_utc())))
                .execute(&mut *db)
                .await?;
                if affected == 1 {
                    verified = true;
                    break;
                }
            }
        }
    }

    if !verified {
        return Err(AutumnError::unprocessable_msg("Invalid code."));
    }

    // If this verification is finishing a password reset (the reset handler
    // parked the new digest for a 2FA-enabled account), commit it now — only
    // after the second factor has been proven.  The conditional UPDATE also
    // guards against a superseded token: if a second reset was requested between
    // parking and now, reset_token_digest in the DB will no longer match the
    // stored token and the update matches 0 rows, which we treat as an error.
    if let Some(new_digest) = session.get("totp_pending_reset_digest").await {
        let stored_token: Option<String> = session.get("totp_pending_reset_token").await;
        session.remove("totp_pending_reset_digest").await;
        session.remove("totp_pending_reset_token").await;
        let committed = if let Some(token) = stored_token {
            let now = chrono::Utc::now().naive_utc();
            // Commit the password change and the session revocation
            // atomically; a transaction error rolls both back (token
            // preserved) and is treated as not-committed below.
            let revoke_existing_sessions =
                state.config_arc().auth.sessions.revoke_on_credential_change;
            let user_id = __SNAKE__.id;
            (*db)
                .transaction::<_, diesel::result::Error, _>(async move |conn| {
                    let updated = diesel::update(__TABLE__::table.find(user_id))
                        .filter(__TABLE__::reset_token_digest.eq(Some(token.as_str())))
                        .filter(__TABLE__::reset_token_expires_at.gt(now))
                        .set((
                            __TABLE__::password_digest.eq(&new_digest),
                            __TABLE__::reset_token_digest.eq(None::<String>),
                            __TABLE__::reset_token_expires_at.eq(None::<chrono::NaiveDateTime>),
                        ))
                        .execute(conn)
                        .await?;
                    // Password changed: revoke every existing session in
                    // the same transaction (defaulted on, configurable via
                    // [auth.sessions].revoke_on_credential_change). The
                    // fresh login is recorded below.
                    if updated == 1 && revoke_existing_sessions {
                        diesel::delete(
                            __SESSTABLE__::table.filter(__SESSTABLE__::user_id.eq(user_id)),
                        )
                        .execute(conn)
                        .await?;
                    }
__MAGIC_LINK_RESET_CLEAR__                    Ok(updated == 1)
                })
                .await
                .unwrap_or(false)
        } else {
            false
        };
        if !committed {
            // This login was authorised solely by the reset link, which has now
            // proven stale (expired or superseded). Tear down the entire pending
            // login — including `totp_pending_id` — so a retry cannot skip the
            // (now-cleared) reset branch and promote to a full session without a
            // fresh login.
            session.remove("totp_pending_id").await;
            session.remove("totp_pending_secret").await;
            return Err(AutumnError::unprocessable_msg(
                "Reset link expired or already used. Please restart the password reset.",
            ));
        }
    }

    // Promote the pending session to a fully authenticated one. Drop any
    // tracked row for the pending id first — the rotation destroys it.
    untrack_current_session(&mut db, &session).await?;
    let from_confirmation = session.get("totp_pending_confirmation").await.is_some();
    session.rotate_id().await;
    session.remove("totp_pending_id").await;
    session.remove("totp_pending_confirmation").await;
    session.insert("__SNAKE___id", __SNAKE__.id.to_string()).await;
    session.insert("__SNAKE___email", &__SNAKE__.email).await;
    session.insert(state.auth_session_key(), __SNAKE__.id.to_string()).await;
    // Password + TOTP proves identity at least as strongly as password-only login,
    // so stamp step-up for normal logins. Email-confirmation + TOTP proves address
    // ownership and second-factor possession but NOT password knowledge — those
    // sessions must still go through /reauth before accessing #[step_up] routes.
    if !from_confirmation {
        autumn_web::step_up::set_last_strong_auth_at(&session).await;
    }
    // Track this login as an active session (device list + revocation).
    record_login_session(&mut db, &session, __SNAKE__.id, addr_ip, &headers).await?;

    let remaining: i64 = recovery_codes::table
        .filter(recovery_codes::user_id.eq(__SNAKE__.id))
        .filter(recovery_codes::used_at.is_null())
        .count()
        .get_result(&mut *db)
        .await
        .unwrap_or(0);
    // Surface remaining recovery-code count via a flash-style query param.
    Ok(redirect_to(&format!("/account?recovery_remaining={}", remaining)))
}
"#;
    // Magic-link token cleanup spliced into the deferred (2FA-gated) password-reset
    // commit inside `login_verify` (#11). Gated on `--magic-link` so the
    // `magic_link_tokens` reference only appears when the table (and its import)
    // exist; empty otherwise so the transaction is unchanged.
    let magic_link_reset_clear = if magic_link {
        magic_link_reset_commit_clear_txn_src()
    } else {
        ""
    };
    // Magic-link token cleanup spliced into the `two_factor_disable` transaction
    // (Codex review). Disabling TOTP removes the second factor that gated a
    // still-outstanding magic link, so a link minted while 2FA was on must not
    // become a direct single-factor login afterwards. Gated on `--magic-link` so
    // the `magic_link_tokens` reference only appears when the table (and its
    // import) exist; empty otherwise so the transaction is unchanged.
    let magic_link_totp_disable_clear = if magic_link {
        magic_link_totp_disable_clear_txn_src()
    } else {
        ""
    };
    TPL.replace("__MAGIC_LINK_RESET_CLEAR__", magic_link_reset_clear)
        .replace(
            "__MAGIC_LINK_TOTP_DISABLE_CLEAR__",
            magic_link_totp_disable_clear,
        )
        .replace("__PASCAL__", pascal_name)
        .replace("__SNAKE__", snake_name)
        .replace("__TABLE__", table)
        .replace("__SESSTABLE__", &sessions_table_name(snake_name))
}

/// Magic-link cleanup for the deferred (2FA-gated) password-reset commit in
/// `login_verify` (issue #1328 hardening, review #11). Mirrors
/// `magic_link_credential_clear_txn_src` but is guarded on `updated == 1` — the
/// parked reset actually committed — and uses the `user_id` binding already in
/// scope in that transaction. A link minted before this reset must not sign the
/// account in afterwards. Emitted only under `--magic-link`.
const fn magic_link_reset_commit_clear_txn_src() -> &'static str {
    r"                    if updated == 1 {
                        // Invalidate any outstanding magic-link login tokens in the
                        // SAME transaction: a link minted before this password reset
                        // must not sign the account in afterwards (magic-link auth
                        // matches an unconsumed, unexpired token, keyed by user id and
                        // independent of the changed credential).
                        diesel::delete(
                            magic_link_tokens::table
                                .filter(magic_link_tokens::user_id.eq(user_id)),
                        )
                        .execute(conn)
                        .await?;
                    }
"
}

/// Magic-link cleanup for the `two_factor_disable` transaction (Codex review).
/// Disabling TOTP flips `totp_enabled` to false, so an outstanding magic-link
/// token that `magic_link_verify` would have gated through `/login/verify` while
/// 2FA was on now takes the DIRECT (single-factor) path and logs the account in
/// fully. Delete the user's outstanding `magic_link_tokens` in the SAME
/// transaction so disabling the second factor cannot retroactively un-gate a
/// previously second-factor-protected link. Uses the `user_id` binding already in
/// scope in that transaction (matching `magic_link_reset_commit_clear_txn_src`).
/// Emitted only under `--magic-link` — the table exists only then.
const fn magic_link_totp_disable_clear_txn_src() -> &'static str {
    r"            // Invalidate any outstanding magic-link login tokens in the SAME
            // transaction: disabling TOTP removes the second factor that gated
            // these links, so a link minted while 2FA was on must not become a
            // direct single-factor login afterwards (magic-link auth matches an
            // unconsumed, unexpired token, keyed by user id).
            diesel::delete(
                magic_link_tokens::table.filter(magic_link_tokens::user_id.eq(user_id)),
            )
            .execute(conn)
            .await?;
"
}

/// Render the passwordless magic-link login section appended to `routes/auth.rs`
/// under `--magic-link` (issue #1328).
///
/// Emits the request form (`GET /login/magic`), the rate-limited request
/// endpoint (`POST /login/magic`), the verify endpoint
/// (`GET /login/magic/verify?token=…`), the mailer helper, and the generic
/// failure page. Uses `__SNAKE__` / `__PASCAL__` / `__TABLE__` placeholders and
/// `.replace()` so the template body can use plain single braces.
#[allow(clippy::too_many_lines)]
fn magic_link_routes_section_src(
    pascal_name: &str,
    snake_name: &str,
    table: &str,
    totp: bool,
) -> String {
    const TPL: &str = r#"
// ── Passwordless magic-link login ───────────────────────────────────────────────
//
// Generated by `autumn generate auth --magic-link` (issue #1328). Edit freely.
//
// Security properties:
// - Tokens are 32-byte random values (`SysRng`); only their SHA-256 digest is
//   persisted (`magic_link_tokens.token_digest`). The raw token appears only in
//   the emailed link — never in the database, logs, or error reports.
// - Scanner-safe verify: `GET /login/magic/verify?token=…` NEVER consumes the
//   token — it only renders a "Confirm sign-in" page whose form POSTs the token
//   back. Email link-scanners / prefetch bots that merely follow the GET can no
//   longer burn a single-use link before the human clicks. Consumption happens
//   in `POST /login/magic/verify` (`magic_link_verify`).
// - Single-use: `magic_link_verify` (the POST) consumes the token atomically
//   (`UPDATE … SET consumed_at = now WHERE consumed_at IS NULL AND expires_at > now
//   RETURNING …`), so a second verify (or an expired/consumed/unknown token) all
//   return the SAME generic failure page — no oracle. The GET confirm page is
//   rendered identically regardless of token validity, so it is not an oracle either.
// - Non-enumerating: `POST /login/magic` always renders the same "check your
//   email" response whether or not the address exists.
// - Rate-limited per-IP by the `#[throttle]` guard and per-email by a DB cooldown.
//   The `POST /login/magic/verify` consume route is likewise per-IP throttled to
//   bound token brute-forcing.
// - `magic_link_verify` rotates the session id BEFORE establishing the
//   authenticated session (session-fixation defense).

// Magic-link token TTL and per-email cooldown are sourced from `autumn.toml`
// via `state.config_arc().auth.magic_link` (see docs/guide/authentication.md):
//
//   [auth.magic_link]
//   ttl_minutes = 15          # link lifetime; keep ≤ 15 min for a tight window (AC5)
//   email_cooldown_secs = 60  # per-email re-mint cooldown (email-bomb throttle)
//
// The documented defaults (15 min TTL, 60s cooldown) apply when the section is
// omitted — see `MagicLinkConfig` in the `autumn-web` crate. Keep `ttl_minutes`
// at 15 or less: a magic link is a bearer credential, so a tight expiry window
// bounds the blast radius of a leaked link.

#[derive(Deserialize)]
pub struct MagicLinkRequestForm {
    pub email: String,
}

/// `GET /login/magic` — render the magic-link request form.
#[get("/login/magic")]
pub async fn magic_link_request_form(
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Markup> {
    Ok(crate::layout("Sign in with a magic link", "/login/magic", html! {}, html! {
        h1 { "Sign in with a magic link" }
        p { "Enter your email and we'll send you a one-time sign-in link — no password required." }
        form action="/login/magic" method="post" {
            @if let Some(ref csrf) = csrf { input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }
            div {
                label for="email" { "Email" }
                input type="email" id="email" name="email" required autocomplete="email";
            }
            button type="submit" { "Email me a link" }
        }
        p { a href="/login" { "Back to login" } }
    }))
}

/// `POST /login/magic` — mint a token (only if the account exists) and email a
/// sign-in link.
///
/// Non-enumerating (AC2): always returns the same "check your email" page
/// whether or not the address is registered. Per-IP rate limiting is enforced
/// by the `#[throttle]` guard (autumn's existing rate-limit middleware); a
/// per-email DB cooldown (AC6) throttles email-bombing one address.
#[post("/login/magic")]
#[throttle(limit = 5, per = "1m", key = "ip")]
pub async fn magic_link_request(
    mut db: Db,
    mailer: Mailer,
    State(state): State<AppState>,
    Form(form): Form<MagicLinkRequestForm>,
) -> AutumnResult<Markup> {
    // Fail fast when mail is not configured. This is independent of the address
    // lookup, so it leaks nothing about which addresses exist.
    if mailer.is_disabled() {
        return Err(AutumnError::internal_server_error_msg(
            "Magic-link login requires mail to be configured. \
             Set [mail] transport in autumn.toml (e.g. transport = \"log\" for dev). \
             The magic-link feature is unavailable until mail is set up.",
        ));
    }

    let email = form.email.trim().to_lowercase();
    let now = chrono::Utc::now().naive_utc();
    // Sourced from `[auth.magic_link]` in autumn.toml (defaults: 15 min TTL, 60s
    // cooldown). Keep `ttl_minutes` ≤ 15 for a tight link-lifetime window.
    // One shared read for both fields; `config()` would deep-clone every
    // config section twice per request.
    let config = state.config_arc();
    let ttl_minutes = config.auth.magic_link.ttl_minutes;
    let email_cooldown_secs = config.auth.magic_link.email_cooldown_secs;
    // Record start time; the response is padded to a constant minimum below so
    // an attacker cannot infer registration status from response latency.
    let t0 = std::time::Instant::now();

    // Non-enumerating: silently skip unknown addresses. Only confirmed accounts
    // may receive a link — an unconfirmed account must confirm its email first.
    let maybe___SNAKE__: Option<__PASCAL__> = __TABLE__::table
        .filter(__TABLE__::email.eq(&email))
        .filter(__TABLE__::email_confirmed_at.is_not_null())
        .select(__PASCAL__::as_select())
        .first(&mut *db)
        .await
        .ok();

    if let Some(__SNAKE__) = maybe___SNAKE__ {
        // Per-email cooldown (AC6): skip re-minting when an unexpired,
        // unconsumed token was issued for this account within the window.
        let cooldown_start = now - chrono::Duration::seconds(email_cooldown_secs as i64);
        let recent: i64 = magic_link_tokens::table
            .filter(magic_link_tokens::user_id.eq(__SNAKE__.id))
            .filter(magic_link_tokens::consumed_at.is_null())
            .filter(magic_link_tokens::expires_at.gt(now))
            .filter(magic_link_tokens::created_at.gt(cooldown_start))
            .count()
            .get_result(&mut *db)
            .await
            .unwrap_or(0);

        if recent == 0 {
            // Reuse the reset-token generator: 32-byte SysRng hex. Only the
            // SHA-256 digest is stored; the raw token appears only in the link.
            let raw_token = generate_reset_token();
            let token_digest = sha256_hex(&raw_token);
            let expires_at = now + chrono::Duration::minutes(ttl_minutes as i64);
            let new_token = NewMagicLinkToken {
                user_id: __SNAKE__.id,
                token_digest,
                expires_at,
                consumed_at: None,
            };
            // Persist the digest, then email the raw link. A mail failure is
            // logged but never surfaced (stays non-enumerating).
            if let Err(e) = diesel::insert_into(magic_link_tokens::table)
                .values(&new_token)
                .execute(&mut *db)
                .await
            {
                tracing::error!("magic-link token insert failed: {e}");
            } else if let Err(e) = send_magic_link_email(&mailer, &__SNAKE__.email, &raw_token, ttl_minutes).await {
                tracing::error!("magic-link email failed: {e}");
            }
        }
    }

    // Pad to a constant minimum so hit and miss paths are timing-indistinguishable.
    if let Some(remaining) = std::time::Duration::from_secs(1).checked_sub(t0.elapsed()) {
        tokio::time::sleep(remaining).await;
    }

    Ok(crate::layout("Check Your Email", "/login/magic", html! {}, html! {
        h1 { "Check Your Email" }
        p {
            "If that address is registered, a one-time sign-in link is on its way. \
             The link expires shortly and can be used only once."
        }
        p { a href="/login" { "Back to login" } }
    }))
}

#[derive(Deserialize)]
pub struct MagicLinkVerifyQuery {
    pub token: String,
}

#[derive(Deserialize)]
pub struct MagicLinkVerifyForm {
    pub token: String,
}

/// Generic magic-link failure page. Expired, consumed, unknown, and malformed
/// tokens ALL render this identical page so nothing acts as an oracle (AC5).
fn magic_link_invalid_page() -> Markup {
    crate::layout("Sign-in link invalid", "/login/magic/verify", html! {}, html! {
        h1 { "This sign-in link is invalid or has expired" }
        p { "Magic sign-in links can be used once and expire quickly. Please request a new one." }
        p { a href="/login/magic" { "Request a new link" } }
        p { a href="/login" { "Back to login" } }
    })
}

/// `GET /login/magic/verify?token=…` — render a "Confirm sign-in" page WITHOUT
/// consuming the token.
///
/// Email link-scanners and prefetch/preview bots follow the GET before the human
/// clicks; if the GET consumed the single-use token, those bots would burn the
/// link. So the GET is side-effect-free: it just echoes the token into a hidden
/// field of a form that POSTs back to `/login/magic/verify`, where the token is
/// actually consumed. The page is rendered IDENTICALLY regardless of whether the
/// token is valid, expired, or unknown — the POST surfaces the generic failure —
/// so the confirm page is not an oracle.
#[get("/login/magic/verify")]
pub async fn magic_link_verify_form(
    flash: Flash,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
    Query(query): Query<MagicLinkVerifyQuery>,
) -> AutumnResult<Markup> {
    Ok(crate::layout("Confirm sign-in", "/login/magic/verify", flash_messages(&flash.consume().await), html! {
        h1 { "Confirm sign-in" }
        p { "Click the button below to finish signing in to your account." }
        form action="/login/magic/verify" method="post" {
            @if let Some(ref csrf) = csrf { input type="hidden" name=(csrf_field.as_ref().map_or("_csrf", |f| f.0.as_str())) value=(csrf.token()); }
            input type="hidden" name="token" value=(query.token);
            button type="submit" { "Sign in" }
        }
        p { a href="/login" { "Back to login" } }
    }))
}

/// `POST /login/magic/verify` — validate the token and, on success, establish an
/// authenticated session. This is where the single-use token is consumed (the
/// GET above only renders the confirmation page, so link-scanners can't burn it).
///
/// Single-use (AC5): an atomic `UPDATE … RETURNING` stamps `consumed_at` while
/// filtering on `consumed_at IS NULL` and `expires_at > now`, so a second
/// verify of the same token — or an expired / consumed / unknown token — matches
/// zero rows and is rejected with the SAME generic failure (no oracle).
///
/// A light per-IP `#[throttle]` (mirroring `POST /login/magic`) bounds token
/// brute-forcing; a legitimate user only POSTs this route once per link.
#[post("/login/magic/verify")]
#[throttle(limit = 5, per = "1m", key = "ip")]
pub async fn magic_link_verify(
    mut db: Db,
    State(state): State<AppState>,
    session: Session,
    MaybeClientIp(addr_ip): MaybeClientIp,
    headers: axum::http::HeaderMap,
    Form(form): Form<MagicLinkVerifyForm>,
) -> AutumnResult<Response> {
    let token_digest = sha256_hex(&form.token);
    let now = chrono::Utc::now().naive_utc();

    // Atomic single-use consume. Only one concurrent verify can match.
    let consumed: MagicLinkToken = match diesel::update(
        magic_link_tokens::table
            .filter(magic_link_tokens::token_digest.eq(&token_digest))
            .filter(magic_link_tokens::consumed_at.is_null())
            .filter(magic_link_tokens::expires_at.gt(now)),
    )
    .set(magic_link_tokens::consumed_at.eq(Some(now)))
    .returning(MagicLinkToken::as_returning())
    .get_result(&mut *db)
    .await
    {
        Ok(row) => row,
        // Expired / consumed / unknown all land here → identical generic failure.
        Err(_) => return Ok(magic_link_invalid_page().into_response()),
    };

    // Load the account the token belongs to; a vanished account fails generically.
    let Ok(__SNAKE__) = __TABLE__::table
        .find(consumed.user_id)
        .select(__PASCAL__::as_select())
        .first::<__PASCAL__>(&mut *db)
        .await
    else {
        return Ok(magic_link_invalid_page().into_response());
    };

    // Defense-in-depth (#1777): re-check the account lock at verify time with a
    // FRESH read of `locked_at` at the DB, AFTER consuming the token but BEFORE
    // establishing any session. A magic link minted BEFORE the account was locked
    // must not complete a login AFTER the lock. The in-memory `__SNAKE__` row was
    // SELECTed above and can be STALE: a concurrent login can cross the lockout
    // threshold between that SELECT and here, so trusting `__SNAKE__.locked_at`
    // would leave a TOCTOU hole (the stale value is still NULL and the link
    // succeeds even though the account is now locked). Mirror the password-login
    // success-path guard EXACTLY: a single guarded UPDATE predicated on
    // `locked_at` re-reads the current lock state at the DB and, like password
    // login, clears an expired lock (WHERE `locked_at IS NULL` OR
    // `locked_at <= now - cooloff`) while resetting `failed_attempts`. If zero
    // rows match, the account is actively locked (concurrently or otherwise) and
    // the login is rejected. Gated on the same `lockout_enabled` predicate, so it
    // is a no-op when lockout is disabled in config. A locked account funnels to
    // the SAME generic failure page as an expired/consumed/unknown token — no
    // oracle distinguishes "locked" from "bad link". This sits before the TOTP
    // branch below, so it gates BOTH the 2FA-park and the direct-login paths.
    // `config_arc` shares the resolved config behind an `Arc`; `config()`
    // would deep-clone every section to read one field on a request path.
    let config = state.config_arc();
    let lockout_cfg = &config.auth.lockout;
    let lockout_enabled = lockout_cfg.enabled && lockout_cfg.threshold > 0;
    if lockout_enabled {
        let cooloff = chrono::Duration::seconds(lockout_cfg.cooloff_secs as i64);
        let lock_expired_before = now - cooloff;
        let rows_cleared = diesel::update(
            __TABLE__::table
                .find(__SNAKE__.id)
                .filter(
                    __TABLE__::locked_at.is_null().or(
                        __TABLE__::locked_at.le(lock_expired_before)
                    )
                ),
        )
        .set((
            __TABLE__::failed_attempts.eq(0),
            __TABLE__::locked_at.eq(None::<chrono::NaiveDateTime>),
        ))
        .execute(&mut *db)
        .await
        .map_err(|e| AutumnError::internal_server_error_msg(&format!("Failed to reset lockout on magic-link login: {e}")))?;
        if rows_cleared == 0 {
            return Ok(magic_link_invalid_page().into_response());
        }
    }

    // This browser may already hold a tracked session for another account. The
    // rotation below destroys that session id, so drop its row now.
    untrack_current_session(&mut db, &session).await?;

    // Magic-link proves EMAIL POSSESSION, not password knowledge. Drop any
    // `reauth_pw_ok` "password already verified, awaiting TOTP" marker left by an
    // unfinished /reauth in this browser BEFORE parking (TOTP) or promoting
    // (direct) the session — otherwise a later /reauth POST could skip the
    // password and mint a fresh step-up claim off an email-only login. This is
    // cleared here (before the 2FA branch, which returns early) so BOTH the
    // parked-pending and direct paths are covered, mirroring
    // `establish_remember_login` (issue #833/#1397). Plain string key, so a
    // magic-link-only build (no --totp) still compiles.
    session.remove("reauth_pw_ok").await;

    // For 2FA-enabled accounts, park the session and redirect to /login/verify
    // before granting a full session — a magic link proves email possession,
    // not TOTP possession (mirrors confirm_email).
__MAGIC_LINK_TOTP_BRANCH__    // Rotate the session id BEFORE inserting the authenticated session id
    // (session-fixation defense, consistent with login/reset/confirm).
    session.rotate_id().await;
    // Magic-link proves EMAIL POSSESSION, not password knowledge. Like
    // `confirm_email`, it MUST NOT call `set_last_strong_auth_at`: doing so
    // would let an emailed link grant password-grade step-up (sudo) freshness.
    // Drop any step-up claim carried over from a previous login in this browser.
    session.remove(autumn_web::step_up::STEP_UP_SESSION_KEY).await;
__MAGIC_LINK_CLEAR_PENDING__    session.insert("__SNAKE___id", __SNAKE__.id.to_string()).await;
    session.insert("__SNAKE___email", &__SNAKE__.email).await;
    // Use the same session key checked by `#[secured]` / `#[authorize]`.
    session.insert(state.auth_session_key(), __SNAKE__.id.to_string()).await;
    // Track this login as an active session (device list + revocation).
    record_login_session(&mut db, &session, __SNAKE__.id, addr_ip, &headers).await?;

    Ok(redirect_to("/account"))
}

/// Send a passwordless magic-link email via the Autumn mailer.
///
/// Goes through the standard `Mail` builder so it inherits dev-mailbox preview,
/// suppression-list gating, and templating (AC7). Suppression is intentionally
/// NOT bypassed (`.ignore_suppression()` is not called).
async fn send_magic_link_email(
    mailer: &Mailer,
    to: &str,
    token: &str,
    ttl_minutes: u64,
) -> AutumnResult<()> {
    // APP_BASE_URL must be the public URL of your app (e.g. https://example.com).
    let base_url = std::env::var("APP_BASE_URL")
        .unwrap_or_else(|_| "http://localhost:3000".to_owned());
    let verify_url = format!("{base_url}/login/magic/verify?token={token}");
    let mail = Mail::builder()
        .to(to.to_owned())
        .subject("Your sign-in link")
        .html(html! {
            p { "Click the link below to sign in. No password required." }
            p { "This link expires in " (ttl_minutes) " minutes and can be used once." }
            p { a href=(&verify_url) { "Sign in" } }
            p { "If you did not request this, you can safely ignore this email." }
        })
        .text(format!(
            "Sign in: {verify_url}\n\
             This link expires in {ttl_minutes} minutes and can be used once.\n\
             If you did not request this you can safely ignore this email."
        ))
        .build()
        .map_err(|e| {
            AutumnError::internal_server_error_msg(format!(
                "Failed to build magic-link email: {e}"
            ))
        })?;
    mailer.send(mail).await.map_err(|e| {
        AutumnError::internal_server_error_msg(format!(
            "Failed to send magic-link email: {e}"
        ))
    })
}
"#;
    // When TOTP is enabled, magic-link verify must honor the second factor just
    // like confirm_email: park a `totp_pending_confirmation` session and redirect
    // to /login/verify. Reusing the confirm branch means completion in
    // `login_verify` deliberately SKIPS the strong-auth stamp (email + TOTP does
    // not prove password knowledge). The branch is already `__SNAKE__`-substituted.
    let totp_branch = if totp {
        totp_confirm_branch_src(snake_name)
    } else {
        String::new()
    };
    // `rotate_id()` preserves session data, so the DIRECT (non-2FA) login path must
    // scrub any abandoned pending-2FA / parked-reset handoff left in this browser
    // before writing the auth keys — otherwise `/login/verify` could resume it under
    // the freshly authenticated session (mirrors password login / reset). Gated on
    // `--totp` so a magic-link-only app never references TOTP-only session keys.
    let clear_pending = if totp { totp_clear_pending_src() } else { "" };
    TPL.replace("__MAGIC_LINK_TOTP_BRANCH__", &totp_branch)
        .replace("__MAGIC_LINK_CLEAR_PENDING__", clear_pending)
        .replace("__PASCAL__", pascal_name)
        .replace("__SNAKE__", snake_name)
        .replace("__TABLE__", table)
}

/// Markdown appended to `docs/guide/authentication.md` under `--totp`.
const TOTP_DOCS_SECTION: &str = r#"## Two-Factor Authentication (TOTP)

Generated with `--totp`. Users can enroll an authenticator app (Google
Authenticator, 1Password, …) and fall back to single-use recovery codes.

### Generated routes

| Method | Path | Handler | Auth |
|--------|------|---------|------|
| GET | `/account/2fa` | `two_factor_status` | **Required** |
| POST | `/account/2fa/enable` | `two_factor_enable` | **Required** |
| POST | `/account/2fa/confirm` | `two_factor_confirm` | **Required** |
| POST | `/account/2fa/disable` | `two_factor_disable` | **Required** |
| GET | `/login/verify` | `login_verify_form` | Pending login |
| POST | `/login/verify` | `login_verify` | Pending login |

### Encryption key

TOTP secrets are encrypted at rest with AES-256-GCM. Set `TOTP_ENC_KEY` to a
base64-encoded 32-byte key before enabling 2FA:

```sh
# 32 random bytes, base64-encoded
export TOTP_ENC_KEY="$(head -c 32 /dev/urandom | base64)"
```

Manage it like any other secret (`autumn credentials`); never commit it. Rotating
the key invalidates existing enrollments.

### Security properties

- Secrets encrypted at rest (never stored plaintext).
- Verification accepts a ±1 time-step window; a consumed step cannot be replayed
  (`totp_last_used_step`), including on the disable path.
- Recovery codes are single-use, bcrypt-hashed, and stamped `used_at` on use.
- Enrolling requires step-up re-authentication (the account password), so a
  stolen/unattended session cannot quietly add an attacker's authenticator.
- Re-enrollment while 2FA is active is rejected — disable first (which itself
  requires a current code or password).
- Login, OAuth callback (guidance), and password reset all route 2FA-enabled
  accounts through `/login/verify`. A password reset for a 2FA account is
  **deferred**: the new password is parked and only committed after the second
  factor is proven, so a reset link alone cannot change the password.
- Disabling 2FA requires re-authentication (current code or password) and clears
  the secret plus all recovery codes.

### Out of scope (follow-ups)

- **Rate-limiting / lockout** on repeated failed second-factor attempts is not
  included — add it before exposing 2FA to untrusted traffic.
- WebAuthn / passkeys and SMS/email OTP are separate tracks.

"#;

/// Markdown appended to `docs/guide/authentication.md` under `--magic-link`.
const MAGIC_LINK_DOCS_SECTION: &str = r#"## Passwordless Magic-Link Login

Generated with `--magic-link` (issue #1328). Users can sign in with a one-time
link emailed to their address — no password required. The flow is composable
with `--oauth`, `--passkeys`, and `--totp` on the same model.

### Routes

| Method | Path | Handler | Auth |
|--------|------|---------|------|
| GET | `/login/magic` | `magic_link_request_form` | Public |
| POST | `/login/magic` | `magic_link_request` | Public (rate-limited) |
| GET | `/login/magic/verify?token=…` | `magic_link_verify_form` | Public |
| POST | `/login/magic/verify` | `magic_link_verify` | Public (rate-limited) |

### How It Works

1. The user submits their email to `POST /login/magic`.
2. **If** the address belongs to a confirmed account, a random 32-byte token is
   generated; only its SHA-256 digest, an expiry, and a `consumed_at` marker are
   persisted in `magic_link_tokens`. The raw token is placed only in the emailed
   verify link.
3. The response is **always** the same "check your email" page whether or not the
   address exists — so the endpoint cannot be used to enumerate accounts.
4. The user clicks the link (`GET /login/magic/verify?token=…`). This renders a
   lightweight **"Confirm sign-in"** page and does **not** consume the token —
   so email link-scanners / prefetch bots that merely follow the GET can't burn
   the single-use link before the human clicks. The page is rendered identically
   whether the token is valid, expired, or unknown (no oracle).
5. Submitting that form (`POST /login/magic/verify`) is where the token is
   validated and **atomically consumed**; on success the session id is
   **rotated** (session-fixation defense) and an authenticated session is
   established. Expired / consumed / unknown tokens all render the same generic
   failure page.

### Configuration Knobs

The TTL and per-email cooldown are read from `autumn.toml` via `state.config_arc()`,
so you can tune them without editing the generated handler:

```toml
[auth.magic_link]
ttl_minutes = 15          # link lifetime; keep ≤ 15 min for a tight window
email_cooldown_secs = 60  # per-email re-mint cooldown (email-bomb throttle)
```

Both keys are optional; omitting the `[auth.magic_link]` section applies the
documented defaults below.

| Knob | Location | Default | Purpose |
|------|----------|---------|---------|
| `auth.magic_link.ttl_minutes` | `[auth.magic_link]` in `autumn.toml` (via `state.config_arc()`) | `15` | Link lifetime (TTL) in minutes. Keep ≤ 15 min for a tight window — a magic link is a bearer credential, so a short expiry bounds the blast radius of a leaked link. |
| `auth.magic_link.email_cooldown_secs` | `[auth.magic_link]` in `autumn.toml` (via `state.config_arc()`) | `60` | Per-email cooldown in seconds: suppresses re-minting a token for the same address within the window (email-bomb throttle). |
| `#[throttle(limit = 5, per = "1m", key = "ip")]` | attribute on `POST /login/magic` and `POST /login/magic/verify` | 5/min/IP | Per-IP rate limit via autumn's existing rate-limit middleware (request minting + token brute-force bound). |

### Security Guarantees

- **No account enumeration**: `POST /login/magic` returns an identical response
  (and constant-time-padded latency) whether or not the address is registered.
- **Digest-only storage**: only `sha256_hex(raw_token)` is stored; the raw token
  lives only in the emailed link, never in the database, logs, or error reports.
- **Scanner-safe verify**: `GET /login/magic/verify` only renders a "Confirm
  sign-in" page and NEVER consumes the token — email link-scanners / prefetch
  bots that follow the GET can't burn the single-use link. Consumption happens on
  the `POST` when the human clicks "Sign in".
- **Single-use**: `magic_link_verify` (the `POST`) consumes the token atomically
  (`UPDATE … SET consumed_at = now WHERE consumed_at IS NULL AND expires_at > now`),
  so a second verify of the same token fails.
- **Generic failure (no oracle)**: expired, already-consumed, unknown, and
  malformed tokens all render the same generic failure page; the GET confirm page
  is likewise rendered identically regardless of token validity.
- **Configurable TTL**: tokens expire after `auth.magic_link.ttl_minutes`
  (default 15), sourced from `autumn.toml` via `state.config_arc()`.
- **Rate-limited**: per-IP (`#[throttle]`) and per-email (DB cooldown).
- **Session-fixation defense**: the session id is rotated before the
  authenticated session is established.
- **Not a step-up factor**: magic-link proves email possession, not password
  knowledge, so it does **not** stamp the step-up (sudo-mode) claim — `#[step_up]`
  routes still require a fresh password reauth, consistent with email confirmation.
- **Mailer integration**: the link is sent through the standard `Mail` builder,
  inheriting dev-mailbox preview, suppression-list gating, and templating.

### Not Included

SMS/OTP, remember-device, and magic-link as a second factor are out of scope for
this scaffold.

"#;

/// Render `tests/auth_2fa.rs` — the generated 2FA integration suite.
fn render_2fa_tests_file(pascal_name: &str, snake_name: &str) -> String {
    const TPL: &str = r#"//! Generated 2FA integration tests for __PASCAL__ (`autumn generate auth --totp`).
//!
//! Like `tests/auth.rs`, these run against a live server started with
//! `AUTUMN_TEST_BASE_URL` and skip when it is unset, so they compile and pass
//! out of the box. Flesh out the bodies once your test harness boots the app
//! with a database and a `TOTP_ENC_KEY`.
//!
//! Covered flows: enroll → confirm → login-with-code → login-with-recovery-code
//! → recovery-code-reuse-rejected → disable.

fn base_url() -> Option<String> {
    std::env::var("AUTUMN_TEST_BASE_URL").ok()
}

#[test]
fn two_factor_enroll_and_confirm() {
    let Some(_base) = base_url() else {
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    };
    // POST /account/2fa/enable then /account/2fa/confirm with a generated code.
}

#[test]
fn login_with_totp_code() {
    let Some(_base) = base_url() else {
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    };
    // Password login redirects to /login/verify; a valid code completes login.
}

#[test]
fn login_with_recovery_code() {
    let Some(_base) = base_url() else {
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    };
    // A single-use recovery code is accepted at /login/verify.
}

#[test]
fn recovery_code_reuse_rejected() {
    let Some(_base) = base_url() else {
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    };
    // Re-submitting a consumed recovery code is rejected.
}

#[test]
fn two_factor_disable() {
    let Some(_base) = base_url() else {
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    };
    // POST /account/2fa/disable with re-auth clears the secret + recovery codes.
}
"#;
    TPL.replace("__PASCAL__", pascal_name)
        .replace("__SNAKE__", snake_name)
}

// ── Passkey (WebAuthn) helpers ────────────────────────────────────────────────

fn passkey_route_entries() -> Vec<String> {
    vec![
        "routes::passkeys::passkey_register_begin".to_owned(),
        "routes::passkeys::passkey_register_finish".to_owned(),
        "routes::passkeys::passkey_login_begin".to_owned(),
        "routes::passkeys::passkey_login_finish".to_owned(),
        "routes::passkeys::passkey_list".to_owned(),
        "routes::passkeys::passkey_revoke".to_owned(),
        "routes::passkeys::passkey_register_page".to_owned(),
        "routes::passkeys::passkey_login_page".to_owned(),
    ]
}

fn render_passkey_migration_up(
    backend: autumn_web::config::DatabaseBackend,
    user_table: &str,
) -> String {
    let d = AuthDdl::for_backend(backend);
    format!(
        "CREATE TABLE webauthn_credentials (\n\
         \x20   id {pk},\n\
         \x20   user_id {big_int} NOT NULL REFERENCES {user_table}(id) ON DELETE CASCADE,\n\
         \x20   credential_id TEXT NOT NULL UNIQUE,\n\
         \x20   credential_json TEXT NOT NULL,\n\
         \x20   name TEXT NOT NULL DEFAULT 'Passkey',\n\
         \x20   created_at {created_at},\n\
         \x20   last_used_at {ts} NULL\n\
         );\n\
         \n\
         CREATE INDEX webauthn_credentials_user_id_idx ON webauthn_credentials (user_id);\n",
        pk = d.pk,
        big_int = d.big_int,
        ts = d.ts,
        created_at = d.ts_not_null_default_now,
    )
}

fn render_passkey_migration_down() -> String {
    "DROP TABLE webauthn_credentials;\n".to_owned()
}

fn render_webauthn_credential_model_file(user_table: &str) -> String {
    format!(
        r"//! Generated by `autumn generate auth --passkeys`.
//!
//! Edit freely — once generated, this is ordinary user code.

use crate::schema::{{webauthn_credentials, {user_table}}};

#[autumn_web::model]
pub struct WebauthnCredential {{
    pub id: i64,
    pub user_id: i64,
    pub credential_id: String,
    pub credential_json: String,
    pub name: String,
    #[default]
    pub last_used_at: Option<chrono::NaiveDateTime>,
    pub created_at: chrono::NaiveDateTime,
}}

diesel::joinable!(webauthn_credentials -> {user_table} (user_id));
"
    )
}

#[allow(clippy::too_many_lines)]
fn render_passkeys_routes_file(pascal_name: &str, snake_name: &str, user_table: &str) -> String {
    let tpl = r##"//! Generated by `autumn generate auth --passkeys`.
//!
//! WebAuthn passkey ceremony handlers.  Edit freely — once generated, this is
//! ordinary user code.
//!
//! # Configuration
//!
//! Add to `autumn.toml`:
//!
//! ```toml
//! [auth.webauthn]
//! rp_id     = "example.com"
//! rp_name   = "My App"
//! rp_origin = "https://example.com"
//! ```
//!
//! # Security notes
//!
//! - `passkey_login_finish` writes `state.auth_session_key()` so downstream
//!   `#[secured]` routes work without modification.
//! - Never store raw credentials — `credential_json` holds the opaque passkey
//!   state returned by webauthn-rs and should not be inspected by app code.

use autumn_web::prelude::*;
use base64::Engine as _;
use diesel::prelude::*;
use diesel_async::AsyncConnection as _;
use diesel_async::RunQueryDsl;
use serde::{Deserialize, Serialize};
use webauthn_rs::prelude::*;

/// Encode an opaque credential ID as a base64url (no padding) string.
///
/// `CredentialID` is a `Vec<u8>` and has no `Display`, so encode the raw
/// bytes. Registration and login use this helper, so the stored
/// `credential_id` and the login lookup key are the same bytes.
fn encode_cred_id(cred_id: &CredentialID) -> String {
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(cred_id.as_slice())
}

fn redirect_to(url: &str) -> axum::response::Redirect {
    axum::response::Redirect::to(url)
}

// ── Config helper ──────────────────────────────────────────────────────────────

fn build_webauthn(state: &AppState) -> AutumnResult<Webauthn> {
    // `config_arc` shares the resolved config behind an `Arc`; `config()`
    // would deep-clone every section to read one field on a request path.
    let config = state.config_arc();
    let cfg = &config.auth.webauthn;
    if cfg.rp_id.is_empty() || cfg.rp_origin.is_empty() {
        return Err(AutumnError::internal_server_error_msg(
            "WebAuthn is not configured. Set [auth.webauthn] rp_id, rp_name, and rp_origin \
             in autumn.toml. See docs/guide/passkeys.md for details.",
        ));
    }
    let origin = Url::parse(&cfg.rp_origin).map_err(|_| {
        AutumnError::internal_server_error_msg(
            "auth.webauthn.rp_origin is not a valid URL. \
             Example: \"https://example.com\"",
        )
    })?;
    WebauthnBuilder::new(&cfg.rp_id, &origin)
        .map_err(|e| {
            AutumnError::internal_server_error_msg(format!(
                "Failed to build WebAuthn instance from auth.webauthn config: {e}"
            ))
        })?
        .rp_name(&cfg.rp_name)
        .build()
        .map_err(|e| {
            AutumnError::internal_server_error_msg(format!(
                "Failed to build WebAuthn instance: {e}"
            ))
        })
}

// ── Forms / JSON types ────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct PasskeyRegisterFinishBody {
    pub response: serde_json::Value,
}

#[derive(Deserialize)]
pub struct PasskeyLoginFinishBody {
    pub response: serde_json::Value,
}

#[derive(Deserialize)]
pub struct PasskeyRevokeForm {
    pub id: i64,
}

// ── Registration ──────────────────────────────────────────────────────────────

/// `GET /passkeys/register` — passkey registration UI page.
#[secured]
#[get("/passkeys/register")]
pub async fn passkey_register_page(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    csrf: Option<CsrfToken>,
    csrf_header: Option<CsrfTokenHeader>,
    nonce: Option<CspNonce>,
) -> AutumnResult<Markup> {
    // Validates the tracked session row (401s immediately if revoked).
    let _ = crate::routes::auth::require_tracked_session(&session, &mut db, &state).await?;
    let csrf_token = csrf.map(|t| t.token().to_owned()).unwrap_or_default();
    let csrf_header_name = csrf_header.map(|h| h.0.clone()).unwrap_or_else(|| "X-CSRF-Token".to_owned());
    let script_nonce = nonce.map(|n| n.value().to_owned());
    Ok(html! {
        html {
            head {
                title { "Register a Passkey" }
                meta name="csrf-token" content=(csrf_token);
                meta name="csrf-token-header" content=(csrf_header_name);
            }
            body {
                h1 { "Register a Passkey" }
                button id="register-btn" { "Register passkey" }
                script nonce=[script_nonce] {
                    (PreEscaped(r#"
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
const csrfHeader = document.querySelector('meta[name="csrf-token-header"]')?.content ?? 'X-CSRF-Token';
document.getElementById('register-btn').addEventListener('click', async () => {
    const beginResp = await fetch('/passkeys/register/begin', {
        method: 'POST',
        headers: { [csrfHeader]: csrfToken },
    });
    const optionsJSON = await beginResp.json();
    const options = PublicKeyCredential.parseCreationOptionsFromJSON(optionsJSON.publicKey);
    const credential = await navigator.credentials.create({ publicKey: options });
    const finishResp = await fetch('/passkeys/register/finish', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', [csrfHeader]: csrfToken },
        body: JSON.stringify({ response: credential.toJSON() }),
    });
    if (finishResp.ok) {
        window.location.href = '/passkeys';
    } else {
        alert('Registration failed');
    }
});
"#))
                }
            }
        }
    })
}

/// `POST /passkeys/register/begin` — start a registration ceremony.
///
/// Requires authentication and a fresh step-up claim to prevent a hijacked
/// session from silently adding a new authenticator.
#[secured]
#[step_up]
#[post("/passkeys/register/begin")]
pub async fn passkey_register_begin(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
) -> AutumnResult<axum::Json<serde_json::Value>> {
    // Validates the tracked session row (401s immediately if revoked).
    let __SNAKE___id: i64 =
        crate::routes::auth::require_tracked_session(&session, &mut db, &state)
            .await?
            .id;
    let __SNAKE___email = session
        .get("__SNAKE___email")
        .await
        .unwrap_or_else(|| "user".to_owned());
    let webauthn = build_webauthn(&state)?;
    let existing_cred_ids: Vec<CredentialID> = {
        use crate::schema::webauthn_credentials;
        webauthn_credentials::table
            .filter(webauthn_credentials::user_id.eq(__SNAKE___id))
            .select(webauthn_credentials::credential_json)
            .load::<String>(&mut *db)
            .await
            .unwrap_or_default()
            .into_iter()
            .filter_map(|json| serde_json::from_str::<Passkey>(&json).ok())
            .map(|p| p.cred_id().clone())
            .collect()
    };
    let user_unique_id = uuid::Uuid::from_u128(__SNAKE___id as u128);
    let (ccr, reg_state) = webauthn
        .start_passkey_registration(
            user_unique_id,
            &__SNAKE___email,
            &__SNAKE___email,
            Some(existing_cred_ids),
        )
        .map_err(|e| {
            AutumnError::internal_server_error_msg(format!("start_passkey_registration: {e}"))
        })?;
    // Store the user_id alongside the reg_state so finish can verify the session
    // user hasn't changed between begin and finish (prevents cross-account TOCTOU).
    session
        .insert(
            "passkey_reg_state",
            serde_json::to_string(&serde_json::json!({
                "user_id": __SNAKE___id,
                "state":   serde_json::to_string(&reg_state).unwrap_or_default(),
            }))
            .unwrap_or_default(),
        )
        .await;
    Ok(axum::Json(serde_json::to_value(ccr).unwrap_or_default()))
}

/// `POST /passkeys/register/finish` — complete a registration ceremony.
///
/// Stores the new credential in `webauthn_credentials`.
#[secured]
#[post("/passkeys/register/finish")]
pub async fn passkey_register_finish(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    axum::Json(body): axum::Json<PasskeyRegisterFinishBody>,
) -> AutumnResult<axum::Json<serde_json::Value>> {
    // Validates the tracked session row (401s immediately if revoked).
    let current =
        crate::routes::auth::require_tracked_session(&session, &mut db, &state).await?;
    let current_id: i64 = current.id;
    let envelope_str: String = session
        .get("passkey_reg_state")
        .await
        .ok_or_else(|| AutumnError::unprocessable_msg("No pending registration."))?;
    session.remove("passkey_reg_state").await;
    let envelope: serde_json::Value = serde_json::from_str(&envelope_str)
        .map_err(|_| AutumnError::unprocessable_msg("Invalid registration state."))?;
    let __SNAKE___id: i64 = envelope["user_id"]
        .as_i64()
        .ok_or_else(|| AutumnError::unprocessable_msg("Invalid registration state."))?;
    if __SNAKE___id != current_id {
        return Err(AutumnError::unauthorized_msg(
            "Session user changed since registration began.",
        ));
    }
    let reg_state_str = envelope["state"]
        .as_str()
        .unwrap_or_default()
        .to_owned();
    let reg_state: PasskeyRegistration = serde_json::from_str(&reg_state_str)
        .map_err(|_| AutumnError::unprocessable_msg("Invalid registration state."))?;
    let webauthn = build_webauthn(&state)?;
    let rpk_finish: RegisterPublicKeyCredential =
        serde_json::from_value(body.response).map_err(|e| {
            AutumnError::unprocessable_msg(format!("Invalid credential response: {e}"))
        })?;
    let passkey = webauthn
        .finish_passkey_registration(&rpk_finish, &reg_state)
        .map_err(|e| AutumnError::unprocessable_msg(format!("Registration failed: {e}")))?;
    let cred_id = encode_cred_id(passkey.cred_id());
    let cred_json = serde_json::to_string(&passkey)
        .map_err(|_| AutumnError::internal_server_error_msg("Failed to serialise passkey."))?;
    // Store the passkey and revoke every *other* session in one
    // transaction: the documented revoke-on-credential-change guarantee
    // (defaulted on, configurable via
    // [auth.sessions].revoke_on_credential_change) can never be silently
    // skipped, and a failure rolls the credential back so the client can
    // retry without storing a duplicate.
    let revoke_other_sessions_in_txn = state.config_arc().auth.sessions.revoke_on_credential_change;
    let current_token_digest = crate::routes::auth::session_token_digest(&session).await;
    (*db)
        .transaction::<_, diesel::result::Error, _>(async move |conn| {
            diesel::insert_into(crate::schema::webauthn_credentials::table)
                .values((
                    crate::schema::webauthn_credentials::user_id.eq(__SNAKE___id),
                    crate::schema::webauthn_credentials::credential_id.eq(&cred_id),
                    crate::schema::webauthn_credentials::credential_json.eq(&cred_json),
                    crate::schema::webauthn_credentials::name.eq("Passkey"),
                ))
                .execute(conn)
                .await?;
            if revoke_other_sessions_in_txn {
                diesel::delete(
                    crate::schema::__SESSTABLE__::table
                        .filter(crate::schema::__SESSTABLE__::user_id.eq(__SNAKE___id))
                        .filter(crate::schema::__SESSTABLE__::token_digest.ne(current_token_digest)),
                )
                .execute(conn)
                .await?;
            }
            Ok(())
        })
        .await
        .map_err(|_| AutumnError::internal_server_error_msg("Failed to store passkey."))?;
    Ok(axum::Json(serde_json::json!({ "ok": true })))
}

// ── Authentication ────────────────────────────────────────────────────────────

/// `GET /passkeys/login` — passkey login UI page.
#[get("/passkeys/login")]
pub async fn passkey_login_page(
    csrf: Option<CsrfToken>,
    csrf_header: Option<CsrfTokenHeader>,
    nonce: Option<CspNonce>,
) -> AutumnResult<Markup> {
    let csrf_token = csrf.map(|t| t.token().to_owned()).unwrap_or_default();
    let csrf_header_name = csrf_header.map(|h| h.0.clone()).unwrap_or_else(|| "X-CSRF-Token".to_owned());
    let script_nonce = nonce.map(|n| n.value().to_owned());
    Ok(html! {
        html {
            head {
                title { "Sign in with Passkey" }
                meta name="csrf-token" content=(csrf_token);
                meta name="csrf-token-header" content=(csrf_header_name);
            }
            body {
                h1 { "Sign in with a Passkey" }
                button id="login-btn" { "Sign in with passkey" }
                script nonce=[script_nonce] {
                    (PreEscaped(r#"
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
const csrfHeader = document.querySelector('meta[name="csrf-token-header"]')?.content ?? 'X-CSRF-Token';
document.getElementById('login-btn').addEventListener('click', async () => {
    const beginResp = await fetch('/passkeys/login/begin', {
        method: 'POST',
        headers: { [csrfHeader]: csrfToken },
    });
    const optionsJSON = await beginResp.json();
    const options = PublicKeyCredential.parseRequestOptionsFromJSON(optionsJSON.publicKey);
    const assertion = await navigator.credentials.get({ publicKey: options });
    const finishResp = await fetch('/passkeys/login/finish', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', [csrfHeader]: csrfToken },
        body: JSON.stringify({ response: assertion.toJSON() }),
    });
    if (finishResp.ok) {
        window.location.href = '/account';
    } else {
        alert('Login failed');
    }
});
"#))
                }
            }
        }
    })
}

/// `POST /passkeys/login/begin` — start a discoverable authentication ceremony.
///
/// Uses `start_discoverable_authentication` so the browser shows the passkey
/// selector without the server knowing the user upfront.  No credential IDs
/// are sent to anonymous clients.
#[post("/passkeys/login/begin")]
pub async fn passkey_login_begin(
    session: Session,
    State(state): State<AppState>,
) -> AutumnResult<axum::Json<serde_json::Value>> {
    let webauthn = build_webauthn(&state)?;
    let (rcr, auth_state) = webauthn
        .start_discoverable_authentication()
        .map_err(|e| {
            AutumnError::internal_server_error_msg(format!(
                "start_discoverable_authentication: {e}"
            ))
        })?;
    session
        .insert(
            "passkey_auth_state",
            serde_json::to_string(&auth_state).unwrap_or_default(),
        )
        .await;
    Ok(axum::Json(serde_json::to_value(rcr).unwrap_or_default()))
}

/// `POST /passkeys/login/finish` — complete a discoverable authentication ceremony.
///
/// On success writes `state.auth_session_key()`, `__SNAKE___id`, and
/// `__SNAKE___email` so downstream `#[secured]` routes work without modification.
#[post("/passkeys/login/finish")]
pub async fn passkey_login_finish(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    crate::routes::auth::MaybeClientIp(addr_ip): crate::routes::auth::MaybeClientIp,
    headers: axum::http::HeaderMap,
    axum::Json(body): axum::Json<PasskeyLoginFinishBody>,
) -> AutumnResult<axum::Json<serde_json::Value>> {
    let auth_state_str: String = session
        .get("passkey_auth_state")
        .await
        .ok_or_else(|| AutumnError::unprocessable_msg("No pending authentication."))?;
    session.remove("passkey_auth_state").await;
    let auth_state: DiscoverableAuthentication = serde_json::from_str(&auth_state_str)
        .map_err(|_| AutumnError::unprocessable_msg("Invalid authentication state."))?;
    let webauthn = build_webauthn(&state)?;
    let pkc: PublicKeyCredential = serde_json::from_value(body.response)
        .map_err(|e| AutumnError::unprocessable_msg(format!("Invalid credential: {e}")))?;
    // Decode user identity from the credential's userHandle (set during registration).
    let (user_uuid, _) = webauthn
        .identify_discoverable_authentication(&pkc)
        .map_err(|e| AutumnError::unauthorized_msg(format!("Cannot identify user: {e}")))?;
    let __SNAKE___id = user_uuid.as_u128() as i64;
    // Load only this user's passkeys for signature verification.
    let disc_keys: Vec<DiscoverableKey> = {
        use crate::schema::webauthn_credentials;
        webauthn_credentials::table
            .filter(webauthn_credentials::user_id.eq(__SNAKE___id))
            .select(webauthn_credentials::credential_json)
            .load::<String>(&mut *db)
            .await
            .unwrap_or_default()
            .into_iter()
            .filter_map(|json| serde_json::from_str::<Passkey>(&json).ok())
            .map(|p| DiscoverableKey::from(&p))
            .collect()
    };
    let auth_result = webauthn
        .finish_discoverable_authentication(&pkc, auth_state, &disc_keys)
        .map_err(|e| AutumnError::unauthorized_msg(format!("Authentication failed: {e}")))?;
    let cred_id_str = encode_cred_id(auth_result.cred_id());
    let (wc_id, cred_json) = {
        use crate::schema::webauthn_credentials;
        webauthn_credentials::table
            .filter(webauthn_credentials::credential_id.eq(&cred_id_str))
            .filter(webauthn_credentials::user_id.eq(__SNAKE___id))
            .select((webauthn_credentials::id, webauthn_credentials::credential_json))
            .first::<(i64, String)>(&mut *db)
            .await
            .map_err(|_| AutumnError::unauthorized_msg("Unknown credential."))?
    };
    let (__SNAKE___email, email_confirmed_at): (String, Option<chrono::NaiveDateTime>) = {
        use crate::schema::__TABLE__;
        __TABLE__::table
            .find(__SNAKE___id)
            .select((__TABLE__::email, __TABLE__::email_confirmed_at))
            .first::<(String, Option<chrono::NaiveDateTime>)>(&mut *db)
            .await
            .map_err(|_| AutumnError::unauthorized_msg("User not found."))?
    };
    // Reject unconfirmed accounts — consistent with the password-login gate.
    if email_confirmed_at.is_none() {
        return Err(AutumnError::unauthorized_msg(
            "Email address not confirmed. Please check your email for a confirmation link.",
        ));
    }
    let now = chrono::Utc::now().naive_utc();
    if auth_result.needs_update() {
        let mut passkey: Passkey = serde_json::from_str(&cred_json)
            .unwrap_or_else(|_| serde_json::from_value(serde_json::Value::Null).unwrap());
        passkey.update_credential(&auth_result);
        let new_json = serde_json::to_string(&passkey).unwrap_or(cred_json.clone());
        diesel::update(crate::schema::webauthn_credentials::table.find(wc_id))
            .set((
                crate::schema::webauthn_credentials::credential_json.eq(&new_json),
                crate::schema::webauthn_credentials::last_used_at.eq(now),
            ))
            .execute(&mut *db)
            .await
            .map_err(|_| {
                AutumnError::internal_server_error_msg("Failed to update credential state.")
            })?;
    } else {
        diesel::update(crate::schema::webauthn_credentials::table.find(wc_id))
            .set(crate::schema::webauthn_credentials::last_used_at.eq(now))
            .execute(&mut *db)
            .await
            .map_err(|_| {
                AutumnError::internal_server_error_msg("Failed to update credential timestamp.")
            })?;
    }
    // Drop any tracked row for the pre-login session — the rotation below
    // destroys its id, which would otherwise leave a phantom device.
    crate::routes::auth::untrack_current_session(&mut db, &session).await?;
    session.rotate_id().await;
    session
        .insert("__SNAKE___id", __SNAKE___id.to_string())
        .await;
    session.insert("__SNAKE___email", &__SNAKE___email).await;
    session
        .insert(state.auth_session_key(), __SNAKE___id.to_string())
        .await;
    // Stamp the step-up claim so `#[step_up]` routes (e.g. passkey management)
    // are immediately accessible after a passkey login.
    autumn_web::step_up::set_last_strong_auth_at(&session).await;
    // Track this login as an active session (device list + revocation).
    crate::routes::auth::record_login_session(&mut db, &session, __SNAKE___id, addr_ip, &headers)
        .await?;
    Ok(axum::Json(serde_json::json!({ "ok": true })))
}

// ── Management ────────────────────────────────────────────────────────────────

/// `GET /passkeys` — list the current user's registered passkeys.
#[secured]
#[get("/passkeys")]
pub async fn passkey_list(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Markup> {
    // Validates the tracked session row (401s immediately if revoked).
    let __SNAKE___id: i64 = crate::routes::auth::require_tracked_session(&session, &mut db, &state)
        .await?
        .id;
    let rows: Vec<(i64, String, chrono::NaiveDateTime)> = {
        use crate::schema::webauthn_credentials;
        webauthn_credentials::table
            .filter(webauthn_credentials::user_id.eq(__SNAKE___id))
            .select((
                webauthn_credentials::id,
                webauthn_credentials::name,
                webauthn_credentials::created_at,
            ))
            .load(&mut *db)
            .await
            .unwrap_or_default()
    };
    Ok(html! {
        html {
            head { title { "Your Passkeys" } }
            body {
                h1 { "Your Passkeys" }
                a href="/passkeys/register" { "Register a new passkey" }
                @if rows.is_empty() {
                    p { "No passkeys registered yet." }
                } @else {
                    ul {
                        @for (id, name, created_at) in &rows {
                            li {
                                (name) " — registered " (created_at.to_string())
                                " "
                                form method="post" action="/passkeys/revoke" style="display:inline" {
                                    @if let Some(ref t) = csrf {
                                        input type="hidden"
                                              name=(csrf_field.as_ref().map(|f| f.0.as_str()).unwrap_or("_csrf"))
                                              value=(t.token());
                                    }
                                    input type="hidden" name="id" value=(id);
                                    button type="submit" { "Revoke" }
                                }
                            }
                        }
                    }
                }
            }
        }
    })
}

/// `DELETE /passkeys/:id` (also accepts `POST /passkeys/revoke`) — remove a passkey.
#[secured]
#[post("/passkeys/revoke")]
pub async fn passkey_revoke(
    session: Session,
    State(state): State<AppState>,
    mut db: Db,
    Form(form): Form<PasskeyRevokeForm>,
) -> AutumnResult<axum::response::Redirect> {
    // Validates the tracked session row (401s immediately if revoked).
    let current =
        crate::routes::auth::require_tracked_session(&session, &mut db, &state).await?;
    // Remove the passkey and revoke every *other* session in one
    // transaction: the documented revoke-on-credential-change guarantee
    // (defaulted on, configurable via
    // [auth.sessions].revoke_on_credential_change) can never be silently
    // skipped, and a failure rolls the removal back instead of 500ing
    // after it.
    let user_id = current.id;
    let credential_id = form.id;
    let revoke_other_sessions_in_txn = state.config_arc().auth.sessions.revoke_on_credential_change;
    let current_token_digest = crate::routes::auth::session_token_digest(&session).await;
    (*db)
        .transaction::<_, diesel::result::Error, _>(async move |conn| {
            diesel::delete(
                crate::schema::webauthn_credentials::table
                    .filter(crate::schema::webauthn_credentials::id.eq(credential_id))
                    .filter(crate::schema::webauthn_credentials::user_id.eq(user_id)),
            )
            .execute(conn)
            .await?;
            if revoke_other_sessions_in_txn {
                diesel::delete(
                    crate::schema::__SESSTABLE__::table
                        .filter(crate::schema::__SESSTABLE__::user_id.eq(user_id))
                        .filter(crate::schema::__SESSTABLE__::token_digest.ne(current_token_digest)),
                )
                .execute(conn)
                .await?;
            }
            Ok(())
        })
        .await
        .map_err(|_| AutumnError::internal_server_error_msg("Failed to revoke passkey."))?;
    Ok(redirect_to("/passkeys"))
}
"##;
    tpl.replace("__PASCAL__", pascal_name)
        .replace("__SNAKE__", snake_name)
        .replace("__TABLE__", user_table)
        .replace("__SESSTABLE__", &sessions_table_name(snake_name))
}

fn render_passkeys_tests_file(pascal_name: &str, _snake_name: &str) -> String {
    format!(
        r#"//! Generated passkey integration tests for {pascal_name} (`autumn generate auth --passkeys`).
//!
//! These tests run against a live server started with `AUTUMN_TEST_BASE_URL`.
//! In CI, start the app, set the env var, and run `cargo test`.
//! They skip when the env var is unset, so they compile and pass out of the box.

fn base_url() -> Option<String> {{
    std::env::var("AUTUMN_TEST_BASE_URL").ok()
}}

#[test]
fn passkey_register_happy_path() {{
    let Some(_base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    // 1. POST /passkeys/register/begin (authenticated session)
    // 2. Simulate navigator.credentials.create response
    // 3. POST /passkeys/register/finish — expect 200 {{ "ok": true }}
}}

#[test]
fn passkey_login_happy_path() {{
    let Some(_base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    // 1. POST /passkeys/login/begin
    // 2. Simulate navigator.credentials.get response
    // 3. POST /passkeys/login/finish — expect 200 {{ "ok": true }} and auth cookie
}}

#[test]
fn passkey_wrong_origin_rejected() {{
    let Some(_base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    // POST /passkeys/login/finish with a credential registered against a different
    // origin — expect 401 or 422.
}}

#[test]
fn passkey_unknown_credential_rejected() {{
    let Some(_base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    // POST /passkeys/login/finish with a credential_id that is not in the DB
    // — expect 401.
}}

#[test]
fn passkey_revoke_then_relogin() {{
    let Some(_base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    // 1. Register a passkey.
    // 2. POST /passkeys/revoke to remove it.
    // 3. Attempt login with the revoked credential — expect failure.
}}
"#
    )
}

fn render_passkeys_docs_file() -> String {
    r#"# Passkeys (WebAuthn)

Generated with `autumn generate auth --passkeys`. Users can register and use
hardware security keys, platform authenticators (Touch ID, Face ID, Windows Hello),
or other FIDO2 compliant devices as passwordless credentials.

## Configuration

Add to `autumn.toml` before enabling passkeys:

```toml
[auth.webauthn]
rp_id     = "example.com"          # domain only (no port, no scheme)
rp_name   = "My App"               # shown in authenticator dialogs
rp_origin = "https://example.com"  # full origin including scheme
```

For local development use:

```toml
[auth.webauthn]
rp_id     = "localhost"
rp_name   = "My App (dev)"
rp_origin = "http://localhost:3000"
```

## Generated routes

| Method | Path | Handler | Auth |
|--------|------|---------|------|
| GET | `/passkeys/register` | `passkey_register_page` | **Required** |
| POST | `/passkeys/register/begin` | `passkey_register_begin` | **Required** |
| POST | `/passkeys/register/finish` | `passkey_register_finish` | **Required** |
| GET | `/passkeys/login` | `passkey_login_page` | Public |
| POST | `/passkeys/login/begin` | `passkey_login_begin` | Public |
| POST | `/passkeys/login/finish` | `passkey_login_finish` | Public |
| GET | `/passkeys` | `passkey_list` | **Required** |
| POST | `/passkeys/revoke` | `passkey_revoke` | **Required** |

## Security properties

- Ceremony challenges are bound to the origin (`rp_origin`) and domain (`rp_id`).
  A credential registered against `example.com` cannot authenticate against
  `evil.com`, even if the credential bytes are stolen.
- `passkey_login_finish` calls `session.rotate_id()` before writing the auth key,
  preventing session fixation.
- Revoked credentials are deleted from `webauthn_credentials`; a subsequent
  login attempt with the revoked credential will fail at the DB lookup step.
- `credential_json` stores opaque passkey state — never expose it to clients.

## Discoverable credentials

`passkey_login_begin` passes `&[]` (an empty allowed-credentials list), enabling
**discoverable credential** (resident key) flow. The browser prompts the user to
select a saved passkey without the server needing to know their identity first.
No credential IDs are sent to anonymous clients.

## Browser compatibility

The generated JavaScript uses `PublicKeyCredential.parseCreationOptionsFromJSON`,
`parseRequestOptionsFromJSON`, and `credential.toJSON()` (Chrome 119+,
Firefox 119+, Safari 17+). Add a polyfill (e.g. `@github/webauthn-json`) for
older browsers.

## Out of scope (follow-ups)

- **Rate-limiting** on ceremony endpoints is not included — add it before
  exposing them to untrusted traffic.
"#
    .to_owned()
}

/// Ensure `autumn-web` in `[dependencies]` has `features = ["webauthn"]`.
fn ensure_autumn_web_webauthn_feature(toml: &str) -> String {
    ensure_autumn_web_feature(toml, "webauthn")
}

fn append_webauthn_stub_to_toml(
    existing: &str,
    rp_id: &str,
    rp_name: &str,
    rp_origin: &str,
) -> String {
    if existing.contains("[auth.webauthn]") {
        return existing.to_owned();
    }
    let mut out = existing.trim_end().to_owned();
    out.push_str("\n\n[auth.webauthn]\n");
    out.push_str("rp_id = \"");
    out.push_str(rp_id);
    out.push_str("\"\nrp_name = \"");
    out.push_str(rp_name);
    out.push_str("\"\nrp_origin = \"");
    out.push_str(rp_origin);
    out.push_str("\"\n");
    out
}

/// Inverse of [`append_oauth_stubs_to_toml`] (`autumn destroy`, issue #1048).
///
/// Removes each `[auth.oauth2.<provider>]` stub block for `providers`, but
/// only when its current content is still byte-identical to the stub
/// `append_oauth_stubs_to_toml` would have inserted — never a block that
/// pre-existed before this `generate` call (real credentials `generate`
/// never touched), and never one the user has since filled in. A no-op for
/// any provider whose header isn't present, or whose content no longer
/// matches (already destroyed, hand-edited, or a pre-existing real config).
pub(super) fn remove_oauth_provider_stubs(existing: &str, providers: &[String]) -> String {
    let mut content = existing.to_owned();
    for name in providers {
        let header = format!("[auth.oauth2.{name}]");
        if toml_table_block_matches(&content, &header, &oauth_provider_stub_block(name)) {
            content = remove_toml_table_block(&content, &header);
        }
    }
    content
}

/// Inverse of [`append_webauthn_stub_to_toml`] (`autumn destroy`, issue #1048).
///
/// A no-op if `[auth.webauthn]` isn't present, or if its content no longer
/// matches exactly what `append_webauthn_stub_to_toml` always inserts (the
/// same "never touch a pre-existing or since-edited block" guard as
/// [`remove_oauth_provider_stubs`]).
pub(super) fn remove_webauthn_stub(existing: &str) -> String {
    const HEADER: &str = "[auth.webauthn]";
    let expected = "[auth.webauthn]\n\
                     rp_id = \"localhost\"\n\
                     rp_name = \"My App\"\n\
                     rp_origin = \"http://localhost:3000\"\n";
    if toml_table_block_matches(existing, HEADER, expected) {
        remove_toml_table_block(existing, HEADER)
    } else {
        existing.to_owned()
    }
}

/// The `(start, end)` line-index span of a top-level `[header]` TOML table —
/// the header line through the last line before the next top-level `[...]`
/// header or EOF. `None` if `header` isn't present.
fn toml_table_block_range(lines: &[&str], header: &str) -> Option<(usize, usize)> {
    let start = lines.iter().position(|l| l.trim() == header)?;
    let end = lines[start + 1..]
        .iter()
        .position(|l| l.trim_start().starts_with('['))
        .map_or(lines.len(), |rel| start + 1 + rel);
    Some((start, end))
}

/// Whether `[header]`'s current block content is byte-identical (ignoring a
/// trailing-newline difference) to `expected_block` — used to verify a stub
/// hasn't been hand-filled with real values, or didn't pre-exist before
/// `generate` ever ran, before `autumn destroy` removes it.
fn toml_table_block_matches(existing: &str, header: &str, expected_block: &str) -> bool {
    let lines: Vec<&str> = existing.lines().collect();
    let Some((start, end)) = toml_table_block_range(&lines, header) else {
        return false;
    };
    lines[start..end].join("\n").trim_end() == expected_block.trim_end()
}

/// Remove a top-level `[header]` TOML table — the header line and every line
/// up to (but not including) the next top-level `[...]` header or EOF — plus
/// one immediately preceding blank separator line, if present.
///
/// This is the exact inverse shape of how [`append_oauth_stubs_to_toml`] and
/// [`append_webauthn_stub_to_toml`] insert a table at the end of the file
/// (`existing.trim_end()` followed by a separator and the new block): consuming
/// one preceding blank line here undoes that separator, and discarding
/// everything from the header to EOF when this is the last table in the file
/// undoes the trailing blank line those functions leave behind. A no-op if
/// `header` isn't present.
fn remove_toml_table_block(existing: &str, header: &str) -> String {
    let lines: Vec<&str> = existing.lines().collect();
    let Some((start, end)) = toml_table_block_range(&lines, header) else {
        return existing.to_owned();
    };

    let mut block_start = start;
    if block_start > 0 && lines[block_start - 1].trim().is_empty() {
        block_start -= 1;
    }

    let mut new_lines: Vec<&str> = Vec::with_capacity(lines.len());
    new_lines.extend_from_slice(&lines[..block_start]);
    new_lines.extend_from_slice(&lines[end..]);
    let mut out = new_lines.join("\n");
    if !out.is_empty() {
        out.push('\n');
    }
    out
}

// ── Unit tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    /// The generated app stamps the majors that this release supports.
    #[test]
    fn generated_auth_stamps_current_dependency_majors() {
        let stamp = |deps: &[(&str, &'static str)], name: &str| {
            deps.iter()
                .find(|(crate_name, _)| *crate_name == name)
                .map_or_else(|| panic!("{name} must be stamped"), |(_, spec)| *spec)
        };
        for (deps, name, version) in [
            (AUTH_EXTRA_DEPS, "sha2", "\"0.11\""),
            (AUTH_EXTRA_DEPS, "rand", "\"0.10\""),
            (PASSKEY_EXTRA_DEPS, "webauthn-rs", "\"0.6\""),
            (PASSKEY_EXTRA_DEPS, "base64", "\"0.23\""),
            (TOTP_EXTRA_DEPS, "aes-gcm", "\"0.11\""),
            (TOTP_EXTRA_DEPS, "base64", "\"0.23\""),
        ] {
            let spec = stamp(deps, name);
            assert!(
                spec.contains(version),
                "{name} must be stamped at {version}, got {spec}"
            );
        }
    }

    /// `ensure_cargo_dependencies` keeps a crate the app already declares. The
    /// generated code uses the `rand` 0.10 and `webauthn-rs` 0.6 APIs, so an
    /// older pin must give a warning, not a silent compile error.
    #[test]
    fn generated_auth_warns_about_an_older_rand_or_webauthn_pin() {
        let tmp = project_with_main();
        fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname=\"x\"\n\n[dependencies]\nautumn-web = \"0.3\"\n\
             rand = \"0.9\"\nwebauthn-rs = \"0.5\"\n",
        )
        .unwrap();
        let plan = plan_auth_full_ex2(
            tmp.path(),
            "User",
            "20260508000000",
            &AuthOAuthOptions::default(),
            false,
            true,
            false,
        )
        .unwrap();
        for name in ["'rand'", "'webauthn-rs'"] {
            assert!(
                plan.warnings.iter().any(|warning| warning.contains(name)),
                "no warning names {name}: {:?}",
                plan.warnings
            );
        }
    }

    /// Issue #3170: every `<label>` must name a control. A bare label gives a
    /// screen reader no accessible name. A label is bound by `for` plus a
    /// matching `id` in the same form, or by wrapping a checkbox. Every visible
    /// input needs an `id` or an `aria-label`. Ids are unique in a form.
    /// Wayfinder audit: every form control the auth scaffold emits has an
    /// accessible name. A sibling `<label>` with no `for=` names nothing, so
    /// the login/signup/reset/reauth inputs were unlabeled to assistive tech
    /// and clicking the visible label did not focus its field.
    #[test]
    fn auth_scaffold_has_no_unlabeled_form_controls() {
        let tmp = project_with_main();
        plan_auth_full_ex2(
            tmp.path(),
            "User",
            "20260508000000",
            &AuthOAuthOptions {
                providers: Vec::new(),
            },
            true, // totp
            true, // passkeys
            true, // magic_link
        )
        .expect("generate auth must scaffold")
        .execute(Flags::default())
        .unwrap();
        let scan = crate::a11y::scan_project(&tmp.path().join("src")).unwrap();
        let unlabeled: Vec<String> = scan
            .findings
            .iter()
            .filter(|f| f.rule_id == "label")
            .map(|f| format!("{}:{} <{}>", f.file, f.line, f.element))
            .collect();
        assert!(
            unlabeled.is_empty(),
            "auth scaffold has unlabeled controls: {unlabeled:#?}"
        );
    }

    #[test]
    fn generated_forms_bind_every_label_and_input() {
        let variants = [
            render_routes_file("User", "user", "users", &[], false, false),
            render_routes_file("User", "user", "users", &[], true, false),
            render_routes_file("User", "user", "users", &[], false, true),
            render_routes_file("User", "user", "users", &["github".to_owned()], true, true),
        ];
        let mut bound = 0;
        for routes in &variants {
            for form in routes.split("form action=").skip(1) {
                let mut ids = Vec::new();
                for (at, _) in form.match_indices("id=\"") {
                    let rest = &form[at + 4..];
                    let id = &rest[..rest.find('"').expect("id value ends")];
                    if form[..at].ends_with("for=\"") {
                        continue;
                    }
                    assert!(!ids.contains(&id), "duplicate id \"{id}\" in one form");
                    ids.push(id);
                }
                // A form helper (issue #3412) writes its label and its id
                // at run time: the field name is both.
                for helper in [
                    "(password_field(\"",
                    "(otp_input_with(&Changeset::new(()), \"",
                ] {
                    for (at, _) in form.match_indices(helper) {
                        let rest = &form[at + helper.len()..];
                        let id = &rest[..rest.find('"').expect("field name ends")];
                        assert!(!ids.contains(&id), "duplicate id \"{id}\" in one form");
                        ids.push(id);
                        bound += 1;
                    }
                }
                for (at, _) in form.match_indices("label ") {
                    if form[..at]
                        .chars()
                        .next_back()
                        .is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '"')
                    {
                        continue;
                    }
                    let rest = &form[at + "label ".len()..];
                    if let Some(after_for) = rest.strip_prefix("for=\"") {
                        let id = &after_for[..after_for.find('"').expect("for value ends")];
                        assert!(ids.contains(&id), "label for=\"{id}\" has no input id");
                        bound += 1;
                    } else if rest.starts_with('{') {
                        let window = &rest[..rest.find('}').expect("label ends")];
                        assert!(
                            window.contains("type=\"checkbox\""),
                            "bare label names no control:\n{window}"
                        );
                    }
                }
                for (at, _) in form.match_indices("input type=\"") {
                    let rest = &form[at..];
                    let stmt = &rest[..rest.find(';').expect("input ends")];
                    let kind = &stmt["input type=\"".len()..];
                    if kind.starts_with("hidden") || kind.starts_with("checkbox") {
                        continue;
                    }
                    assert!(
                        stmt.contains("id=\"")
                            || stmt.contains("id={")
                            || stmt.contains("aria-label="),
                        "input has no id or aria-label:\n{stmt}"
                    );
                }
            }
        }
        assert!(bound >= 40, "scan found too few labels: {bound}");
    }

    /// Issue #3412: each password field uses `password_input_with`, with a
    /// reveal button and an `autocomplete` token. A new password also has a
    /// strength hint. No raw password input stays.
    #[test]
    fn password_fields_use_the_form_helper() {
        for (totp, magic) in [(false, false), (true, false), (false, true), (true, true)] {
            let routes = render_routes_file("User", "user", "users", &[], totp, magic);
            assert!(
                routes.contains("use autumn_web::form::{FieldOptions, password_input_with};"),
                "missing import"
            );
            assert!(
                routes.contains("password_input_with(&Changeset::new(()), field, label, &options)"),
                "the helper uses the form helper"
            );
            assert!(
                !routes.contains("input type=\"password\""),
                "a raw password input stays:\n{routes}"
            );
            let calls: Vec<&str> = routes
                .match_indices("(password_field(\"")
                .map(|(at, _)| {
                    let rest = &routes[at..];
                    &rest[..rest.find("))").expect("call ends") + 2]
                })
                .collect();
            let expected = if totp { 11 } else { 9 };
            assert_eq!(calls.len(), expected, "password fields: {calls:#?}");
            for call in &calls {
                assert!(
                    call.contains(".current_password()") || call.contains(".new_password()"),
                    "no autocomplete token: {call}"
                );
                assert!(
                    call.contains(".reveal()") || call.contains(".reveal_label(\"Show "),
                    "no reveal button: {call}"
                );
            }
            // Three buttons on one page have three names.
            for label in [
                "Show current password",
                "Show new password",
                "Show confirmation",
            ] {
                assert!(
                    routes.contains(&format!(".reveal_label(\"{label}\")")),
                    "{label}"
                );
            }
            // Signup, reset and the new password of a change get the hint.
            assert_eq!(
                calls
                    .iter()
                    .filter(|c| c.contains(".strength_hint()"))
                    .count(),
                3,
                "{calls:#?}"
            );
            assert_eq!(
                calls
                    .iter()
                    .filter(|c| c.contains(".new_password().minlength(min_len)"))
                    .count(),
                2,
                "signup and reset keep the minimum length: {calls:#?}"
            );
        }
    }

    /// Issue #3412: the two 6-digit fields on `/account/2fa` use
    /// `otp_input_with`. `/login/verify` and `/reauth` also take a recovery
    /// code (`a1b2c-3d4e5`), so they keep a text input.
    #[test]
    fn totp_code_fields_use_the_otp_helper() {
        let routes = render_routes_file("User", "user", "users", &[], true, false);
        assert!(routes.contains("use autumn_web::form::{OtpFormat, otp_input_with};"));
        let calls = routes
            .matches("(otp_input_with(&Changeset::new(()), \"code\"")
            .count();
        assert_eq!(calls, 2, "{routes}");
        assert!(routes.contains("OtpFormat::digits(6), &FieldOptions::new().required()))"));
        assert!(!routes.contains("id=\"confirm-code\""));
        assert!(!routes.contains("id=\"disable-code\""));
        // A recovery code has letters and a dash: no digits-only field.
        let verify = &routes[routes
            .find("pub async fn login_verify_form(")
            .expect("form")..];
        let verify = &verify[..verify.find("\n}\n").expect("fn ends")];
        assert!(
            verify.contains("input type=\"text\" id=\"code\" name=\"code\""),
            "{verify}"
        );
        assert!(!verify.contains("otp_input"), "{verify}");
        // Without --totp, nothing imports the OTP helper.
        let plain = render_routes_file("User", "user", "users", &[], false, false);
        assert!(!plain.contains("otp_input_with"));
    }

    /// Issue #3106: a placeholder is not a label or an instruction. The TOTP
    /// code fields keep their hint in a `<small id>` that the input names with
    /// `aria-describedby`. The placeholder holds no instruction.
    #[test]
    fn totp_code_fields_link_a_visible_hint() {
        let routes = render_routes_file("User", "user", "users", &[], true, false);
        let sources = [routes, totp_reauth_field_src()];
        let (mut fields, mut hints) = (0, 0);
        for src in &sources {
            for (at, _) in src.match_indices("input type=\"text\" id=\"totp-code\"") {
                let stmt = &src[at..at + src[at..].find(';').expect("input ends")];
                fields += 1;
                assert!(
                    stmt.contains("aria-describedby=\"totp-hint\""),
                    "totp input has no aria-describedby:\n{stmt}"
                );
                assert!(!stmt.contains("placeholder="), "placeholder in:\n{stmt}");
            }
            hints += src.matches("small id=\"totp-hint\"").count();
            hints += src.matches("small id=\\\"totp-hint\\\"").count();
            assert!(src.contains("6-digit code or a recovery code"));
        }
        assert!(fields >= 3, "expected 3 or more totp inputs, got {fields}");
        assert_eq!(hints, fields, "each input needs its own hint");
    }

    /// Issue #3106: the session device-label input has a visible `<label>`
    /// bound by `for`/`id`. A row id keeps the id unique on the page.
    #[test]
    fn device_label_input_has_a_bound_visible_label() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let rows = routes.find("\"/account/sessions/\"").expect("session rows");
        let at = rows
            + routes[rows..]
                .find("name=\"label\"")
                .expect("device label input");
        let before = &routes[..at];
        let input = &before[before.rfind("input type=\"text\"").expect("input start")..];
        assert!(
            input.contains("id={ \"device-label-\" (s.id) }"),
            "no row id:\n{input}"
        );
        let form = &before[before
            .rfind("form action={ \"/account/sessions/\"")
            .expect("form")..];
        assert!(
            form.contains("label for={ \"device-label-\" (s.id) }"),
            "no bound label:\n{form}"
        );
    }

    /// Issue #2347: while impersonating, `{snake}_id` is the target but the
    /// tracked row belongs to the operator. The lookup must use the operator's
    /// id, or the next request would miss the row and 401.
    #[test]
    fn require_tracked_session_matches_the_row_owner_while_impersonating() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let start = routes
            .find("pub async fn require_tracked_session")
            .expect("require_tracked_session is generated");
        let len = routes[start..].find("\n}\n").expect("fn body ends");
        let body = &routes[start..start + len];
        assert!(
            body.contains("impersonation::audit_actor_id"),
            "row owner must resolve through the impersonation record:\n{body}"
        );
    }

    /// Issue #2347: any `rotate_id()` while logged in moves the digest the
    /// tracked row is keyed by. The startup hook must register a rotation hook
    /// that re-points the row, so flows without an explicit rebind (such as
    /// impersonation) do not 401 on the next request.
    #[test]
    fn startup_hook_registers_a_tracked_session_rotation_hook() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let hook_at = routes
            .find("pub async fn remember_me_startup")
            .expect("startup hook is generated");
        let body_len = routes[hook_at..].find("\n}\n").expect("hook body ends");
        let body = &routes[hook_at..hook_at + body_len];
        assert!(
            body.contains(".session_rotation_hooks()") && body.contains(".register("),
            "startup hook must register a rotation hook:\n{body}"
        );
        assert!(
            routes.contains("async fn rebind_tracked_session_on_rotation"),
            "rotation hook body must be generated"
        );
        assert!(
            routes.contains("rotation.earlier_ids"),
            "the hook must find a row an earlier hop already moved"
        );
    }

    /// Generated request handlers must read config through `state.config_arc()`,
    /// never `state.config()`.
    ///
    /// `config()` hands back an owned snapshot, which deep-clones every section
    /// of `AutumnConfig` (~65 allocations) to read one field. In a handler that
    /// is paid per request, and a handler reading two sections pays it twice —
    /// which is how a downstream app measured whole-config clones at ~30% of its
    /// per-request allocations. `config_arc()` clones the `Arc` instead, so the
    /// same read is a refcount bump.
    ///
    /// The one legitimate `config()` in the emitted file is the boot-time
    /// `remember_me_startup` hook: it runs once and hands `init_remember_pool` an
    /// owned `RememberConfig`. This pins that exception to exactly one site, so a
    /// `config()` re-introduced into any handler fails here rather than in a
    /// downstream profile.
    #[test]
    fn generated_handlers_read_config_through_the_shared_arc() {
        const STARTUP_HOOK: &str = "pub async fn remember_me_startup";

        for (label, routes) in [
            (
                "plain",
                render_routes_file("User", "user", "users", &[], false, false),
            ),
            (
                "totp",
                render_routes_file("User", "user", "users", &[], true, false),
            ),
            (
                "magic-link",
                render_routes_file("User", "user", "users", &[], false, true),
            ),
            (
                "oauth",
                render_routes_file(
                    "User",
                    "user",
                    "users",
                    &["github".to_owned()],
                    false,
                    false,
                ),
            ),
        ] {
            let hook_at = routes
                .find(STARTUP_HOOK)
                .unwrap_or_else(|| panic!("{label}: expected a {STARTUP_HOOK} definition"));
            // The hook's own `config()` sits a few lines into its body; anything
            // further out is a handler paying a deep clone per request.
            let hook_body_end = hook_at + 600;

            for (offset, _) in routes.match_indices("state.config()") {
                assert!(
                    (hook_at..hook_body_end).contains(&offset),
                    "{label}: generated code calls state.config() outside the boot-time \
                     {STARTUP_HOOK} hook (byte {offset}), which deep-clones every config \
                     section on a request path — use state.config_arc() instead:\n{}",
                    &routes[offset.saturating_sub(300)..(offset + 200).min(routes.len())]
                );
            }

            assert!(
                routes.contains("state.config_arc()"),
                "{label}: generated handlers must read config through state.config_arc()"
            );
        }
    }

    fn project_with_main() -> TempDir {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname=\"x\"\n\n[dependencies]\nautumn-web = \"0.3\"\n",
        )
        .unwrap();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        fs::write(tmp.path().join("src/main.rs"), main_with_layout()).unwrap();
        tmp
    }

    /// A `src/main.rs` exposing a shared 4-arg
    /// `pub fn layout(title, current_path, flash, content)` — what `autumn new`
    /// emits and what the auth generator's views render through
    /// (`crate::layout`, issue #1353). The auth preflight requires this.
    fn main_with_layout() -> &'static str {
        "use autumn_web::prelude::*;\n\n\
         pub fn layout(title: &str, current_path: &str, flash: maud::Markup, content: maud::Markup) -> maud::Markup {\n\
         \x20   let _ = (current_path, flash);\n\
         \x20   maud::html! {\n\
         \x20       title { (title) }\n\
         \x20       (content)\n\
         \x20   }\n\
         }\n\n\
         #[autumn_web::main]\n\
         async fn main() {\n\
         \x20   autumn_web::app().routes(routes![]).run().await;\n\
         }\n"
    }

    /// A `src/main.rs` with no shared `pub fn layout` — used to exercise the
    /// actionable error the auth generator raises when the target app has no
    /// shared layout for its HTML views to render through (issue #1353).
    fn main_without_layout() -> &'static str {
        "use autumn_web::prelude::*;\n\n\
         #[autumn_web::main]\n\
         async fn main() {\n\
         \x20   autumn_web::app().routes(routes![]).run().await;\n\
         }\n"
    }

    /// A Cargo.toml matching what `autumn new`'s own template ships
    /// (`autumn-web`, `diesel_migrations`, and `maud` already present — see
    /// `TEMPLATE_SHIPPED_CARGO_DEPS`), used by the round-trip tests below so
    /// those three names are genuinely pre-existing rather than freshly
    /// added by this generator (and thus rightly excluded from its
    /// `Revert::CargoDeps`).
    fn template_shipped_cargo_toml() -> &'static str {
        "[package]\nname=\"x\"\n\n[dependencies]\nautumn-web = \"0.3\"\n\
         diesel_migrations = \"2\"\nmaud = { version = \"0.27\", features = [\"axum\"] }\n"
    }

    // ── generate/destroy round trips (issue #1048) ──────────────────────────
    //
    // `autumn destroy auth` recomputes the exact same plan `generate` did and
    // interprets it in reverse (see `Plan::revert`): every `Create`d file is
    // deleted, and every shared-file edit recorded via `plan.push_revert(...)`
    // is undone. These tests assert the round trip is byte-identical for the
    // base scaffold plus each optional feature flag.

    /// The scaffolded `docs/guide/authentication.md` hands the operator
    /// copy-paste SQL, so it must be in the app's own dialect too (issue
    /// #1927) — the same rule `render_sessions_docs_file` and
    /// `render_oauth_docs_file` already follow.
    #[test]
    fn authentication_docs_sql_is_backend_aware() {
        use autumn_web::config::DatabaseBackend;

        let pg = render_docs_file(DatabaseBackend::Postgres, "User", true, true);
        let sqlite = render_docs_file(DatabaseBackend::Sqlite, "User", true, true);

        // Postgres output is unchanged by the fork: each retrofit block verbatim.
        assert!(
            pg.contains(
                "ALTER TABLE {table}\n  \
                 ADD COLUMN IF NOT EXISTS failed_attempts INT NOT NULL DEFAULT 0,\n  \
                 ADD COLUMN IF NOT EXISTS locked_at TIMESTAMP NULL;"
            ),
            "{pg}"
        );
        assert!(
            pg.contains(
                "ALTER TABLE {table}\n  \
                 DROP COLUMN IF EXISTS failed_attempts,\n  \
                 DROP COLUMN IF EXISTS locked_at;"
            ),
            "{pg}"
        );
        assert!(
            pg.contains(
                "ALTER TABLE {table}\n  \
                 ADD COLUMN IF NOT EXISTS confirm_token_digest TEXT NULL,\n  \
                 ADD COLUMN IF NOT EXISTS confirm_token_expires_at TIMESTAMP NULL,\n  \
                 ADD COLUMN IF NOT EXISTS email_confirmed_at TIMESTAMP NULL,\n  \
                 ADD COLUMN IF NOT EXISTS pending_email TEXT NULL;"
            ),
            "{pg}"
        );
        assert!(
            pg.contains(
                "UPDATE {table} SET email_confirmed_at = NOW() WHERE email_confirmed_at IS NULL;"
            ),
            "{pg}"
        );
        assert!(pg.contains("email_confirmed_at = NOW()"), "{pg}");

        // SQLite has none of those: no `IF NOT EXISTS` on ADD COLUMN, one
        // column per `ALTER TABLE`, and `CURRENT_TIMESTAMP` for the clock.
        for leak in [
            "IF NOT EXISTS",
            "IF EXISTS",
            "NOW()",
            "TIMESTAMP NULL",
            "INT NOT NULL",
        ] {
            assert!(
                !sqlite.contains(leak),
                "SQLite authentication.md leaked Postgres-only `{leak}`:\n{sqlite}"
            );
        }
        assert!(
            sqlite.contains(
                "ALTER TABLE {table} ADD COLUMN failed_attempts INTEGER NOT NULL DEFAULT 0;"
            ),
            "{sqlite}"
        );
        assert!(
            sqlite.contains("ALTER TABLE {table} ADD COLUMN locked_at TEXT NULL;"),
            "{sqlite}"
        );
        assert!(
            sqlite.contains("email_confirmed_at = CURRENT_TIMESTAMP"),
            "{sqlite}"
        );
    }

    /// Backend-aware DDL (issue #1927): `generate auth` on a `SQLite` app now
    /// scaffolds its migrations in `SQLite` dialect (`INTEGER PRIMARY KEY
    /// AUTOINCREMENT`, `DEFAULT CURRENT_TIMESTAMP`) instead of being rejected —
    /// covering the users table AND the DB-backed sessions table (issue #1908) —
    /// and no Postgres-only `BIGSERIAL` / `BIGINT` / `NOW()` leaks into the
    /// `SQLite` migration.
    #[test]
    fn plan_auth_emits_sqlite_ddl_including_sessions() {
        let tmp = project_with_main();
        fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nprimary_url = \"sqlite://app.db\"\n",
        )
        .unwrap();
        // `--totp`/`--magic-link` cover the recovery-code + magic-link-token
        // tables too, so every hand-written auth DDL string is exercised.
        plan_auth_full_ex2(
            tmp.path(),
            "User",
            "20260508000000",
            &AuthOAuthOptions {
                providers: Vec::new(),
            },
            true,  // totp
            false, // passkeys
            true,  // magic_link
        )
        .expect("generate auth must scaffold on a SQLite app")
        .execute(Flags::default())
        .unwrap();
        assert!(tmp.path().join("src/models/user.rs").exists());

        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/up.sql"),
        )
        .unwrap();
        // Every auto-increment id uses the SQLite spelling.
        assert!(
            up.contains("id INTEGER PRIMARY KEY AUTOINCREMENT"),
            "SQLite up.sql must use INTEGER PRIMARY KEY AUTOINCREMENT: {up}"
        );
        // The DB-backed sessions table (#1908) is created in SQLite dialect.
        assert!(
            up.contains("CREATE TABLE user_sessions (")
                && up.contains("last_seen_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP"),
            "user_sessions must be SQLite-dialect: {up}"
        );
        // The recovery-code (--totp) and magic-link (--magic-link) tables too.
        assert!(
            up.contains("CREATE TABLE recovery_codes (")
                && up.contains("CREATE TABLE magic_link_tokens ("),
            "totp + magic-link tables must be scaffolded: {up}"
        );
        // Foreign keys and timestamp columns are SQLite-typed.
        assert!(
            up.contains("user_id INTEGER NOT NULL REFERENCES users(id)"),
            "FK columns must be INTEGER on SQLite: {up}"
        );
        assert!(
            up.contains("created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP"),
            "created_at must default to CURRENT_TIMESTAMP on SQLite: {up}"
        );
        for leak in ["BIGSERIAL", "BIGINT", "NOW()"] {
            assert!(
                !up.contains(leak),
                "SQLite up.sql leaked Postgres-only `{leak}`: {up}"
            );
        }
    }

    /// Collect every generated `.rs` file under `root`, recursively.
    fn generated_rust_files(root: &Path) -> Vec<(std::path::PathBuf, String)> {
        let mut out = Vec::new();
        let mut stack = vec![root.to_path_buf()];
        while let Some(dir) = stack.pop() {
            for entry in fs::read_dir(&dir).unwrap().flatten() {
                let path = entry.path();
                if path.is_dir() {
                    stack.push(path);
                } else if path.extension().is_some_and(|e| e == "rs") {
                    out.push((path.clone(), fs::read_to_string(&path).unwrap()));
                }
            }
        }
        out
    }

    /// Scaffold the full auth surface into a project whose configured backend
    /// is `url`, and return every generated `.rs` file.
    fn auth_scaffold_rust_files(url: &str) -> Vec<(std::path::PathBuf, String)> {
        let tmp = project_with_main();
        fs::write(
            tmp.path().join("autumn.toml"),
            format!("[database]\nprimary_url = \"{url}\"\n"),
        )
        .unwrap();
        plan_auth_full_ex2(
            tmp.path(),
            "User",
            "20260508000000",
            &AuthOAuthOptions {
                providers: Vec::new(),
            },
            true, // totp
            true, // passkeys
            true, // magic_link
        )
        .expect("generate auth must scaffold")
        .execute(Flags::default())
        .unwrap();
        generated_rust_files(&tmp.path().join("src"))
    }

    /// DB-backed sessions store on `SQLite` (issue #1908): the generated
    /// session/remember store must bound its connections by the backend-agnostic
    /// `::autumn_web::RuntimeBackend` alias, never a hard-coded `diesel::pg::Pg`.
    /// A `pg::Pg` bound does not accept the `SQLite` `RuntimeConnection`, so the
    /// scaffolded app would not compile on a `SQLite` target.
    #[test]
    fn auth_store_connection_bounds_are_backend_agnostic() {
        for url in ["sqlite://app.db", "postgres://localhost/app"] {
            let files = auth_scaffold_rust_files(url);
            for (path, body) in &files {
                // The whole path, not just the connection bound: a regression
                // could reintroduce Postgres as `SelectableHelper<diesel::pg::Pg>`
                // or `check_for_backend(diesel::pg::Pg)`. The auth surface emits
                // no legitimate `Pg` reference, so absence is the right bar.
                assert!(
                    !body.contains("diesel::pg::Pg"),
                    "{} hard-codes the Postgres backend ({url})",
                    path.display()
                );
            }
            let session_model = files
                .iter()
                .find(|(p, _)| p.ends_with("user_session.rs"))
                .expect("the sessions store model must be generated");
            assert!(
                session_model
                    .1
                    .contains("Backend = ::autumn_web::RuntimeBackend"),
                "the sessions store must bind RuntimeBackend ({url}): {}",
                session_model.1
            );
        }
    }

    /// The scaffolded session-management guide hands the operator SQL for the
    /// sessions table. It must be in the app's own dialect (issue #1908):
    /// Postgres keeps `NOW() - INTERVAL`, `SQLite` gets `datetime('now', …)`.
    #[test]
    fn sessions_doc_sql_matches_the_app_backend() {
        let pg = render_sessions_docs_file(
            autumn_web::config::DatabaseBackend::Postgres,
            "User",
            "user",
            "users",
        );
        assert!(
            pg.contains("last_seen_at < NOW() - INTERVAL '90 days'"),
            "Postgres retention SQL must be unchanged: {pg}"
        );
        assert!(
            pg.contains("id BIGSERIAL PRIMARY KEY")
                && pg.contains("last_seen_at TIMESTAMP NOT NULL DEFAULT NOW()"),
            "Postgres migration-path DDL must be unchanged: {pg}"
        );

        let sqlite = render_sessions_docs_file(
            autumn_web::config::DatabaseBackend::Sqlite,
            "User",
            "user",
            "users",
        );
        assert!(
            sqlite.contains("last_seen_at < datetime('now', '-90 days')"),
            "SQLite retention SQL must use datetime(): {sqlite}"
        );
        assert!(
            sqlite.contains("id INTEGER PRIMARY KEY AUTOINCREMENT")
                && sqlite.contains("last_seen_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP")
                && sqlite.contains("user_id INTEGER NOT NULL REFERENCES users(id)"),
            "SQLite migration-path DDL must be SQLite dialect: {sqlite}"
        );
        for leak in ["BIGSERIAL", "BIGINT", "NOW()"] {
            assert!(
                !sqlite.contains(leak),
                "SQLite sessions guide leaked Postgres-only `{leak}`: {sqlite}"
            );
        }
    }

    /// Regression guard: on a Postgres app (the default) the auth migration
    /// stays byte-for-byte the historical Postgres DDL.
    #[test]
    fn plan_auth_emits_postgres_ddl_by_default() {
        let tmp = project_with_main();
        fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nprimary_url = \"postgres://localhost/app\"\n",
        )
        .unwrap();
        plan_auth(tmp.path(), "User", "20260508000000")
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/up.sql"),
        )
        .unwrap();
        assert!(
            up.contains("id BIGSERIAL PRIMARY KEY"),
            "Postgres up.sql must keep BIGSERIAL PRIMARY KEY: {up}"
        );
        assert!(
            up.contains("CREATE TABLE user_sessions (")
                && up.contains("last_seen_at TIMESTAMP NOT NULL DEFAULT NOW()"),
            "Postgres user_sessions must keep TIMESTAMP DEFAULT NOW(): {up}"
        );
        assert!(
            up.contains("user_id BIGINT NOT NULL REFERENCES users(id)"),
            "Postgres FK columns must stay BIGINT: {up}"
        );
    }

    /// DB-backed sessions store on `SQLite` (issue #1908): the generated
    /// `routes/auth.rs` types its connection pools against the backend-agnostic
    /// `::autumn_web::RuntimeConnection` alias (which resolves to `AsyncPgConnection`
    /// on Postgres and the `SQLite` connection under the `sqlite` feature), never a
    /// hard-coded `diesel_async::AsyncPgConnection`, so the generated app compiles
    /// on whichever backend it selected.
    #[test]
    fn generated_session_pool_uses_runtime_connection_not_pg() {
        // magic-link on/off both emit the remember-me middleware pool sites.
        for magic_link in [false, true] {
            let routes = render_routes_file("User", "user", "users", &[], false, magic_link);
            assert!(
                routes.contains("deadpool::Pool<::autumn_web::RuntimeConnection>"),
                "session pool must be typed against RuntimeConnection (magic_link={magic_link}): {routes}"
            );
            assert!(
                !routes.contains("Pool<diesel_async::AsyncPgConnection>"),
                "session pool must not hard-code AsyncPgConnection (magic_link={magic_link})"
            );
        }
    }

    /// The `--oauth` (`oauth_identities`) and `--passkeys`
    /// (`webauthn_credentials`) migrations are backend-aware too (issue #1927):
    /// `SQLite` dialect on a `SQLite` app, historical Postgres DDL otherwise.
    #[test]
    fn oauth_and_passkey_migrations_are_backend_aware() {
        use autumn_web::config::DatabaseBackend;

        for (render, table) in [
            (
                render_oauth_migration_up as fn(DatabaseBackend, &str) -> String,
                "oauth_identities",
            ),
            (render_passkey_migration_up, "webauthn_credentials"),
        ] {
            let sqlite = render(DatabaseBackend::Sqlite, "users");
            assert!(
                sqlite.contains("id INTEGER PRIMARY KEY AUTOINCREMENT")
                    && sqlite.contains("user_id INTEGER NOT NULL REFERENCES users(id)")
                    && sqlite.contains("created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP"),
                "{table} SQLite DDL must use SQLite dialect: {sqlite}"
            );
            for leak in ["BIGSERIAL", "BIGINT", "NOW()"] {
                assert!(
                    !sqlite.contains(leak),
                    "{table} SQLite DDL leaked `{leak}`: {sqlite}"
                );
            }
            let pg = render(DatabaseBackend::Postgres, "users");
            assert!(
                pg.contains("id BIGSERIAL PRIMARY KEY")
                    && pg.contains("user_id BIGINT NOT NULL REFERENCES users(id)")
                    && pg.contains("created_at TIMESTAMP NOT NULL DEFAULT NOW()"),
                "{table} Postgres DDL must stay historical: {pg}"
            );
        }
    }

    /// The scaffolded OAuth guide documents the schema of the migration the same
    /// run writes, so it must be in the same dialect (issue #1908) — the drift
    /// `render_sessions_table_ddl` removed for the sessions guide.
    #[test]
    fn oauth_doc_schema_matches_the_app_backend() {
        use autumn_web::config::DatabaseBackend;

        let providers = vec!["github".to_owned()];

        let pg = render_oauth_docs_file(DatabaseBackend::Postgres, &providers, "users");
        assert!(
            pg.contains("id         BIGSERIAL PRIMARY KEY,")
                && pg
                    .contains("user_id    BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,")
                && pg.contains("created_at TIMESTAMP NOT NULL DEFAULT NOW(),"),
            "the Postgres OAuth guide must be unchanged: {pg}"
        );

        let sqlite = render_oauth_docs_file(DatabaseBackend::Sqlite, &providers, "users");
        assert!(
            sqlite.contains("id         INTEGER PRIMARY KEY AUTOINCREMENT,")
                && sqlite.contains(
                    "user_id    INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,"
                )
                && sqlite.contains("created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,"),
            "the SQLite OAuth guide must be SQLite dialect: {sqlite}"
        );
        for leak in ["BIGSERIAL", "BIGINT", "NOW()"] {
            assert!(
                !sqlite.contains(leak),
                "the SQLite OAuth guide leaked Postgres-only `{leak}`: {sqlite}"
            );
        }
    }

    /// A Postgres app (the default) is not rejected — `generate auth` still
    /// plans its files.
    #[test]
    fn plan_auth_not_rejected_on_postgres_app() {
        let tmp = project_with_main();
        fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nprimary_url = \"postgres://localhost/app\"\n",
        )
        .unwrap();
        assert!(plan_auth(tmp.path(), "User", "20260508000000").is_ok());
    }

    /// `autumn destroy auth` recomputes this same plan via the `for_revert`
    /// builder before [`Plan::revert`], so it must build a revert plan on a
    /// `SQLite` app (the `for_revert` flag still suppresses the generate-only
    /// shared-layout preflight — issue #1927 made the migrations `SQLite`-valid, so
    /// generate no longer rejects, but the preflight-suppression path must stay
    /// exercised).
    #[test]
    fn plan_auth_for_revert_not_rejected_on_sqlite_app() {
        let tmp = project_with_main();
        fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nprimary_url = \"sqlite://app.db\"\n",
        )
        .unwrap();
        let oauth = AuthOAuthOptions {
            providers: Vec::new(),
        };
        // The destroy/revert plan builder must still produce a plan to revert.
        assert!(
            plan_auth_full_ex2_for_revert(
                tmp.path(),
                "User",
                "20260508000000",
                &oauth,
                false,
                false,
                false,
            )
            .is_ok(),
            "destroy auth must build its revert plan on a SQLite app"
        );
    }

    #[test]
    fn generate_then_destroy_base_auth_round_trips_to_original_project_state() {
        let tmp = project_with_main();
        let cargo_path = tmp.path().join("Cargo.toml");
        fs::write(&cargo_path, template_shipped_cargo_toml()).unwrap();
        let main_path = tmp.path().join("src/main.rs");
        let original_cargo = fs::read_to_string(&cargo_path).unwrap();
        let original_main = fs::read_to_string(&main_path).unwrap();

        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        assert!(tmp.path().join("src/models/user.rs").exists());
        assert!(
            fs::read_to_string(&main_path)
                .unwrap()
                .contains("routes::auth::signup")
        );
        assert!(fs::read_to_string(&cargo_path).unwrap().contains("axum"));

        let destroy_plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        destroy_plan.revert(Flags::default()).unwrap();

        assert!(!tmp.path().join("src/models").exists());
        assert!(!tmp.path().join("src/routes").exists());
        assert!(!tmp.path().join("src/schema.rs").exists());
        assert!(!tmp.path().join("tests/auth.rs").exists());
        assert!(!tmp.path().join("tests/auth_sessions.rs").exists());
        assert!(!tmp.path().join("docs/guide/authentication.md").exists());
        assert!(!tmp.path().join("migrations").exists());
        assert_eq!(fs::read_to_string(&main_path).unwrap(), original_main);
        assert_eq!(fs::read_to_string(&cargo_path).unwrap(), original_cargo);
    }

    #[test]
    fn generate_then_destroy_auth_with_totp_round_trips_to_original_project_state() {
        let tmp = project_with_main();
        let cargo_path = tmp.path().join("Cargo.toml");
        fs::write(&cargo_path, template_shipped_cargo_toml()).unwrap();
        let main_path = tmp.path().join("src/main.rs");
        let original_cargo = fs::read_to_string(&cargo_path).unwrap();
        let original_main = fs::read_to_string(&main_path).unwrap();

        let plan =
            plan_auth_with_providers(tmp.path(), "User", "20260508000000", &[], true).unwrap();
        plan.execute(Flags::default()).unwrap();
        assert!(tmp.path().join("src/models/recovery_code.rs").exists());
        assert!(tmp.path().join("tests/auth_2fa.rs").exists());
        assert!(fs::read_to_string(&cargo_path).unwrap().contains("totp-rs"));
        assert!(
            fs::read_to_string(tmp.path().join("src/schema.rs"))
                .unwrap()
                .contains("recovery_codes")
        );

        let destroy_plan =
            plan_auth_with_providers(tmp.path(), "User", "20260508000000", &[], true).unwrap();
        destroy_plan.revert(Flags::default()).unwrap();

        assert!(!tmp.path().join("src/models").exists());
        assert!(!tmp.path().join("src/routes").exists());
        assert!(!tmp.path().join("src/schema.rs").exists());
        assert!(!tmp.path().join("tests/auth_2fa.rs").exists());
        assert!(!tmp.path().join("migrations").exists());
        assert_eq!(fs::read_to_string(&main_path).unwrap(), original_main);
        assert_eq!(fs::read_to_string(&cargo_path).unwrap(), original_cargo);
    }

    #[test]
    fn generate_then_destroy_auth_with_oauth_round_trips_to_original_project_state() {
        let tmp = project_with_main();
        let cargo_path = tmp.path().join("Cargo.toml");
        fs::write(&cargo_path, template_shipped_cargo_toml()).unwrap();
        let main_path = tmp.path().join("src/main.rs");
        let autumn_toml_path = tmp.path().join("autumn.toml");
        fs::write(&autumn_toml_path, "[server]\nport = 3000\n").unwrap();
        let original_cargo = fs::read_to_string(&cargo_path).unwrap();
        let original_main = fs::read_to_string(&main_path).unwrap();
        let original_toml = fs::read_to_string(&autumn_toml_path).unwrap();

        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned(), "google".to_owned()],
        };
        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        plan.execute(Flags::default()).unwrap();
        assert!(tmp.path().join("src/routes/oauth.rs").exists());
        assert!(
            fs::read_to_string(&autumn_toml_path)
                .unwrap()
                .contains("[auth.oauth2.github]")
        );
        assert!(fs::read_to_string(&cargo_path).unwrap().contains("oauth2"));
        assert!(
            fs::read_to_string(tmp.path().join("src/schema.rs"))
                .unwrap()
                .contains("oauth_identities")
        );

        let destroy_plan =
            plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        destroy_plan.revert(Flags::default()).unwrap();

        assert!(!tmp.path().join("src/models").exists());
        assert!(!tmp.path().join("src/routes").exists());
        assert!(!tmp.path().join("src/schema.rs").exists());
        assert!(!tmp.path().join("docs/guide/oauth.md").exists());
        assert!(!tmp.path().join("migrations").exists());
        assert_eq!(fs::read_to_string(&main_path).unwrap(), original_main);
        assert_eq!(fs::read_to_string(&cargo_path).unwrap(), original_cargo);
        assert_eq!(
            fs::read_to_string(&autumn_toml_path).unwrap(),
            original_toml
        );
    }

    #[test]
    fn destroy_never_removes_a_pre_existing_oauth_provider_block_with_real_credentials() {
        let tmp = project_with_main();
        fs::write(tmp.path().join("Cargo.toml"), template_shipped_cargo_toml()).unwrap();
        let autumn_toml_path = tmp.path().join("autumn.toml");
        let real_github_block = "[server]\nport = 3000\n\n[auth.oauth2.github]\n\
             client_id = \"real-client-id\"\n\
             client_secret = \"real-client-secret\"\n\
             authorize_url = \"https://github.com/login/oauth/authorize\"\n\
             token_url = \"https://github.com/login/oauth/access_token\"\n\
             userinfo_url = \"https://api.github.com/user\"\n\
             redirect_uri = \"https://myapp.example.com/auth/github/callback\"\n\
             scope = \"read:user user:email\"\n";
        fs::write(&autumn_toml_path, real_github_block).unwrap();

        // `--oauth github,google`: github's block already exists (with real
        // credentials) so `append_oauth_stubs_to_toml` leaves it untouched;
        // only google's stub is freshly inserted.
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned(), "google".to_owned()],
        };
        plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(
            fs::read_to_string(&autumn_toml_path)
                .unwrap()
                .contains("real-client-secret")
        );

        plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth)
            .unwrap()
            .revert(Flags::default())
            .unwrap();

        let toml_after = fs::read_to_string(&autumn_toml_path).unwrap();
        assert!(
            toml_after.contains("[auth.oauth2.github]"),
            "pre-existing github block must survive destroy: {toml_after}"
        );
        assert!(
            toml_after.contains("real-client-secret"),
            "real credentials must never be deleted: {toml_after}"
        );
        assert!(
            !toml_after.contains("[auth.oauth2.google]"),
            "google's freshly-inserted stub must still be removed: {toml_after}"
        );
    }

    #[test]
    fn generate_then_destroy_auth_with_passkeys_round_trips_to_original_project_state() {
        let tmp = project_with_main();
        let cargo_path = tmp.path().join("Cargo.toml");
        fs::write(&cargo_path, template_shipped_cargo_toml()).unwrap();
        let main_path = tmp.path().join("src/main.rs");
        let autumn_toml_path = tmp.path().join("autumn.toml");
        fs::write(&autumn_toml_path, "[server]\nport = 3000\n").unwrap();
        let original_cargo = fs::read_to_string(&cargo_path).unwrap();
        let original_main = fs::read_to_string(&main_path).unwrap();
        let original_toml = fs::read_to_string(&autumn_toml_path).unwrap();

        let plan = plan_auth_full_ex(
            tmp.path(),
            "User",
            "20260508000000",
            &AuthOAuthOptions::default(),
            false,
            true,
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        assert!(tmp.path().join("src/routes/passkeys.rs").exists());
        assert!(
            fs::read_to_string(&autumn_toml_path)
                .unwrap()
                .contains("[auth.webauthn]")
        );
        assert!(
            fs::read_to_string(&cargo_path)
                .unwrap()
                .contains("webauthn-rs")
        );
        assert!(
            fs::read_to_string(tmp.path().join("src/schema.rs"))
                .unwrap()
                .contains("webauthn_credentials")
        );

        let destroy_plan = plan_auth_full_ex(
            tmp.path(),
            "User",
            "20260508000000",
            &AuthOAuthOptions::default(),
            false,
            true,
        )
        .unwrap();
        destroy_plan.revert(Flags::default()).unwrap();

        assert!(!tmp.path().join("src/models").exists());
        assert!(!tmp.path().join("src/routes").exists());
        assert!(!tmp.path().join("src/schema.rs").exists());
        assert!(!tmp.path().join("tests/auth_passkeys.rs").exists());
        assert!(!tmp.path().join("docs/guide/passkeys.md").exists());
        assert!(!tmp.path().join("migrations").exists());
        assert_eq!(fs::read_to_string(&main_path).unwrap(), original_main);
        assert_eq!(fs::read_to_string(&cargo_path).unwrap(), original_cargo);
        assert_eq!(
            fs::read_to_string(&autumn_toml_path).unwrap(),
            original_toml
        );
    }

    #[test]
    fn generate_then_destroy_auth_with_totp_oauth_and_passkeys_round_trips_to_original_project_state()
     {
        // Combines every optional flag in one plan, exercising the trickiest
        // case for the `autumn.toml` reverts: `--oauth` appends its stub
        // block first, then `--passkeys` appends `[auth.webauthn]` on top of
        // that (reading the base plan's already-updated content) — both
        // edits must unwind cleanly regardless of their relative order in
        // the file.
        let tmp = project_with_main();
        let cargo_path = tmp.path().join("Cargo.toml");
        fs::write(&cargo_path, template_shipped_cargo_toml()).unwrap();
        let main_path = tmp.path().join("src/main.rs");
        let autumn_toml_path = tmp.path().join("autumn.toml");
        fs::write(&autumn_toml_path, "[server]\nport = 3000\n").unwrap();
        let original_cargo = fs::read_to_string(&cargo_path).unwrap();
        let original_main = fs::read_to_string(&main_path).unwrap();
        let original_toml = fs::read_to_string(&autumn_toml_path).unwrap();

        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        let plan =
            plan_auth_full_ex(tmp.path(), "User", "20260508000000", &oauth, true, true).unwrap();
        plan.execute(Flags::default()).unwrap();
        let toml_after_generate = fs::read_to_string(&autumn_toml_path).unwrap();
        assert!(toml_after_generate.contains("[auth.oauth2.github]"));
        assert!(toml_after_generate.contains("[auth.webauthn]"));

        let destroy_plan =
            plan_auth_full_ex(tmp.path(), "User", "20260508000000", &oauth, true, true).unwrap();
        destroy_plan.revert(Flags::default()).unwrap();

        assert!(!tmp.path().join("src/models").exists());
        assert!(!tmp.path().join("src/routes").exists());
        assert!(!tmp.path().join("src/schema.rs").exists());
        assert!(!tmp.path().join("migrations").exists());
        assert_eq!(fs::read_to_string(&main_path).unwrap(), original_main);
        assert_eq!(fs::read_to_string(&cargo_path).unwrap(), original_cargo);
        assert_eq!(
            fs::read_to_string(&autumn_toml_path).unwrap(),
            original_toml
        );
    }

    // ── Magic-link login (issue #1328) ───────────────────────────────────────

    /// Build a `--magic-link` plan (no oauth/totp/passkeys) over a fresh project.
    fn magic_link_plan(path: &std::path::Path) -> Plan {
        plan_auth_full_ex2(
            path,
            "User",
            "20260508000000",
            &AuthOAuthOptions::default(),
            false,
            false,
            true,
        )
        .unwrap()
    }

    /// Execute a `--magic-link` plan and return the generated `routes/auth.rs`.
    fn magic_link_routes(path: &std::path::Path) -> String {
        magic_link_plan(path).execute(Flags::default()).unwrap();
        fs::read_to_string(path.join("src/routes/auth.rs")).unwrap()
    }

    #[test]
    fn magic_link_emits_request_email_verify_routes() {
        let tmp = project_with_main();
        let routes = magic_link_routes(tmp.path());
        assert!(
            routes.contains("#[get(\"/login/magic\")]"),
            "must emit GET /login/magic request form: {routes}"
        );
        assert!(
            routes.contains("#[post(\"/login/magic\")]"),
            "must emit POST /login/magic request endpoint"
        );
        assert!(
            routes.contains("#[get(\"/login/magic/verify\")]"),
            "must emit GET /login/magic/verify endpoint (renders confirm page)"
        );
        assert!(
            routes.contains("#[post(\"/login/magic/verify\")]"),
            "must emit POST /login/magic/verify endpoint (consumes token)"
        );
    }

    #[test]
    fn magic_link_verify_get_renders_confirm_without_consuming() {
        // Scanner-safety: the GET verify handler renders a "Confirm sign-in" page
        // and must NOT consume the token or establish a session. Consumption +
        // login lives entirely in the POST handler.
        let tmp = project_with_main();
        let routes = magic_link_routes(tmp.path());

        // GET handler body: from its signature up to the POST consume handler.
        let get_start = routes
            .find("pub async fn magic_link_verify_form(")
            .expect("GET confirm handler present");
        let get_end = routes[get_start..]
            .find("pub async fn magic_link_verify(")
            .map(|o| get_start + o)
            .expect("POST verify handler follows the GET form");
        let get_body = &routes[get_start..get_end];
        assert!(
            !get_body.contains("magic_link_tokens::consumed_at.eq(Some(now))"),
            "GET verify must NOT consume the token: {get_body}"
        );
        assert!(
            !get_body.contains("session.insert(state.auth_session_key()"),
            "GET verify must NOT establish an authenticated session: {get_body}"
        );
        // It renders a POST-back confirmation form carrying the token.
        assert!(
            get_body.contains("form action=\"/login/magic/verify\" method=\"post\"")
                && get_body.contains("name=\"token\" value=(query.token)"),
            "GET verify must render a form that POSTs the token back: {get_body}"
        );

        // POST handler body: it DOES consume + establish the session.
        let post_body = magic_link_verify_body(&routes);
        assert!(
            post_body.contains("magic_link_tokens::consumed_at.eq(Some(now))"),
            "POST verify must consume the token: {post_body}"
        );
        assert!(
            post_body.contains("session.insert(state.auth_session_key()"),
            "POST verify must establish an authenticated session: {post_body}"
        );
        // The POST consume route is per-IP throttled to bound token brute-forcing.
        let post_attr = routes
            .find("#[post(\"/login/magic/verify\")]")
            .expect("POST verify attr present");
        let after = &routes[post_attr..];
        let throttle_rel = after
            .find("#[throttle(")
            .expect("POST verify throttle attr present");
        let handler_rel = after
            .find("pub async fn magic_link_verify(")
            .expect("POST verify handler present");
        assert!(
            throttle_rel < handler_rel && after[..handler_rel].contains("key = \"ip\""),
            "POST verify must carry a per-IP #[throttle] between the method attr and handler: {after}"
        );
    }

    #[test]
    fn magic_link_post_route_is_throttled_per_ip() {
        let tmp = project_with_main();
        let routes = magic_link_routes(tmp.path());
        // Method attribute outermost, #[throttle] inner, per the macro contract.
        let post_pos = routes
            .find("#[post(\"/login/magic\")]")
            .expect("post attr present");
        let after = &routes[post_pos..];
        let throttle_rel = after.find("#[throttle(").expect("throttle attr present");
        let handler_rel = after
            .find("pub async fn magic_link_request(")
            .expect("handler present");
        assert!(
            throttle_rel < handler_rel,
            "#[throttle] must sit between #[post] and the handler (method attr outermost)"
        );
        assert!(
            after[..handler_rel].contains("key = \"ip\""),
            "throttle must key on ip for per-IP rate limiting"
        );
    }

    #[test]
    fn magic_link_request_is_non_enumerating() {
        let tmp = project_with_main();
        let routes = magic_link_routes(tmp.path());
        let start = routes
            .find("pub async fn magic_link_request(")
            .expect("request handler");
        let end = routes[start..]
            .find("pub async fn magic_link_verify(")
            .map_or(routes.len(), |o| start + o);
        let body = &routes[start..end];
        // Minting only happens inside the account-exists branch.
        assert!(
            body.contains("if let Some(user)"),
            "token minting must be gated on the account existing: {body}"
        );
        // The final response is the same shared page regardless of existence.
        assert!(
            body.contains("If that address is registered"),
            "must render the same non-enumerating check-your-email response: {body}"
        );
        // Constant-time padding so hit/miss are latency-indistinguishable.
        assert!(
            body.contains("tokio::time::sleep"),
            "request handler must pad response time to avoid a timing oracle"
        );
    }

    #[test]
    fn magic_link_stores_only_token_digest() {
        let tmp = project_with_main();
        let routes = magic_link_routes(tmp.path());
        assert!(
            routes.contains("let token_digest = sha256_hex(&raw_token);"),
            "only the SHA-256 digest of the raw token may be stored"
        );
        // The migration stores a digest column, never a raw-token column.
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/up.sql"),
        )
        .unwrap();
        assert!(
            up.contains("token_digest TEXT NOT NULL UNIQUE"),
            "magic_link_tokens must persist a unique token_digest: {up}"
        );
        assert!(
            !up.contains("raw_token"),
            "the raw token must never be a persisted column"
        );
    }

    #[test]
    fn magic_link_verify_does_not_stamp_step_up() {
        let tmp = project_with_main();
        let routes = magic_link_routes(tmp.path());
        let start = routes
            .find("pub async fn magic_link_verify(")
            .expect("verify handler");
        let end = routes[start..]
            .find("async fn send_magic_link_email(")
            .map(|o| start + o)
            .expect("mailer helper follows verify");
        let body = &routes[start..end];
        // The explanatory comment mentions the name, so assert on the actual
        // CALL form (with the `step_up::` path + open paren), not the bare name.
        assert!(
            !body.contains("step_up::set_last_strong_auth_at("),
            "magic-link verify must NOT stamp step-up (proves email possession, \
             not password knowledge): {body}"
        );
    }

    #[test]
    fn magic_link_verify_rotates_session_before_auth() {
        let tmp = project_with_main();
        let routes = magic_link_routes(tmp.path());
        let start = routes
            .find("pub async fn magic_link_verify(")
            .expect("verify handler");
        let end = routes[start..]
            .find("async fn send_magic_link_email(")
            .map(|o| start + o)
            .expect("mailer helper follows verify");
        let body = &routes[start..end];
        let rotate = body
            .find("session.rotate_id().await")
            .expect("rotate present");
        let auth_insert = body
            .find("session.insert(state.auth_session_key()")
            .expect("auth key insert present");
        assert!(
            rotate < auth_insert,
            "session must be rotated BEFORE the authenticated session id is set \
             (session-fixation defense)"
        );
    }

    #[test]
    fn magic_link_verify_is_single_use_and_generic_failure() {
        let tmp = project_with_main();
        let routes = magic_link_routes(tmp.path());
        // Atomic consume: stamp consumed_at while filtering unconsumed + unexpired.
        assert!(
            routes.contains("magic_link_tokens::consumed_at.is_null()")
                && routes.contains("magic_link_tokens::consumed_at.eq(Some(now))"),
            "verify must atomically consume the token (single-use)"
        );
        // Expired/consumed/unknown all funnel to one generic failure page.
        assert!(
            routes.contains("fn magic_link_invalid_page()"),
            "a single generic failure page must exist (no oracle)"
        );
    }

    #[test]
    fn magic_link_verify_accepts_query_token() {
        let tmp = project_with_main();
        let routes = magic_link_routes(tmp.path());
        assert!(
            routes.contains("pub struct MagicLinkVerifyQuery")
                && routes.contains("Query(query): Query<MagicLinkVerifyQuery>"),
            "verify must read the token from the ?token= query parameter (AC4)"
        );
    }

    /// Extract just the `magic_link_verify` handler body from a rendered routes
    /// file (from the handler signature up to the mailer helper that follows it).
    fn magic_link_verify_body(routes: &str) -> &str {
        let start = routes
            .find("pub async fn magic_link_verify(")
            .expect("verify handler");
        let end = routes[start..]
            .find("async fn send_magic_link_email(")
            .map(|o| start + o)
            .expect("mailer helper follows verify");
        &routes[start..end]
    }

    #[test]
    fn magic_link_verify_honors_totp_second_factor() {
        // With `--magic-link --totp`, a 2FA-enrolled account must be parked and
        // redirected to /login/verify — NOT straight-logged-in (Fix 1).
        let routes = render_routes_file("User", "user", "users", &[], true, true);
        let body = magic_link_verify_body(&routes);
        assert!(
            body.contains("if user.totp_enabled {"),
            "verify must branch on totp_enabled under --totp: {body}"
        );
        assert!(
            body.contains(".insert(\"totp_pending_id\""),
            "must set the totp_pending_id marker for the interstitial: {body}"
        );
        // Mirror confirm_email: mark the pending login confirmation-origin so
        // login_verify skips the strong-auth stamp (email + TOTP ≠ password).
        assert!(
            body.contains("session.insert(\"totp_pending_confirmation\", \"1\")"),
            "must mark the pending login as confirmation-origin: {body}"
        );
        assert!(
            body.contains("return Ok(redirect_to(\"/login/verify\"));"),
            "a 2FA account must be redirected to /login/verify, not logged in: {body}"
        );
        // The direct auth-session insert must sit AFTER the 2FA early-return, so a
        // TOTP-enrolled user is never logged in without the second factor.
        let pending_return = body
            .find("return Ok(redirect_to(\"/login/verify\"));")
            .expect("2FA early-return present");
        let auth_insert = body
            .find("session.insert(state.auth_session_key()")
            .expect("direct auth-session insert present");
        assert!(
            pending_return < auth_insert,
            "the direct auth-session insert must be gated behind the 2FA early-return: {body}"
        );
    }

    #[test]
    fn magic_link_verify_rechecks_account_lock() {
        // #1777: the POST verify handler must re-check `locked_at` AFTER the
        // atomic token consume and BEFORE establishing the session, so a link
        // minted before a lockout cannot complete a login after it. Non-totp
        // variant. Mirrors the password-login success-path guard.
        let routes = render_routes_file("User", "user", "users", &[], false, true);
        let body = magic_link_verify_body(&routes);
        // Reads the same [auth.lockout] config the password-login path uses.
        assert!(
            body.contains("let lockout_cfg = &config.auth.lockout;")
                && body.contains("let config = state.config_arc();"),
            "verify must read [auth.lockout] through the shared config handle: {body}"
        );
        // TOCTOU-safe: the recheck must NOT trust the stale in-memory `user` row
        // SELECTed earlier — it must re-read `locked_at` at the DB. The stale
        // in-memory check (`if let Some(locked_at) = user.locked_at`) is gone.
        assert!(
            !body.contains("if let Some(locked_at) = user.locked_at {"),
            "verify must NOT gate on the stale in-memory user.locked_at row \
             (TOCTOU race): {body}"
        );
        // Fresh DB read: a guarded UPDATE predicated on `locked_at` re-reads the
        // current lock state, clearing an expired lock and rejecting an active one
        // — the same guard the password success path uses right before the session.
        assert!(
            body.contains("let rows_cleared = diesel::update(")
                && body.contains("users::locked_at.is_null().or(")
                && body.contains("users::locked_at.le(lock_expired_before)")
                && body.contains("users::failed_attempts.eq(0),")
                && body.contains("if rows_cleared == 0 {"),
            "verify must re-read locked_at at the DB via a guarded UPDATE (mirrors \
             password login), not the stale in-memory row: {body}"
        );
        // Ordering: guard sits AFTER the atomic consume and BEFORE the auth insert.
        let consume = body
            .find("magic_link_tokens::consumed_at.eq(Some(now))")
            .expect("token consume present");
        let recheck = body
            .find("let rows_cleared = diesel::update(")
            .expect("lock recheck present");
        let auth_insert = body
            .find("session.insert(state.auth_session_key()")
            .expect("auth insert present");
        assert!(
            consume < recheck && recheck < auth_insert,
            "lock recheck must be AFTER the token consume and BEFORE the session is \
             established: {body}"
        );
    }

    #[test]
    fn magic_link_verify_rechecks_account_lock_with_totp() {
        // #1777: the same fresh-DB lock recheck must be present in the
        // `--magic-link --totp` variant, and must gate BOTH the 2FA park and the
        // direct login (it sits before the /login/verify early-return).
        let routes = render_routes_file("User", "user", "users", &[], true, true);
        let body = magic_link_verify_body(&routes);
        assert!(
            body.contains("let lockout_cfg = &config.auth.lockout;")
                && body.contains("let config = state.config_arc();"),
            "totp variant must read [auth.lockout] through the shared config handle: {body}"
        );
        assert!(
            !body.contains("if let Some(locked_at) = user.locked_at {"),
            "totp variant must NOT gate on the stale in-memory user.locked_at row \
             (TOCTOU race): {body}"
        );
        assert!(
            body.contains("let rows_cleared = diesel::update(")
                && body.contains("users::locked_at.is_null().or(")
                && body.contains("users::locked_at.le(lock_expired_before)")
                && body.contains("if rows_cleared == 0 {"),
            "totp variant must re-read locked_at at the DB via a guarded UPDATE: {body}"
        );
        let consume = body
            .find("magic_link_tokens::consumed_at.eq(Some(now))")
            .expect("token consume present");
        let recheck = body
            .find("let rows_cleared = diesel::update(")
            .expect("lock recheck present");
        let pending_return = body
            .find("return Ok(redirect_to(\"/login/verify\"));")
            .expect("2FA early-return present");
        assert!(
            consume < recheck && recheck < pending_return,
            "lock recheck must sit after the consume and before the 2FA park/redirect: {body}"
        );
    }

    #[test]
    fn magic_link_verify_locked_account_uses_generic_failure_page() {
        // #1777 (no oracle): a locked account must be indistinguishable from a
        // bad/expired/consumed token — both render magic_link_invalid_page().
        for (totp, label) in [(false, "--magic-link"), (true, "--magic-link --totp")] {
            let routes = render_routes_file("User", "user", "users", &[], totp, true);
            let body = magic_link_verify_body(&routes);
            // The token-failure path already returns the generic page.
            assert!(
                body.contains("Err(_) => return Ok(magic_link_invalid_page().into_response())"),
                "{label}: token-failure path must render the generic page: {body}"
            );
            // The fresh-DB lock guard returns the SAME generic page when zero rows
            // match (account actively locked) — no distinct response, no oracle.
            let recheck = body
                .find("if rows_cleared == 0 {")
                .expect("lock recheck present");
            let tail = &body[recheck..];
            let next_brace = tail.find('}').unwrap_or(tail.len());
            let recheck_block = &tail[..next_brace];
            assert!(
                recheck_block.contains("return Ok(magic_link_invalid_page().into_response());"),
                "{label}: locked account must render the SAME generic failure page \
                 (no oracle): {body}"
            );
        }
    }

    #[test]
    fn magic_link_verify_without_totp_logs_in_directly() {
        // With `--magic-link` and no `--totp`, verify logs in directly.
        let routes = render_routes_file("User", "user", "users", &[], false, true);
        let body = magic_link_verify_body(&routes);
        assert!(
            !body.contains("totp_enabled"),
            "no totp branch may be emitted without --totp: {body}"
        );
        assert!(
            !body.contains("redirect_to(\"/login/verify\")"),
            "must not redirect to /login/verify without --totp: {body}"
        );
        assert!(
            body.contains("session.insert(state.auth_session_key()"),
            "must log in directly by inserting the auth session key: {body}"
        );
        assert!(
            body.contains("record_login_session("),
            "direct login must record the session: {body}"
        );
    }

    #[test]
    fn magic_link_verify_never_stamps_strong_auth_with_or_without_totp() {
        // In NEITHER case may magic-link verify stamp password-grade strong-auth:
        // magic-link proves email possession, not password knowledge (Fix 1).
        for totp in [false, true] {
            let routes = render_routes_file("User", "user", "users", &[], totp, true);
            let body = magic_link_verify_body(&routes);
            assert!(
                !body.contains("step_up::set_last_strong_auth_at("),
                "magic-link verify must never stamp strong-auth (totp={totp}): {body}"
            );
        }
    }

    #[test]
    fn magic_link_verify_clears_stale_totp_pending_under_totp() {
        // Direct (non-2FA) magic-link login rotates the session id, which PRESERVES
        // session data. An abandoned `totp_pending_*` / parked-reset handoff left in
        // this browser from a prior `/login/verify` would otherwise survive and could
        // be resumed under the freshly authenticated session. Mirror the
        // `totp_clear_pending` scrub password login / reset perform, BEFORE the auth
        // keys are written.
        let routes = render_routes_file("User", "user", "users", &[], true, true);
        let body = magic_link_verify_body(&routes);
        for key in [
            "session.remove(\"totp_pending_id\").await;",
            "session.remove(\"totp_pending_reset_digest\").await;",
            "session.remove(\"totp_pending_reset_token\").await;",
            "session.remove(\"totp_pending_secret\").await;",
            "session.remove(\"totp_pending_confirmation\").await;",
        ] {
            assert!(
                body.contains(key),
                "magic-link direct login must clear stale pending state ({key}): {body}"
            );
        }
        // The scrub must run BEFORE the authenticated session key is written.
        let clear = body
            .find("session.remove(\"totp_pending_id\").await;")
            .expect("pending-id scrub present");
        let auth_insert = body
            .find("session.insert(state.auth_session_key()")
            .expect("auth key insert present");
        assert!(
            clear < auth_insert,
            "pending-state cleanup must precede the auth key insert: {body}"
        );
    }

    #[test]
    fn magic_link_verify_without_totp_omits_pending_cleanup() {
        // A magic-link-only build (no --totp) must not reference the TOTP-only
        // pending session keys at all — there is no /login/verify handoff to scrub.
        let routes = render_routes_file("User", "user", "users", &[], false, true);
        let body = magic_link_verify_body(&routes);
        assert!(
            !body.contains("totp_pending"),
            "magic-link-only build must not reference TOTP pending keys: {body}"
        );
    }

    #[test]
    fn magic_link_verify_clears_reauth_pw_ok_before_parking_and_promoting() {
        // Magic-link proves EMAIL possession, not password knowledge. An
        // unfinished /reauth in this browser may have left a `reauth_pw_ok`
        // "password already verified" marker; `rotate_id()` preserves it. If it
        // survived a magic-link login, a later /reauth POST could skip the
        // password and mint a fresh step-up claim off an email-only login. Verify
        // the marker is scrubbed on BOTH the parked (TOTP) and direct paths,
        // mirroring `establish_remember_login` (issue #833/#1397).
        const REMOVE: &str = "session.remove(\"reauth_pw_ok\").await;";

        // Under --totp the marker must be dropped BEFORE the 2FA early-return
        // parks the session (which returns before the direct-path cleanup).
        let routes_totp = render_routes_file("User", "user", "users", &[], true, true);
        let body_totp = magic_link_verify_body(&routes_totp);
        assert!(
            body_totp.contains(REMOVE),
            "magic-link verify must clear reauth_pw_ok under --totp: {body_totp}"
        );
        let remove_at = body_totp
            .find(REMOVE)
            .expect("reauth_pw_ok scrub present under --totp");
        let park_return = body_totp
            .find("return Ok(redirect_to(\"/login/verify\"));")
            .expect("2FA early-return present");
        assert!(
            remove_at < park_return,
            "reauth_pw_ok must be cleared BEFORE the session is parked: {body_totp}"
        );
        let auth_insert_totp = body_totp
            .find("session.insert(state.auth_session_key()")
            .expect("direct auth-session insert present");
        assert!(
            remove_at < auth_insert_totp,
            "reauth_pw_ok must be cleared BEFORE the direct-path promotion: {body_totp}"
        );

        // Without --totp the direct path must ALSO scrub the marker before it
        // promotes the session, and use a plain string key so the magic-link-only
        // build still compiles (no TOTP-only session-key reference).
        let routes = render_routes_file("User", "user", "users", &[], false, true);
        let body = magic_link_verify_body(&routes);
        assert!(
            body.contains(REMOVE),
            "magic-link verify must clear reauth_pw_ok without --totp: {body}"
        );
        let remove_at = body.find(REMOVE).expect("reauth_pw_ok scrub present");
        let auth_insert = body
            .find("session.insert(state.auth_session_key()")
            .expect("auth key insert present");
        assert!(
            remove_at < auth_insert,
            "reauth_pw_ok must be cleared BEFORE the auth key insert: {body}"
        );
    }

    #[test]
    fn two_factor_disable_clears_magic_link_tokens_under_magic_link() {
        // Codex review: an outstanding magic-link token issued while TOTP was on is
        // gated by `magic_link_verify`'s `if user.totp_enabled` branch (routes to
        // /login/verify). Disabling TOTP flips that flag to false, so the SAME
        // still-unconsumed token would then take the DIRECT single-factor path and
        // log the account in fully. The disable transaction must therefore delete
        // the user's outstanding `magic_link_tokens` so disabling 2FA cannot
        // retroactively un-gate a previously second-factor-protected link.
        let routes = render_routes_file("User", "user", "users", &[], true, true);
        let start = routes
            .find("pub async fn two_factor_disable(")
            .expect("disable handler present");
        let end = routes[start..]
            .find("pub async fn login_verify_form(")
            .map(|o| start + o)
            .expect("login_verify_form follows disable handler");
        let body = &routes[start..end];
        assert!(
            body.contains(
                "magic_link_tokens::table.filter(magic_link_tokens::user_id.eq(user_id))"
            ),
            "disable transaction must delete the user's outstanding magic-link tokens: {body}"
        );
        // The delete must sit INSIDE the transaction (before the closing `Ok(())`),
        // so a mid-operation failure can't leave the tokens live after 2FA is off.
        let delete_at = body
            .find("magic_link_tokens::table.filter(magic_link_tokens::user_id.eq(user_id))")
            .expect("magic-link delete present");
        let txn_ok = body
            .find("            Ok(())")
            .expect("transaction Ok(()) present");
        assert!(
            delete_at < txn_ok,
            "the magic-link delete must sit inside the disable transaction: {body}"
        );
    }

    #[test]
    fn two_factor_disable_without_magic_link_omits_token_clear() {
        // A `--totp` build with no `--magic-link` has no `magic_link_tokens` table,
        // so the disable transaction must not reference it (or the crate won't
        // compile).
        let routes = render_routes_file("User", "user", "users", &[], true, false);
        let start = routes
            .find("pub async fn two_factor_disable(")
            .expect("disable handler present");
        let end = routes[start..]
            .find("pub async fn login_verify_form(")
            .map(|o| start + o)
            .expect("login_verify_form follows disable handler");
        let body = &routes[start..end];
        assert!(
            !body.contains("magic_link_tokens"),
            "a non-magic-link build must not reference magic_link_tokens in disable: {body}"
        );
    }

    #[test]
    fn magic_link_ttl_is_config_sourced_with_15_minute_default() {
        let tmp = project_with_main();
        let routes = magic_link_routes(tmp.path());
        // TTL is sourced from autumn.toml via the shared config handle, not a const.
        assert!(
            routes.contains("let ttl_minutes = config.auth.magic_link.ttl_minutes;")
                && routes.contains("let config = state.config_arc();"),
            "TTL must be sourced from auth.magic_link via config_arc: {routes}"
        );
        // The documented default (15) and the ≤ 15-minute guidance must survive
        // the move to config so operators keep the tight-window recommendation.
        assert!(
            routes.contains("ttl_minutes = 15") && routes.contains("≤ 15 min"),
            "generated docs/comments must keep the 15-minute default and ≤ 15 min guidance: {routes}"
        );
        // The per-email cooldown is likewise config-sourced.
        assert!(
            routes
                .contains("let email_cooldown_secs = config.auth.magic_link.email_cooldown_secs;"),
            "per-email cooldown must be sourced from auth.magic_link: {routes}"
        );
    }

    #[test]
    fn magic_link_config_knobs_are_unsigned_to_reject_negative_values() {
        // `MagicLinkConfig::{ttl_minutes,email_cooldown_secs}` are `u64`, so a
        // negative value in autumn.toml fails deserialization instead of
        // silently breaking the throttle/expiry. The generated code proves it
        // consumes those unsigned knobs: the chrono math casts through `as i64`
        // (a negative cooldown would push `cooldown_start` into the future and
        // defeat the per-email email-bomb throttle), and the mailer helper takes
        // an unsigned `ttl_minutes`. Assert for BOTH the --magic-link and
        // --magic-link --totp variants.
        for totp in [false, true] {
            let routes = render_routes_file("User", "user", "users", &[], totp, true);
            assert!(
                routes.contains("chrono::Duration::seconds(email_cooldown_secs as i64)"),
                "cooldown math must cast the unsigned config knob via `as i64` (totp={totp}): {routes}"
            );
            assert!(
                routes.contains("chrono::Duration::minutes(ttl_minutes as i64)"),
                "TTL math must cast the unsigned config knob via `as i64` (totp={totp}): {routes}"
            );
            assert!(
                routes.contains("ttl_minutes: u64,"),
                "send_magic_link_email must take an unsigned ttl_minutes (totp={totp}): {routes}"
            );
        }
    }

    #[test]
    fn magic_link_email_goes_through_mail_builder_without_suppression_bypass() {
        let tmp = project_with_main();
        let routes = magic_link_routes(tmp.path());
        assert!(
            routes.contains("async fn send_magic_link_email(")
                && routes.contains("Mail::builder()")
                && routes.contains("/login/magic/verify?token="),
            "the link must be sent via the Mail builder with a verify URL"
        );
        let start = routes
            .find("async fn send_magic_link_email(")
            .expect("mailer helper");
        let body = &routes[start..];
        assert!(
            !body.contains("ignore_suppression"),
            "magic-link email must inherit suppression-list gating (AC7)"
        );
    }

    #[test]
    fn magic_link_migration_creates_dedicated_table() {
        let tmp = project_with_main();
        magic_link_plan(tmp.path())
            .execute(Flags::default())
            .unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/up.sql"),
        )
        .unwrap();
        assert!(
            up.contains("CREATE TABLE magic_link_tokens"),
            "must create a dedicated magic_link_tokens table: {up}"
        );
        assert!(
            up.contains("consumed_at TIMESTAMP NULL")
                && up.contains("expires_at TIMESTAMP NOT NULL"),
            "table must carry single-use consumed_at + expiry columns"
        );
        let down = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/down.sql"),
        )
        .unwrap();
        assert!(
            down.contains("DROP TABLE magic_link_tokens;"),
            "down migration must drop the table (clean reverse): {down}"
        );
        let schema = fs::read_to_string(tmp.path().join("src/schema.rs")).unwrap();
        assert!(
            schema.contains("magic_link_tokens (id)"),
            "schema.rs must declare the magic_link_tokens table: {schema}"
        );
    }

    #[test]
    fn magic_link_model_file_created() {
        let tmp = project_with_main();
        magic_link_plan(tmp.path())
            .execute(Flags::default())
            .unwrap();
        let model = fs::read_to_string(tmp.path().join("src/models/magic_link_token.rs")).unwrap();
        assert!(
            model.contains("pub struct MagicLinkToken")
                && model.contains("pub token_digest: String")
                && model.contains("pub consumed_at: Option<chrono::NaiveDateTime>"),
            "magic_link_token model must mirror the reset-token invariants: {model}"
        );
        let model_mod = fs::read_to_string(tmp.path().join("src/models/mod.rs")).unwrap();
        assert!(
            model_mod.contains("magic_link_token"),
            "models/mod.rs must declare the module"
        );
    }

    #[test]
    fn magic_link_routes_registered_in_main() {
        let tmp = project_with_main();
        magic_link_plan(tmp.path())
            .execute(Flags::default())
            .unwrap();
        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        for handler in [
            "routes::auth::magic_link_request_form",
            "routes::auth::magic_link_request",
            "routes::auth::magic_link_verify_form",
            "routes::auth::magic_link_verify",
        ] {
            assert!(
                main.contains(handler),
                "main.rs must register {handler}: {main}"
            );
        }
    }

    #[test]
    fn magic_link_adds_login_page_link() {
        let tmp = project_with_main();
        let routes = magic_link_routes(tmp.path());
        assert!(
            routes.contains("Email me a magic sign-in link"),
            "login page must link to /login/magic when --magic-link is set"
        );
    }

    #[test]
    fn magic_link_docs_document_ttl_ratelimit_enumeration_and_single_use() {
        let tmp = project_with_main();
        magic_link_plan(tmp.path())
            .execute(Flags::default())
            .unwrap();
        let docs = fs::read_to_string(tmp.path().join("docs/guide/authentication.md")).unwrap();
        assert!(
            docs.contains("Passwordless Magic-Link Login"),
            "docs section"
        );
        assert!(
            docs.contains("auth.magic_link.ttl_minutes"),
            "docs must document the config-sourced TTL knob"
        );
        assert!(
            docs.contains("#[throttle(") && docs.contains("auth.magic_link.email_cooldown_secs"),
            "docs must document per-IP + per-email rate limiting"
        );
        assert!(
            docs.contains("enumerat"),
            "docs must document the no-enumeration guarantee"
        );
        assert!(
            docs.contains("Single-use")
                || docs.contains("single-use")
                || docs.contains("used once"),
            "docs must document the single-use guarantee"
        );
    }

    #[test]
    fn magic_link_emits_ignored_live_db_test() {
        let tmp = project_with_main();
        magic_link_plan(tmp.path())
            .execute(Flags::default())
            .unwrap();
        let tests = fs::read_to_string(tmp.path().join("tests/auth.rs")).unwrap();
        assert!(
            tests.contains("fn magic_link_request_and_consume_logs_in()")
                && tests.contains("#[ignore"),
            "an #[ignore]d live-DB magic-link test must be emitted (AC7): {tests}"
        );
    }

    #[test]
    fn without_magic_link_nothing_is_emitted() {
        let tmp = project_with_main();
        // Every optional flag OFF.
        plan_auth(tmp.path(), "User", "20260508000000")
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            !routes.contains("/login/magic"),
            "no magic-link routes without --magic-link"
        );
        assert!(
            !routes.contains("MagicLinkToken"),
            "no magic-link model references without --magic-link"
        );
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/up.sql"),
        )
        .unwrap();
        assert!(
            !up.contains("magic_link_tokens"),
            "no magic_link_tokens table without --magic-link"
        );
        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(
            !main.contains("magic_link"),
            "no magic-link routes registered without --magic-link"
        );
        assert!(
            !tmp.path().join("src/models/magic_link_token.rs").exists(),
            "no magic-link model file without --magic-link"
        );
        let docs = fs::read_to_string(tmp.path().join("docs/guide/authentication.md")).unwrap();
        assert!(
            !docs.contains("Magic-Link"),
            "no magic-link docs without --magic-link"
        );
    }

    #[test]
    fn magic_link_composes_with_totp_passkeys_and_oauth() {
        let tmp = project_with_main();
        fs::write(tmp.path().join("Cargo.toml"), template_shipped_cargo_toml()).unwrap();
        fs::write(tmp.path().join("autumn.toml"), "[server]\nport = 3000\n").unwrap();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        plan_auth_full_ex2(
            tmp.path(),
            "User",
            "20260508000000",
            &oauth,
            true,
            true,
            true,
        )
        .unwrap()
        .execute(Flags::default())
        .unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        // Magic-link, TOTP, and password flows all coexist in auth.rs.
        assert!(
            routes.contains("#[get(\"/login/magic/verify\")]"),
            "magic-link present"
        );
        assert!(
            routes.contains("Two-factor authentication (TOTP)"),
            "totp present"
        );
        // Passkeys and OAuth live in their own route files.
        assert!(
            tmp.path().join("src/routes/passkeys.rs").exists(),
            "passkeys present"
        );
        assert!(
            tmp.path().join("src/routes/oauth.rs").exists(),
            "oauth present"
        );
        assert!(
            tmp.path().join("src/models/magic_link_token.rs").exists(),
            "magic-link model present alongside the others"
        );
    }

    #[test]
    fn generate_then_destroy_auth_with_magic_link_round_trips_to_original_project_state() {
        let tmp = project_with_main();
        let cargo_path = tmp.path().join("Cargo.toml");
        fs::write(&cargo_path, template_shipped_cargo_toml()).unwrap();
        let main_path = tmp.path().join("src/main.rs");
        let original_cargo = fs::read_to_string(&cargo_path).unwrap();
        let original_main = fs::read_to_string(&main_path).unwrap();

        magic_link_plan(tmp.path())
            .execute(Flags::default())
            .unwrap();
        assert!(tmp.path().join("src/models/magic_link_token.rs").exists());
        assert!(
            fs::read_to_string(tmp.path().join("src/schema.rs"))
                .unwrap()
                .contains("magic_link_tokens")
        );

        magic_link_plan(tmp.path())
            .revert(Flags::default())
            .unwrap();
        assert!(!tmp.path().join("src/models").exists());
        assert!(!tmp.path().join("src/routes").exists());
        assert!(!tmp.path().join("src/schema.rs").exists());
        assert!(!tmp.path().join("migrations").exists());
        assert_eq!(fs::read_to_string(&main_path).unwrap(), original_main);
        assert_eq!(fs::read_to_string(&cargo_path).unwrap(), original_cargo);
    }

    // ── Plan structure ──────────────────────────────────────────────────────

    #[test]
    fn plan_auth_creates_expected_files() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        let paths: Vec<String> = plan
            .actions
            .iter()
            .map(|a| {
                a.path()
                    .strip_prefix(tmp.path())
                    .unwrap()
                    .display()
                    .to_string()
                    .replace('\\', "/")
            })
            .collect();

        for expected in [
            "src/models/user.rs",
            "src/models/mod.rs",
            "src/schema.rs",
            "migrations/20260508000000_create_users/up.sql",
            "migrations/20260508000000_create_users/down.sql",
            "src/routes/auth.rs",
            "src/routes/mod.rs",
            "tests/auth.rs",
            "docs/guide/authentication.md",
            "src/main.rs",
        ] {
            assert!(
                paths.iter().any(|p| p == expected),
                "missing expected action for {expected}; got {paths:?}"
            );
        }
    }

    #[test]
    fn plan_auth_errors_when_not_in_project() {
        let tmp = TempDir::new().unwrap();
        let err = plan_auth(tmp.path(), "User", "20260508000000").unwrap_err();
        assert!(matches!(err, GenerateError::NotInProject));
    }

    // ── Migration SQL ───────────────────────────────────────────────────────

    #[test]
    fn migration_up_sql_creates_users_table_with_digest_columns() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/up.sql"),
        )
        .unwrap();
        assert!(
            up.contains("CREATE TABLE users"),
            "missing CREATE TABLE: {up}"
        );
        assert!(up.contains("email"), "missing email column: {up}");
        assert!(
            up.contains("password_digest"),
            "missing password_digest: {up}"
        );
        assert!(
            up.contains("reset_token_digest"),
            "missing reset_token_digest: {up}"
        );
        assert!(
            up.contains("reset_token_expires_at"),
            "missing reset_token_expires_at: {up}"
        );
        assert!(up.contains("UNIQUE"), "email column must be UNIQUE: {up}");
        assert!(
            !up.contains("password TEXT"),
            "raw password must never be stored: {up}"
        );
        assert!(
            !up.contains("reset_token TEXT"),
            "raw reset_token must never be stored: {up}"
        );
    }

    #[test]
    fn migration_down_sql_drops_users_table() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let down = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/down.sql"),
        )
        .unwrap();
        assert!(
            down.contains("DROP TABLE users"),
            "missing DROP TABLE: {down}"
        );
    }

    // ── schema.rs ───────────────────────────────────────────────────────────

    #[test]
    fn schema_rs_contains_diesel_table_for_auth_table() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let schema = fs::read_to_string(tmp.path().join("src/schema.rs")).unwrap();
        assert!(
            schema.contains("users (id)"),
            "schema missing table block: {schema}"
        );
        assert!(
            schema.contains("email -> Text"),
            "schema missing email column: {schema}"
        );
        assert!(
            schema.contains("password_digest -> Text"),
            "schema missing password_digest: {schema}"
        );
        assert!(
            schema.contains("reset_token_digest -> Nullable<Text>"),
            "schema missing nullable reset_token_digest: {schema}"
        );
        assert!(
            schema.contains("reset_token_expires_at -> Nullable<Timestamp>"),
            "schema missing nullable reset_token_expires_at: {schema}"
        );
    }

    // ── Model file ──────────────────────────────────────────────────────────

    #[test]
    fn model_file_contains_struct_and_digest_fields() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let model = fs::read_to_string(tmp.path().join("src/models/user.rs")).unwrap();
        assert!(model.contains("pub struct User"), "missing struct: {model}");
        assert!(
            model.contains("pub email: String"),
            "missing email: {model}"
        );
        assert!(
            model.contains("pub password_digest: String"),
            "missing password_digest: {model}"
        );
        assert!(
            model.contains("pub reset_token_digest: Option<String>"),
            "reset_token_digest must be nullable: {model}"
        );
        assert!(
            !model.contains("pub password:"),
            "raw password must not be a field: {model}"
        );
        assert!(
            !model.contains("pub reset_token:"),
            "raw reset_token must not be a field: {model}"
        );
    }

    #[test]
    fn model_mod_rs_declares_module() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let mod_rs = fs::read_to_string(tmp.path().join("src/models/mod.rs")).unwrap();
        assert!(
            mod_rs.contains("pub mod user;"),
            "missing pub mod user: {mod_rs}"
        );
    }

    // ── Step-up / reauth correctness ─────────────────────────────────────────

    #[test]
    fn confirm_email_does_not_stamp_step_up_claim() {
        // Email confirmation proves inbox access, not password knowledge.
        // set_last_strong_auth_at must NOT be called in confirm_email so that
        // an attacker with a stolen confirmation link cannot bypass #[step_up].
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let confirm_pos = routes
            .find("pub async fn confirm_email(")
            .expect("confirm_email handler missing");
        let after_confirm = &routes[confirm_pos..];
        let next_fn = after_confirm
            .find("\npub async fn ")
            .unwrap_or(after_confirm.len());
        let confirm_body = &after_confirm[..next_fn];
        assert!(
            !confirm_body.contains("set_last_strong_auth_at"),
            "confirm_email must NOT stamp set_last_strong_auth_at (email != password proof): {confirm_body}"
        );
        // confirm_email must also actively remove any inherited step-up claim so a
        // browser session that previously held last_strong_auth_at cannot carry it
        // into the newly confirmed account's session.
        assert!(
            confirm_body.contains("STEP_UP_SESSION_KEY"),
            "confirm_email must remove STEP_UP_SESSION_KEY after rotate_id: {confirm_body}"
        );
    }

    #[test]
    fn confirm_email_rejects_pending_email_change_tokens() {
        // A change-email token shares the `confirm_token_digest` column but sets
        // `pending_email`. The signup confirm_email UPDATE must guard on
        // `pending_email IS NULL` so a change-email token can never satisfy it
        // (Fix 2 — otherwise it consumes the token, stamps email_confirmed_at,
        // orphans pending_email, and mints an unintended session).
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let confirm_pos = routes
            .find("pub async fn confirm_email(")
            .expect("confirm_email handler missing");
        let after_confirm = &routes[confirm_pos..];
        let next_fn = after_confirm
            .find("\npub async fn ")
            .unwrap_or(after_confirm.len());
        let confirm_body = &after_confirm[..next_fn];
        // The reverse guard must be present in the signup-confirm UPDATE filter.
        assert!(
            confirm_body.contains("pending_email.is_null()"),
            "confirm_email UPDATE must filter on pending_email IS NULL to reject \
             email-change tokens: {confirm_body}"
        );
    }

    #[test]
    fn reauth_rotates_session_before_stamping_step_up() {
        // Rotating the session ID at the privilege-elevation point invalidates
        // any attacker-held copy of the old cookie, preventing a stolen session
        // from benefiting from the legitimate user's reauth.
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let reauth_pos = routes
            .find("pub async fn reauth(")
            .expect("reauth handler missing");
        let reauth_body = &routes[reauth_pos..];
        let rotate_pos = reauth_body
            .find("rotate_id")
            .expect("reauth must call session.rotate_id()");
        let stamp_pos = reauth_body
            .find("set_last_strong_auth_at")
            .expect("reauth must call set_last_strong_auth_at");
        assert!(
            rotate_pos < stamp_pos,
            "session.rotate_id() must come before set_last_strong_auth_at to invalidate the old cookie"
        );
    }

    #[test]
    fn totp_reauth_does_not_embed_password_in_form() {
        // The TOTP re-render form must not include the raw password in a hidden
        // field — that would expose it in the DOM to any script on the page.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let reauth_pos = routes
            .find("pub async fn reauth(")
            .expect("reauth handler missing");
        let reauth_body = &routes[reauth_pos..];
        // The only password input in reauth should be type="password" (visible field),
        // never type="hidden" with name="password".
        assert!(
            !reauth_body.contains("name=\"password\" value"),
            "TOTP reauth must not embed the raw password in a hidden field: {reauth_body}"
        );
    }

    #[test]
    fn totp_reauth_requires_second_factor_for_enrolled_accounts() {
        // When --totp is enabled, the reauth handler must verify the TOTP code
        // for accounts with totp_enabled = true. Password alone is insufficient.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let reauth_pos = routes
            .find("pub async fn reauth(")
            .expect("reauth handler missing");
        let reauth_body = &routes[reauth_pos..];
        assert!(
            reauth_body.contains("totp_enabled"),
            "TOTP reauth handler must check totp_enabled: {reauth_body}"
        );
        assert!(
            reauth_body.contains("totp_code"),
            "TOTP reauth handler must check totp_code from form: {reauth_body}"
        );
        assert!(
            reauth_body.contains("verify_totp_code"),
            "TOTP reauth must call verify_totp_code for enrolled accounts: {reauth_body}"
        );
    }

    #[test]
    fn totp_reauth_form_has_totp_field() {
        // The reauth form must include a TOTP input when --totp is enabled so
        // that users with two-factor authentication can provide their code.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let reauth_pos = routes
            .find("pub async fn reauth_form(")
            .expect("reauth_form handler missing");
        let reauth_body = &routes[reauth_pos..];
        assert!(
            reauth_body.contains("totp_code"),
            "reauth form must include totp_code input field: {reauth_body}"
        );
    }

    // ── Routes file ─────────────────────────────────────────────────────────

    #[test]
    fn routes_file_contains_all_handlers() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        for needle in [
            "pub async fn signup_form",
            "pub async fn signup",
            "pub async fn login_form",
            "pub async fn login",
            "pub async fn logout",
            "pub async fn account",
            "pub async fn account_destroy",
            "pub async fn reauth_form",
            "pub async fn reauth",
            "pub async fn forgot_password_form",
            "pub async fn forgot_password",
            "pub async fn reset_password_form",
            "pub async fn reset_password",
        ] {
            assert!(routes.contains(needle), "routes missing handler: {needle}");
        }
    }

    #[test]
    fn routes_file_uses_session_invalidation_on_logout() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        // Scope the assertion to the logout handler body so it cannot be
        // satisfied by `session.destroy()` calls in other handlers.
        let logout_pos = routes
            .find("pub async fn logout(")
            .expect("logout handler missing");
        let after = &routes[logout_pos..];
        let next_fn = after[1..]
            .find("\npub async fn ")
            .map_or(after.len(), |p| p + 1);
        let logout_body = &after[..next_fn];
        // Logout must invalidate the session so the pre-logout cookie cannot be
        // replayed: clear the data (drops auth keys) and rotate the id (the old
        // id is destroyed in the store on save). This is equivalent to
        // `destroy()` for replay safety while letting a one-shot logout notice
        // ride the rotated session to the login page.
        assert!(
            logout_body.contains("session.clear()") && logout_body.contains("session.rotate_id()"),
            "logout must invalidate the session via clear + rotate: {logout_body}"
        );
    }

    /// #2152: a failed remember-chain delete must fail the logout, not be
    /// swallowed. The remember cookie is a long-lived bearer credential; if
    /// the delete fails silently, the cookie clears client-side but the chain
    /// still authenticates on the server, while the response tells the user
    /// they signed out.
    #[test]
    fn logout_propagates_remember_chain_revocation_failure() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();

        let sig_start = routes
            .find("async fn revoke_remember_from_cookie")
            .expect("revoke_remember_from_cookie must be defined");
        let sig_end = sig_start
            + routes[sig_start..]
                .find('{')
                .expect("function signature must have a body");
        let signature = &routes[sig_start..sig_end];
        assert!(
            signature.contains("-> autumn_web::AutumnResult<()>")
                || signature.contains("-> AutumnResult<()>"),
            "revoke_remember_from_cookie must return a Result so a failed \
             delete can fail the logout, not `()`: {signature}"
        );

        let logout_pos = routes
            .find("pub async fn logout(")
            .expect("logout handler missing");
        let after = &routes[logout_pos..];
        let next_fn = after[1..]
            .find("\npub async fn ")
            .map_or(after.len(), |p| p + 1);
        let logout_body = &after[..next_fn];
        assert!(
            logout_body
                .contains("revoke_remember_from_cookie(&mut db, remember_cfg, &headers).await"),
            "logout must call revoke_remember_from_cookie and keep its result \
             to propagate later, not discard it: {logout_body}"
        );
    }

    /// #2152 follow-up: the session is the primary credential, so logout must
    /// invalidate it (`clear` + `rotate_id`) even when the remember-chain
    /// delete fails. Propagating that failure with `?` BEFORE invalidating
    /// the session would let a transient DB error on the remember-chain
    /// delete leave the pre-logout session cookie live — worse than the bug
    /// this was meant to fix, since the session is more sensitive than the
    /// remember cookie.
    #[test]
    fn logout_invalidates_session_before_propagating_remember_chain_failure() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();

        let logout_pos = routes
            .find("pub async fn logout(")
            .expect("logout handler missing");
        let after = &routes[logout_pos..];
        let next_fn = after[1..]
            .find("\npub async fn ")
            .map_or(after.len(), |p| p + 1);
        let logout_body = &after[..next_fn];

        let revoke_call_at = logout_body
            .find("revoke_remember_from_cookie(&mut db, remember_cfg, &headers).await")
            .expect("logout must call revoke_remember_from_cookie");
        assert!(
            !logout_body[revoke_call_at..]
                .starts_with("revoke_remember_from_cookie(&mut db, remember_cfg, &headers).await?"),
            "the revoke call must not short-circuit the handler with `?` \
             directly — that skips session invalidation on failure: {logout_body}"
        );

        let clear_at = logout_body
            .find("session.clear()")
            .expect("logout must clear the session");
        let rotate_at = logout_body
            .find("session.rotate_id()")
            .expect("logout must rotate the session id");
        assert!(
            clear_at > revoke_call_at && rotate_at > revoke_call_at,
            "logout must invalidate the session after calling \
             revoke_remember_from_cookie: {logout_body}"
        );

        let propagate_at = logout_body
            .find("if let Err(")
            .filter(|&p| p > rotate_at)
            .expect(
                "logout must branch on the remember-chain revocation result \
                 AFTER the session is invalidated",
            );
        assert!(propagate_at > clear_at && propagate_at > rotate_at);
    }

    /// #2811 review finding: on a failed remember-chain delete, `logout` must
    /// still clear the remember cookie in the error response. Otherwise the
    /// browser keeps presenting a still-valid remember cookie, and once the
    /// database recovers `remember_me` silently re-establishes a session on
    /// the user's very next request — undoing the logout entirely.
    #[test]
    fn logout_clears_remember_cookie_even_on_revocation_failure() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();

        let logout_pos = routes
            .find("pub async fn logout(")
            .expect("logout handler missing");
        let after = &routes[logout_pos..];
        let next_fn = after[1..]
            .find("\npub async fn ")
            .map_or(after.len(), |p| p + 1);
        let logout_body = &after[..next_fn];

        // The error branch must build its own response and attach the clear
        // cookie rather than bailing out with a bare `revoke_result?;` that
        // hands back the framework's default error response untouched.
        assert!(
            !logout_body.contains("revoke_result?;"),
            "a bare `revoke_result?;` skips attaching the remember-clear \
             cookie to the error response: {logout_body}"
        );
        assert!(
            logout_body.contains("if let Err(") && logout_body.contains("revoke_result"),
            "logout must branch on revoke_result to attach the clear cookie \
             to the error response: {logout_body}"
        );

        let clear_cookie_calls = logout_body
            .matches("append_set_cookie(&mut response, &build_remember_clear_cookie(remember_cfg))")
            .count();
        assert!(
            clear_cookie_calls >= 2,
            "logout must clear the remember cookie on BOTH the success path \
             and the revocation-failure error path: {logout_body}"
        );
    }

    #[test]
    fn routes_file_emits_flash_messages() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        // Flashes are set on the PRG-compatible auth flows.
        assert!(
            routes.contains(r#"flash.success("Logged in.")"#),
            "login success must set a flash: {routes}"
        );
        assert!(
            routes.contains(r#"flash.info("You have been logged out.")"#),
            "logout must set a flash: {routes}"
        );
        assert!(
            routes.contains("flash.info(\"Account created"),
            "signup must set a flash: {routes}"
        );
        // Issue #1353/#1240: the redirect-target pages render pending flashes
        // through the shared, accessible `flash_messages()` helper threaded into
        // the layout's 3rd argument — NOT the older in-content `flash.render()`.
        assert!(
            !routes.contains("flash.render().await"),
            "auth pages must not use the old in-content flash.render() path: {routes}"
        );
        assert!(
            routes.contains("flash_messages(&flash.consume().await)"),
            "auth pages must render pending flashes via flash_messages(): {routes}"
        );
        assert!(
            routes.contains("pub async fn login_form(flash: Flash"),
            "login_form must take the Flash extractor to render notices: {routes}"
        );
    }

    /// Issue #1353: every auth view renders through the application's shared
    /// `crate::layout(title, current_path, flash, content)` (4 args) rather than
    /// a private per-file `fn layout(title, content)` stub. The private stub —
    /// and its bare DOCTYPE shell — must be gone, and representative pages must
    /// call `crate::layout` with a per-page `current_path` and the flash arg.
    #[test]
    fn auth_views_render_through_shared_layout() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        // The private layout stub is gone.
        assert!(
            !routes.contains("fn layout(title: &str, content: Markup)"),
            "the private 2-arg layout stub must be removed: {routes}"
        );
        // Views render through the shared 4-arg layout.
        assert!(
            routes.contains("crate::layout("),
            "auth views must render through crate::layout: {routes}"
        );
        assert!(
            !routes.contains(" layout(") || routes.contains("crate::layout("),
            "no bare 2-arg layout() calls may remain: {routes}"
        );
        // Login renders through the shared layout with its own current_path and
        // the flash threaded to the 3rd arg (mirrors scaffold's assertions).
        assert!(
            routes.contains(
                "crate::layout(\"Log In\", \"/login\", flash_messages(&flash.consume().await),"
            ),
            "login_form must render through crate::layout with /login + flash: {routes}"
        );
        // The account page likewise threads its current_path + flash.
        assert!(
            routes.contains(
                "crate::layout(\"Your Account\", \"/account\", flash_messages(&flash.consume().await),"
            ),
            "account must render through crate::layout with /account + flash: {routes}"
        );
        // A page that shows no flash still passes a per-page current_path and an
        // empty flash markup as the 3rd arg.
        assert!(
            routes.contains("crate::layout(\"Sign Up\", \"/signup\", html! {},"),
            "signup form must render through crate::layout with /signup: {routes}"
        );
    }

    /// Issue #1353: the TOTP (`--totp`) and magic-link (`--magic-link`) views
    /// also render through the shared `crate::layout`, with per-page paths.
    #[test]
    fn auth_totp_and_magic_link_views_render_through_shared_layout() {
        let routes = render_routes_file("User", "user", "users", &[], true, true);
        assert!(
            !routes.contains("fn layout(title: &str, content: Markup)"),
            "the private layout stub must be removed under --totp/--magic-link: {routes}"
        );
        assert!(
            routes.contains(
                "crate::layout(\"Two-Factor Verification\", \"/login/verify\", html! {},"
            ),
            "the TOTP verify page must render through crate::layout: {routes}"
        );
        assert!(
            routes.contains(
                "crate::layout(\"Confirm sign-in\", \"/login/magic/verify\", flash_messages(&flash.consume().await),"
            ),
            "the magic-link confirm page must thread flash through crate::layout: {routes}"
        );
    }

    /// Issue #1353: `autumn generate auth` requires the target app to expose a
    /// shared 4-arg `pub fn layout` (as `autumn new` emits) so its views can
    /// render through `crate::layout`. When `src/main.rs` has no such layout —
    /// e.g. an `autumn new --api` project — the generator fails early with an
    /// actionable Config error rather than emitting routes that fail to compile.
    /// Mirrors the scaffold generator's preflight (issue #1130).
    #[test]
    fn plan_auth_errors_when_main_rs_has_no_shared_layout() {
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join("Cargo.toml"), "[package]\nname=\"x\"\n").unwrap();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        fs::write(tmp.path().join("src/main.rs"), main_without_layout()).unwrap();
        let err = plan_auth(tmp.path(), "User", "20260508000000").unwrap_err();
        match err {
            GenerateError::Config(msg) => {
                assert!(
                    msg.contains("pub fn layout") && msg.contains("autumn new"),
                    "missing shared layout must yield the actionable error: {msg}"
                );
            }
            other => panic!("expected an actionable Config error, got: {other:?}"),
        }
    }

    /// Issue #1353: a genuinely absent `src/main.rs` surfaces the same
    /// actionable shared-layout Config error (pointing at `autumn new`), not a
    /// raw Io "missing" error.
    #[test]
    fn plan_auth_errors_when_main_rs_missing() {
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join("Cargo.toml"), "[package]\nname=\"x\"\n").unwrap();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        let err = plan_auth(tmp.path(), "User", "20260508000000").unwrap_err();
        match err {
            GenerateError::Config(msg) => {
                assert!(
                    msg.contains("pub fn layout") && msg.contains("autumn new"),
                    "absent main.rs must yield the actionable shared-layout error: {msg}"
                );
            }
            other => panic!("expected an actionable Config error, got: {other:?}"),
        }
    }

    /// Issue #1353 follow-up: `autumn destroy auth` recomputes the identical
    /// plan before reverting it. The shared-layout preflight is a generate-time
    /// guard only — it must NOT fire on the destroy/revert path, or cleanup
    /// would hard-fail in a project whose shared `pub fn layout` is missing or
    /// renamed (e.g. one scaffolded by an older CLI), stranding the generated
    /// files. The revert-only plan builder must therefore succeed even when
    /// `src/main.rs` exposes no shared 4-arg layout.
    #[test]
    fn plan_auth_for_revert_succeeds_without_shared_layout() {
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join("Cargo.toml"), "[package]\nname=\"x\"\n").unwrap();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        // A project with NO shared `pub fn layout` — the exact input the
        // generate-time preflight rejects.
        fs::write(tmp.path().join("src/main.rs"), main_without_layout()).unwrap();
        let oauth = AuthOAuthOptions {
            providers: Vec::new(),
        };
        // The revert builder must not consult the shared layout at all.
        let plan = plan_auth_full_ex2_for_revert(
            tmp.path(),
            "User",
            "20260508000000",
            &oauth,
            false,
            false,
            false,
        )
        .expect("destroy auth must build its revert plan without a shared layout");
        // Sanity: it produced the auth routes file a normal auth plan would, so
        // `Plan::revert` has something to remove.
        assert!(
            find_plan_content_for_path(&plan, &tmp.path().join("src/routes/auth.rs")).is_some(),
            "revert plan should still include the auth routes it will remove"
        );

        // And the generate path over the SAME project still fails fast — the
        // guard is bypassed only for revert, never weakened for generation.
        let err = plan_auth(tmp.path(), "User", "20260508000000").unwrap_err();
        assert!(
            matches!(err, GenerateError::Config(ref msg) if msg.contains("pub fn layout")),
            "generate path must still reject a missing shared layout: {err:?}"
        );
    }

    #[test]
    fn routes_file_rotates_session_on_login() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("session.rotate_id"),
            "login must rotate the session ID to prevent fixation: {routes}"
        );
    }

    #[test]
    fn routes_file_uses_configured_auth_session_key_for_policy_identity() {
        let routes = render_routes_file("Account", "account", "accounts", &[], false, false);
        assert!(
            routes.contains("State(state): State<AppState>"),
            "auth routes must receive AppState: {routes}"
        );
        assert!(
            routes.contains("session.insert(state.auth_session_key()"),
            "auth routes must populate the same session key used by policy context: {routes}"
        );
        assert!(
            !routes.contains("session.insert(\"user_id\""),
            "non-User auth routes must not hard-code user_id as the policy session key: {routes}"
        );
    }

    #[test]
    fn routes_file_account_is_protected() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("#[secured]"),
            "account route must use #[secured] for protection: {routes}"
        );
    }

    #[test]
    fn account_destroy_carries_step_up_by_default() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();

        // Find the account_destroy fn and verify #[step_up] precedes it.
        let destroy_pos = routes
            .find("pub async fn account_destroy")
            .expect("account_destroy handler missing from scaffold");
        let before_destroy = &routes[..destroy_pos];
        assert!(
            before_destroy.rfind("#[step_up]").is_some(),
            "account_destroy must carry #[step_up] for step-up protection"
        );
    }

    #[test]
    fn mfa_remove_has_builtin_reauth_and_no_step_up_double_prompt() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions::default();
        let plan = plan_auth_full(tmp.path(), "User", "20260508000000", &oauth, true).unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();

        // two_factor_disable already verifies the user's TOTP code or password
        // in its body; a separate #[step_up] would cause a double re-auth prompt
        // (once via /reauth, once in the form itself). The handler must be present.
        assert!(
            routes.contains("pub async fn two_factor_disable"),
            "two_factor_disable handler missing from scaffold"
        );
    }

    #[test]
    fn routes_mod_rs_declares_auth_module() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let mod_rs = fs::read_to_string(tmp.path().join("src/routes/mod.rs")).unwrap();
        assert!(
            mod_rs.contains("pub mod auth;"),
            "missing pub mod auth: {mod_rs}"
        );
    }

    #[test]
    fn routes_file_forgot_password_checks_mailer_is_disabled() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("mailer.is_disabled()"),
            "forgot_password must guard against disabled mail transport: {routes}"
        );
        assert!(
            routes.contains("mailer.send(mail).await"),
            "forgot_password must use async mailer.send(): {routes}"
        );
        // The is_disabled guard must appear before the DB lookup (maybe_user)
        // so it fires unconditionally and cannot enumerate registered addresses.
        // Search within the forgot_password function body, which is identified
        // by the unique `maybe_user` variable that only appears there.
        let disabled_pos = routes.find("mailer.is_disabled()").unwrap();
        let maybe_user_pos = routes.find("let maybe_user").unwrap();
        assert!(
            disabled_pos < maybe_user_pos,
            "is_disabled guard must come before the DB lookup in forgot_password"
        );
    }

    // ── Change password / change email (issue #1396) ─────────────────────────

    /// Slice out a single handler body from the rendered routes file: from
    /// `pub async fn <name>(` up to the next handler declaration.
    fn handler_body<'a>(routes: &'a str, name: &str) -> &'a str {
        let needle = format!("pub async fn {name}(");
        let start = routes
            .find(&needle)
            .unwrap_or_else(|| panic!("handler {name} missing from routes"));
        let after = &routes[start..];
        let next = after[1..]
            .find("\npub async fn ")
            .map_or(after.len(), |p| p + 1);
        &after[..next]
    }

    #[test]
    fn routes_file_has_change_password_and_email_handlers() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        for needle in [
            "pub async fn change_password_form(",
            "pub async fn change_password(",
            "pub async fn change_email_form(",
            "pub async fn change_email(",
            "pub async fn confirm_email_change(",
        ] {
            assert!(routes.contains(needle), "routes missing handler: {needle}");
        }
        // Both POST forms carry the documented field names.
        assert!(
            routes.contains("current_password"),
            "missing current_password field"
        );
        assert!(
            routes.contains("new_password_confirmation"),
            "missing confirmation field"
        );
        assert!(routes.contains("new_email"), "missing new_email field");
        assert!(
            routes.contains(r#"action="/account/password""#),
            "change-password form must post to /account/password"
        );
        assert!(
            routes.contains(r#"action="/account/email""#),
            "change-email form must post to /account/email"
        );
    }

    #[test]
    fn change_password_post_carries_secured_and_step_up() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let pos = routes
            .find("pub async fn change_password(")
            .expect("change_password handler missing");
        let before = &routes[..pos];
        // The attributes immediately preceding the handler must be, in order,
        // #[secured] then #[step_up] then #[post(...)] — matching account_destroy.
        let secured = before
            .rfind("#[secured]")
            .expect("change_password needs #[secured]");
        let step_up = before
            .rfind("#[step_up]")
            .expect("change_password needs #[step_up]");
        let post = before
            .rfind(r#"#[post("/account/password")]"#)
            .expect("change_password needs its #[post] route");
        assert!(
            secured < step_up && step_up < post,
            "attribute order must be secured, step_up, post"
        );
    }

    #[test]
    fn change_email_post_carries_secured_and_step_up() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let pos = routes
            .find("pub async fn change_email(")
            .expect("change_email handler missing");
        let before = &routes[..pos];
        let secured = before
            .rfind("#[secured]")
            .expect("change_email needs #[secured]");
        let step_up = before
            .rfind("#[step_up]")
            .expect("change_email needs #[step_up]");
        let post = before
            .rfind(r#"#[post("/account/email")]"#)
            .expect("change_email needs its #[post] route");
        assert!(
            secured < step_up && step_up < post,
            "attribute order must be secured, step_up, post"
        );
    }

    #[test]
    fn change_password_verifies_current_rotates_and_revokes_others() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let body = handler_body(&routes, "change_password");
        assert!(
            body.contains("verify_password("),
            "must verify the current password"
        );
        assert!(
            body.contains("validate_password("),
            "must apply the password policy"
        );
        assert!(
            body.contains("hash_password("),
            "must hash the new password"
        );
        assert!(
            body.contains("session.rotate_id()"),
            "must rotate the session id"
        );
        assert!(
            body.contains("set_last_strong_auth_at"),
            "must re-stamp the step-up claim on success"
        );
        // Revokes OTHER tracked sessions (delete where digest != current) and the
        // remember chains.
        assert!(
            body.contains("user_sessions::token_digest.ne"),
            "must revoke other tracked sessions"
        );
        assert!(
            body.contains("user_remember_tokens::table"),
            "must revoke persistent remember-me chains"
        );
    }

    #[test]
    fn change_password_wrong_current_returns_422_and_no_update() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let body = handler_body(&routes, "change_password");
        // Wrong current password re-renders the form via form_unprocessable (422)
        // and returns BEFORE any password_digest update.
        let wrong_pos = body
            .find("Current password is incorrect.")
            .expect("must show a clear wrong-password error");
        let update_pos = body
            .find("password_digest.eq")
            .expect("must update the password digest on success");
        assert!(
            wrong_pos < update_pos,
            "wrong-password branch must return before any update"
        );
        assert!(
            routes.contains("StatusCode::UNPROCESSABLE_ENTITY"),
            "rejected form submissions must carry a 422 status"
        );
    }

    #[test]
    fn change_password_clears_reset_token() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let body = handler_body(&routes, "change_password");
        // The same transaction that writes the new password_digest must also null
        // any outstanding forgot-password token, so a reset link minted before the
        // change cannot overwrite the just-secured password (reset_password
        // authenticates SOLELY by matching an unexpired reset_token_digest).
        assert!(
            body.contains("password_digest.eq(&new_digest)"),
            "must update the password digest"
        );
        assert!(
            body.contains("reset_token_digest.eq(None::<String>)"),
            "change_password must clear reset_token_digest"
        );
        assert!(
            body.contains("reset_token_expires_at.eq(None::<chrono::NaiveDateTime>)"),
            "change_password must clear reset_token_expires_at"
        );
    }

    #[test]
    fn change_password_clears_magic_link_tokens_only_when_enabled() {
        // #7: a magic link minted before the password change must not sign the
        // account in afterwards, so the credential-change transaction deletes the
        // user's outstanding magic_link_tokens — but only under --magic-link (the
        // table exists only then).
        let with = render_routes_file("User", "user", "users", &[], false, true);
        let body = handler_body(&with, "change_password");
        assert!(
            body.contains(
                "magic_link_tokens::table.filter(magic_link_tokens::user_id.eq(user_id))"
            ),
            "with --magic-link, change_password must delete the user's magic_link_tokens"
        );
        // The delete must sit inside the credential-change transaction (before the
        // final `Ok(())`), alongside the reset-token clear.
        let clear_pos = body
            .find("magic_link_tokens::table.filter")
            .expect("magic-link delete present");
        let rem_pos = body
            .find("user_remember_tokens::table")
            .expect("remember-chain delete present");
        assert!(
            rem_pos < clear_pos,
            "magic-link delete belongs inside the same transaction as the other revocations"
        );

        let without = render_routes_file("User", "user", "users", &[], false, false);
        let body_without = handler_body(&without, "change_password");
        assert!(
            !body_without.contains("magic_link_tokens"),
            "without --magic-link, change_password must not reference magic_link_tokens"
        );
    }

    #[test]
    fn reset_password_clears_magic_link_tokens_only_when_enabled() {
        // #11: reset_password sets a new password digest and revokes sessions /
        // remember chains, so — like change_password / confirm_email_change — it must
        // delete the user's outstanding magic_link_tokens in the SAME transaction, or
        // a sign-in link minted/intercepted before the recovery flow stays valid
        // afterwards. Emitted only under --magic-link (the table exists only then).
        let with = render_routes_file("User", "user", "users", &[], false, true);
        let body = handler_body(&with, "reset_password");
        assert!(
            body.contains(
                "magic_link_tokens::table.filter(magic_link_tokens::user_id.eq(user_id))"
            ),
            "with --magic-link, reset_password must delete the user's magic_link_tokens"
        );
        // The delete must sit inside the reset transaction (before the final
        // `Ok(())`), after the remember-chain revocation.
        let clear_pos = body
            .find("magic_link_tokens::table.filter")
            .expect("magic-link delete present");
        let rem_pos = body
            .find("user_remember_tokens::table")
            .expect("remember-chain delete present");
        let ok_pos = body
            .rfind("Ok(())")
            .expect("transaction closes with Ok(())");
        assert!(
            rem_pos < clear_pos && clear_pos < ok_pos,
            "magic-link delete belongs inside the reset transaction with the other revocations"
        );

        let without = render_routes_file("User", "user", "users", &[], false, false);
        let body_without = handler_body(&without, "reset_password");
        assert!(
            !body_without.contains("magic_link_tokens"),
            "without --magic-link, reset_password must not reference magic_link_tokens"
        );
    }

    #[test]
    fn login_verify_reset_commit_clears_magic_link_tokens_only_when_enabled() {
        // #11: for a 2FA-enabled account the password-reset commit is deferred to
        // login_verify. That deferred commit also writes a new password_digest and
        // revokes sessions, so it must likewise delete the user's outstanding
        // magic_link_tokens — guarded on the commit succeeding (`updated == 1`) and
        // only under --magic-link.
        let with = render_routes_file("User", "user", "users", &[], true, true);
        let body = handler_body(&with, "login_verify");
        assert!(
            body.contains("magic_link_tokens::table")
                && body.contains("magic_link_tokens::user_id.eq(user_id)"),
            "with --magic-link + --totp, login_verify's deferred reset commit must delete \
             magic_link_tokens"
        );
        // The delete must sit inside the deferred-commit transaction, after the
        // password write and before the transaction returns `Ok(updated == 1)`.
        let commit_pos = body
            .find("password_digest.eq(&new_digest)")
            .expect("deferred reset commit writes the new digest");
        let clear_pos = body
            .find("magic_link_tokens::user_id.eq(user_id)")
            .expect("magic-link delete present");
        let ret_pos = body
            .find("Ok(updated == 1)")
            .expect("deferred commit transaction returns Ok(updated == 1)");
        assert!(
            commit_pos < clear_pos && clear_pos < ret_pos,
            "magic-link delete must sit inside the deferred reset commit transaction"
        );
        // Guarded on the parked reset actually committing.
        assert!(
            body.contains("if updated == 1 {"),
            "magic-link delete must be guarded on the parked reset committing"
        );

        let without = render_routes_file("User", "user", "users", &[], true, false);
        let body_without = handler_body(&without, "login_verify");
        assert!(
            !body_without.contains("magic_link_tokens"),
            "without --magic-link, login_verify must not reference magic_link_tokens"
        );
    }

    #[test]
    fn change_password_gates_other_session_revocation_on_opt_out() {
        // #8: the other-device sign-out honours
        // [auth.sessions].revoke_on_credential_change, mirroring the
        // reset/TOTP/passkey paths — but the current session is always rebound and
        // reset tokens are always cleared regardless of the flag.
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let body = handler_body(&routes, "change_password");
        assert!(
            body.contains("state.config_arc().auth.sessions.revoke_on_credential_change"),
            "change_password must read the revoke_on_credential_change opt-out"
        );
        // The OTHER-session delete is gated on the captured flag.
        let flag_pos = body
            .find("let revoke_other_sessions_in_txn =")
            .expect("must capture the revocation flag");
        let gate_pos = body
            .find("if revoke_other_sessions_in_txn {")
            .expect("other-session delete must be gated on the flag");
        let other_delete_pos = body
            .find("user_sessions::token_digest.ne")
            .expect("other-session delete present");
        assert!(
            flag_pos < gate_pos && gate_pos < other_delete_pos,
            "the other-session delete must sit inside `if revoke_other_sessions_in_txn`"
        );
        // The current session is ALWAYS rebound onto the rotated id (not gated).
        assert!(
            body.contains("token_digest.eq(&post_rotation_digest)"),
            "change_password must always rebind the current session onto the rotated id"
        );
        // Reset tokens are cleared unconditionally (not inside the gate).
        assert!(
            body.contains("reset_token_digest.eq(None::<String>)"),
            "reset tokens must be cleared regardless of the opt-out"
        );
    }

    #[test]
    fn change_email_guards_disabled_mail_first_and_stores_pending() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let body = handler_body(&routes, "change_email");
        // Disabled-mail guard must come before the DB session lookup, mirroring
        // forgot_password — so it fires unconditionally.
        let disabled = body
            .find("mailer.is_disabled()")
            .expect("must guard disabled mail");
        let lookup = body
            .find("require_tracked_session")
            .expect("must load the session");
        assert!(
            disabled < lookup,
            "is_disabled guard must precede the session lookup"
        );
        assert!(
            body.contains("verify_password("),
            "must verify the current password"
        );
        assert!(
            body.contains("pending_email.eq"),
            "must store the new address as pending"
        );
        assert!(
            body.contains("send_email_change_confirmation"),
            "must send a confirmation link to the new address"
        );
        assert!(
            body.contains("send_email_change_notice"),
            "must send a change-notice to the old address"
        );
        // Old address stays valid: the request handler must NOT SWAP the active
        // address here (only the later confirm sets `email`). A read-only
        // availability filter that references `users::email.eq(&new_email)` is fine;
        // the swap is uniquely the `.set` form with a trailing comma.
        assert!(
            !body.contains("email.eq(&new_email),"),
            "change_email request must NOT swap the active address"
        );
    }

    #[test]
    fn change_email_prechecks_availability_before_sending() {
        // If the requested address already belongs to ANOTHER account, the handler
        // must short-circuit to the SAME generic "check your email" response
        // WITHOUT emailing that third party and WITHOUT storing a doomed pending
        // change (the later confirm would collide on email's unique index). The
        // availability check must therefore run BEFORE both the mail send and the
        // pending-state persist. Non-enumerating: the caller cannot distinguish a
        // taken address from an available one.
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let body = handler_body(&routes, "change_email");
        let precheck = body
            .find("users::email.eq(&new_email)")
            .expect("must look up whether the new address is already taken");
        let send = body
            .find("send_email_change_confirmation")
            .expect("must send the confirmation mail");
        let persist = body
            .find("pending_email.eq(Some(&new_email))")
            .expect("must persist the pending change");
        assert!(
            precheck < send,
            "availability check must precede the confirmation mail send: {body}"
        );
        assert!(
            precheck < persist,
            "availability check must precede the pending-state persist: {body}"
        );
    }

    #[test]
    fn confirm_email_change_swaps_address_and_stamps_confirmed() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let body = handler_body(&routes, "confirm_email_change");
        assert!(
            body.contains("pending_email.is_not_null()"),
            "must target a pending change only"
        );
        assert!(
            body.contains("users::email.eq(&new_email)"),
            "must swap the active address"
        );
        assert!(
            body.contains("pending_email.eq(None::<String>)"),
            "must clear pending_email on confirm"
        );
        assert!(
            body.contains("email_confirmed_at.eq(Some(now))"),
            "must stamp email_confirmed_at on confirm"
        );
        // Single generic error (no oracle): the not-found / expired / consumed
        // paths all return the same message.
        assert!(
            body.contains("This email-change link is invalid or has expired."),
            "must return a single non-revealing error"
        );
        assert!(
            routes.contains(r#"#[get("/account/email/confirm/{token}")]"#),
            "confirm route must be registered under /account/email/confirm/{{token}}"
        );
    }

    #[test]
    fn confirm_email_change_clears_reset_token() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let body = handler_body(&routes, "confirm_email_change");
        // The atomic confirm UPDATE swaps the address; it must ALSO null any
        // outstanding reset token so a reset link sent to the OLD mailbox before
        // the change cannot reset the account after it has moved.
        assert!(
            body.contains("users::email.eq(&new_email)"),
            "must swap the active address"
        );
        assert!(
            body.contains("reset_token_digest.eq(None::<String>)"),
            "confirm_email_change must clear reset_token_digest"
        );
        assert!(
            body.contains("reset_token_expires_at.eq(None::<chrono::NaiveDateTime>)"),
            "confirm_email_change must clear reset_token_expires_at"
        );
    }

    #[test]
    fn confirm_email_change_clears_magic_link_tokens_only_when_enabled() {
        // #10: a magic link sent to the OLD mailbox before the change must not
        // sign the account in after the address moves, so the confirmation
        // transaction deletes the user's outstanding magic_link_tokens — gated on
        // --magic-link.
        let with = render_routes_file("User", "user", "users", &[], false, true);
        let body = handler_body(&with, "confirm_email_change");
        assert!(
            body.contains(
                "magic_link_tokens::table.filter(magic_link_tokens::user_id.eq(user_id))"
            ),
            "with --magic-link, confirm_email_change must delete the user's magic_link_tokens"
        );
        // The cleanup runs in the same transaction as the address swap.
        let swap_pos = body
            .find("users::email.eq(&new_email")
            .expect("address swap present");
        let clear_pos = body
            .find("magic_link_tokens::table.filter")
            .expect("magic-link delete present");
        assert!(
            swap_pos < clear_pos,
            "magic-link delete must follow the address swap in the same transaction"
        );

        let without = render_routes_file("User", "user", "users", &[], false, false);
        let body_without = handler_body(&without, "confirm_email_change");
        assert!(
            !body_without.contains("magic_link_tokens"),
            "without --magic-link, confirm_email_change must not reference magic_link_tokens"
        );
    }

    #[test]
    fn account_page_links_to_change_password_and_email() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        let body = handler_body(&routes, "account");
        assert!(
            body.contains(r#"href="/account/password""#),
            "account page must link to change-password"
        );
        assert!(
            body.contains(r#"href="/account/email""#),
            "account page must link to change-email"
        );
    }

    #[test]
    fn change_email_confirm_uses_secured_only_on_get_forms() {
        let routes = render_routes_file("User", "user", "users", &[], false, false);
        // The GET form pages are #[secured] but NOT #[step_up].
        for form_fn in ["change_password_form", "change_email_form"] {
            let pos = routes
                .find(&format!("pub async fn {form_fn}("))
                .unwrap_or_else(|| panic!("{form_fn} missing"));
            // Look at the attribute block immediately preceding this handler
            // (bounded by the previous handler) so a #[step_up] on some later
            // handler cannot satisfy the check.
            let before = &routes[..pos];
            let prev_fn = before.rfind("pub async fn ").unwrap_or(0);
            let attrs = &before[prev_fn..];
            assert!(attrs.contains("#[secured]"), "{form_fn} must be #[secured]");
            assert!(
                !attrs.contains("#[step_up]"),
                "{form_fn} GET form must NOT be #[step_up]"
            );
        }
    }

    #[test]
    fn migration_and_model_and_schema_have_pending_email() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/up.sql"),
        )
        .unwrap();
        assert!(
            up.contains("pending_email TEXT NULL"),
            "migration missing pending_email: {up}"
        );
        let model = fs::read_to_string(tmp.path().join("src/models/user.rs")).unwrap();
        assert!(
            model.contains("pub pending_email: Option<String>"),
            "model missing pending_email: {model}"
        );
        let schema = fs::read_to_string(tmp.path().join("src/schema.rs")).unwrap();
        assert!(
            schema.contains("pending_email"),
            "schema missing pending_email: {schema}"
        );
    }

    #[test]
    fn main_rs_registers_change_password_and_email_routes() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        for entry in [
            "routes::auth::change_password_form",
            "routes::auth::change_password",
            "routes::auth::change_email_form",
            "routes::auth::change_email",
            "routes::auth::confirm_email_change",
        ] {
            assert!(main.contains(entry), "main.rs missing route entry: {entry}");
        }
    }

    // ── Generated tests ─────────────────────────────────────────────────────

    #[test]
    fn tests_file_covers_all_required_flows() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let tests = fs::read_to_string(tmp.path().join("tests/auth.rs")).unwrap();
        for needle in [
            "auth_signup_returns_200",
            "auth_login_returns_200",
            "auth_logout_redirects",
            "auth_forgot_password_returns_200",
            "auth_reset_password_returns_200",
            "auth_account_rejects_anonymous",
        ] {
            assert!(tests.contains(needle), "tests missing flow: {needle}");
        }
    }

    // ── main.rs registration ────────────────────────────────────────────────

    #[test]
    fn main_rs_registers_auth_routes() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        for entry in [
            "routes::auth::signup_form",
            "routes::auth::signup",
            "routes::auth::login_form",
            "routes::auth::login",
            "routes::auth::logout",
            "routes::auth::account",
            "routes::auth::forgot_password_form",
            "routes::auth::forgot_password",
            "routes::auth::reset_password_form",
            "routes::auth::reset_password",
        ] {
            assert!(main.contains(entry), "main.rs missing route entry: {entry}");
        }
    }

    #[test]
    fn main_rs_declares_models_and_routes_mods() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(
            main.contains("mod models;"),
            "main.rs missing mod models: {main}"
        );
        assert!(
            main.contains("mod routes;"),
            "main.rs missing mod routes: {main}"
        );
    }

    // ── Dry run ─────────────────────────────────────────────────────────────

    #[test]
    fn dry_run_writes_no_files() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags {
            dry_run: true,
            force: false,
        })
        .unwrap();
        assert!(
            !tmp.path().join("src/models/user.rs").exists(),
            "dry run must not create model file"
        );
        assert!(
            !tmp.path().join("src/routes/auth.rs").exists(),
            "dry run must not create routes file"
        );
    }

    // ── Cargo.toml feature injection ────────────────────────────────────────

    #[test]
    fn cargo_toml_gets_mail_feature_simple_string_form() {
        let input = "[dependencies]\nautumn-web = \"0.3\"\n";
        let out = ensure_autumn_web_mail_feature(input);
        assert!(
            out.contains("features = [\"mail\"]"),
            "mail feature missing: {out}"
        );
        assert_eq!(out.matches("autumn-web =").count(), 1, "must not duplicate");
    }

    #[test]
    fn cargo_toml_gets_mail_feature_inline_table_with_existing_features() {
        let input = "[dependencies]\nautumn-web = { version = \"0.3\", features = [\"ws\"] }\n";
        let out = ensure_autumn_web_mail_feature(input);
        assert!(out.contains("\"mail\""), "mail missing: {out}");
        assert!(
            out.contains("\"ws\""),
            "existing feature must be kept: {out}"
        );
    }

    /// Characterization: `oauth2`/`webauthn` must behave exactly like `mail`
    /// (above) for the plain `autumn-web = "x.y"` form — pinned ahead of the
    /// #2753 `ensure_autumn_web_feature` extraction, which only `mail` had an
    /// explicit test for.
    #[test]
    fn cargo_toml_gets_oauth2_feature_simple_string_form() {
        let input = "[dependencies]\nautumn-web = \"0.3\"\n";
        let out = ensure_autumn_web_oauth2_feature(input);
        assert!(
            out.contains("features = [\"oauth2\"]"),
            "oauth2 feature missing: {out}"
        );
        assert_eq!(out.matches("autumn-web =").count(), 1, "must not duplicate");
    }

    #[test]
    fn cargo_toml_gets_oauth2_feature_inline_table_with_existing_features() {
        let input = "[dependencies]\nautumn-web = { version = \"0.3\", features = [\"ws\"] }\n";
        let out = ensure_autumn_web_oauth2_feature(input);
        assert!(out.contains("\"oauth2\""), "oauth2 missing: {out}");
        assert!(
            out.contains("\"ws\""),
            "existing feature must be kept: {out}"
        );
    }

    #[test]
    fn cargo_toml_gets_webauthn_feature_simple_string_form() {
        let input = "[dependencies]\nautumn-web = \"0.3\"\n";
        let out = ensure_autumn_web_webauthn_feature(input);
        assert!(
            out.contains("features = [\"webauthn\"]"),
            "webauthn feature missing: {out}"
        );
        assert_eq!(out.matches("autumn-web =").count(), 1, "must not duplicate");
    }

    #[test]
    fn cargo_toml_gets_webauthn_feature_inline_table_with_existing_features() {
        let input = "[dependencies]\nautumn-web = { version = \"0.3\", features = [\"ws\"] }\n";
        let out = ensure_autumn_web_webauthn_feature(input);
        assert!(out.contains("\"webauthn\""), "webauthn missing: {out}");
        assert!(
            out.contains("\"ws\""),
            "existing feature must be kept: {out}"
        );
    }

    #[test]
    fn cargo_toml_mail_feature_idempotent() {
        let input = "[dependencies]\nautumn-web = { version = \"0.3\", features = [\"mail\"] }\n";
        let out = ensure_autumn_web_mail_feature(input);
        assert_eq!(
            out.matches("\"mail\"").count(),
            1,
            "must not duplicate feature"
        );
    }

    /// Cargo does not normalize `-`/`_` in a dependency table key: `[dependencies.autumn_web]`
    /// names an unrelated package `autumn_web` unless its body renames it back with
    /// `package = "autumn-web"` (`cargo metadata` on a manifest with
    /// `[dependencies.async_trait]` and no `package` key: "no matching package found ...
    /// perhaps you meant: async-trait" — it does not fall back to the hyphenated name).
    /// Every fixture below therefore carries that `package` line, matching how `autumn
    /// new`/`cargo add --rename` would actually produce this form.
    ///
    /// `ensure_autumn_web_oauth2_feature` and `_webauthn_feature` both check
    /// `[dependencies.autumn_web]` via a `subtable_header_underscore` variable, and —
    /// like `ensure_autumn_web_mail_feature` before the rename-gate fix — neither
    /// verified the `package` rename, so they too would incorrectly match (and
    /// mutate) an unrelated `autumn_web` dependency that isn't actually this
    /// framework. The rename gate below (`cargo_toml_*_feature_ignores_unrenamed_`
    /// `underscore_subtable`) pins that fix for both copies, the same gate
    /// #2752's `mail` copy carries.
    #[test]
    fn cargo_toml_gets_oauth2_feature_subtable_underscore_form() {
        let input = "[dependencies.autumn_web]\nversion = \"0.3\"\npackage = \"autumn-web\"\n";
        let out = ensure_autumn_web_oauth2_feature(input);
        assert!(
            out.contains("features = [\"oauth2\"]"),
            "oauth2 feature missing for underscore subtable form: {out}"
        );
    }

    #[test]
    fn cargo_toml_gets_webauthn_feature_subtable_underscore_form() {
        let input = "[dependencies.autumn_web]\nversion = \"0.3\"\npackage = \"autumn-web\"\n";
        let out = ensure_autumn_web_webauthn_feature(input);
        assert!(
            out.contains("features = [\"webauthn\"]"),
            "webauthn feature missing for underscore subtable form: {out}"
        );
    }

    /// Missed-fix regression: `ensure_autumn_web_mail_feature` must recognize a
    /// properly `package`-renamed `[dependencies.autumn_web]` the same way its
    /// `oauth2`/`webauthn` siblings do (see
    /// `cargo_toml_gets_oauth2_feature_subtable_underscore_form` above). Before this
    /// fix the function silently returned the TOML unmodified for this form.
    #[test]
    fn cargo_toml_gets_mail_feature_subtable_underscore_form() {
        let input = "[dependencies.autumn_web]\nversion = \"0.3\"\npackage = \"autumn-web\"\n";
        let out = ensure_autumn_web_mail_feature(input);
        assert!(
            out.contains("features = [\"mail\"]"),
            "mail feature missing for underscore subtable form: {out}"
        );
    }

    /// Negative case for the fix above: `[dependencies.autumn_web]` with no `package`
    /// rename names a real (if unlikely) dependency on a crate literally called
    /// `autumn_web` — not this framework. `ensure_autumn_web_mail_feature` must leave
    /// it untouched rather than injecting `mail` into an unrelated dependency's
    /// features.
    #[test]
    fn cargo_toml_mail_feature_ignores_unrenamed_underscore_subtable() {
        let input = "[dependencies.autumn_web]\nversion = \"0.3\"\n";
        let out = ensure_autumn_web_mail_feature(input);
        assert_eq!(
            out, input,
            "must not treat an unrenamed `autumn_web` dependency as autumn-web: {out}"
        );
    }

    /// Soundness regression (#2753): an unrenamed `[dependencies.autumn_web]`
    /// names a crate literally called `autumn_web`, not this framework. Both
    /// `ensure_autumn_web_oauth2_feature` and
    /// `ensure_autumn_web_webauthn_feature` must leave it untouched rather than
    /// injecting their feature into an unrelated dependency's feature list —
    /// the same gate `ensure_autumn_web_mail_feature` gained in #2752.
    #[test]
    fn cargo_toml_oauth2_feature_ignores_unrenamed_underscore_subtable() {
        let input = "[dependencies.autumn_web]\nversion = \"0.3\"\n";
        let out = ensure_autumn_web_oauth2_feature(input);
        assert_eq!(
            out, input,
            "must not treat an unrenamed `autumn_web` dependency as autumn-web: {out}"
        );
    }

    #[test]
    fn cargo_toml_webauthn_feature_ignores_unrenamed_underscore_subtable() {
        let input = "[dependencies.autumn_web]\nversion = \"0.3\"\n";
        let out = ensure_autumn_web_webauthn_feature(input);
        assert_eq!(
            out, input,
            "must not treat an unrenamed `autumn_web` dependency as autumn-web: {out}"
        );
    }

    /// The rename gate must accept TOML-quoted `package` keys (Codex review on
    /// #2771): `"package" = "autumn-web"` is valid TOML that Cargo treats as
    /// the same key, and this form was patched before the gate was added, so
    /// rejecting it would leave generated routes uncompilable.
    #[test]
    fn cargo_toml_oauth2_feature_accepts_quoted_package_key_underscore_subtable() {
        let input = "[dependencies.autumn_web]\nversion = \"0.3\"\n\"package\" = \"autumn-web\"\n";
        let out = ensure_autumn_web_oauth2_feature(input);
        assert!(
            out.contains("features = [\"oauth2\"]"),
            "oauth2 feature missing for quoted-key rename form: {out}"
        );
    }

    #[test]
    fn cargo_toml_webauthn_feature_accepts_quoted_package_key_underscore_subtable() {
        let input = "[dependencies.autumn_web]\nversion = \"0.3\"\n'package' = 'autumn-web'\n";
        let out = ensure_autumn_web_webauthn_feature(input);
        assert!(
            out.contains("features = [\"webauthn\"]"),
            "webauthn feature missing for quoted-key rename form: {out}"
        );
    }

    #[test]
    fn model_file_created_at_is_marked_default() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let model = fs::read_to_string(tmp.path().join("src/models/user.rs")).unwrap();
        assert!(
            model.contains("#[default]"),
            "created_at must be marked #[default] so NewUser excludes it: {model}"
        );
    }

    #[test]
    fn cargo_toml_adds_axum_and_tracing_deps() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let cargo = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();
        assert!(cargo.contains("axum"), "axum dep missing: {cargo}");
        assert!(cargo.contains("tracing"), "tracing dep missing: {cargo}");
        assert!(
            cargo.contains("\"mail\""),
            "autumn-web mail feature missing: {cargo}"
        );
    }

    // ── Non-default model name ──────────────────────────────────────────────

    #[test]
    fn plan_auth_supports_custom_model_name() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "Account", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        assert!(
            tmp.path().join("src/models/account.rs").exists(),
            "model file should use snake_case of given name"
        );
        let model = fs::read_to_string(tmp.path().join("src/models/account.rs")).unwrap();
        assert!(
            model.contains("pub struct Account"),
            "struct name should match given name"
        );
    }

    // ── OAuth2 generator tests (RED phase) ──────────────────────────────────

    #[test]
    fn plan_auth_with_oauth_creates_oauth_identities_migration() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned(), "google".to_owned()],
        };
        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        let paths: Vec<String> = plan
            .actions
            .iter()
            .map(|a| {
                a.path()
                    .strip_prefix(tmp.path())
                    .unwrap()
                    .display()
                    .to_string()
                    .replace('\\', "/")
            })
            .collect();
        assert!(
            paths.iter().any(|p| p.contains("oauth_identities")),
            "oauth_identities migration missing; got {paths:?}"
        );
    }

    #[test]
    fn plan_auth_without_oauth_is_unchanged() {
        let tmp = project_with_main();
        // Calling with empty providers must produce the same plan as plain plan_auth.
        let oauth = AuthOAuthOptions { providers: vec![] };
        let plan_with =
            plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        let plan_plain = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        // Plans should have the same number of actions and the same paths.
        let paths_with: std::collections::HashSet<String> = plan_with
            .actions
            .iter()
            .map(|a| {
                a.path()
                    .strip_prefix(tmp.path())
                    .unwrap()
                    .display()
                    .to_string()
                    .replace('\\', "/")
            })
            .collect();
        let paths_plain: std::collections::HashSet<String> = plan_plain
            .actions
            .iter()
            .map(|a| {
                a.path()
                    .strip_prefix(tmp.path())
                    .unwrap()
                    .display()
                    .to_string()
                    .replace('\\', "/")
            })
            .collect();
        assert_eq!(
            paths_with, paths_plain,
            "empty --oauth must not add any extra files"
        );
    }

    #[test]
    fn oauth_migration_up_has_provider_subject_and_fk_columns() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        plan.execute(Flags::default()).unwrap();

        // Find the oauth_identities up.sql — timestamp is base+1 to avoid Diesel conflicts.
        let mig_dir = tmp
            .path()
            .join("migrations/20260508000001_create_oauth_identities");
        let up = fs::read_to_string(mig_dir.join("up.sql")).unwrap();
        assert!(
            up.contains("CREATE TABLE oauth_identities"),
            "missing CREATE TABLE oauth_identities: {up}"
        );
        assert!(up.contains("provider"), "missing provider column: {up}");
        assert!(up.contains("subject"), "missing subject column: {up}");
        assert!(
            up.contains("UNIQUE"),
            "provider+subject must have UNIQUE constraint: {up}"
        );
        assert!(
            !up.contains("plaintext") && !up.contains("access_token"),
            "oauth_identities must not store provider access tokens: {up}"
        );
    }

    #[test]
    fn oauth_routes_file_contains_redirect_and_callback_handlers() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/oauth.rs")).unwrap();
        assert!(
            routes.contains("pub async fn oauth_redirect"),
            "oauth_redirect handler missing: {routes}"
        );
        assert!(
            routes.contains("pub async fn oauth_callback"),
            "oauth_callback handler missing: {routes}"
        );
        assert!(
            routes.contains("oauth2_authorize_url"),
            "oauth_redirect must call oauth2_authorize_url: {routes}"
        );
        assert!(
            routes.contains("oauth2_finish_login"),
            "oauth_callback must call oauth2_finish_login: {routes}"
        );
    }

    #[test]
    fn oauth_callback_uses_state_nonce_validation() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/oauth.rs")).unwrap();
        // oauth2_finish_login handles state+nonce internally, so its presence
        // is the contract that state/nonce checking is enforced.
        assert!(
            routes.contains("oauth2_finish_login"),
            "callback must use oauth2_finish_login (which enforces state+nonce): {routes}"
        );
    }

    #[test]
    fn plan_auth_with_oauth_creates_oauth_doc() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["google".to_owned()],
        };
        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        plan.execute(Flags::default()).unwrap();

        let doc = fs::read_to_string(tmp.path().join("docs/guide/oauth.md")).unwrap();
        assert!(
            doc.contains("OAuth") || doc.contains("oauth"),
            "oauth.md must reference OAuth: {doc}"
        );
        assert!(
            doc.contains("google") || doc.contains("Google"),
            "oauth.md must mention configured providers: {doc}"
        );
        assert!(
            doc.contains("client_id"),
            "oauth.md must cover client_id configuration: {doc}"
        );
        assert!(
            doc.contains("PKCE") || doc.contains("pkce"),
            "oauth.md must document PKCE security property: {doc}"
        );
    }

    #[test]
    fn plan_auth_with_oauth_adds_oauth2_feature_to_autumn_web() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        plan.execute(Flags::default()).unwrap();

        let cargo = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();
        assert!(
            cargo.contains("\"oauth2\""),
            "Cargo.toml must enable autumn-web's oauth2 feature: {cargo}"
        );
    }

    #[test]
    fn plan_auth_without_oauth_does_not_add_oauth2_feature() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();

        let cargo = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();
        assert!(
            !cargo.contains("\"oauth2\""),
            "Cargo.toml must NOT enable oauth2 feature when --oauth not used: {cargo}"
        );
    }

    #[test]
    fn oauth_routes_registered_in_main_rs() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        plan.execute(Flags::default()).unwrap();

        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(
            main.contains("routes::oauth"),
            "main.rs must register oauth routes: {main}"
        );
    }

    #[test]
    fn oauth_migration_has_distinct_timestamp_from_base_auth_migration() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        plan.execute(Flags::default()).unwrap();

        let mig_entries: Vec<_> = fs::read_dir(tmp.path().join("migrations"))
            .unwrap()
            .filter_map(Result::ok)
            .map(|e| e.file_name().to_string_lossy().to_string())
            .collect();
        let auth_mig = mig_entries
            .iter()
            .find(|n| n.contains("create_users") || n.contains("create_accounts"));
        let oauth_mig = mig_entries.iter().find(|n| n.contains("oauth_identities"));
        if let (Some(a), Some(o)) = (auth_mig, oauth_mig) {
            let a_ts = a.split('_').next().unwrap_or("");
            let o_ts = o.split('_').next().unwrap_or("");
            assert_ne!(
                a_ts, o_ts,
                "oauth_identities migration must have a different timestamp than the auth migration"
            );
        }
    }

    #[test]
    fn oauth_mod_rs_preserves_base_auth_module_declaration() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        plan.execute(Flags::default()).unwrap();

        let mod_rs = fs::read_to_string(tmp.path().join("src/routes/mod.rs")).unwrap();
        assert!(
            mod_rs.contains("pub mod auth;"),
            "routes/mod.rs must keep pub mod auth: {mod_rs}"
        );
        assert!(
            mod_rs.contains("pub mod oauth;"),
            "routes/mod.rs must add pub mod oauth: {mod_rs}"
        );
    }

    #[test]
    fn oauth_handlers_have_route_macros() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/oauth.rs")).unwrap();
        assert!(
            routes.contains("#[get("),
            "oauth handlers must have #[get(...)] route macros for routes! registration: {routes}"
        );
    }

    #[test]
    fn oauth_callback_does_not_set_session_key_before_account_link() {
        let routes =
            render_oauth_routes_file("User", "user", "users", &["github".to_owned()], false);
        // The TODO comment may mention the call; verify the EXECUTABLE line is absent.
        // Executable session.insert calls are not prefixed with "//" or "#".
        let executable_insert = routes
            .lines()
            .filter(|l| !l.trim_start().starts_with("//"))
            .any(|l| l.contains("session.insert(&auth_cfg.session_key"));
        assert!(
            !executable_insert,
            "generated callback must not execute session.insert before account linking: {routes}"
        );
    }

    #[test]
    fn plan_auth_with_oauth_adds_oauth_identities_to_schema_rs() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        plan.execute(Flags::default()).unwrap();

        let schema = fs::read_to_string(tmp.path().join("src/schema.rs")).unwrap();
        assert!(
            schema.contains("oauth_identities (id)"),
            "schema.rs must contain oauth_identities table block: {schema}"
        );
        assert!(
            schema.contains("provider -> Text"),
            "schema.rs must contain provider column: {schema}"
        );
        assert!(
            schema.contains("subject -> Text"),
            "schema.rs must contain subject column: {schema}"
        );
        assert!(
            schema.contains("user_id -> Int8"),
            "schema.rs must contain user_id column: {schema}"
        );
        assert!(
            schema.contains("email -> Nullable<Text>"),
            "schema.rs must contain nullable email: {schema}"
        );
        assert!(
            schema.contains("name -> Nullable<Text>"),
            "schema.rs must contain nullable name: {schema}"
        );
    }

    #[test]
    fn plan_auth_with_oauth_appends_stubs_to_autumn_toml() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned(), "google".to_owned()],
        };
        // Setup mock autumn.toml
        fs::write(tmp.path().join("autumn.toml"), "[server]\nport = 3000\n").unwrap();

        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        plan.execute(Flags::default()).unwrap();

        let toml = fs::read_to_string(tmp.path().join("autumn.toml")).unwrap();
        assert!(
            toml.contains("[auth.oauth2.github]"),
            "autumn.toml missing github preset"
        );
        assert!(
            toml.contains("[auth.oauth2.google]"),
            "autumn.toml missing google preset"
        );
        assert!(
            toml.contains("scope = \"read:user user:email\""),
            "autumn.toml missing github scope"
        );
    }

    #[test]
    fn oauth_routes_file_contains_login_buttons() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned(), "google".to_owned()],
        };
        let plan = plan_auth_with_options(tmp.path(), "User", "20260508000000", &oauth).unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("Or sign in with:"),
            "login form routes file must render OAuth provider buttons"
        );
        assert!(
            routes.contains("a href=\"/auth/github/redirect\""),
            "login form routes file missing github redirect link"
        );
        assert!(
            routes.contains("a href=\"/auth/google/redirect\""),
            "login form routes file missing google redirect link"
        );
    }

    // ── TOTP two-factor generator tests (S-061 / #799) ──────────────────────

    fn totp_plan(tmp: &std::path::Path) -> Plan {
        let oauth = AuthOAuthOptions::default();
        plan_auth_full(tmp, "User", "20260508000000", &oauth, true).unwrap()
    }

    #[test]
    fn totp_migration_adds_totp_columns_and_recovery_table() {
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/up.sql"),
        )
        .unwrap();
        assert!(
            up.contains("totp_secret_encrypted"),
            "missing totp_secret_encrypted: {up}"
        );
        assert!(up.contains("totp_enabled"), "missing totp_enabled: {up}");
        assert!(
            up.contains("CREATE TABLE recovery_codes"),
            "missing recovery_codes table: {up}"
        );
        assert!(up.contains("code_digest"), "missing code_digest: {up}");
        assert!(up.contains("used_at"), "missing used_at: {up}");
        assert!(
            !up.contains("totp_secret TEXT") && !up.contains("recovery_code TEXT"),
            "raw secret / raw recovery code must never be stored: {up}"
        );
        let down = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/down.sql"),
        )
        .unwrap();
        assert!(
            down.contains("DROP TABLE recovery_codes"),
            "down.sql must drop recovery_codes: {down}"
        );
    }

    #[test]
    fn totp_model_has_totp_fields_and_recovery_model() {
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let model = fs::read_to_string(tmp.path().join("src/models/user.rs")).unwrap();
        assert!(
            model.contains("pub totp_secret_encrypted: Option<String>"),
            "{model}"
        );
        assert!(model.contains("pub totp_enabled: bool"), "{model}");
        let rc = fs::read_to_string(tmp.path().join("src/models/recovery_code.rs")).unwrap();
        assert!(rc.contains("pub struct RecoveryCode"), "{rc}");
        assert!(rc.contains("pub code_digest: String"), "{rc}");
        assert!(rc.contains("pub used_at: Option<"), "{rc}");
        let mod_rs = fs::read_to_string(tmp.path().join("src/models/mod.rs")).unwrap();
        assert!(mod_rs.contains("pub mod recovery_code;"), "{mod_rs}");
    }

    #[test]
    fn totp_schema_has_totp_and_recovery_columns() {
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let schema = fs::read_to_string(tmp.path().join("src/schema.rs")).unwrap();
        assert!(
            schema.contains("totp_secret_encrypted -> Nullable<Text>"),
            "{schema}"
        );
        assert!(schema.contains("totp_enabled -> Bool"), "{schema}");
        assert!(schema.contains("recovery_codes (id)"), "{schema}");
        assert!(schema.contains("code_digest -> Text"), "{schema}");
        assert!(
            schema.contains("used_at -> Nullable<Timestamp>"),
            "{schema}"
        );
    }

    #[test]
    fn totp_routes_have_2fa_handlers_and_paths() {
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        for needle in [
            "pub async fn two_factor_status",
            "pub async fn two_factor_enable",
            "pub async fn two_factor_confirm",
            "pub async fn two_factor_disable",
            "pub async fn login_verify_form",
            "pub async fn login_verify",
        ] {
            assert!(
                routes.contains(needle),
                "routes missing 2fa handler: {needle}"
            );
        }
        for path in [
            "\"/account/2fa\"",
            "\"/account/2fa/enable\"",
            "\"/account/2fa/disable\"",
            "\"/login/verify\"",
        ] {
            assert!(routes.contains(path), "routes missing 2fa path: {path}");
        }
    }

    #[test]
    fn totp_login_marks_pending_and_redirects_to_verify() {
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("totp_pending_id"),
            "login must set totp_pending marker: {routes}"
        );
        assert!(
            routes.contains("totp_enabled"),
            "login must branch on totp_enabled: {routes}"
        );
        assert!(
            routes.contains("/login/verify"),
            "login must redirect to /login/verify: {routes}"
        );
    }

    #[test]
    fn totp_login_clears_abandoned_reset_marker() {
        // P2 (#1057): an ordinary password login must clear any stale
        // totp_pending_reset_digest so it can't commit a stale password change.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let login_pos = routes.find("pub async fn login(").expect("login fn");
        let logout_pos = routes.find("pub async fn logout(").unwrap_or(routes.len());
        let login_body = &routes[login_pos..logout_pos];
        assert!(
            login_body.contains("session.remove(\"totp_pending_reset_digest\")"),
            "login interstitial must clear an abandoned deferred-reset marker: {login_body}"
        );
    }

    #[test]
    fn totp_signup_clears_pending_state() {
        // P2 (#1057 round 6): signing up establishes a fresh authenticated
        // session, so it must clear any abandoned pending-2FA / reset / enrollment
        // markers — otherwise a later /login/verify could switch accounts.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let signup_pos = routes.find("pub async fn signup(").expect("signup fn");
        let next_pos = routes[signup_pos + 1..]
            .find("pub async fn ")
            .map_or(routes.len(), |p| signup_pos + 1 + p);
        let signup_body = &routes[signup_pos..next_pos];
        assert!(
            signup_body.contains("session.remove(\"totp_pending_id\")")
                && signup_body.contains("session.remove(\"totp_pending_secret\")"),
            "signup must clear pending 2FA / enrollment markers: {signup_body}"
        );
    }

    #[test]
    fn totp_clear_pending_includes_enrollment_secret() {
        // P2 (#1057 round 6): a stale totp_pending_secret must not survive a fresh
        // full login, or two_factor_confirm could accept it for a different account.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let login_pos = routes.find("pub async fn login(").expect("login fn");
        let logout_pos = routes.find("pub async fn logout(").unwrap_or(routes.len());
        let login_body = &routes[login_pos..logout_pos];
        assert!(
            login_body.contains("session.remove(\"totp_pending_secret\")"),
            "login must clear a stale enrollment secret: {login_body}"
        );
    }

    #[test]
    fn totp_interstitial_rejects_session_key_collision() {
        // P2 (#1057 round 6): if [auth].session_key collides with a reserved
        // totp_pending_* key, parking the pending marker would set the trusted
        // auth key. The interstitials must refuse such a configuration.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("fn is_reserved_totp_pending_key"),
            "must define the reserved-pending-key guard helper: {routes}"
        );
        let login_pos = routes.find("pub async fn login(").expect("login fn");
        let logout_pos = routes.find("pub async fn logout(").unwrap_or(routes.len());
        let login_body = &routes[login_pos..logout_pos];
        assert!(
            login_body.contains("is_reserved_totp_pending_key(state.auth_session_key())"),
            "login interstitial must reject a colliding auth session key: {login_body}"
        );
    }

    #[test]
    fn totp_pending_handoff_clears_live_auth_keys() {
        // P2 (#1057 round 9): rotate_id() preserves session data, so a pending-2FA
        // handoff started while already authenticated as another account must drop
        // the live auth keys, or #[secured] would still trust the old account.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        // Login interstitial: before parking totp_pending_id it must remove the
        // configured auth session key.
        let login_pos = routes.find("pub async fn login(").expect("login fn");
        let logout_pos = routes.find("pub async fn logout(").unwrap_or(routes.len());
        let login_body = &routes[login_pos..logout_pos];
        let park_at = login_body
            .find("insert(\"totp_pending_id\"")
            .expect("login parks totp_pending_id");
        let before_park = &login_body[..park_at];
        assert!(
            before_park.contains("session.remove(state.auth_session_key())"),
            "login interstitial must clear the live auth key before parking 2FA: {login_body}"
        );
        // Reset interstitial must do the same.
        let reset_pos = routes
            .find("pub async fn reset_password(")
            .expect("reset_password fn");
        let reset_body = &routes[reset_pos..reset_pos + 6000.min(routes.len() - reset_pos)];
        let reset_park = reset_body
            .find("insert(\"totp_pending_id\"")
            .expect("reset parks totp_pending_id");
        assert!(
            reset_body[..reset_park].contains("session.remove(state.auth_session_key())"),
            "reset interstitial must clear the live auth key before parking 2FA: {reset_body}"
        );
    }

    #[test]
    fn totp_login_verify_falls_back_to_recovery_on_broken_secret() {
        // P2 (#1057 round 8): a decrypt/build failure (e.g. rotated TOTP_ENC_KEY)
        // must not abort login_verify before the recovery-code branch — recovery
        // codes are the only escape from that lockout.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let verify_pos = routes
            .find("pub async fn login_verify(")
            .expect("login_verify fn");
        // Up to the recovery-code branch, the TOTP attempt must not use `?` on
        // decrypt_secret/build_totp (which would abort the whole handler).
        let verify_to_recovery = &routes[verify_pos..];
        let recovery_at = verify_to_recovery
            .find("try an unused recovery code")
            .expect("recovery-code comment");
        let totp_branch = &verify_to_recovery[..recovery_at];
        assert!(
            !totp_branch.contains("decrypt_secret(stored)?"),
            "login_verify TOTP branch must not abort on decrypt failure: {totp_branch}"
        );
        assert!(
            totp_branch.contains("decrypt_secret(stored)") && totp_branch.contains(".ok()"),
            "login_verify must treat a broken secret as a miss and fall through: {totp_branch}"
        );
    }

    #[test]
    fn totp_disable_falls_back_to_password_on_broken_secret() {
        // P2 (#1057 round 8): the disable code path must likewise not abort on a
        // decrypt failure, so the password fallback can still re-authenticate.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let disable_pos = routes
            .find("pub async fn two_factor_disable(")
            .expect("two_factor_disable fn");
        let next = routes[disable_pos + 1..]
            .find("pub async fn ")
            .map_or(routes.len(), |p| disable_pos + 1 + p);
        let disable_body = &routes[disable_pos..next];
        assert!(
            !disable_body.contains("decrypt_secret(stored)?"),
            "disable must not abort on decrypt failure before the password fallback: {disable_body}"
        );
    }

    #[test]
    fn totp_build_totp_sanitizes_colon_in_account_label() {
        // P2 (#1057 round 8): totp-rs rejects account labels containing ':', so an
        // email like a:b@example.com would 500. build_totp must strip colons.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let build_pos = routes.find("fn build_totp(").expect("build_totp fn");
        let build_body = &routes[build_pos..build_pos + 600.min(routes.len() - build_pos)];
        assert!(
            build_body.contains("account.replace(':'"),
            "build_totp must sanitize colons in the account label: {build_body}"
        );
    }

    #[test]
    fn totp_oauth_pending_note_guards_session_key_collision() {
        // P2 (#1057 round 8): the OAuth pending-2FA guidance must mirror the
        // password/reset reserved-key rejection before parking totp_pending_id.
        let tmp = project_with_main();
        let oauth_opts = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        plan_auth_full(tmp.path(), "User", "20260508000000", &oauth_opts, true)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        let oauth = fs::read_to_string(tmp.path().join("src/routes/oauth.rs")).unwrap();
        assert!(
            oauth.contains("is_reserved_totp_pending_key(&auth_cfg.session_key)"),
            "OAuth pending-2FA guidance must guard against an auth-key collision: {oauth}"
        );
    }

    #[test]
    fn totp_rejects_recovery_code_name_collision() {
        // P2 (#1057 round 7): `--totp` always emits a recovery_code model/table,
        // so an auth resource that resolves to that name would emit it twice and
        // produce an unusable app. The generator must reject it up front.
        let tmp = project_with_main();
        // Both forms resolve to snake `recovery_code` / table `recovery_codes`,
        // which is exactly the helper model/table emitted under --totp.
        for name in ["RecoveryCode", "recovery_code"] {
            let err = plan_auth_with_providers(tmp.path(), name, "20260508000000", &[], true)
                .expect_err("recovery_code collision must be rejected under --totp");
            assert!(
                matches!(err, GenerateError::InvalidName(_, _)),
                "expected InvalidName for {name}, got {err:?}"
            );
        }
        // Without --totp the same name is fine (no recovery_code table emitted).
        assert!(
            plan_auth_with_providers(tmp.path(), "RecoveryCode", "20260508000000", &[], false)
                .is_ok(),
            "recovery_code name must be allowed without --totp"
        );
    }

    #[test]
    fn totp_rejects_existing_recovery_codes_table() {
        // P2 (#1057 round 11): if the project already declares a `recovery_codes`
        // table, the unconditional --totp migration would CREATE it again and
        // `diesel migration run` would fail. Reject up front.
        let tmp = project_with_main();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        fs::write(
            tmp.path().join("src/schema.rs"),
            "diesel::table! {\n    recovery_codes (id) {\n        id -> Int8,\n    }\n}\n",
        )
        .unwrap();
        let err = plan_auth_with_providers(tmp.path(), "User", "20260508000000", &[], true)
            .expect_err("existing recovery_codes table must be rejected under --totp");
        assert!(
            matches!(err, GenerateError::InvalidName(_, _)),
            "expected InvalidName, got {err:?}"
        );
        // Without --totp there's no recovery_codes helper, so it's fine.
        assert!(
            plan_auth_with_providers(tmp.path(), "User", "20260508000000", &[], false).is_ok(),
            "existing recovery_codes table is irrelevant without --totp"
        );
    }

    #[test]
    fn adoption_migration_docs_include_pending_email() {
        // The generated routes/schema always reference `pending_email` (signup-confirm
        // disambiguation + email-change flow), so the documented "adoption path"
        // migration for existing apps must add that column in up.sql and drop it in
        // down.sql — otherwise the regenerated app queries a missing column.
        let docs = render_docs_file(
            autumn_web::config::DatabaseBackend::Postgres,
            "User",
            false,
            false,
        );
        let up_marker = "-- migrations/<timestamp>_add_email_confirmation_to_{table}/up.sql";
        let down_marker = "-- migrations/<timestamp>_add_email_confirmation_to_{table}/down.sql";
        let up_pos = docs.find(up_marker).expect("adoption up.sql block present");
        let down_pos = docs
            .find(down_marker)
            .expect("adoption down.sql block present");
        let up_block = &docs[up_pos..down_pos];
        let down_block = &docs[down_pos..];
        assert!(
            up_block.contains("ADD COLUMN IF NOT EXISTS pending_email TEXT NULL"),
            "adoption up.sql must add pending_email: {up_block}"
        );
        assert!(
            down_block.contains("DROP COLUMN IF EXISTS pending_email"),
            "adoption down.sql must drop pending_email: {down_block}"
        );
    }

    #[test]
    fn magic_link_rejects_helper_name_collision() {
        // `--magic-link` always emits a magic_link_token model/table, so an auth
        // resource that resolves to those names would emit the CREATE TABLE twice and
        // overwrite the auth model with the helper model. The generator must reject it.
        let tmp = project_with_main();
        for name in ["MagicLinkToken", "magic_link_token"] {
            let err =
                plan_auth_with_providers_ex(tmp.path(), name, "20260508000000", &[], false, true)
                    .expect_err("magic_link_token collision must be rejected under --magic-link");
            assert!(
                matches!(err, GenerateError::InvalidName(_, _)),
                "expected InvalidName for {name}, got {err:?}"
            );
        }
        // Without --magic-link the same name is fine (no magic_link_tokens table emitted).
        assert!(
            plan_auth_with_providers_ex(
                tmp.path(),
                "MagicLinkToken",
                "20260508000000",
                &[],
                false,
                false,
            )
            .is_ok(),
            "magic_link_token name must be allowed without --magic-link"
        );
    }

    #[test]
    fn magic_link_rejects_existing_magic_link_tokens_table() {
        // If the project already declares a `magic_link_tokens` table, the
        // unconditional --magic-link migration would CREATE it again. Reject up front.
        let tmp = project_with_main();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        fs::write(
            tmp.path().join("src/schema.rs"),
            "diesel::table! {\n    magic_link_tokens (id) {\n        id -> Int8,\n    }\n}\n",
        )
        .unwrap();
        let err =
            plan_auth_with_providers_ex(tmp.path(), "User", "20260508000000", &[], false, true)
                .expect_err("existing magic_link_tokens table must be rejected under --magic-link");
        assert!(
            matches!(err, GenerateError::InvalidName(_, _)),
            "expected InvalidName, got {err:?}"
        );
        // Without --magic-link there's no helper table, so it's fine.
        assert!(
            plan_auth_with_providers_ex(tmp.path(), "User", "20260508000000", &[], false, false)
                .is_ok(),
            "existing magic_link_tokens table is irrelevant without --magic-link"
        );
    }

    #[test]
    fn totp_enable_rejects_reserved_session_key() {
        // P2 (#1057 round 11): two_factor_enable stashes totp_pending_secret, so it
        // must also reject a [auth].session_key that collides with a reserved key.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let enable_pos = routes
            .find("pub async fn two_factor_enable(")
            .expect("enable fn");
        let confirm_pos = routes
            .find("pub async fn two_factor_confirm(")
            .unwrap_or(routes.len());
        let enable_body = &routes[enable_pos..confirm_pos];
        assert!(
            enable_body.contains("is_reserved_totp_pending_key(state.auth_session_key())"),
            "two_factor_enable must reject a reserved auth session key: {enable_body}"
        );
    }

    #[test]
    fn totp_oauth_full_login_note_rotates_session() {
        // P2 (#1057 round 11): the non-2FA OAuth full-login guidance must rotate the
        // session id before promoting, mirroring password login (anti-fixation).
        let tmp = project_with_main();
        let oauth_opts = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        plan_auth_full(tmp.path(), "User", "20260508000000", &oauth_opts, true)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        let oauth = fs::read_to_string(tmp.path().join("src/routes/oauth.rs")).unwrap();
        let note_pos = oauth
            .find("otherwise, fully authenticate")
            .expect("full-login guidance");
        let after = &oauth[note_pos..];
        assert!(
            after.contains("session.rotate_id()"),
            "OAuth full-login guidance must rotate the session: {after}"
        );
    }

    #[test]
    fn ensure_totp_rs_features_promotes_simple_version() {
        let toml = "[dependencies]\ntotp-rs = \"5\"\n";
        let out = ensure_totp_rs_features(toml);
        assert!(
            out.contains("\"qr\"") && out.contains("\"gen_secret\"") && out.contains("\"otpauth\""),
            "simple version must be promoted with required features: {out}"
        );
    }

    #[test]
    fn ensure_totp_rs_features_merges_into_partial_features() {
        let toml = "[dependencies]\ntotp-rs = { version = \"5\", features = [\"qr\"] }\n";
        let out = ensure_totp_rs_features(toml);
        assert!(
            out.contains("\"qr\"") && out.contains("\"gen_secret\"") && out.contains("\"otpauth\""),
            "missing features must be merged in: {out}"
        );
        // The pre-existing feature must not be duplicated.
        assert_eq!(out.matches("\"qr\"").count(), 1, "qr duplicated: {out}");
    }

    #[test]
    fn ensure_totp_rs_features_adds_features_key_when_absent() {
        let toml = "[dependencies]\ntotp-rs = { version = \"5\" }\n";
        let out = ensure_totp_rs_features(toml);
        assert!(
            out.contains("features = [")
                && out.contains("\"gen_secret\"")
                && out.contains("\"otpauth\""),
            "a features key must be added: {out}"
        );
    }

    #[test]
    fn ensure_totp_rs_features_is_idempotent_when_complete() {
        let toml = "[dependencies]\ntotp-rs = { version = \"5\", features = [\"qr\", \"gen_secret\", \"otpauth\"] }\n";
        assert_eq!(
            ensure_totp_rs_features(toml),
            toml,
            "already-complete features must be left untouched"
        );
    }

    #[test]
    fn ensure_totp_rs_features_merges_subtable_with_partial_features() {
        // P2 (#1057 round 12): the `[dependencies.totp-rs]` subtable form must also
        // gain the missing features.
        let toml = "[dependencies.totp-rs]\nversion = \"5\"\nfeatures = [\"qr\"]\n";
        let out = ensure_totp_rs_features(toml);
        assert!(
            out.contains("\"qr\"") && out.contains("\"gen_secret\"") && out.contains("\"otpauth\""),
            "subtable features must be merged: {out}"
        );
        assert_eq!(out.matches("\"qr\"").count(), 1, "qr duplicated: {out}");
    }

    #[test]
    fn ensure_totp_rs_features_adds_subtable_features_key_when_absent() {
        let toml = "[dependencies.totp-rs]\nversion = \"5\"\n";
        let out = ensure_totp_rs_features(toml);
        assert!(
            out.contains("features = [")
                && out.contains("\"qr\"")
                && out.contains("\"gen_secret\"")
                && out.contains("\"otpauth\""),
            "a features key must be added to the subtable: {out}"
        );
    }

    #[test]
    fn ensure_totp_rs_features_strips_inline_comment_on_simple_version() {
        // P2 (#1057 round 13): a trailing inline comment must not be folded into
        // the version string (which would make Cargo.toml invalid).
        let toml = "[dependencies]\ntotp-rs = \"5\" # used by metrics\n";
        let out = ensure_totp_rs_features(toml);
        assert!(
            out.contains("version = \"5\"") && out.contains("features = ["),
            "version must be parsed cleanly: {out}"
        );
        assert!(
            !out.contains("\"5\" # used by metrics\""),
            "the comment must not leak into the version string: {out}"
        );
        // The comment is preserved after the rewritten table.
        assert!(
            out.contains("# used by metrics"),
            "the trailing comment should be preserved: {out}"
        );
    }

    #[test]
    fn ensure_totp_rs_features_merges_multiline_subtable_array() {
        // P2 (#1057 round 13): a multiline `features = [` array in the subtable
        // form must still gain the missing features.
        let toml = "[dependencies.totp-rs]\nversion = \"5\"\nfeatures = [\n    \"qr\",\n]\n";
        let out = ensure_totp_rs_features(toml);
        assert!(
            out.contains("\"qr\"") && out.contains("\"gen_secret\"") && out.contains("\"otpauth\""),
            "multiline subtable features must be merged: {out}"
        );
        assert_eq!(out.matches("\"qr\"").count(), 1, "qr duplicated: {out}");
    }

    #[test]
    fn ensure_autumn_web_mail_feature_merges_multiline_subtable_array() {
        // #2753 missed-fix #2: a multiline `features = [` array in the
        // `[dependencies.autumn-web]` subtable form silently kept `mail` unset.
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\",\n]\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert!(
            out.contains("\"ws\"") && out.contains("\"mail\""),
            "multiline subtable features must be merged: {out}"
        );
        assert_eq!(out.matches("\"mail\"").count(), 1, "mail duplicated: {out}");
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_merges_multiline_subtable_array() {
        // #2753 missed-fix #2: same gap as the mail copy, in the webauthn copy.
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\",\n]\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert!(
            out.contains("\"ws\"") && out.contains("\"webauthn\""),
            "multiline subtable features must be merged: {out}"
        );
        assert_eq!(
            out.matches("\"webauthn\"").count(),
            1,
            "webauthn duplicated: {out}"
        );
    }

    /// Characterization: pins the same multiline-subtable-array behavior for
    /// `oauth2` ahead of the #2753 extraction — the mail/webauthn copies above
    /// already had this test, oauth2 did not.
    #[test]
    fn ensure_autumn_web_oauth2_feature_merges_multiline_subtable_array() {
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\",\n]\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert!(
            out.contains("\"ws\"") && out.contains("\"oauth2\""),
            "multiline subtable features must be merged: {out}"
        );
        assert_eq!(
            out.matches("\"oauth2\"").count(),
            1,
            "oauth2 duplicated: {out}"
        );
    }

    /// Characterization: every existing subtable-form fixture for all three
    /// `ensure_autumn_web_*_feature` copies used a multiline `features = [...]`
    /// array, so the single-line subtable branch (`features = ["ws"]` on one
    /// line, non-empty) had zero coverage before #3358's
    /// `ensure_autumn_web_feature` extraction — codecov's patch-coverage check
    /// on that PR only surfaced it once `generate::auth::` was actually
    /// instrumented (ci.yml db-ignored lane).
    #[test]
    fn ensure_autumn_web_mail_feature_subtable_single_line_array_appends_feature() {
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\"ws\"]\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert!(
            out.contains("\"ws\"") && out.contains("\"mail\""),
            "single-line subtable features must be merged: {out}"
        );
        assert_eq!(out.matches("\"mail\"").count(), 1, "mail duplicated: {out}");
    }

    /// Same gap, the empty-array case: a single-line subtable `features = []`
    /// has no existing entries, so the "insert the first feature" path
    /// (rather than "append with a comma") must run instead.
    #[test]
    fn ensure_autumn_web_oauth2_feature_subtable_single_line_empty_array_inserts_feature() {
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = []\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert!(
            out.contains("features = [\"oauth2\"]"),
            "oauth2 feature missing for single-line empty subtable array: {out}"
        );
    }

    /// Same gap, the inline-table form: every existing inline-table fixture
    /// either had no `features` key or a non-empty one, so the inline-table
    /// "existing list is empty" path was never exercised either.
    #[test]
    fn ensure_autumn_web_webauthn_feature_inline_table_empty_array_inserts_feature() {
        let toml = "autumn-web = { version = \"0.3\", features = [] }\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert!(
            out.contains("features = [\"webauthn\"]"),
            "webauthn feature missing for empty inline-table array: {out}"
        );
    }

    #[test]
    fn ensure_webauthn_rs_features_merges_multiline_subtable_array() {
        // #2753 missed-fix #2: same gap as the two autumn-web copies, in the
        // webauthn-rs copy — this one merges a list of features, not just one.
        let toml = "[dependencies.webauthn-rs]\nversion = \"0.5\"\nfeatures = [\n    \"conditional-ui\",\n]\n";
        let out = ensure_webauthn_rs_features(toml);
        assert!(
            out.contains("\"conditional-ui\"")
                && out.contains("\"danger-allow-state-serialisation\""),
            "multiline subtable features must be merged: {out}"
        );
        assert_eq!(
            out.matches("\"conditional-ui\"").count(),
            1,
            "conditional-ui duplicated: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_mail_feature_multiline_array_without_trailing_comma_stays_valid_toml() {
        // Codex review on #2948: when the last entry before `]` has no
        // trailing comma, inserting the new feature right before the
        // bracket produced e.g. `"ws"\n"mail"]` — invalid TOML (missing the
        // separator between array elements).
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\"\n]\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert!(
            out.contains("\"mail\""),
            "mail feature must be merged: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_multiline_array_without_trailing_comma_stays_valid_toml()
    {
        // Same gap as the mail copy, in the webauthn copy.
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\"\n]\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert!(
            out.contains("\"webauthn\""),
            "webauthn feature must be merged: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_oauth2_feature_multiline_array_without_trailing_comma_stays_valid_toml() {
        // Same gap as its two siblings, in the one copy that already had the
        // multiline fallback before #2948.
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\"\n]\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert!(
            out.contains("\"oauth2\""),
            "oauth2 feature must be merged: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_mail_feature_trailing_comment_on_last_entry_stays_valid_toml() {
        // Codex review on #2948's first fix: the backward scan for "does the
        // last entry already end with a comma?" read a commented entry line
        // (`"ws", # note`) as not ending in ',' — since the comment text was
        // still attached — and inserted a second, invalid comma ahead of it.
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\", # websocket support\n]\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert!(
            out.contains("\"mail\""),
            "mail feature must be merged: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_trailing_comment_on_last_entry_stays_valid_toml() {
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\", # websocket support\n]\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert!(
            out.contains("\"webauthn\""),
            "webauthn feature must be merged: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_oauth2_feature_trailing_comment_on_last_entry_stays_valid_toml() {
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\", # websocket support\n]\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert!(
            out.contains("\"oauth2\""),
            "oauth2 feature must be merged: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_mail_feature_ignores_commented_out_feature_mention() {
        // Codex review on #2948's second fix: a commented-out mention of the
        // feature (`# "mail" is intentionally disabled`) is not TOML, but the
        // raw substring check treated it as though the feature were already
        // present and left it unset.
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\", # \"mail\" is intentionally disabled\n]\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert_eq!(
            out.matches("\"mail\"").count(),
            2,
            "mail must be merged as a real feature (the comment's mention is the other match): {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_ignores_commented_out_feature_mention() {
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\", # \"webauthn\" is intentionally disabled\n]\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert_eq!(
            out.matches("\"webauthn\"").count(),
            2,
            "webauthn must be merged as a real feature (the comment's mention is the other match): {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_oauth2_feature_ignores_commented_out_feature_mention() {
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\", # \"oauth2\" is intentionally disabled\n]\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert_eq!(
            out.matches("\"oauth2\"").count(),
            2,
            "oauth2 must be merged as a real feature (the comment's mention is the other match): {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_mail_feature_inline_table_ignores_commented_out_mention() {
        // Same comment-blindness bug as the subtable branch's "already
        // present?" check, in the inline-table (`autumn-web = { ... }`)
        // branch's own guard.
        let toml = "autumn-web = { version = \"0.3\", features = [\"ws\"] } # \"mail\" is intentionally disabled\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert_eq!(
            out.matches("\"mail\"").count(),
            2,
            "mail must be merged as a real feature (the comment's mention is the other match): {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_inline_table_ignores_commented_out_mention() {
        let toml = "autumn-web = { version = \"0.3\", features = [\"ws\"] } # \"webauthn\" is intentionally disabled\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert_eq!(
            out.matches("\"webauthn\"").count(),
            2,
            "webauthn must be merged as a real feature (the comment's mention is the other match): {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_oauth2_feature_inline_table_ignores_commented_out_mention() {
        let toml = "autumn-web = { version = \"0.3\", features = [\"ws\"] } # \"oauth2\" is intentionally disabled\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert_eq!(
            out.matches("\"oauth2\"").count(),
            2,
            "oauth2 must be merged as a real feature (the comment's mention is the other match): {out}"
        );
    }

    // #2753 missed-fix #3: a multiline `features = [` array inside the
    // *inline-table* form (`autumn-web = { ..., features = [\n ... \n] }`,
    // legal TOML since 1.0) was only handled by two of the three autumn-web
    // copies. `oauth2`/`webauthn` already scanned forward for the real
    // closing `]`; `mail` indexed the same-line search result with `.unwrap()`
    // and panicked on this exact input instead of silently no-op'ing like
    // missed-fix #1/#2 — a worse failure mode (CLI crash, not silent no-op).
    #[test]
    fn ensure_autumn_web_mail_feature_merges_multiline_inline_table_array() {
        let toml =
            "[dependencies]\nautumn-web = { version = \"0.3\", features = [\n    \"ws\",\n] }\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert!(
            out.contains("\"ws\"") && out.contains("\"mail\""),
            "multiline inline-table features must be merged: {out}"
        );
        assert_eq!(out.matches("\"mail\"").count(), 1, "mail duplicated: {out}");
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_merges_multiline_inline_table_array() {
        let toml =
            "[dependencies]\nautumn-web = { version = \"0.3\", features = [\n    \"ws\",\n] }\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert!(
            out.contains("\"ws\"") && out.contains("\"webauthn\""),
            "multiline inline-table features must be merged: {out}"
        );
        assert_eq!(
            out.matches("\"webauthn\"").count(),
            1,
            "webauthn duplicated: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_oauth2_feature_merges_multiline_inline_table_array() {
        let toml =
            "[dependencies]\nautumn-web = { version = \"0.3\", features = [\n    \"ws\",\n] }\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert!(
            out.contains("\"ws\"") && out.contains("\"oauth2\""),
            "multiline inline-table features must be merged: {out}"
        );
        assert_eq!(
            out.matches("\"oauth2\"").count(),
            1,
            "oauth2 duplicated: {out}"
        );
    }

    // Codex review on #3084: a first version of the inline-table multiline
    // fix (ported from oauth2/webauthn's own, then-unhardened branch) only
    // looked at the closing line for the separator decision, so a last
    // entry with no trailing comma on an earlier line produced invalid TOML
    // — the same defect #2948 already fixed once for the subtable form.
    #[test]
    fn ensure_autumn_web_mail_feature_inline_table_multiline_array_without_trailing_comma_stays_valid_toml()
     {
        let toml =
            "[dependencies]\nautumn-web = { version = \"0.3\", features = [\n    \"ws\"\n] }\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert!(
            out.contains("\"ws\"") && out.contains("\"mail\""),
            "both features must be present: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_inline_table_multiline_array_without_trailing_comma_stays_valid_toml()
     {
        let toml =
            "[dependencies]\nautumn-web = { version = \"0.3\", features = [\n    \"ws\"\n] }\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert!(
            out.contains("\"ws\"") && out.contains("\"webauthn\""),
            "both features must be present: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_oauth2_feature_inline_table_multiline_array_without_trailing_comma_stays_valid_toml()
     {
        let toml =
            "[dependencies]\nautumn-web = { version = \"0.3\", features = [\n    \"ws\"\n] }\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert!(
            out.contains("\"ws\"") && out.contains("\"oauth2\""),
            "both features must be present: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    // Codex review on #3084: the first version's "already present?" check
    // only looked at the opener line, not the rest of a multiline
    // inline-table array, so a feature already merged on a continuation
    // line got a duplicate appended — the same defect #2948 already fixed
    // once for the subtable form.
    #[test]
    fn ensure_autumn_web_mail_feature_does_not_duplicate_across_multiline_inline_table_array() {
        let toml = "[dependencies]\nautumn-web = { version = \"0.3\", features = [\n    \"ws\",\n    \"mail\",\n] }\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert_eq!(out.matches("\"mail\"").count(), 1, "mail duplicated: {out}");
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_does_not_duplicate_across_multiline_inline_table_array() {
        let toml = "[dependencies]\nautumn-web = { version = \"0.3\", features = [\n    \"ws\",\n    \"webauthn\",\n] }\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert_eq!(
            out.matches("\"webauthn\"").count(),
            1,
            "webauthn duplicated: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_oauth2_feature_does_not_duplicate_across_multiline_inline_table_array() {
        let toml = "[dependencies]\nautumn-web = { version = \"0.3\", features = [\n    \"ws\",\n    \"oauth2\",\n] }\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert_eq!(
            out.matches("\"oauth2\"").count(),
            1,
            "oauth2 duplicated: {out}"
        );
    }

    // Codex review on #3084: an inline table's `}` can carry another
    // comma-separated field after the array's `]` on the same line, unlike
    // the subtable form. The "already present?" check read the whole
    // closing line, so a field whose own string value happened to equal the
    // feature name (`path = "mail"`) made the array look already merged
    // when it was not, and the feature never got added.
    #[test]
    fn ensure_autumn_web_mail_feature_inline_table_field_value_matching_feature_name_is_not_mistaken_for_already_present()
     {
        let toml = "[dependencies]\nautumn-web = { version = \"0.3\", features = [\n    \"ws\",\n], path = \"mail\" }\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert_eq!(
            out.matches("\"mail\"").count(),
            2,
            "mail must be merged into the array, not mistaken for the trailing path field: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_inline_table_field_value_matching_feature_name_is_not_mistaken_for_already_present()
     {
        let toml = "[dependencies]\nautumn-web = { version = \"0.3\", features = [\n    \"ws\",\n], path = \"webauthn\" }\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert_eq!(
            out.matches("\"webauthn\"").count(),
            2,
            "webauthn must be merged into the array, not mistaken for the trailing path field: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_oauth2_feature_inline_table_field_value_matching_feature_name_is_not_mistaken_for_already_present()
     {
        let toml = "[dependencies]\nautumn-web = { version = \"0.3\", features = [\n    \"ws\",\n], path = \"oauth2\" }\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert_eq!(
            out.matches("\"oauth2\"").count(),
            2,
            "oauth2 must be merged into the array, not mistaken for the trailing path field: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_mail_feature_opener_comment_neither_hides_feature_nor_misclassifies() {
        // Codex review on 40a19c56: the same comment-blindness bug in the
        // *opener* line itself (`features = [ # ...`), one step earlier than
        // the interior-line scans already fixed — a `"mail"` mention in the
        // opener's comment falsely read as "already present", and a `]`
        // inside that same comment falsely dispatched a genuinely multiline
        // array down the single-line merge path (which would then merge
        // into dead text past the `#`, never touching the real array below).
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [ # \"mail\" is disabled, see [defaults] doc\n    \"ws\",\n]\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert!(
            out.contains("\"ws\""),
            "existing feature must survive: {out}"
        );
        assert_eq!(
            out.matches("\"mail\"").count(),
            2,
            "mail must be merged as a real feature (the comment's mention is the other match): {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_opener_comment_neither_hides_feature_nor_misclassifies() {
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [ # \"webauthn\" is disabled, see [defaults] doc\n    \"ws\",\n]\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert!(
            out.contains("\"ws\""),
            "existing feature must survive: {out}"
        );
        assert_eq!(
            out.matches("\"webauthn\"").count(),
            2,
            "webauthn must be merged as a real feature (the comment's mention is the other match): {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_oauth2_feature_opener_comment_neither_hides_feature_nor_misclassifies() {
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [ # \"oauth2\" is disabled, see [defaults] doc\n    \"ws\",\n]\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert!(
            out.contains("\"ws\""),
            "existing feature must survive: {out}"
        );
        assert_eq!(
            out.matches("\"oauth2\"").count(),
            2,
            "oauth2 must be merged as a real feature (the comment's mention is the other match): {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_mail_feature_respects_hash_inside_quoted_path() {
        // Codex review on 28a9cb82: `strip_line_comment` itself was the bug
        // this time — its naive `split_once('#')` treated a `#` inside a
        // quoted value (a git-fork path fragment, valid TOML) as a comment
        // start, hiding the real `features = [...]` that follows it. That
        // made an already-satisfied feature look absent, so the generator
        // appended a duplicate on every re-run.
        let toml = "autumn-web = { path = \"../autumn#fork\", features = [\"mail\"] }\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert!(
            out.contains("\"../autumn#fork\""),
            "the quoted path must survive untouched: {out}"
        );
        assert_eq!(
            out.matches("\"mail\"").count(),
            1,
            "the already-present feature must not be duplicated: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_respects_hash_inside_quoted_path() {
        let toml = "autumn-web = { path = \"../autumn#fork\", features = [\"webauthn\"] }\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert!(
            out.contains("\"../autumn#fork\""),
            "the quoted path must survive untouched: {out}"
        );
        assert_eq!(
            out.matches("\"webauthn\"").count(),
            1,
            "the already-present feature must not be duplicated: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_oauth2_feature_respects_hash_inside_quoted_path() {
        let toml = "autumn-web = { path = \"../autumn#fork\", features = [\"oauth2\"] }\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert!(
            out.contains("\"../autumn#fork\""),
            "the quoted path must survive untouched: {out}"
        );
        assert_eq!(
            out.matches("\"oauth2\"").count(),
            1,
            "the already-present feature must not be duplicated: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_mail_feature_ignores_bracket_inside_quoted_feature_name() {
        // Codex review on e1e5d48: Cargo permits unusual feature names (e.g.
        // on a path/git fork) containing characters like `]` or `,`. The
        // multiline "is this the closing bracket?" scan didn't know about
        // quoting, so a quoted `]` in an existing feature name was mistaken
        // for the array's real terminator, truncating the rebuild and
        // leaving the actual tail (further entries, the real `]`) behind.
        let toml =
            "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"foo]bar\",\n]\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert!(
            out.contains("\"foo]bar\""),
            "the quoted feature name must survive whole: {out}"
        );
        assert!(
            out.contains("\"mail\""),
            "mail feature must be merged: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_ignores_bracket_inside_quoted_feature_name() {
        let toml =
            "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"foo]bar\",\n]\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert!(
            out.contains("\"foo]bar\""),
            "the quoted feature name must survive whole: {out}"
        );
        assert!(
            out.contains("\"webauthn\""),
            "webauthn feature must be merged: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_oauth2_feature_ignores_bracket_inside_quoted_feature_name() {
        let toml =
            "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"foo]bar\",\n]\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert!(
            out.contains("\"foo]bar\""),
            "the quoted feature name must survive whole: {out}"
        );
        assert!(
            out.contains("\"oauth2\""),
            "oauth2 feature must be merged: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_webauthn_rs_features_ignores_bracket_inside_quoted_feature_name() {
        let toml =
            "[dependencies.webauthn-rs]\nversion = \"0.5\"\nfeatures = [\n    \"foo]bar\",\n]\n";
        let out = ensure_webauthn_rs_features(toml);
        assert!(
            out.contains("\"foo]bar\""),
            "the quoted feature name must survive whole: {out}"
        );
        assert!(
            out.contains("\"conditional-ui\"")
                && out.contains("\"danger-allow-state-serialisation\""),
            "both required features must be present: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_webauthn_rs_features_preserves_comma_inside_quoted_feature_name() {
        // Codex review on e1e5d48: collapsing a multiline array split on
        // every raw `,`, so a feature name containing a literal comma (also
        // valid for a path/git fork) was torn into two garbage entries.
        let toml =
            "[dependencies.webauthn-rs]\nversion = \"0.5\"\nfeatures = [\n    \"foo,bar\",\n]\n";
        let out = ensure_webauthn_rs_features(toml);
        assert!(
            out.contains("\"foo,bar\""),
            "the quoted feature name must survive whole, not split on its comma: {out}"
        );
        assert!(
            out.contains("\"conditional-ui\"")
                && out.contains("\"danger-allow-state-serialisation\""),
            "both required features must be present: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_webauthn_rs_features_finds_key_past_quoted_lookalike_text() {
        // Codex review on 445675f2: a quoted path containing the literal
        // text "features = [" (valid, if contrived, TOML) fooled the
        // quote-blind `line.find("features = [")` into anchoring the
        // bracket scan inside that quoted value instead of at the real
        // features key, so `find_unquoted` (which only starts tracking
        // quotes from that wrong position onward) got confused and missed
        // the real array entirely.
        let toml =
            "webauthn-rs = { path = \"../features = [fork\", features = [\"conditional-ui\"] }\n";
        let out = ensure_webauthn_rs_features(toml);
        assert!(
            out.contains("\"../features = [fork\""),
            "the quoted path must survive untouched: {out}"
        );
        assert!(
            out.contains("\"conditional-ui\"")
                && out.contains("\"danger-allow-state-serialisation\""),
            "both required features must be present: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_mail_feature_finds_key_past_quoted_lookalike_text_without_panicking() {
        // Same gap as the webauthn-rs case, but mail's inline-table branch
        // has no multiline fallback and unwraps the bracket search directly
        // — an unfixed quote-blind key lookup here would panic, not just
        // produce a wrong result.
        let toml = "autumn-web = { path = \"../features = [fork\", features = [\"mail\"] }\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert!(
            out.contains("\"../features = [fork\""),
            "the quoted path must survive untouched: {out}"
        );
        assert!(
            out.contains("\"mail\""),
            "mail feature must be present: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_mail_feature_ignores_commented_out_features_key() {
        // Codex review on 4f9291f9: the "already present?" guard strips
        // comments before checking, but the separate "does a real features
        // key exist here?" lookup this PR just fixed for quoting still
        // searched the raw line for comment-stripping too, so a
        // commented-out `features = [...]` (e.g. left behind by a manual
        // edit) was found and rewritten — inside the comment, never in
        // real code — instead of a genuine key being inserted.
        let toml = "autumn-web = { version = \"0.3\" } # features = [\"mail\"]\n";
        let out = ensure_autumn_web_mail_feature(toml);
        let code = out.split('#').next().unwrap();
        assert!(
            code.contains("features = [\"mail\"]"),
            "a real, uncommented features key must be inserted: {out}"
        );
    }

    /// Characterization: pins the same quote-aware key lookup for `oauth2`/
    /// `webauthn` ahead of the #2753 extraction — only `mail` had this test,
    /// though all three copies already shared the hardened `find_unquoted_str`
    /// lookup this pins.
    #[test]
    fn ensure_autumn_web_oauth2_feature_finds_key_past_quoted_lookalike_text_without_panicking() {
        let toml = "autumn-web = { path = \"../features = [fork\", features = [\"oauth2\"] }\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert!(
            out.contains("\"../features = [fork\""),
            "the quoted path must survive untouched: {out}"
        );
        assert!(
            out.contains("\"oauth2\""),
            "oauth2 feature must be present: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_finds_key_past_quoted_lookalike_text_without_panicking() {
        let toml = "autumn-web = { path = \"../features = [fork\", features = [\"webauthn\"] }\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert!(
            out.contains("\"../features = [fork\""),
            "the quoted path must survive untouched: {out}"
        );
        assert!(
            out.contains("\"webauthn\""),
            "webauthn feature must be present: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_oauth2_feature_ignores_commented_out_features_key() {
        let toml = "autumn-web = { version = \"0.3\" } # features = [\"oauth2\"]\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        let code = out.split('#').next().unwrap();
        assert!(
            code.contains("features = [\"oauth2\"]"),
            "a real, uncommented features key must be inserted: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_ignores_commented_out_features_key() {
        let toml = "autumn-web = { version = \"0.3\" } # features = [\"webauthn\"]\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        let code = out.split('#').next().unwrap();
        assert!(
            code.contains("features = [\"webauthn\"]"),
            "a real, uncommented features key must be inserted: {out}"
        );
    }

    #[test]
    fn ensure_totp_rs_features_ignores_bracket_inside_quoted_feature_name() {
        let toml = "[dependencies.totp-rs]\nversion = \"5\"\nfeatures = [\n    \"foo]bar\",\n]\n";
        let out = ensure_totp_rs_features(toml);
        assert!(
            out.contains("\"foo]bar\""),
            "the quoted feature name must survive whole: {out}"
        );
        assert!(
            out.contains("\"qr\"") && out.contains("\"gen_secret\"") && out.contains("\"otpauth\""),
            "all three required features must be present: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_totp_rs_features_preserves_comma_inside_quoted_feature_name() {
        let toml = "[dependencies.totp-rs]\nversion = \"5\"\nfeatures = [\n    \"foo,bar\",\n]\n";
        let out = ensure_totp_rs_features(toml);
        assert!(
            out.contains("\"foo,bar\""),
            "the quoted feature name must survive whole, not split on its comma: {out}"
        );
        assert!(
            out.contains("\"qr\"") && out.contains("\"gen_secret\"") && out.contains("\"otpauth\""),
            "all three required features must be present: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_webauthn_rs_features_opener_comment_bracket_does_not_misclassify() {
        // Codex review on 40a19c56: the single-line-vs-multiline dispatch
        // itself scanned the raw opener line, so a `]` inside a comment on
        // that same line (`features = [ # defaults [see docs]`) made a
        // genuinely multiline array look single-line — merging the missing
        // feature into dead text past the `#` instead of the real array.
        let toml = "[dependencies.webauthn-rs]\nversion = \"0.5\"\nfeatures = [ # defaults [see docs]\n    \"conditional-ui\",\n]\n";
        let out = ensure_webauthn_rs_features(toml);
        assert!(
            out.contains("\"conditional-ui\"")
                && out.contains("\"danger-allow-state-serialisation\""),
            "both features must be present: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_totp_rs_features_opener_comment_bracket_does_not_misclassify() {
        let toml = "[dependencies.totp-rs]\nversion = \"5\"\nfeatures = [ # defaults [see docs]\n    \"qr\",\n]\n";
        let out = ensure_totp_rs_features(toml);
        assert!(
            out.contains("\"qr\"") && out.contains("\"gen_secret\"") && out.contains("\"otpauth\""),
            "all three features must be present: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_webauthn_rs_features_ignores_bracket_inside_comment_before_real_close() {
        // Codex review on #2948's second fix: a comment containing a `]`
        // before the real closing bracket (e.g. `# defaults [see docs]`) is
        // not TOML syntax, but the raw-text search for the array's close
        // matched the bracket inside the comment instead of the real one,
        // truncating the rebuilt array and leaving the true tail behind.
        let toml = "[dependencies.webauthn-rs]\nversion = \"0.5\"\nfeatures = [\n    \"conditional-ui\", # defaults [see docs]\n]\n";
        let out = ensure_webauthn_rs_features(toml);
        assert!(
            out.contains("\"conditional-ui\"")
                && out.contains("\"danger-allow-state-serialisation\""),
            "both features must be present: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_totp_rs_features_ignores_bracket_inside_comment_before_real_close() {
        let toml = "[dependencies.totp-rs]\nversion = \"5\"\nfeatures = [\n    \"qr\", # defaults [see docs]\n]\n";
        let out = ensure_totp_rs_features(toml);
        assert!(
            out.contains("\"qr\"") && out.contains("\"gen_secret\"") && out.contains("\"otpauth\""),
            "all three features must be present: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_autumn_web_mail_feature_does_not_duplicate_across_multiline_array() {
        // Codex review on #2948: the "already present?" check only looked at
        // the `features = [` opener line, not the rest of a multiline array,
        // so re-running the generator kept appending another `"mail"`.
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\",\n    \"mail\",\n]\n";
        let out = ensure_autumn_web_mail_feature(toml);
        assert_eq!(out.matches("\"mail\"").count(), 1, "mail duplicated: {out}");
    }

    #[test]
    fn ensure_autumn_web_webauthn_feature_does_not_duplicate_across_multiline_array() {
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\",\n    \"webauthn\",\n]\n";
        let out = ensure_autumn_web_webauthn_feature(toml);
        assert_eq!(
            out.matches("\"webauthn\"").count(),
            1,
            "webauthn duplicated: {out}"
        );
    }

    #[test]
    fn ensure_autumn_web_oauth2_feature_does_not_duplicate_across_multiline_array() {
        let toml = "[dependencies.autumn-web]\nversion = \"0.3\"\nfeatures = [\n    \"ws\",\n    \"oauth2\",\n]\n";
        let out = ensure_autumn_web_oauth2_feature(toml);
        assert_eq!(
            out.matches("\"oauth2\"").count(),
            1,
            "oauth2 duplicated: {out}"
        );
    }

    #[test]
    fn ensure_webauthn_rs_features_preserves_valid_toml_around_interior_comment() {
        // Codex review on #2948: collapsing every line of a multiline array
        // onto one line without stripping trailing `# comment`s let a
        // comment on an interior entry swallow the rest of the line
        // (including the real closing `]`), producing an unterminated
        // array — invalid TOML.
        let toml = "[dependencies.webauthn-rs]\nversion = \"0.5\"\nfeatures = [\n    \"conditional-ui\", # keep this one\n]\n";
        let out = ensure_webauthn_rs_features(toml);
        assert!(
            out.contains("\"conditional-ui\"")
                && out.contains("\"danger-allow-state-serialisation\""),
            "both features must be present: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn ensure_totp_rs_features_preserves_valid_toml_around_interior_comment() {
        let toml = "[dependencies.totp-rs]\nversion = \"5\"\nfeatures = [\n    \"qr\", # needed for enrollment\n]\n";
        let out = ensure_totp_rs_features(toml);
        assert!(
            out.contains("\"qr\"") && out.contains("\"gen_secret\"") && out.contains("\"otpauth\""),
            "all three features must be present: {out}"
        );
        toml::from_str::<toml::Value>(&out)
            .unwrap_or_else(|e| panic!("rewritten Cargo.toml must still parse: {e}\n{out}"));
    }

    #[test]
    fn totp_disable_wraps_cleanup_in_transaction() {
        // P2 (#1057 round 12): disabling 2FA must be atomic — the flag/secret clear
        // and recovery-code delete run in one transaction.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let disable_pos = routes
            .find("pub async fn two_factor_disable(")
            .expect("disable fn");
        let next = routes[disable_pos + 1..]
            .find("pub async fn ")
            .map_or(routes.len(), |p| disable_pos + 1 + p);
        let body = &routes[disable_pos..next];
        assert!(
            body.contains(".transaction::<_, diesel::result::Error, _>"),
            "two_factor_disable must run cleanup in a transaction: {body}"
        );
        // Both the flag clear and the recovery-code delete must be inside it.
        assert!(
            body.contains("totp_enabled.eq(false)")
                && body.contains("delete(recovery_codes::table"),
            "transaction must cover both the disable update and recovery-code delete: {body}"
        );
    }

    #[test]
    fn totp_login_verify_tears_down_pending_on_stale_reset() {
        // P2 (#1057 round 7): if the parked reset token is stale, login_verify must
        // clear totp_pending_id too — otherwise a retry skips the (now-cleared)
        // reset branch and promotes the session to a full login.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let verify_pos = routes
            .find("pub async fn login_verify(")
            .expect("login_verify fn");
        let verify_body = &routes[verify_pos..];
        // The stale-reset failure path (before the success-promotion block) must
        // remove totp_pending_id.
        let promote_at = verify_body
            .find("Promote the pending session")
            .expect("promotion comment");
        let failure_block = &verify_body[..promote_at];
        assert!(
            failure_block.contains("session.remove(\"totp_pending_id\")")
                && failure_block.contains("Please restart the password reset"),
            "stale-reset path must tear down the pending login: {failure_block}"
        );
    }

    #[test]
    fn totp_oauth_full_login_note_clears_pending_state() {
        // P2 (#1057 round 7): the OAuth non-2FA full-login guidance must also clear
        // abandoned totp_pending_* state, mirroring password login/signup.
        let tmp = project_with_main();
        let oauth_opts = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        plan_auth_full(tmp.path(), "User", "20260508000000", &oauth_opts, true)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        let oauth = fs::read_to_string(tmp.path().join("src/routes/oauth.rs")).unwrap();
        let note_pos = oauth
            .find("otherwise, fully authenticate")
            .expect("full-login guidance");
        let after = &oauth[note_pos..];
        assert!(
            after.contains("totp_pending_secret") && after.contains("totp_pending_id"),
            "OAuth full-login guidance must clear pending 2FA/enrollment state: {after}"
        );
        // P2 (#1057 round 10): the full-login guidance must also set the
        // model-specific identity keys the generated handlers read, not only the
        // configured auth key.
        assert!(
            after.contains("session.insert(\"user_id\", local_user.id.to_string())")
                && after.contains("session.insert(\"user_email\", &local_user.email)"),
            "OAuth full-login guidance must set the model identity keys: {after}"
        );
    }

    #[test]
    fn totp_reset_password_routes_2fa_users_through_verify() {
        // P1 (#1057): a reset link must not bypass the second factor.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        // The 2FA interstitial branch must appear inside reset_password too.
        let reset_pos = routes
            .find("pub async fn reset_password(")
            .expect("reset_password fn");
        let after = &routes[reset_pos..];
        let body_end = after.find("\n}").unwrap_or(after.len());
        let body = &after[..body_end];
        assert!(
            body.contains("totp_pending_id") && body.contains("/login/verify"),
            "reset_password must route 2FA-enabled users through /login/verify: {body}"
        );
    }

    #[test]
    fn totp_reset_password_defers_password_commit_until_verify() {
        // P2 (#1057): for a 2FA-enabled account the password must NOT be written
        // until /login/verify passes; the reset handler parks the digest and the
        // verify handler commits it.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let reset_pos = routes
            .find("pub async fn reset_password(")
            .expect("reset_password fn");
        let reset_tail = &routes[reset_pos..];
        let reset_body = &reset_tail[..reset_tail.find("\n/// `").unwrap_or(reset_tail.len())];
        // The deferral branch (which returns to /login/verify) must come BEFORE
        // the password_digest UPDATE in the handler body.
        let park_at = reset_body
            .find("totp_pending_reset_digest")
            .expect("reset must park the pending digest");
        let write_at = reset_body
            .find("password_digest.eq(&new_digest)")
            .expect("reset still writes the digest for non-2FA users");
        assert!(
            park_at < write_at,
            "reset must park (and return) before committing the password for 2FA users"
        );
        // login_verify must commit a parked reset once the factor is proven.
        let verify_pos = routes
            .find("pub async fn login_verify(")
            .expect("login_verify fn");
        let verify_body = &routes[verify_pos..];
        assert!(
            verify_body.contains("totp_pending_reset_digest")
                && verify_body.contains("password_digest.eq(&new_digest)"),
            "login_verify must commit a parked password reset after 2FA: {verify_body}"
        );
    }

    #[test]
    fn totp_reset_branch_parks_token_digest() {
        // P2 (#1057 round 5): the reset interstitial must store totp_pending_reset_token
        // (the authorising SHA-256 digest) in the session alongside the new password
        // digest so login_verify can revalidate it before committing.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let reset_pos = routes
            .find("pub async fn reset_password(")
            .expect("reset_password fn");
        let reset_tail = &routes[reset_pos..];
        let reset_body = &reset_tail[..reset_tail.find("\n/// `").unwrap_or(reset_tail.len())];
        assert!(
            reset_body.contains("totp_pending_reset_token"),
            "reset_password 2FA branch must park the token digest: {reset_body}"
        );
        assert!(
            reset_body.contains("token_digest"),
            "reset_password must have token_digest in scope when parking: {reset_body}"
        );
    }

    #[test]
    fn totp_login_verify_revalidates_token_before_commit() {
        // P2 (#1057 round 5): login_verify must make the deferred password commit
        // conditional on the authorising token still matching the DB row — a
        // superseded or expired reset token must cause 0 rows updated and be rejected.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let verify_pos = routes
            .find("pub async fn login_verify(")
            .expect("login_verify fn");
        let verify_body = &routes[verify_pos..];
        assert!(
            verify_body.contains("totp_pending_reset_token"),
            "login_verify must load the stored token from the session: {verify_body}"
        );
        assert!(
            verify_body.contains("reset_token_digest"),
            "login_verify update must filter by reset_token_digest: {verify_body}"
        );
        assert!(
            verify_body.contains("reset_token_expires_at"),
            "login_verify update must filter by reset_token_expires_at: {verify_body}"
        );
    }

    #[test]
    fn totp_login_verify_stamps_step_up_claim_on_success() {
        // Issue #833 / Codex P2: TOTP login (password + second factor) proves
        // identity at least as strongly as password-only login. login_verify must
        // call set_last_strong_auth_at so that #[step_up]-protected routes are
        // immediately accessible without forcing a redundant /reauth.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let verify_pos = routes
            .find("pub async fn login_verify(")
            .expect("login_verify fn");
        let verify_body = &routes[verify_pos..];
        assert!(
            verify_body.contains("set_last_strong_auth_at"),
            "login_verify (TOTP) must stamp set_last_strong_auth_at on success: {verify_body}"
        );
    }

    #[test]
    fn totp_oauth_callback_note_clears_both_pending_markers() {
        // P2 (#1057 round 5): the OAuth callback guidance comment must instruct
        // developers to clear both pending-reset markers before parking the 2FA
        // state — mirroring what the password-login handler does.
        let tmp = project_with_main();
        let oauth_opts = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        let plan = plan_auth_full(tmp.path(), "User", "20260508000000", &oauth_opts, true).unwrap();
        plan.execute(Flags::default()).unwrap();
        let oauth = fs::read_to_string(tmp.path().join("src/routes/oauth.rs")).unwrap();
        assert!(
            oauth.contains("totp_pending_reset_digest"),
            "OAuth callback note must mention totp_pending_reset_digest: {oauth}"
        );
        assert!(
            oauth.contains("totp_pending_reset_token"),
            "OAuth callback note must mention totp_pending_reset_token: {oauth}"
        );
    }

    #[test]
    fn totp_enroll_requires_password_reauth() {
        // P2 (#1057): first enrollment must require step-up password re-auth.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("struct TotpEnableForm"),
            "enable must take a password form: {routes}"
        );
        let enable_pos = routes
            .find("pub async fn two_factor_enable(")
            .expect("enable fn");
        let confirm_pos = routes
            .find("pub async fn two_factor_confirm(")
            .expect("confirm fn");
        let enable_body = &routes[enable_pos..confirm_pos];
        assert!(
            enable_body.contains("verify_password(&form.password"),
            "two_factor_enable must verify the account password before enrolling: {enable_body}"
        );
        // The status-page enable form must collect the password.
        assert!(
            routes.contains("Confirm your password to begin enrollment"),
            "enable form must prompt for the password: {routes}"
        );
    }

    #[test]
    fn totp_disable_applies_replay_guard_on_code() {
        // P2 (#1057): a TOTP code used to disable must advance/respect
        // totp_last_used_step so a code already spent on login can't be replayed.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let disable_pos = routes
            .find("pub async fn two_factor_disable(")
            .expect("disable fn");
        let after = &routes[disable_pos..];
        let body_end = after.find("\n/// ").unwrap_or(after.len());
        let body = &after[..body_end];
        assert!(
            body.contains("totp_last_used_step") && body.contains("affected == 1"),
            "disable must consume the TOTP step with the same atomic guard: {body}"
        );
    }

    #[test]
    fn totp_confirm_guards_against_double_submit() {
        // P2 (#1057): the final enable flip is conditional on totp_enabled=false
        // with a rollback, so concurrent confirms don't desync recovery codes.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let confirm_pos = routes
            .find("pub async fn two_factor_confirm(")
            .expect("confirm fn");
        let after = &routes[confirm_pos..];
        let disable_pos = after
            .find("pub async fn two_factor_disable(")
            .unwrap_or(after.len());
        let body = &after[..disable_pos];
        assert!(
            body.contains("totp_enabled.eq(false)") && body.contains("RollbackTransaction"),
            "confirm must claim the enable transition conditionally and roll back on loss: {body}"
        );
    }

    #[test]
    fn totp_enable_does_not_disable_live_secret() {
        // P1 (#1057): starting re-enrollment must not flip totp_enabled=false on
        // the live account. The pending secret lives in the session instead.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let enable_pos = routes
            .find("pub async fn two_factor_enable(")
            .expect("enable fn");
        let confirm_pos = routes
            .find("pub async fn two_factor_confirm(")
            .expect("confirm fn");
        let enable_body = &routes[enable_pos..confirm_pos];
        assert!(
            enable_body.contains("session.insert(\"totp_pending_secret\""),
            "enable must stash the pending secret in the session: {enable_body}"
        );
        assert!(
            !enable_body.contains("totp_enabled.eq("),
            "enable must NOT write totp_enabled on the live row: {enable_body}"
        );
        assert!(
            !enable_body.contains("totp_secret_encrypted.eq("),
            "enable must NOT overwrite the live secret before confirmation: {enable_body}"
        );
    }

    #[test]
    fn totp_enable_rejects_reenrollment_while_active() {
        // P2 (#1057): a hijacked session must not swap the authenticator without
        // first disabling (which re-authenticates). Both enable and confirm guard
        // on the live `totp_enabled` flag.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let enable_pos = routes
            .find("pub async fn two_factor_enable(")
            .expect("enable fn");
        let confirm_pos = routes
            .find("pub async fn two_factor_confirm(")
            .expect("confirm fn");
        let disable_pos = routes
            .find("pub async fn two_factor_disable(")
            .expect("disable fn");
        let enable_body = &routes[enable_pos..confirm_pos];
        let confirm_body = &routes[confirm_pos..disable_pos];
        assert!(
            enable_body.contains("if __SNAKE__.totp_enabled")
                || enable_body.contains("if user.totp_enabled"),
            "two_factor_enable must reject re-enrollment while 2FA is active: {enable_body}"
        );
        assert!(
            confirm_body.contains("if user.totp_enabled") || confirm_body.contains("totp_enabled"),
            "two_factor_confirm must reject re-enrollment while 2FA is active: {confirm_body}"
        );
    }

    #[test]
    fn totp_confirm_persists_codes_before_enabling_in_transaction() {
        // P2 (#1057): enable + recovery-code replacement must be atomic and the
        // flag flipped only after codes are persisted.
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        let confirm_pos = routes
            .find("pub async fn two_factor_confirm(")
            .expect("confirm fn");
        let after = &routes[confirm_pos..];
        let disable_pos = after
            .find("pub async fn two_factor_disable(")
            .unwrap_or(after.len());
        let body = &after[..disable_pos];
        assert!(
            body.contains(".transaction"),
            "confirm must use a transaction: {body}"
        );
        assert!(
            body.contains("RECOVERY_CODE_COUNT"),
            "confirm must generate N codes: {body}"
        );
        assert!(
            body.contains("hash_password"),
            "recovery codes must be bcrypt-hashed: {body}"
        );
        // totp_enabled flip must come AFTER the recovery-code inserts.
        let enabled_at = body.find("totp_enabled.eq(true)").expect("enable flag set");
        let insert_at = body
            .find("insert_into(recovery_codes::table")
            .expect("code insert");
        assert!(
            enabled_at > insert_at,
            "totp_enabled must be set after codes are persisted"
        );
        // The pending secret must be read from the session, not the live row.
        assert!(
            body.contains("totp_pending_secret"),
            "confirm must consume session pending secret: {body}"
        );
    }

    #[test]
    fn totp_verification_window_and_atomic_replay_guard() {
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        // ±1 step skew window helper.
        assert!(
            routes.contains("[-1i64, 0, 1]"),
            "verification must use a ±1 step window: {routes}"
        );
        // Atomic, conditional consumption: rows-affected guard on the step update.
        assert!(routes.contains("totp_last_used_step"), "{routes}");
        assert!(
            routes.contains("affected == 1"),
            "step + recovery consumption must require exactly one affected row: {routes}"
        );
        assert!(
            routes.contains("recovery_codes::used_at.is_null()"),
            "recovery consumption must be guarded by used_at IS NULL: {routes}"
        );
    }

    #[test]
    fn totp_recovery_code_marked_used_and_count_surfaced() {
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("used_at"),
            "consumed recovery code must be stamped used: {routes}"
        );
        assert!(
            routes.contains("remaining"),
            "remaining count must be surfaced: {routes}"
        );
    }

    #[test]
    fn totp_disable_requires_reauth_and_clears_secret() {
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("verify_password") && routes.contains("two_factor_disable"),
            "disable must require re-auth: {routes}"
        );
        assert!(
            routes.contains("totp_secret_encrypted.eq(None"),
            "disable must clear the stored secret: {routes}"
        );
        assert!(
            routes.contains("delete(recovery_codes::table"),
            "disable must delete recovery codes: {routes}"
        );
    }

    #[test]
    fn totp_secret_encrypted_at_rest() {
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("Aes256Gcm"),
            "totp secret must be AES-GCM encrypted: {routes}"
        );
        assert!(
            routes.contains("fn encrypt_secret") && routes.contains("fn decrypt_secret"),
            "generated code must provide encrypt/decrypt helpers: {routes}"
        );
        assert!(
            routes.contains("otpauth://") || routes.contains("get_url"),
            "must expose otpauth URI: {routes}"
        );
    }

    #[test]
    fn totp_generates_2fa_integration_tests() {
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let tests = fs::read_to_string(tmp.path().join("tests/auth_2fa.rs")).unwrap();
        for flow in [
            "two_factor_enroll_and_confirm",
            "login_with_totp_code",
            "login_with_recovery_code",
            "recovery_code_reuse_rejected",
            "two_factor_disable",
        ] {
            assert!(
                tests.contains(flow),
                "tests/auth_2fa.rs missing flow: {flow}"
            );
        }
    }

    #[test]
    fn totp_registers_routes_in_main_rs_and_adds_deps() {
        let tmp = project_with_main();
        totp_plan(tmp.path()).execute(Flags::default()).unwrap();
        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        for entry in [
            "routes::auth::two_factor_enable",
            "routes::auth::two_factor_confirm",
            "routes::auth::two_factor_disable",
            "routes::auth::login_verify",
        ] {
            assert!(main.contains(entry), "main.rs missing 2fa route: {entry}");
        }
        let cargo = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();
        assert!(
            cargo.contains("totp-rs"),
            "Cargo.toml missing totp-rs: {cargo}"
        );
        assert!(
            cargo.contains("aes-gcm"),
            "Cargo.toml missing aes-gcm: {cargo}"
        );
    }

    #[test]
    fn without_totp_no_totp_artifacts() {
        let tmp = project_with_main();
        plan_auth(tmp.path(), "User", "20260508000000")
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        let model = fs::read_to_string(tmp.path().join("src/models/user.rs")).unwrap();
        assert!(
            !model.contains("totp_enabled"),
            "default model must not contain totp fields: {model}"
        );
        assert!(!tmp.path().join("src/models/recovery_code.rs").exists());
        assert!(!tmp.path().join("tests/auth_2fa.rs").exists());
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            !routes.contains("two_factor_enable"),
            "default routes must not have 2fa handlers"
        );
    }

    #[test]
    fn totp_combines_with_oauth_and_gates_callback() {
        // P2 (#1057): OAuth callback guidance must be TOTP-aware.
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        plan_auth_full(tmp.path(), "User", "20260508000000", &oauth, true)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(tmp.path().join("src/routes/oauth.rs").exists());
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("two_factor_enable"),
            "totp+oauth must keep 2fa handlers"
        );
        assert!(
            routes.contains("Or sign in with:"),
            "totp+oauth must keep oauth buttons"
        );
        let oauth_routes = fs::read_to_string(tmp.path().join("src/routes/oauth.rs")).unwrap();
        assert!(
            oauth_routes.contains("totp_pending_id") && oauth_routes.contains("/login/verify"),
            "oauth callback guidance must route 2FA users through /login/verify: {oauth_routes}"
        );
    }

    #[test]
    fn oauth_without_totp_has_no_2fa_callback_note() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        plan_auth_full(tmp.path(), "User", "20260508000000", &oauth, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        let oauth_routes = fs::read_to_string(tmp.path().join("src/routes/oauth.rs")).unwrap();
        assert!(
            !oauth_routes.contains("TWO-FACTOR"),
            "oauth-only scaffold must not mention the 2FA callback note: {oauth_routes}"
        );
    }

    // ── Passkeys (WebAuthn) generator tests (S-062 / #806) ──────────────────────

    fn passkey_plan(tmp: &std::path::Path) -> Plan {
        plan_auth_full_ex(
            tmp,
            "User",
            "20260508000000",
            &AuthOAuthOptions::default(),
            false,
            true,
        )
        .unwrap()
    }

    #[test]
    fn passkeys_flag_defaults_off() {
        // Without --passkeys, plan_auth_full (the 5-arg form) must not emit any
        // passkey artefacts — passkeys are opt-in.
        let tmp = project_with_main();
        plan_auth_full(
            tmp.path(),
            "User",
            "20260508000000",
            &AuthOAuthOptions::default(),
            false,
        )
        .unwrap()
        .execute(Flags::default())
        .unwrap();
        assert!(
            !tmp.path().join("src/routes/passkeys.rs").exists(),
            "passkeys.rs must not be created without --passkeys"
        );
        assert!(
            !tmp.path().join("tests/auth_passkeys.rs").exists(),
            "auth_passkeys.rs must not be created without --passkeys"
        );
    }

    #[test]
    fn passkeys_plan_emits_webauthn_credentials_migration() {
        let tmp = project_with_main();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        // The migration directory name is timestamp+1 relative to the base ts.
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000001_create_webauthn_credentials/up.sql"),
        )
        .unwrap();
        assert!(
            up.contains("CREATE TABLE webauthn_credentials"),
            "missing CREATE TABLE webauthn_credentials: {up}"
        );
        assert!(up.contains("user_id"), "missing user_id column: {up}");
        assert!(
            up.contains("credential_id"),
            "missing credential_id column: {up}"
        );
        assert!(
            up.contains("credential_json"),
            "missing credential_json column: {up}"
        );
        let down = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000001_create_webauthn_credentials/down.sql"),
        )
        .unwrap();
        assert!(
            down.contains("DROP TABLE webauthn_credentials"),
            "down.sql must drop webauthn_credentials: {down}"
        );
    }

    #[test]
    fn passkeys_plan_emits_four_ceremony_routes() {
        let tmp = project_with_main();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/passkeys.rs")).unwrap();
        for needle in [
            "passkey_register_begin",
            "passkey_register_finish",
            "passkey_login_begin",
            "passkey_login_finish",
        ] {
            assert!(
                routes.contains(needle),
                "passkeys.rs missing ceremony handler: {needle}"
            );
        }
    }

    #[test]
    fn passkeys_plan_emits_list_and_revoke_surface() {
        let tmp = project_with_main();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/passkeys.rs")).unwrap();
        assert!(
            routes.contains("passkey_list"),
            "missing passkey_list: {routes}"
        );
        assert!(
            routes.contains("passkey_revoke"),
            "missing passkey_revoke: {routes}"
        );
        assert!(
            routes.contains("#[secured]"),
            "revoke/list must use #[secured]: {routes}"
        );
    }

    #[test]
    fn passkeys_login_finish_writes_session_auth_key() {
        let tmp = project_with_main();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/passkeys.rs")).unwrap();
        assert!(
            routes.contains("state.auth_session_key()"),
            "passkey_login_finish must call session.insert(state.auth_session_key(), ...): {routes}"
        );
        // After template substitution ("User" → "user"), __SNAKE___id becomes user_id.
        assert!(
            routes.contains("\"user_id\""),
            "passkey_login_finish must store user_id in session: {routes}"
        );
        assert!(
            routes.contains("\"user_email\""),
            "passkey_login_finish must store user_email in session: {routes}"
        );
    }

    #[test]
    fn passkeys_plan_emits_rp_config_in_autumn_toml() {
        let tmp = project_with_main();
        // Create an autumn.toml so the generator can update it.
        fs::write(tmp.path().join("autumn.toml"), "[server]\nport = 3000\n").unwrap();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        let toml = fs::read_to_string(tmp.path().join("autumn.toml")).unwrap();
        assert!(
            toml.contains("[auth.webauthn]"),
            "autumn.toml missing [auth.webauthn]: {toml}"
        );
        assert!(toml.contains("rp_id"), "autumn.toml missing rp_id: {toml}");
        assert!(
            toml.contains("rp_name"),
            "autumn.toml missing rp_name: {toml}"
        );
        assert!(
            toml.contains("rp_origin"),
            "autumn.toml missing rp_origin: {toml}"
        );
    }

    #[test]
    fn passkeys_plan_adds_webauthn_feature_to_autumn_web() {
        let tmp = project_with_main();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        let cargo = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();
        assert!(
            cargo.contains("webauthn"),
            "Cargo.toml must reference webauthn feature or dep: {cargo}"
        );
        assert!(
            cargo.contains("webauthn-rs"),
            "Cargo.toml missing webauthn-rs dep: {cargo}"
        );
    }

    #[test]
    fn passkeys_plan_generates_integration_tests() {
        let tmp = project_with_main();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        let tests = fs::read_to_string(tmp.path().join("tests/auth_passkeys.rs")).unwrap();
        for needle in [
            "passkey_register_happy_path",
            "passkey_login_happy_path",
            "passkey_wrong_origin_rejected",
            "passkey_unknown_credential_rejected",
            "passkey_revoke_then_relogin",
        ] {
            assert!(
                tests.contains(needle),
                "auth_passkeys.rs missing test: {needle}"
            );
        }
    }

    #[test]
    fn passkeys_plan_writes_docs() {
        let tmp = project_with_main();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        let docs = fs::read_to_string(tmp.path().join("docs/guide/passkeys.md")).unwrap();
        assert!(
            docs.contains("rp_id") || docs.contains("rp_origin") || docs.contains("WebAuthn"),
            "docs/guide/passkeys.md should cover rp config or WebAuthn: {docs}"
        );
    }

    #[test]
    fn passkeys_plan_maud_template_has_js_shim() {
        let tmp = project_with_main();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/passkeys.rs")).unwrap();
        assert!(
            routes.contains("navigator.credentials"),
            "passkeys.rs Maud template must include navigator.credentials JS: {routes}"
        );
    }

    #[test]
    fn passkeys_plan_registers_routes_in_main() {
        let tmp = project_with_main();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        for entry in [
            "routes::passkeys::passkey_register_begin",
            "routes::passkeys::passkey_register_finish",
            "routes::passkeys::passkey_login_begin",
            "routes::passkeys::passkey_login_finish",
            "routes::passkeys::passkey_list",
            "routes::passkeys::passkey_revoke",
        ] {
            assert!(
                main.contains(entry),
                "main.rs missing passkey route: {entry}"
            );
        }
    }

    #[test]
    fn passkeys_can_combine_with_oauth_and_totp() {
        let tmp = project_with_main();
        let oauth = AuthOAuthOptions {
            providers: vec!["github".to_owned()],
        };
        plan_auth_full_ex(tmp.path(), "User", "20260508000000", &oauth, true, true)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(tmp.path().join("src/routes/passkeys.rs").exists());
        assert!(tmp.path().join("src/routes/oauth.rs").exists());
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("two_factor_enable"),
            "totp+passkeys+oauth must keep 2fa handlers"
        );
    }

    #[test]
    fn passkeys_misconfiguration_fails_fast_error_message() {
        let tmp = project_with_main();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/passkeys.rs")).unwrap();
        assert!(
            routes.contains("auth.webauthn"),
            "build_webauthn error must mention auth.webauthn config key: {routes}"
        );
    }

    #[test]
    fn ensure_webauthn_rs_features_merges_into_shorthand() {
        let toml = "webauthn-rs = \"0.5\"\n";
        let out = ensure_webauthn_rs_features(toml);
        assert!(
            out.contains("danger-allow-state-serialisation"),
            "shorthand should be promoted: {out}"
        );
        assert!(
            out.contains("conditional-ui"),
            "missing conditional-ui: {out}"
        );
    }

    #[test]
    fn ensure_webauthn_rs_features_merges_into_partial_inline() {
        let toml = "webauthn-rs = { version = \"0.5\", features = [\"danger-allow-state-serialisation\"] }\n";
        let out = ensure_webauthn_rs_features(toml);
        assert!(
            out.contains("conditional-ui"),
            "conditional-ui should be added to partial features: {out}"
        );
    }

    #[test]
    fn ensure_webauthn_rs_features_is_idempotent() {
        let toml = "webauthn-rs = { version = \"0.5\", features = [\"danger-allow-state-serialisation\", \"conditional-ui\"] }\n";
        let out = ensure_webauthn_rs_features(toml);
        assert_eq!(out, toml, "idempotent: should not duplicate features");
    }

    #[test]
    fn passkeys_routes_template_has_redirect_to() {
        let tmp = project_with_main();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/passkeys.rs")).unwrap();
        assert!(
            routes.contains("fn redirect_to"),
            "passkeys.rs must define redirect_to: {routes}"
        );
        assert!(
            routes.contains("fn redirect_to(url: &str) -> axum::response::Redirect"),
            "redirect_to must return a concrete axum::response::Redirect \
             (impl Trait is illegal nested in AutumnResult<_>): {routes}"
        );
    }

    #[test]
    fn passkeys_register_begin_binds_user_id() {
        let tmp = project_with_main();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/passkeys.rs")).unwrap();
        assert!(
            routes.contains("user_id"),
            "register begin should store user_id in passkey_reg_state envelope: {routes}"
        );
    }

    #[test]
    fn passkeys_templates_accept_csrf_header_and_nonce() {
        let tmp = project_with_main();
        passkey_plan(tmp.path()).execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/passkeys.rs")).unwrap();

        assert!(
            routes.contains("pub async fn passkey_register_page("),
            "passkey_register_page is missing"
        );
        assert!(
            routes.contains("csrf_header: Option<CsrfTokenHeader>"),
            "passkey_register_page must take csrf_header"
        );
        assert!(
            routes.contains("nonce: Option<CspNonce>"),
            "passkey_register_page must take nonce"
        );
        assert!(
            routes.contains("pub async fn passkey_login_page("),
            "passkey_login_page is missing"
        );
        assert!(
            routes.contains("csrf_header: Option<CsrfTokenHeader>"),
            "passkey_login_page must take csrf_header"
        );
        assert!(
            routes.contains("nonce: Option<CspNonce>"),
            "passkey_login_page must take nonce"
        );

        assert!(
            routes.contains("script nonce=[script_nonce]"),
            "templates must output script tags with nonce attribute: {routes}"
        );
        assert!(
            routes.contains("const csrfHeader = document.querySelector('meta[name=\"csrf-token-header\"]')?.content ?? 'X-CSRF-Token';"),
            "templates must dynamically resolve csrf header name: {routes}"
        );
        assert!(
            routes.contains("[csrfHeader]: csrfToken"),
            "templates must use dynamic csrf header key in fetch calls: {routes}"
        );
    }

    // ── Account lockout (issue #814) ────────────────────────────────────────

    #[test]
    fn migration_up_sql_contains_lockout_columns() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/up.sql"),
        )
        .unwrap();
        assert!(
            up.contains("failed_attempts"),
            "migration must include failed_attempts column: {up}"
        );
        assert!(
            up.contains("locked_at"),
            "migration must include locked_at column: {up}"
        );
    }

    #[test]
    fn model_file_contains_lockout_fields() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let model = fs::read_to_string(tmp.path().join("src/models/user.rs")).unwrap();
        assert!(
            model.contains("pub failed_attempts"),
            "model must include failed_attempts field: {model}"
        );
        assert!(
            model.contains("pub locked_at"),
            "model must include locked_at field: {model}"
        );
    }

    #[test]
    fn schema_rs_contains_lockout_columns() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let schema = fs::read_to_string(tmp.path().join("src/schema.rs")).unwrap();
        assert!(
            schema.contains("failed_attempts"),
            "schema must include failed_attempts: {schema}"
        );
        assert!(
            schema.contains("locked_at"),
            "schema must include locked_at: {schema}"
        );
    }

    #[test]
    fn routes_file_checks_lockout_state_on_login() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("locked_at"),
            "login handler must check locked_at for lockout: {routes}"
        );
        assert!(
            routes.contains("failed_attempts"),
            "login handler must track failed_attempts: {routes}"
        );
    }

    #[test]
    fn routes_file_lockout_response_indistinguishable_from_wrong_password() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        // Lockout must return the same auth_err closure as wrong password (non-enumerating).
        let auth_err_count = routes.matches("auth_err()").count();
        assert!(
            auth_err_count >= 2,
            "lockout must reuse auth_err() for non-enumerating response (found {auth_err_count}): {routes}"
        );
    }

    #[test]
    fn routes_file_resets_failed_attempts_on_successful_login() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("failed_attempts.eq(0)"),
            "successful login must reset failed_attempts to 0: {routes}"
        );
    }

    #[test]
    fn routes_file_emits_telemetry_event_on_lockout_transition() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("account_locked"),
            "lockout transition must emit a structured telemetry event with account_locked: {routes}"
        );
    }

    #[test]
    fn routes_file_respects_lockout_enabled_config() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        // Must check enabled flag or threshold so operators can disable lockout.
        assert!(
            routes.contains("lockout")
                && (routes.contains("enabled") || routes.contains("threshold")),
            "routes must respect lockout enabled/threshold config for opt-out: {routes}"
        );
    }

    /// #2500, #2531: one helper stamps the lock. Login and reauth both call it.
    /// The stamp is a guarded UPDATE: it needs `failed_attempts >= threshold`
    /// and `locked_at IS NULL`. The clock is read inside the helper, just
    /// before the write, never at the start of the request.
    #[test]
    fn routes_file_stamps_lock_once_through_one_guarded_helper() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();

        assert_eq!(
            routes.matches("async fn stamp_lockout(").count(),
            1,
            "expected one `stamp_lockout` helper: {routes}"
        );
        assert_eq!(
            routes.matches("stamp_lockout(&mut db").count(),
            2,
            "login and reauth must both call `stamp_lockout`: {routes}"
        );
        assert!(
            !routes.contains("locked_at.eq(Some(now))"),
            "no handler may stamp `locked_at` with its request-start `now`: {routes}"
        );
        let stamp_at = routes
            .find("locked_at.eq(Some(")
            .expect("helper must stamp locked_at");
        assert_eq!(routes.matches("locked_at.eq(Some(").count(), 1, "{routes}");
        let preceding = routes
            .get(stamp_at.saturating_sub(500)..stamp_at)
            .unwrap_or_default();
        assert!(
            preceding.contains("failed_attempts.ge(threshold)")
                && preceding.contains("locked_at.is_null()"),
            "stamp must be guarded by failed_attempts and locked_at IS NULL: {routes}"
        );
        let following = routes.get(stamp_at..stamp_at + 120).unwrap_or_default();
        assert!(
            following.contains("chrono::Utc::now().naive_utc()"),
            "stamp must read the clock inside the helper, at write time: {routes}"
        );
    }

    /// #2500, #2531: `account_locked` logs once per lock. Only the call whose
    /// UPDATE changed a row may log. Concurrent calls get `false`.
    #[test]
    fn routes_file_gates_lockout_telemetry_on_rows_actually_locked() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();

        let helper = routes
            .find("async fn stamp_lockout(")
            .expect("helper must exist");
        let body_end = routes[helper..]
            .find("\n}\n")
            .map_or(routes.len(), |e| helper + e);
        let helper_body = &routes[helper..body_end];
        assert!(
            helper_body.contains("Ok(locked_rows > 0)") && !helper_body.contains("account_locked"),
            "helper must return whether it changed a row and must not log: {helper_body}"
        );
        let call = routes
            .find("stamp_lockout(&mut db")
            .expect("login must call the helper");
        let telemetry = routes[call..]
            .find("account_locked")
            .expect("telemetry must follow the helper call");
        let between = &routes[call..call + telemetry];
        assert!(
            between.contains("if newly_locked"),
            "telemetry must sit behind `if newly_locked`: {between}"
        );
    }

    /// #2152: the `account_locked` digest salt must come from the app's
    /// configured signing secret, not an ad hoc env var chain. A deployment
    /// that sets `AUTUMN_SECURITY__SIGNING_SECRET` (the documented signing
    /// secret) — and nothing else — must not silently fall back to the
    /// public constant salt, which lets anyone holding the logs invert the
    /// digest back to an account id.
    #[test]
    fn account_locked_digest_salts_from_the_signing_secret() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();

        let digest_start = routes
            .find("let account_id_digest")
            .expect("login handler must compute account_id_digest");
        let digest_end = digest_start
            + routes[digest_start..]
                .find("hex::encode")
                .expect("account_id_digest must hex-encode the hash");
        let digest_block = &routes[digest_start..digest_end];

        assert!(
            digest_block.contains("signing_secret"),
            "account_locked digest salt must derive from \
             config.security.signing_secret: {digest_block}"
        );
        assert!(
            !digest_block.contains("SECRET_KEY_BASE")
                && !digest_block.contains("AUTUMN_ADMIN_SECRET"),
            "account_locked digest salt must not read SECRET_KEY_BASE or \
             AUTUMN_ADMIN_SECRET — AUTUMN_SECURITY__SIGNING_SECRET is the \
             documented signing secret and must be consulted instead: {digest_block}"
        );
    }

    #[test]
    fn generated_tests_cover_lockout_scenarios() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let tests = fs::read_to_string(tmp.path().join("tests/auth.rs")).unwrap();
        // AC8a: N+1 failed attempts reject correct credentials
        assert!(
            tests.contains("auth_lockout_rejects_correct_credentials"),
            "generated tests must cover: N+1 failed attempts with correct creds are rejected: {tests}"
        );
        // AC8b: successful login resets counter
        assert!(
            tests.contains("auth_successful_login_resets_lockout_counter"),
            "generated tests must cover: successful login resets counter: {tests}"
        );
        // AC8c: locked-state response byte-identical to wrong-password
        assert!(
            tests.contains("auth_lockout_response_identical_to_wrong_password"),
            "generated tests must verify lockout response is byte-identical to wrong-password: {tests}"
        );
    }

    #[test]
    fn docs_file_documents_lockout_config() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let docs = fs::read_to_string(tmp.path().join("docs/guide/authentication.md")).unwrap();
        assert!(
            docs.contains("lockout"),
            "docs must document the lockout policy: {docs}"
        );
        assert!(
            docs.contains("threshold"),
            "docs must document the threshold setting: {docs}"
        );
        assert!(
            docs.contains("cooloff") || docs.contains("cool_off") || docs.contains("cool-off"),
            "docs must document the cool-off period: {docs}"
        );
    }

    #[test]
    fn docs_file_documents_operator_unlock_path() {
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let docs = fs::read_to_string(tmp.path().join("docs/guide/authentication.md")).unwrap();
        assert!(
            docs.contains("unlock"),
            "docs must document operator unlock path: {docs}"
        );
    }

    // ── GDPR data export & account deletion (issue #820) ─────────────────────

    #[test]
    fn plan_auth_creates_data_export_route() {
        // AC#1: auth starter generates a "Download my data" route
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("data_export") || routes.contains("download_my_data"),
            "generated routes must include a data-export handler: {routes}"
        );
    }

    #[test]
    fn plan_auth_data_export_route_requires_auth() {
        // AC#1: the export route must be protected by authentication
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        // Find the data_export function and verify it extracts Auth
        let export_pos = routes
            .find("data_export")
            .expect("data_export route must be present");
        let export_body = &routes[export_pos..export_pos + 500.min(routes.len() - export_pos)];
        // Authentication is enforced either via the tracked-session gate
        // (#819) or a session/Auth extractor check.
        assert!(
            export_body.contains("require_tracked_session")
                || export_body.contains("Auth")
                || export_body.contains("auth"),
            "data_export route must require authentication: {export_body}"
        );
    }

    #[test]
    fn plan_auth_creates_delete_account_route() {
        // AC#3: auth starter generates a "Delete my account" flow
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("delete_account") || routes.contains("account_delete"),
            "generated routes must include an account-deletion handler: {routes}"
        );
    }

    #[test]
    fn plan_auth_delete_account_has_confirmation_step() {
        // AC#3: deletion flow requires a confirmation step
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("confirm") || routes.contains("confirmation"),
            "delete_account handler must include a confirmation step: {routes}"
        );
    }

    #[test]
    fn plan_auth_delete_account_writes_audit_log() {
        // AC#3: account deletion must write an audit log entry
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("audit") || routes.contains("AuditEvent"),
            "delete_account handler must write an audit log entry: {routes}"
        );
    }

    #[test]
    fn plan_auth_migration_includes_deletion_tracking_columns() {
        // AC#3: migration must include grace-period deletion tracking columns
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/up.sql"),
        )
        .unwrap();
        assert!(
            up.contains("delete_requested_at") || up.contains("deletion_requested_at"),
            "migration must include a deletion-request timestamp column: {up}"
        );
        assert!(
            up.contains("delete_scheduled_at")
                || up.contains("deletion_scheduled_at")
                || up.contains("delete_grace_until"),
            "migration must include a grace-period deadline column: {up}"
        );
    }

    #[test]
    fn plan_auth_migration_includes_export_tracking_columns() {
        // AC#1/#5: migration must include export-request tracking columns
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260508000000_create_users/up.sql"),
        )
        .unwrap();
        assert!(
            up.contains("export_requested_at") || up.contains("data_export_requested_at"),
            "migration must include an export-request timestamp column: {up}"
        );
    }

    #[test]
    fn plan_auth_creates_export_job() {
        // AC#5: auth starter generates a background export job
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/auth.rs")).unwrap();
        assert!(
            routes.contains("export_job")
                || routes.contains("ExportJob")
                || routes.contains("enqueue"),
            "generated code must enqueue a background export job: {routes}"
        );
    }

    #[test]
    fn plan_auth_gdpr_docs_file_created() {
        // AC#7: auth starter generates a GDPR compliance documentation file
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let paths: Vec<String> = plan
            .actions
            .iter()
            .map(|a| {
                a.path()
                    .strip_prefix(tmp.path())
                    .unwrap()
                    .display()
                    .to_string()
                    .replace('\\', "/")
            })
            .collect();
        assert!(
            paths
                .iter()
                .any(|p| p.contains("gdpr") || p.contains("compliance")),
            "plan must include a GDPR/compliance documentation file; got: {paths:?}"
        );
    }

    #[test]
    fn plan_auth_gdpr_docs_references_article_15_and_17() {
        // AC#7: GDPR docs must reference Article 15 (right of access) and Article 17 (erasure)
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();

        // Find the GDPR compliance docs file
        let docs_path = plan
            .actions
            .iter()
            .find(|a| {
                let path_str = a.path().to_string_lossy().to_lowercase();
                path_str.contains("gdpr") || path_str.contains("compliance")
            })
            .map(|a| a.path().to_owned())
            .expect("plan must include a GDPR/compliance documentation file");

        let content = fs::read_to_string(&docs_path).unwrap();
        assert!(
            content.contains("Article 15") || content.contains("article 15"),
            "GDPR docs must reference Article 15 (right of access): {content}"
        );
        assert!(
            content.contains("Article 17") || content.contains("article 17"),
            "GDPR docs must reference Article 17 (right to erasure): {content}"
        );
    }

    #[test]
    fn plan_auth_model_includes_delete_requested_at_field() {
        // AC#3: generated User model must include deletion tracking fields
        let tmp = project_with_main();
        let plan = plan_auth(tmp.path(), "User", "20260508000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let model = fs::read_to_string(tmp.path().join("src/models/user.rs")).unwrap();
        assert!(
            model.contains("delete_requested_at") || model.contains("deletion_requested_at"),
            "User model must include deletion tracking field: {model}"
        );
    }
}