autumn-cli 0.5.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
//! `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 destroys the session (old session cannot remain authenticated).

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, append_schema_table, schema_has_table, update_main_rs,
};
use super::{Flags, GenerateError, ensure_project_root, 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.10\", features = [] }"),
    ("hex", "\"0.4\""),
    ("rand", "{ version = \"0.9\", features = [\"os_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 0.5.
const PASSKEY_EXTRA_DEPS: &[(&str, &str)] = &[
    (
        "webauthn-rs",
        "{ version = \"0.5\", features = [\"danger-allow-state-serialisation\", \"conditional-ui\"] }",
    ),
    ("uuid", "{ version = \"1\", features = [\"v4\"] }"),
];

/// 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.
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 = line.find("features = [")?;
        let list_start = feat_bracket + "features = [".len();
        let close_off = line[list_start..].find(']')?;
        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.5");
            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 !trimmed.contains("features = [") {
                // 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 let Some(new_line) = merge_missing(&t) {
                        lines[j] = format!("{ind2}{new_line}");
                    }
                    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.10\""),
    ("base64", "\"0.22\""),
];

/// `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 = line.find(bracket_search)?;
        let list_start = feat_bracket + bracket_search.len();
        let close_off = line[list_start..].find(']')?;
        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 tj.contains(']') {
                    // 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.
                    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 lines[k].contains(']') {
                            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 = lines[fl][fl_bracket + 1..].to_owned();
                        for line in &lines[fl + 1..cl] {
                            list_text.push(' ');
                            list_text.push_str(line.trim());
                        }
                        let cl_close = lines[cl].find(']').unwrap_or(lines[cl].len());
                        list_text.push(' ');
                        list_text.push_str(&lines[cl][..cl_close]);
                        let trailing =
                            lines[cl][cl_close.saturating_add(1).min(lines[cl].len())..].to_owned();

                        let mut entries: Vec<String> = list_text
                            .split(',')
                            .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)
}

#[allow(clippy::too_many_lines)]
pub fn plan_auth_with_providers(
    project_root: &Path,
    name: &str,
    timestamp: &str,
    providers: &[String],
    totp: bool,
) -> Result<Plan, GenerateError> {
    ensure_project_root(project_root)?;
    super::model::validate_resource_name(name)?;

    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(),
        ));
    }

    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(&snake_name, &table, totp),
    );
    plan.create(
        mig_dir.join("down.sql"),
        render_migration_down(&snake_name, &table, totp),
    );

    // ── 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),
    );
    model_mod = add_mod_declaration(&model_mod, &format!("{snake_name}_session"));
    plan.modify(model_mod_path, model_mod);

    // ── 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", "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("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.
    if totp && schema_has_table(&schema_existing, "recovery_codes") {
        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."
            ),
        ));
    }
    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);
    plan.modify(schema_path, schema_new);

    // ── 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),
    );
    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"),
    );

    // ── Generated tests ────────────────────────────────────────────────────
    let tests_dir = project_root.join("tests");
    plan.create(
        tests_dir.join("auth.rs"),
        render_tests_file(&pascal_name, &snake_name),
    );
    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(&pascal_name, totp),
    );
    plan.create(docs_dir.join("gdpr-compliance.md"), render_gdpr_docs_file());
    plan.create(
        docs_dir.join("session-management.md"),
        render_sessions_docs_file(&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);
    let updated = update_main_rs(&main_existing, &["models", "routes", "schema"], &entries);
    plan.modify(main_path, updated);

    // ── 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();
    // 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, final_cargo);
    }

    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)
}

/// 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)
}

/// 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)
}

/// Shared implementation: base (optionally TOTP-aware, optionally passkey-aware)
/// scaffold plus, when providers are supplied, the OAuth artifacts.
#[allow(clippy::too_many_lines)]
fn plan_auth_options_impl(
    project_root: &Path,
    name: &str,
    timestamp: &str,
    oauth: &AuthOAuthOptions,
    totp: bool,
    passkeys: bool,
) -> Result<Plan, GenerateError> {
    // Start with the base auth plan with providers (and optional TOTP) applied.
    let mut plan = plan_auth_with_providers(project_root, name, timestamp, &oauth.providers, totp)?;

    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(&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, updated_schema);

        // ── 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, updated_route_mod);

        // ── 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, updated_main);

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

        // ── 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, with_oauth2);
        }

        // ── 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, updated_toml);
            }
        }
    }

    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.
        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") {
            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(&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,
            add_mod_declaration(&model_mod_base, "webauthn_credential"),
        );

        // ── 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, updated_schema);

        // ── 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,
            add_mod_declaration(&route_mod_base, "passkeys"),
        );

        // ── 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, updated_main);

        // ── 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, updated_toml);
            }
        }

        // ── 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();
        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, with_webauthn);
        }
    }

    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)
        .map(|a| match a {
            Action::Create { contents, .. } | Action::Modify { contents, .. } => contents.clone(),
        })
}

/// Ensure `autumn-web` in `[dependencies]` has `features = ["oauth2"]`.
#[allow(clippy::too_many_lines)]
fn ensure_autumn_web_oauth2_feature(toml: &str) -> String {
    const CRATE: &str = "autumn-web";
    const FEATURE: &str = "\"oauth2\"";

    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) {
            if trimmed.contains(FEATURE) {
                break; // already present
            }
            if let Some(feat_bracket) = trimmed.find("features = [") {
                let list_start = feat_bracket + "features = [".len();
                if let Some(close_bracket) = trimmed[list_start..].find(']') {
                    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 {
                    let mut j = i + 1;
                    while j < lines.len() {
                        let tj = lines[j].trim();
                        if tj.starts_with('[') {
                            break;
                        }
                        if let Some(close_idx) = tj.find(']') {
                            let before_close = tj[..close_idx].trim();
                            let sep = if before_close.is_empty() || before_close.ends_with(',') {
                                ""
                            } else {
                                ", "
                            };
                            let indent_j: String = lines[j]
                                .chars()
                                .take_while(char::is_ascii_whitespace)
                                .collect();
                            lines[j] = format!(
                                "{indent_j}{before_close}{sep}{FEATURE}{}",
                                &tj[close_idx..]
                            );
                            break;
                        }
                        j += 1;
                    }
                }
            } 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;
        }

        if trimmed == subtable_header || trimmed == subtable_header_underscore {
            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;
                    if t.contains(FEATURE) {
                        break;
                    }
                    if let Some(open) = t.find('[') {
                        if let Some(close) = t.rfind(']') {
                            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 {
                            let mut k = j + 1;
                            while k < lines.len() {
                                let tk = lines[k].trim();
                                if tk.starts_with('[') {
                                    break;
                                }
                                if let Some(close_idx) = tk.find(']') {
                                    let before_close = tk[..close_idx].trim();
                                    let sep =
                                        if before_close.is_empty() || before_close.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;
                                }
                                k += 1;
                            }
                        }
                    }
                    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
}

/// 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);
        }
    }
}

fn read_or_empty(path: &Path) -> String {
    std::fs::read_to_string(path).unwrap_or_default()
}

/// Ensure `autumn-web` in `[dependencies]` has `features = ["mail"]`.
///
/// 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
fn ensure_autumn_web_mail_feature(toml: &str) -> String {
    const CRATE: &str = "autumn-web";
    const FEATURE: &str = "\"mail\"";

    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 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) {
            // autumn-web = "0.3"
            let version = rest.trim_end_matches('"');
            lines[i] =
                format!("{indent}{CRATE} = {{ version = \"{version}\", features = [{FEATURE}] }}");
            break;
        }

        if trimmed.starts_with(&table_prefix) {
            if trimmed.contains(FEATURE) {
                break; // already present
            }
            if let Some(feat_bracket) = trimmed.find("features = [") {
                // Add to existing features list.
                let list_start = feat_bracket + "features = [".len();
                let list_end = trimmed[list_start..].find(']').unwrap() + 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 {
                // No features key — insert before closing `}`.
                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;
        }

        if trimmed == subtable_header {
            // Scan ahead within the subtable.
            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;
                    if !t.contains(FEATURE)
                        && let (Some(open), Some(close)) = (t.find('['), t.rfind(']'))
                    {
                        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}]");
                    }
                    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
}

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;
        }
        let preset = match name.as_str() {
            "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"
"#
            }
            "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"
"#
            }
            "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"
"#
            }
            _ => &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"
"#
            ),
        };
        out.push('\n');
        out.push_str(preset.trim_start());
    }
    out.push('\n');
    out
}

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

/// 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")
}

fn render_migration_up(snake_name: &str, table: &str, totp: bool) -> String {
    // 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 {
        "\x20   totp_secret_encrypted TEXT NULL,\n\
         \x20   totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,\n\
         \x20   totp_last_used_step BIGINT NULL,\n"
    } else {
        ""
    };
    let mut out = format!(
        "CREATE TABLE {table} (\n\
         \x20   id BIGSERIAL PRIMARY KEY,\n\
         \x20   email TEXT NOT NULL UNIQUE,\n\
         \x20   password_digest TEXT NOT NULL,\n\
         {totp_columns}\
         \x20   failed_attempts INT NOT NULL DEFAULT 0,\n\
         \x20   locked_at TIMESTAMP NULL,\n\
         \x20   reset_token_digest TEXT NULL,\n\
         \x20   reset_token_expires_at TIMESTAMP NULL,\n\
         \x20   confirm_token_digest TEXT NULL,\n\
         \x20   confirm_token_expires_at TIMESTAMP NULL,\n\
         \x20   email_confirmed_at TIMESTAMP NULL,\n\
         \x20   export_requested_at TIMESTAMP NULL,\n\
         \x20   delete_requested_at TIMESTAMP NULL,\n\
         \x20   delete_scheduled_at TIMESTAMP NULL,\n\
         \x20   created_at TIMESTAMP NOT NULL DEFAULT NOW()\n\
         );\n"
    );
    if totp {
        out.push_str(
            "\n\
             CREATE TABLE recovery_codes (\n\
             \x20   id BIGSERIAL PRIMARY KEY,\n\
             \x20   user_id BIGINT NOT NULL REFERENCES ",
        );
        out.push_str(table);
        out.push_str(
            "(id) ON DELETE CASCADE,\n\
             \x20   code_digest TEXT NOT NULL,\n\
             \x20   used_at TIMESTAMP NULL,\n\
             \x20   created_at TIMESTAMP NOT NULL DEFAULT NOW()\n\
             );\n\
             \n\
             CREATE INDEX recovery_codes_user_id_idx ON recovery_codes (user_id);\n",
        );
    }
    // 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 sess_table = sessions_table_name(snake_name);
    let _ = write!(
        out,
        "\n\
         CREATE TABLE {sess_table} (\n\
         \x20   id BIGSERIAL PRIMARY KEY,\n\
         \x20   user_id BIGINT NOT NULL REFERENCES {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 TIMESTAMP NOT NULL DEFAULT NOW(),\n\
         \x20   created_at TIMESTAMP NOT NULL DEFAULT NOW()\n\
         );\n\
         \n\
         CREATE INDEX {sess_table}_user_id_idx ON {sess_table} (user_id);\n",
    );
    out
}

fn render_migration_down(snake_name: &str, table: &str, totp: bool) -> String {
    // Drop the dependent tables first so the FK constraints are satisfied.
    let sess_table = sessions_table_name(snake_name);
    if totp {
        format!("DROP TABLE {sess_table};\nDROP TABLE recovery_codes;\nDROP TABLE {table};\n")
    } else {
        format!("DROP 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 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>,
    #[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 = diesel::pg::Pg>,
    ) -> 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 = diesel::pg::Pg>,
        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 = diesel::pg::Pg>,
        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 = diesel::pg::Pg>,
    ) -> 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}}"
                ))
            }})
    }}
}}
"#
    )
}

#[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,
) -> String {
    let sess_table = sessions_table_name(snake_name);
    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),
            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 destroys the session so the old session cannot remain authenticated.
//! - 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::{{hash_password, verify_password}};
use autumn_web::extract::Query;
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::schema::{sess_table};
use crate::schema::{table};
{totp_imports}

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

fn layout(title: &str, content: Markup) -> Markup {{
    html! {{
        (autumn_web::PreEscaped("<!DOCTYPE html>"))
        html lang="en" {{
            head {{
                meta charset="utf-8";
                title {{ (title) }}
            }}
            body {{ (content) }}
        }}
    }}
}}

fn redirect_to(url: &str) -> Response {{
    axum::response::Redirect::to(url).into_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."))?;

    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({snake_name}_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.
    let sessions_cfg = state.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.
fn sessions_list_fragment(
    sessions: &[{pascal_name}Session],
    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() {{
                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());
                            }}
                            input type="text" name="label" placeholder="Device label"
                                value=[s.label.as_deref()];
                            button type="submit" {{ "Save label" }}
                        }}
                    }}
                }}
            }}
            // 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?;
    Ok(
        sessions_list_fragment(&sessions, &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 fragment =
        sessions_list_fragment(&sessions, &current_digest, csrf.as_ref(), csrf_field.as_ref());
    if hx.is_htmx {{
        return Ok(fragment.into_response());
    }}
    Ok(layout("Active Sessions", 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. \
             Revoke any session you don't recognise — that device is signed \
             out immediately."
        }}
        (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/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?;
    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 ────────────────────────────────────────────────────────────────────

/// `GET /signup` — render the signup form.
#[get("/signup")]
pub async fn signup_form(csrf: Option<CsrfToken>, csrf_field: Option<CsrfFormField>) -> AutumnResult<Markup> {{
    Ok(layout("Sign Up", html! {{
        h1 {{ "Create an Account" }}
        form action="/signup" 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 {{ "Email" }}
                input type="email" name="email" required autocomplete="email";
            }}
            div {{
                label {{ "Password (8+ characters)" }}
                input type="password" name="password" required
                      autocomplete="new-password" minlength="8";
            }}
            button type="submit" {{ "Sign Up" }}
        }}
        p {{ a href="/login" {{ "Already have an account? Log in" }} }}
    }}))
}}

#[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(
    mut db: Db,
    mailer: Mailer,
    session: Session,
    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());
    }}
    if form.password.len() < 8 {{
        return Err(AutumnError::unprocessable_msg(
            "Password must be at least 8 characters.",
        ));
    }}

    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(),
        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.",
        ));
    }}

    Ok(redirect_to("/check-your-email"))
}}

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

/// `GET /login` — render the login form.
#[get("/login")]
pub async fn login_form(csrf: Option<CsrfToken>, csrf_field: Option<CsrfFormField>) -> AutumnResult<Markup> {{
    Ok(layout("Log In", 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 {{ "Email" }}
                input type="email" name="email" required autocomplete="email";
            }}
            div {{
                label {{ "Password" }}
                input type="password" name="password" required
                      autocomplete="current-password";
            }}
            button type="submit" {{ "Log In" }}
        }}
        {oauth_buttons}
        p {{ a href="/signup" {{ "New here? Create an account" }} }}
        p {{ a href="/forgot-password" {{ "Forgot your password?" }} }}
        p {{ a href="/auth/confirm/resend" {{ "Resend confirmation email" }} }}
    }}))
}}

#[derive(Deserialize)]
pub struct LoginForm {{
    pub email: String,
    pub password: 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))
    }}
}}

/// `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,
    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.
    let lockout_cfg = state.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() {{
                    // Account transitions into the locked state — stamp locked_at
                    // atomically. Propagate errors: if this write fails the account
                    // is not locked despite the counter crossing the threshold, which
                    // would allow a successful login to slip through.
                    diesel::update({table}::table.find({snake_name}.id))
                        .set({table}::locked_at.eq(Some(now)))
                        .execute(&mut *db)
                        .await
                        .map_err(|e| AutumnError::internal_server_error_msg(&format!("Failed to lock account: {{e}}")))?;

                    // 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 deployment secret so the
                    // account ID cannot be recovered by hashing small integers.
                    let account_id_digest = {{
                        use sha2::{{Digest, Sha256}};
                        // Require a deployment secret for the digest salt. Operators
                        // MUST set SECRET_KEY_BASE (already required for sessions) or
                        // AUTUMN_ADMIN_SECRET. The static fallback prevents reversibility
                        // only within this process; set the env var in production.
                        let salt = std::env::var("SECRET_KEY_BASE")
                            .or_else(|_| std::env::var("AUTUMN_ADMIN_SECRET"))
                            .unwrap_or_else(|_| "autumn-lockout-fallback-salt".to_string());
                        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?;
    Ok(redirect_to("/account"))
}}

// ── 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, mut db: Db) -> AutumnResult<Response> {{
    // Best-effort: the device must sign out even if the row delete hiccups.
    let _ = untrack_current_session(&mut db, &session).await;
    session.destroy().await;
    Ok(redirect_to("/login"))
}}

// ── 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(layout("Account Unlocked", 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, 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(layout("Your Account", 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/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())
}}

// ── 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(layout("Confirm your identity", 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);
            div {{
                label {{ "Password" }}
                input type="password" name="password" autocomplete="current-password" required;
            }}
            {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| {{
            layout("Confirm your identity", 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);
                    div {{
                        label {{ "Password" }}
                        input type="password" name="password" autocomplete="current-password" required;
                    }}
                    {totp_reauth_field}
                    button type="submit" {{ "Confirm" }}
                }}
            }}).into_response()
        }};

        // ── Account lockout policy ──────────────────────────────────────────
        let lockout_cfg = state.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() {{
                    diesel::update({table}::table.find({snake_name}.id))
                        .set({table}::locked_at.eq(Some(now)))
                        .execute(&mut *db)
                        .await
                        .map_err(|e| AutumnError::internal_server_error_msg(&format!("Failed to lock account: {{e}}")))?;
                }}
                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(layout("Forgot Password", 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 {{ "Email" }}
                input type="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(layout("Check Your Email", 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,
}}

/// `GET /reset-password?token=<raw>` — render the reset-password form.
#[get("/reset-password")]
pub async fn reset_password_form(
    Query(query): Query<ResetPasswordQuery>,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Markup> {{
    Ok(layout("Reset Password", html! {{
        h1 {{ "Set a New Password" }}
        form action="/reset-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()); }}
            input type="hidden" name="token" value=(query.token);
            div {{
                label {{ "New Password (8+ characters)" }}
                input type="password" name="password" required
                      autocomplete="new-password" minlength="8";
            }}
            button type="submit" {{ "Set New Password" }}
        }}
    }}))
}}

#[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,
    Form(form): Form<ResetPasswordForm>,
) -> AutumnResult<Response> {{
    if form.password.len() < 8 {{
        return Err(AutumnError::unprocessable_msg(
            "Password must be at least 8 characters.",
        ));
    }}

    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().auth.sessions.revoke_on_credential_change;
    let {snake_name}_id = {snake_name}.id;
    (*db)
        .transaction::<_, diesel::result::Error, _>(|conn| {{
            Box::pin(async move {{
                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?;
                }}
                diesel::insert_into({sess_table}::table)
                    .values(&new_session_row)
                    .execute(conn)
                    .await?;
                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::TryRngCore;
    let mut bytes = [0u8; 32];
    rand::rngs::OsRng
        .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() -> AutumnResult<Markup> {{
    Ok(layout("Check Your Email", 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)),
    )
    .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(layout("Resend Confirmation Email", 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 {{ "Email" }}
                input type="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(layout("Confirmation Email Sent", 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::TryRngCore;
    let mut bytes = [0u8; 32];
    rand::rngs::OsRng
        .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(layout("Download My Data", 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(layout("Export Already Pending", 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(layout("Export Requested", 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(layout("Delete My Account", 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(layout("Delete My Account", 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(layout("Deletion Scheduled", 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}"##
    )
}

#[allow(clippy::too_many_lines)]
fn render_tests_file(pascal_name: &str, _snake_name: &str) -> String {
    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
}}

#[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}}"
    );
}}

/// AC9 — changing an email address on an existing account re-enters the
/// unconfirmed state for the new address and keeps the old address valid for
/// sign-in until the new address is confirmed.
///
/// This test documents the contract; the email-change flow is scaffolded via
/// the account settings page. See docs/guide/authentication.md for the
/// customization point documentation.
#[test]
fn email_change_reenters_unconfirmed() {{
    let Some(base) = base_url() else {{
        eprintln!("skipping: AUTUMN_TEST_BASE_URL not set");
        return;
    }};
    // Verify the resend endpoint accepts POST and returns a sensible response
    // (full email-change flow requires an authenticated session and SMTP).
    let resp = get(&base, "/auth/confirm/resend");
    assert!(
        resp.contains("HTTP/1.1 200") || resp.contains("HTTP/1.0 200"),
        "GET /auth/confirm/resend must return 200:\n{{resp}}"
    );
}}
"#
    )
}

#[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(pascal_name: &str, snake_name: &str, user_table: &str) -> String {
    let sess_table = sessions_table_name(snake_name);
    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 < NOW() - INTERVAL '90 days';
  ```

  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
CREATE TABLE {sess_table} (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL REFERENCES {user_table}(id) ON DELETE CASCADE,
    token_digest TEXT NOT NULL UNIQUE,
    ip TEXT NOT NULL DEFAULT '',
    user_agent TEXT NOT NULL DEFAULT '',
    ua_family TEXT NOT NULL DEFAULT '',
    ua_os TEXT NOT NULL DEFAULT '',
    ua_device TEXT NOT NULL DEFAULT '',
    label TEXT NULL,
    last_seen_at TIMESTAMP NOT NULL DEFAULT NOW(),
    created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX {sess_table}_user_id_idx ON {sess_table} (user_id);
```

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(pascal_name: &str, totp: bool) -> String {
    let totp_docs = if totp { TOTP_DOCS_SECTION } else { "" };
    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 `OsRng`; 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 calls `session.destroy()` so an old session
  cookie cannot be replayed.
- **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).
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
ALTER TABLE {{table}}
  ADD COLUMN IF NOT EXISTS failed_attempts INT NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS locked_at TIMESTAMP NULL;
```

```sql
-- migrations/<timestamp>_add_lockout_to_{{table}}/down.sql
ALTER TABLE {{table}}
  DROP COLUMN IF EXISTS failed_attempts,
  DROP COLUMN IF EXISTS locked_at;
```

```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
ALTER TABLE {{table}}
  ADD COLUMN IF NOT EXISTS confirm_token_digest TEXT NULL,
  ADD COLUMN IF NOT EXISTS confirm_token_expires_at TIMESTAMP NULL,
  ADD COLUMN IF NOT EXISTS email_confirmed_at TIMESTAMP NULL;
```

```sql
-- migrations/<timestamp>_add_email_confirmation_to_{{table}}/down.sql
ALTER TABLE {{table}}
  DROP COLUMN IF EXISTS confirm_token_digest,
  DROP COLUMN IF EXISTS confirm_token_expires_at,
  DROP COLUMN IF EXISTS email_confirmed_at;
```

```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 = 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}## 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) -> 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::sessions_page".to_owned(),
        "routes::auth::sessions_revoke".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(),
        ]);
    }
    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(user_table: &str) -> String {
    format!(
        "CREATE TABLE oauth_identities (\n\
         \x20   id BIGSERIAL PRIMARY KEY,\n\
         \x20   provider TEXT NOT NULL,\n\
         \x20   subject TEXT NOT NULL,\n\
         \x20   user_id BIGINT NOT NULL REFERENCES {user_table}(id) ON DELETE CASCADE,\n\
         \x20   email TEXT NULL,\n\
         \x20   name TEXT NULL,\n\
         \x20   created_at TIMESTAMP NOT NULL DEFAULT NOW(),\n\
         \x20   UNIQUE (provider, subject)\n\
         );\n\
         \n\
         CREATE INDEX oauth_identities_user_id_idx ON oauth_identities (user_id);\n"
    )
}

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();
    }}

    let auth_cfg = state.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();
    }}

    let auth_cfg = state.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(providers: &[String]) -> String {
    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         BIGSERIAL PRIMARY KEY,
    provider   TEXT NOT NULL,
    subject    TEXT NOT NULL,         -- provider's user identifier (sub / id)
    user_id    BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    email      TEXT NULL,
    name       TEXT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    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),
    )
}

// ── 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 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 {{ \"Authenticator code\" }}\n\
     \x20               input type=\"text\" name=\"totp_code\" autocomplete=\"one-time-code\"\n\
     \x20                   inputmode=\"text\" pattern=\"[0-9a-fA-F \\\\-]*\" placeholder=\"6-digit code or recovery code\";\n\
     \x20               small {{ \"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(layout("Confirm your identity", 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 {{ "Authenticator code" }}
                        input type="text" name="totp_code" autocomplete="one-time-code"
                            inputmode="numeric" pattern="[0-9 ]*" required
                            placeholder="6-digit code or recovery code";
                        small {{ "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(layout("Confirm your identity", 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 {{ "Authenticator code" }}
                        input type="text" name="totp_code" autocomplete="one-time-code"
                            inputmode="numeric" pattern="[0-9 ]*" required
                            placeholder="6-digit code or recovery code";
                        small {{ "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) -> 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::TryRngCore;
    let key = totp_enc_key()?;
    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&key));
    let mut nonce_bytes = [0u8; 12];
    rand::rngs::OsRng
        .try_fill_bytes(&mut nonce_bytes)
        .map_err(|_| AutumnError::internal_server_error_msg("RNG failure generating nonce"))?;
    let nonce = Nonce::from_slice(&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_slice(&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::from_slice(nonce_bytes);
    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::TryRngCore;
    let mut bytes = [0u8; 5];
    rand::rngs::OsRng
        .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(layout("Two-Factor Authentication", 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()); }
                p {
                    label { "Confirm with your password or a current 6-digit code:" }
                    input type="password" name="password" autocomplete="current-password";
                    input type="text" name="code" inputmode="numeric" autocomplete="one-time-code";
                }
                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()); }
                p {
                    label { "Confirm your password to begin enrollment:" }
                    input type="password" name="password" autocomplete="current-password" required;
                }
                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(layout("Enable Two-Factor", 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()); }
            input type="text" name="code" inputmode="numeric" autocomplete="one-time-code" 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().auth.sessions.revoke_on_credential_change;
    let current_token_digest = session_token_digest(&session).await;
    let txn_result = (*db)
        .transaction::<_, diesel::result::Error, _>(|conn| {
        Box::pin(async move {
            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(layout("Save Your Recovery Codes", 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().auth.sessions.revoke_on_credential_change;
    let current_token_digest = session_token_digest(&session).await;
    (*db)
        .transaction::<_, diesel::result::Error, _>(|conn| {
            Box::pin(async move {
                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?;
                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(layout("Two-Factor Verification", 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 { "Authentication code or recovery code" }
                input type="text" 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().auth.sessions.revoke_on_credential_change;
            let user_id = __SNAKE__.id;
            (*db)
                .transaction::<_, diesel::result::Error, _>(|conn| {
                    Box::pin(async move {
                        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?;
                        }
                        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)))
}
"#;
    TPL.replace("__PASCAL__", pascal_name)
        .replace("__SNAKE__", snake_name)
        .replace("__TABLE__", table)
        .replace("__SESSTABLE__", &sessions_table_name(snake_name))
}

/// 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.

"#;

/// 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(user_table: &str) -> String {
    format!(
        "CREATE TABLE webauthn_credentials (\n\
         \x20   id BIGSERIAL PRIMARY KEY,\n\
         \x20   user_id BIGINT 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 TIMESTAMP NOT NULL DEFAULT NOW(),\n\
         \x20   last_used_at TIMESTAMP NULL\n\
         );\n\
         \n\
         CREATE INDEX webauthn_credentials_user_id_idx ON webauthn_credentials (user_id);\n"
    )
}

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,
    pub created_at: chrono::NaiveDateTime,
    #[default]
    pub last_used_at: Option<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 diesel::prelude::*;
use diesel_async::AsyncConnection as _;
use diesel_async::RunQueryDsl;
use serde::{Deserialize, Serialize};
use webauthn_rs::prelude::*;

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

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

fn build_webauthn(state: &AppState) -> AutumnResult<Webauthn> {
    let cfg = &state.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 = passkey.cred_id().to_string();
    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().auth.sessions.revoke_on_credential_change;
    let current_token_digest = crate::routes::auth::session_token_digest(&session).await;
    (*db)
        .transaction::<_, diesel::result::Error, _>(|conn| {
            Box::pin(async move {
                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 = auth_result.cred_id().to_string();
    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<impl IntoResponse> {
    // 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().auth.sessions.revoke_on_credential_change;
    let current_token_digest = crate::routes::auth::session_token_digest(&session).await;
    (*db)
        .transaction::<_, diesel::result::Error, _>(|conn| {
            Box::pin(async move {
                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"]`.
#[allow(clippy::too_many_lines)]
fn ensure_autumn_web_webauthn_feature(toml: &str) -> String {
    const CRATE: &str = "autumn-web";
    const FEATURE: &str = "\"webauthn\"";

    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) {
            if trimmed.contains(FEATURE) {
                break; // already present
            }
            if let Some(feat_bracket) = trimmed.find("features = [") {
                let list_start = feat_bracket + "features = [".len();
                if let Some(close_bracket) = trimmed[list_start..].find(']') {
                    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 {
                    let mut j = i + 1;
                    while j < lines.len() {
                        let tj = lines[j].trim();
                        if tj.starts_with('[') {
                            break;
                        }
                        if let Some(close_idx) = tj.find(']') {
                            let before_close = tj[..close_idx].trim();
                            let sep = if before_close.is_empty() || before_close.ends_with(',') {
                                ""
                            } else {
                                ", "
                            };
                            let indent_j: String = lines[j]
                                .chars()
                                .take_while(char::is_ascii_whitespace)
                                .collect();
                            lines[j] = format!(
                                "{indent_j}{before_close}{sep}{FEATURE}{}",
                                &tj[close_idx..]
                            );
                            break;
                        }
                        j += 1;
                    }
                }
            } else {
                // No features key — insert before closing `}`.
                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;
        }

        if trimmed == subtable_header || trimmed == subtable_header_underscore {
            // Scan ahead within the subtable.
            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;
                    if !t.contains(FEATURE)
                        && let (Some(open), Some(close)) = (t.find('['), t.rfind(']'))
                    {
                        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}]");
                    }
                    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
}

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
}

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

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

    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"),
            "use autumn_web::prelude::*;\n\n\
             #[autumn_web::main]\n\
             async fn main() {\n\
             \x20   autumn_web::app().routes(routes![]).run().await;\n\
             }\n",
        )
        .unwrap();
        tmp
    }

    // ── 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 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();
        assert!(
            routes.contains("session.destroy"),
            "logout must destroy the session: {routes}"
        );
    }

    #[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);
        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"
        );
    }

    // ── 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}"
        );
    }

    #[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"
        );
    }

    #[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 + 4000.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 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 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("impl IntoResponse"),
            "redirect_to must return impl IntoResponse: {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}"
        );
    }

    #[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}"
        );
    }
}