lific 2.8.0

Local-first, lightweight issue tracker. Single binary, SQLite-backed, MCP-native.
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
use std::{net::SocketAddr, sync::Arc};

use axum::{
    Router,
    extract::{ConnectInfo, DefaultBodyLimit, Json, Query, State},
    http::{HeaderMap, StatusCode},
    response::{Html, IntoResponse, Redirect, Response},
    routing::{get, post},
};
use hmac::{Hmac, Mac};
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::db::models::AuthUser;
use tracing::{info, warn};

use crate::auth::{hex_encode, sha256_hex};
use crate::db::DbPool;
use crate::error::LificError;
use crate::ratelimit::RateLimiter;

type HmacSha256 = Hmac<Sha256>;

const MAX_OAUTH_BODY_BYTES: usize = 64 * 1024;
const MAX_CLIENT_NAME_BYTES: usize = 128;
const MAX_REDIRECT_URIS: usize = 8;
const MAX_REDIRECT_URI_BYTES: usize = 2048;
// Leave room for JSON quotes, separators, and escaping around the maximum
// number and size of redirect URIs.
const MAX_REDIRECT_METADATA_BYTES: usize = 32 * 1024;
const DYNAMIC_CLIENT_RETENTION_DAYS: i64 = 7;
const MAX_DYNAMIC_CLIENT_ROWS: i64 = 1024;
const MAX_DYNAMIC_CLIENT_STORAGE_BYTES: i64 = 4 * 1024 * 1024;
const MAX_DEVICE_CODE_ROWS: i64 = 1024;

/// Per-process CSRF secret, generated randomly on startup.
static CSRF_SECRET: std::sync::LazyLock<[u8; 32]> = std::sync::LazyLock::new(rand::random);

/// Generate a CSRF token bound to the approving session: `timestamp.hmac(ts || binding)`.
///
/// SECURITY: the token MUST be bound to the credential (`binding`) the request
/// carries. The authorize page is served unauthenticated (`GET /oauth/authorize`),
/// so an attacker can freely mint a token there; without binding, that harvested
/// token would validate against a *victim's* cross-site POST, defeating the whole
/// defense. Binding to the session means a token minted with no/attacker session
/// (`binding=""` or the attacker's own) won't validate against the victim's
/// session presented on the forged POST. `binding` is HMAC *input*, never echoed,
/// so passing the raw session token here does not leak it.
fn generate_csrf_token(binding: &str) -> String {
    let ts = chrono::Utc::now().timestamp();
    let mut mac = HmacSha256::new_from_slice(&*CSRF_SECRET).unwrap();
    mac.update(ts.to_le_bytes().as_ref());
    mac.update(b".");
    mac.update(binding.as_bytes());
    let sig = hex_encode(&mac.finalize().into_bytes());
    format!("{ts}.{sig}")
}

/// Validate a CSRF token against the binding it must have been issued for.
/// Returns true only if the HMAC matches AND the token is not older than 10 minutes.
fn validate_csrf_token(token: &str, binding: &str) -> bool {
    let Some((ts_str, sig)) = token.split_once('.') else {
        return false;
    };
    let Ok(ts) = ts_str.parse::<i64>() else {
        return false;
    };
    // Check expiry (10 minutes)
    let now = chrono::Utc::now().timestamp();
    if now - ts > 600 || ts > now + 60 {
        return false;
    }
    // Verify HMAC over (timestamp || binding). LIF-208: use the MAC's own
    // constant-time `verify_slice` rather than `expected == sig` on the hex
    // strings, which short-circuits on the first mismatched byte and leaks a
    // timing oracle. Decode the presented hex first; malformed hex is a reject.
    let Ok(sig_bytes) = hex_decode(sig) else {
        return false;
    };
    let mut mac = HmacSha256::new_from_slice(&*CSRF_SECRET).unwrap();
    mac.update(ts.to_le_bytes().as_ref());
    mac.update(b".");
    mac.update(binding.as_bytes());
    mac.verify_slice(&sig_bytes).is_ok()
}

struct AuthorizationRequest<'a> {
    client_id: &'a str,
    redirect_uri: &'a str,
    response_type: &'a str,
    state: Option<&'a str>,
    code_challenge: Option<&'a str>,
    code_challenge_method: Option<&'a str>,
    scope: Option<&'a str>,
}

impl AuthorizationRequest<'_> {
    fn csrf_binding(&self, session: &str) -> String {
        let mut binding = String::new();
        for value in [
            Some(session),
            Some(self.client_id),
            Some(self.redirect_uri),
            Some(self.response_type),
            self.state,
            self.code_challenge,
            self.code_challenge_method,
            self.scope,
        ] {
            let value = value.unwrap_or_default();
            binding.push_str(&value.len().to_string());
            binding.push(':');
            binding.push_str(value);
        }
        binding
    }

    fn csrf_token(&self, session: &str) -> String {
        generate_csrf_token(&self.csrf_binding(session))
    }

    fn validates_csrf_token(&self, token: &str, session: &str) -> bool {
        validate_csrf_token(token, &self.csrf_binding(session))
    }
}

/// Extract the session credential a browser would present: the `Authorization:
/// Bearer` header first, then the `lific_token` cookie. Returns an empty string
/// when neither is present, so the CSRF binding is still well-defined for the
/// unauthenticated case. Used to bind a CSRF token to its session both when the
/// authorize page is rendered and when the approval is submitted.
fn session_credential(headers: &HeaderMap) -> String {
    headers
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .map(|s| s.trim().to_string())
        .or_else(|| {
            headers
                .get("cookie")
                .and_then(|v| v.to_str().ok())
                .and_then(|cookies| {
                    cookies.split(';').find_map(|c| {
                        c.trim()
                            .strip_prefix("lific_token=")
                            .map(|v| v.trim().to_string())
                    })
                })
        })
        .unwrap_or_default()
}

fn authenticated_user_id(db: &DbPool, headers: &HeaderMap) -> Option<i64> {
    let token = session_credential(headers);
    token.starts_with("lific_sess_").then_some(())?;
    db.read()
        .ok()
        .and_then(|conn| crate::db::queries::users::validate_session(&conn, &token).ok())
        .map(|user| user.id)
}

fn authenticated_user_identity(db: &DbPool, headers: &HeaderMap) -> Option<String> {
    authenticated_user_id(db, headers).and_then(|user_id| user_identity(db, user_id))
}

fn device_confirmation_token(session: &str, user_code: &str) -> String {
    generate_csrf_token(&format!("device-confirmation:{session}:{user_code}"))
}

fn validate_device_confirmation_token(token: &str, session: &str, user_code: &str) -> bool {
    validate_csrf_token(token, &format!("device-confirmation:{session}:{user_code}"))
}

#[derive(Clone)]
pub struct OAuthState {
    pub db: DbPool,
    pub issuer: String, // e.g. https://lific.example.com/lific
    /// True when the issuer comes from an explicit `server.public_url`.
    /// An explicit issuer is advertised as-is; request-derived fallback
    /// (LIF-287) only applies when this is false.
    pub issuer_is_explicit: bool,
    /// Hostnames this server considers its own (the same allowlist the MCP
    /// DNS-rebinding check uses). Used to gate Host-derived issuer fallback.
    pub allowed_hosts: Arc<[String]>,
    /// Per-IP rate limiter for the unauthenticated /oauth/register endpoint.
    /// Prevents anyone from flooding the server with throwaway clients.
    pub register_limiter: Arc<RateLimiter>,
    /// Trusted reverse-proxy ranges parsed once at server startup.
    pub trusted_proxies: Arc<[crate::ratelimit::IpNetwork]>,
}

/// Resolve the issuer to advertise for this request (LIF-287).
///
/// When `server.public_url` is set, it always wins: metadata is static and
/// spoofed headers can't move the advertised endpoints. When it is unset, the
/// bind-derived issuer (e.g. `http://127.0.0.1:3456`) can mismatch the URL the
/// client actually dialed (`http://localhost:3456`), which fails the RFC 8707
/// audience check. In that case we derive the issuer from the request `Host`,
/// but ONLY when its hostname is in the same allowlist the MCP DNS-rebinding
/// check uses. Anything else falls back to the static issuer with a loud
/// warning, because an unrecognized Host means a proxied deployment that needs
/// `server.public_url` configured.
///
/// `X-Forwarded-Proto` / `X-Forwarded-Host` are deliberately ignored: these
/// are unauthenticated endpoints, and trusting forwarded headers here would
/// let any direct client control the advertised authorization/token endpoint
/// URLs (issuer spoofing).
fn effective_issuer(state: &OAuthState, headers: &HeaderMap) -> String {
    if state.issuer_is_explicit {
        return state.issuer.clone();
    }
    let Some(host_header) = headers
        .get(axum::http::header::HOST)
        .and_then(|v| v.to_str().ok())
        .map(str::trim)
        .filter(|h| !h.is_empty())
    else {
        return state.issuer.clone();
    };
    match crate::links::parse_http_authority(host_header) {
        Some(authority)
            if crate::links::authority_is_allowlisted(&authority, &state.allowed_hosts) =>
        {
            // Allowlisted hosts are loopback names (a proxy host only enters
            // the allowlist via public_url, which makes the issuer explicit),
            // so plain http matches what the client dialed.
            format!("http://{authority}")
        }
        Some(_) => {
            warn!(
                host = %host_header,
                issuer = %state.issuer,
                "request Host does not match the advertised OAuth issuer; \
                 set server.public_url for proxied deployments"
            );
            state.issuer.clone()
        }
        None => state.issuer.clone(),
    }
}

/// Validate a redirect URI submitted to dynamic client registration.
///
/// We only accept absolute `http://` or `https://` URLs. This explicitly
/// rejects schemes that have been used in past OAuth attacks (e.g.
/// `javascript:`, `data:`, `file:`, `vbscript:`, `blob:`, `about:`,
/// custom app schemes, and bare scheme-less strings).
///
/// Note: we deliberately do NOT block private/loopback hosts because
/// `http://localhost/callback` is the standard pattern for desktop
/// OAuth clients.
pub(crate) fn validate_redirect_uri(uri: &str) -> Result<(), &'static str> {
    let trimmed = uri.trim();
    if trimmed.is_empty() {
        return Err("redirect_uri must not be empty");
    }
    if trimmed != uri {
        return Err("redirect_uri must not have surrounding whitespace");
    }
    if trimmed.chars().any(char::is_control) {
        return Err("redirect_uri must not contain control characters");
    }
    // Lowercase the scheme prefix only; the rest of the URI is case-sensitive.
    let lower_prefix: String = trimmed
        .chars()
        .take_while(|c| *c != ':')
        .flat_map(char::to_lowercase)
        .collect();
    match lower_prefix.as_str() {
        "http" | "https" => {}
        _ => return Err("redirect_uri must use http or https scheme"),
    }
    // Require the scheme to be followed by `://` (rejects e.g. `http:evil`).
    let after_scheme = &trimmed[lower_prefix.len()..];
    if !after_scheme.starts_with("://") {
        return Err("redirect_uri must be an absolute URL (scheme://host/...)");
    }
    // Require some host after `://`.
    let rest = &after_scheme[3..];
    let host_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    if rest[..host_end].is_empty() {
        return Err("redirect_uri must include a host");
    }
    if trimmed.contains('#') {
        return Err("redirect_uri must not contain a fragment");
    }
    Ok(())
}

pub fn router(state: OAuthState) -> Router {
    Router::new()
        .route(
            "/.well-known/oauth-protected-resource",
            get(protected_resource_metadata),
        )
        .route(
            "/.well-known/oauth-authorization-server",
            get(authorization_server_metadata),
        )
        // some clients append the resource path
        .route(
            "/.well-known/oauth-protected-resource/mcp",
            get(protected_resource_metadata),
        )
        .route("/oauth/register", post(register_client))
        .route(
            "/oauth/authorize",
            get(authorize_page).post(authorize_approve),
        )
        .route("/oauth/device_authorization", post(device_authorization))
        .route("/oauth/device", get(device_page).post(device_approve))
        .route("/oauth/token", post(token_exchange))
        .route("/oauth/revoke", post(revoke_token))
        // Claude.ai strips /oauth/ prefix (known bug anthropics/claude-ai-mcp#82)
        .route("/register", post(register_client))
        .route("/authorize", get(authorize_page).post(authorize_approve))
        .route("/device_authorization", post(device_authorization))
        .route("/device", get(device_page).post(device_approve))
        .route("/token", post(token_exchange))
        .route("/revoke", post(revoke_token))
        .layer(DefaultBodyLimit::max(MAX_OAUTH_BODY_BYTES))
        .with_state(state)
}

// ── Discovery ────────────────────────────────────────────────────────────

async fn protected_resource_metadata(
    State(state): State<OAuthState>,
    headers: HeaderMap,
) -> Json<serde_json::Value> {
    let issuer = effective_issuer(&state, &headers);
    // RFC 9728 / Claude connector requirement: the `resource` field MUST match
    // the MCP server URL the user enters in Claude *including the path component*
    // (`/mcp`). Claude derives the RFC 8707 audience from the URL it was given
    // (`https://host/mcp`) and rejects the issued token if the protected-resource
    // metadata advertises a different resource (e.g. the bare origin). Returning
    // the bare issuer here is what surfaced as "Authorization with the MCP server
    // failed" on claude.ai web even though the token exchange succeeded.
    let resource = format!("{}/mcp", issuer.trim_end_matches('/'));
    Json(serde_json::json!({
        "resource": resource,
        "authorization_servers": [issuer],
        "scopes_supported": ["mcp"],
        "bearer_methods_supported": ["header"]
    }))
}

async fn authorization_server_metadata(
    State(state): State<OAuthState>,
    headers: HeaderMap,
) -> Json<serde_json::Value> {
    let issuer = effective_issuer(&state, &headers);
    Json(serde_json::json!({
        "issuer": issuer,
        "authorization_endpoint": format!("{issuer}/oauth/authorize"),
        "token_endpoint": format!("{issuer}/oauth/token"),
        "registration_endpoint": format!("{issuer}/oauth/register"),
        "revocation_endpoint": format!("{issuer}/oauth/revoke"),
        "device_authorization_endpoint": format!("{issuer}/oauth/device_authorization"),
        "scopes_supported": ["mcp"],
        "response_types_supported": ["code"],
        "response_modes_supported": ["query"],
        "grant_types_supported": [
            "authorization_code",
            "urn:ietf:params:oauth:grant-type:device_code"
        ],
        // LIF-415: `none` only. Lific issues no client secrets (registration
        // returns a client_id and nothing else) and the token endpoint never
        // looks for one, so advertising `client_secret_post` described an
        // authentication method that does not exist here. A client that took
        // the metadata at its word and sent a secret would have it silently
        // ignored, which reads as "authenticated" when it isn't.
        "token_endpoint_auth_methods_supported": ["none"],
        "code_challenge_methods_supported": ["S256"]
    }))
}

// ── Dynamic Client Registration ──────────────────────────────────────────

#[derive(Deserialize)]
struct RegisterRequest {
    #[serde(default)]
    redirect_uris: Vec<String>,
    client_name: Option<String>,
    // LIF-415: a submitted `token_endpoint_auth_method` is deliberately not
    // captured. Unknown fields are ignored by serde, and the registration
    // response always reports `none` because that is the only method this
    // server implements.
    #[serde(default)]
    grant_types: Option<Vec<String>>,
    #[serde(default)]
    response_types: Option<Vec<String>>,
}

async fn register_client(
    State(state): State<OAuthState>,
    ConnectInfo(peer): ConnectInfo<SocketAddr>,
    headers: HeaderMap,
    Json(req): Json<RegisterRequest>,
) -> Response {
    // ── Rate limit per source IP ──
    // /oauth/register is unauthenticated by spec (RFC 7591), so without this
    // anyone on the internet can mint unlimited clients.
    let ip = crate::ratelimit::client_ip(peer.ip(), &headers, &state.trusted_proxies);
    let key = format!("oauth_register:{ip}");
    if !state.register_limiter.check(&key) {
        let retry = state.register_limiter.retry_after(&key);
        warn!(ip = %ip, "oauth client registration rate limited");
        let mut resp = (
            StatusCode::TOO_MANY_REQUESTS,
            Json(serde_json::json!({
                "error": "too_many_requests",
                "error_description": crate::ratelimit::retry_after_message(
                    "too many client registrations",
                    retry,
                )
            })),
        )
            .into_response();
        if retry > 0
            && let Ok(v) = retry.to_string().parse()
        {
            resp.headers_mut().insert("retry-after", v);
        }
        return resp;
    }

    let device_only = matches!(req.grant_types.as_deref(), Some([grant]) if grant == DEVICE_CODE_GRANT)
        && req
            .response_types
            .as_deref()
            .is_none_or(<[String]>::is_empty);
    if req.redirect_uris.is_empty() && !device_only {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({
                "error": "invalid_redirect_uri",
                "error_description": "at least one redirect_uri is required"
            })),
        )
            .into_response();
    }

    if req.redirect_uris.len() > MAX_REDIRECT_URIS
        || req
            .redirect_uris
            .iter()
            .any(|uri| uri.len() > MAX_REDIRECT_URI_BYTES)
    {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({
                "error": "invalid_redirect_uri",
                "error_description": "too many or oversized redirect_uris"
            })),
        )
            .into_response();
    }

    let client_name = req.client_name.unwrap_or_else(|| "MCP Client".into());
    if client_name.len() > MAX_CLIENT_NAME_BYTES || client_name.chars().any(|c| c.is_control()) {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({
                "error": "invalid_client_metadata",
                "error_description": "client_name is too long or contains control characters"
            })),
        )
            .into_response();
    }

    // ── Validate every submitted redirect_uri ──
    for uri in &req.redirect_uris {
        if let Err(reason) = validate_redirect_uri(uri) {
            warn!(ip = %ip, uri = %uri, reason = %reason, "rejected oauth registration");
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({
                    "error": "invalid_redirect_uri",
                    "error_description": reason
                })),
            )
                .into_response();
        }
    }

    let redirect_uris_json =
        serde_json::to_string(&req.redirect_uris).unwrap_or_else(|_| "[]".into());
    if redirect_uris_json.len() > MAX_REDIRECT_METADATA_BYTES {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({
                "error": "invalid_client_metadata",
                "error_description": "client metadata is too large"
            })),
        )
            .into_response();
    }

    let db = state.db;
    let conn = match db.write() {
        Ok(c) => c,
        Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response(),
    };
    // Drop grants that can never authenticate anything again, so the client
    // reclaim below can actually see the client as unused.
    //
    // `oauth_clients` is referenced by `oauth_codes.client_id` and
    // `oauth_tokens.client_id`, both NOT NULL with no ON DELETE clause, so a
    // client keeps its row for as long as *any* row points at it -- alive or
    // dead. Before this, one revoked token pinned its client forever, and
    // since device grants now carry a real registered client instead of the
    // old shared `device` row, every CLI login that was later revoked
    // permanently consumed one of MAX_DYNAMIC_CLIENT_ROWS. Enough of them and
    // registration fails for everyone, on an instance that looks idle.
    //
    // Expired-but-unrevoked tokens are deliberately kept. Connected Tools
    // treats a bot as connected while it holds any unrevoked token,
    // independent of OAuth expiry (see `users::list_bots`), so deleting those
    // rows would silently disconnect tools that are still authorized.
    if let Err(error) = conn.execute(
        "DELETE FROM oauth_codes WHERE datetime(expires_at) <= datetime('now')",
        [],
    ) {
        warn!(%error, "failed to clean up expired OAuth codes");
        return (StatusCode::SERVICE_UNAVAILABLE, "database cleanup error").into_response();
    }
    if let Err(error) = conn.execute("DELETE FROM oauth_tokens WHERE revoked = 1", []) {
        warn!(%error, "failed to clean up revoked OAuth tokens");
        return (StatusCode::SERVICE_UNAVAILABLE, "database cleanup error").into_response();
    }
    // Device grants reference a client too, and are otherwise only swept when
    // someone starts a device flow, so an instance that never uses one keeps
    // expired rows forever.
    if let Err(error) = cleanup_expired_device_codes(&conn) {
        warn!(%error, "failed to clean up expired OAuth device codes");
        return (StatusCode::SERVICE_UNAVAILABLE, "database cleanup error").into_response();
    }

    // Anonymous registrations are disposable. Reclaim old clients that have
    // never participated in a code/token/device flow before inserting a new
    // row.
    //
    // Every referencing table has to be listed here. These are real foreign
    // keys with no ON DELETE, so a client that is still referenced does not
    // merely survive the delete: it fails the whole statement, and this
    // handler answers 503. Missing one turns a leftover row into an outage
    // for every registration on the instance.
    if let Err(error) = conn.execute(
        "DELETE FROM oauth_clients
         WHERE created_at < datetime('now', ?1)
           AND NOT EXISTS (SELECT 1 FROM oauth_codes c WHERE c.client_id = oauth_clients.client_id)
           AND NOT EXISTS (SELECT 1 FROM oauth_tokens t WHERE t.client_id = oauth_clients.client_id)
           AND NOT EXISTS (
                 SELECT 1 FROM oauth_device_codes d
                  WHERE d.client_id = oauth_clients.client_id
           )",
        [format!("-{DYNAMIC_CLIENT_RETENTION_DAYS} days")],
    ) {
        warn!(%error, "failed to clean up stale OAuth clients");
        return (StatusCode::SERVICE_UNAVAILABLE, "database cleanup error").into_response();
    }
    let client_id = uuid_v4();
    let client_bytes = (client_id.len() + client_name.len() + redirect_uris_json.len()) as i64;
    let storage = conn.query_row(
        "SELECT COUNT(*), COALESCE(SUM(
             length(CAST(client_id AS BLOB))
             + length(CAST(client_name AS BLOB))
             + length(CAST(redirect_uris AS BLOB))
         ), 0)
         FROM oauth_clients",
        [],
        |row| Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?)),
    );
    let (client_count, client_storage_bytes) = match storage {
        Ok(storage) => storage,
        Err(error) => {
            warn!(%error, "failed to inspect OAuth client storage");
            return (StatusCode::SERVICE_UNAVAILABLE, "database error").into_response();
        }
    };
    if client_count >= MAX_DYNAMIC_CLIENT_ROWS
        || client_storage_bytes.saturating_add(client_bytes) > MAX_DYNAMIC_CLIENT_STORAGE_BYTES
    {
        warn!("OAuth dynamic client storage limit reached");
        return (
            StatusCode::TOO_MANY_REQUESTS,
            Json(serde_json::json!({
                "error": "temporarily_unavailable",
                "error_description": "OAuth registration storage is temporarily full"
            })),
        )
            .into_response();
    }
    if let Err(e) = conn.execute(
        "INSERT INTO oauth_clients (client_id, client_name, redirect_uris) VALUES (?1, ?2, ?3)",
        params![client_id, client_name, redirect_uris_json],
    ) {
        tracing::error!(error = %e, "failed to register OAuth client");
        return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
    }
    drop(conn);

    info!(client_id = %client_id, name = %client_name, "OAuth client registered");

    (
        StatusCode::CREATED,
        Json(serde_json::json!({
            "client_id": client_id,
            "client_name": client_name,
            "redirect_uris": req.redirect_uris,
            // LIF-415: RFC 7591 §3.2.1 — the response states the metadata the
            // server actually registered, not the client's wish. Every client
            // here is public: no secret is issued, so echoing back a requested
            // `client_secret_post` would claim a registration we did not make.
            "token_endpoint_auth_method": "none",
            "grant_types": req.grant_types.unwrap_or_else(|| vec!["authorization_code".into()]),
            "response_types": req.response_types.unwrap_or_else(|| vec!["code".into()])
        })),
    )
        .into_response()
}

/// LIFIC-15: read the tool a registered client has been mapped to, if any.
///
/// Remembering the tool per client means a reconnect pre-fills (or skips) the
/// approval pick-list instead of re-asking — the choice is a stable attribute
/// of the persistent DCR client, not re-derived on every visit. Returns `None`
/// for clients that have never been approved. (Writing happens inside
/// [`resolve_approval_bot`], which owns the same DB handle.)
fn client_tool_id(db: &DbPool, client_id: &str) -> Option<String> {
    let conn = db.read().ok()?;
    conn.query_row(
        "SELECT tool_id FROM oauth_clients WHERE client_id = ?1",
        params![client_id],
        |row| row.get(0),
    )
    .ok()
    .flatten()
}

// ── Authorization ────────────────────────────────────────────────────────

const OAUTH_SCOPE: &str = "mcp";
const ACCESS_TOKEN_EXPIRES_IN: u64 = 3600 * 24 * 30;
const ACCESS_TOKEN_LIFETIME_LABEL: &str = "30 days";

fn oauth_scope_label(scope: &str) -> &str {
    match scope {
        OAUTH_SCOPE => "MCP issue-tracker access",
        _ => scope,
    }
}

#[derive(Deserialize)]
struct AuthorizeParams {
    client_id: String,
    redirect_uri: String,
    response_type: String,
    state: Option<String>,
    code_challenge: Option<String>,
    code_challenge_method: Option<String>,
    scope: Option<String>,
}

/// Validate the authorization request shape before rendering consent or
/// issuing an authorization code. Lific supports one capability and requires
/// PKCE for every authorization-code flow.
fn valid_authorize_request(
    response_type: &str,
    scope: Option<&str>,
    code_challenge: Option<&str>,
    code_challenge_method: Option<&str>,
) -> bool {
    response_type == "code"
        && scope == Some(OAUTH_SCOPE)
        && code_challenge.is_some_and(valid_s256_challenge)
        && code_challenge_method == Some("S256")
}

async fn authorize_page(
    State(oauth): State<OAuthState>,
    headers: HeaderMap,
    Query(params): Query<AuthorizeParams>,
) -> Response {
    if let Err(reason) = validate_redirect_uri(&params.redirect_uri) {
        return (
            StatusCode::BAD_REQUEST,
            Html(format!("<h1>Invalid redirect URI</h1><p>{reason}</p>")),
        )
            .into_response();
    }
    let requested_scope = params.scope.as_deref().unwrap_or_default();
    if !valid_authorize_request(
        &params.response_type,
        params.scope.as_deref(),
        params.code_challenge.as_deref(),
        params.code_challenge_method.as_deref(),
    ) {
        return (
            StatusCode::BAD_REQUEST,
            Html("<h1>Unsupported OAuth request</h1><p>Only authorization-code access to the MCP capability is supported.</p>".to_string()),
        )
            .into_response();
    }

    // Resolve the registered client before showing consent. A generic
    // "application" prompt trains users to approve phishing clients and gives
    // no meaningful capability disclosure. The redirect URI is checked here
    // as well as on POST so a crafted GET cannot produce a misleading screen.
    let client_name = oauth
        .db
        .read()
        .ok()
        .and_then(|conn| {
            conn.query_row(
                "SELECT client_name, redirect_uris FROM oauth_clients WHERE client_id = ?1",
                params![params.client_id],
                |row| {
                    let name: String = row.get(0)?;
                    let uris_json: String = row.get(1)?;
                    Ok((name, uris_json))
                },
            )
            .ok()
        })
        .and_then(|(name, uris_json)| {
            let uris: Vec<String> = serde_json::from_str(&uris_json).ok()?;
            uris.iter()
                .any(|uri| uri == &params.redirect_uri)
                .then_some(name)
        });
    let Some(client_name) = client_name else {
        return (
            StatusCode::BAD_REQUEST,
            Html(
                "<h1>Invalid OAuth client</h1><p>The client or redirect URI is not registered.</p>"
                    .to_string(),
            ),
        )
            .into_response();
    };

    // Bind the CSRF token to the session the browser presents when loading this
    // page (sent on the top-level GET navigation under SameSite=Lax). The POST
    // approval must carry the same session for the token to validate.
    let session = session_credential(&headers);
    let request = AuthorizationRequest {
        client_id: &params.client_id,
        redirect_uri: &params.redirect_uri,
        response_type: &params.response_type,
        state: params.state.as_deref(),
        code_challenge: params.code_challenge.as_deref(),
        code_challenge_method: params.code_challenge_method.as_deref(),
        scope: params.scope.as_deref(),
    };
    let csrf_token = request.csrf_token(&session);
    // Consent must name the account that would be granting access, so this
    // page requires a session where it previously rendered for anyone. That
    // makes an arriving-signed-out user the normal first case rather than an
    // edge case, so it has to offer a way forward: a bare 401 here strands
    // every browser client that sends its user straight to /oauth/authorize.
    // Both approval POSTs already link to the sign-in page; match them.
    let Some(approving_identity) = authenticated_user_identity(&oauth.db, &headers) else {
        return (
            StatusCode::UNAUTHORIZED,
            Html(
                "<h1>Authentication required</h1><p>You must be signed in to review OAuth access. \
                 <a href=\"/#/login\">Sign in</a>, then start the connection again from the \
                 application that sent you here.</p>"
                    .to_string(),
            ),
        )
            .into_response();
    };
    // LIFIC-13: the approval screen asks which tool is connecting so the audit
    // log can attribute requests to a per-tool bot. Options come from the same
    // Connected Tools registry `lific connect` uses; a free-text field covers
    // unrecognized tools. LIFIC-15: if this client is already remembered,
    // pre-select that tool instead of re-asking on a reconnect.
    let preset_id = client_tool_id(&oauth.db, &params.client_id);
    let tool_pick_list = tool_pick_list_html(preset_id.as_deref());

    (
        StatusCode::OK,
        Html(format!(
        r#"<!DOCTYPE html>
<html>
<head>
    <title>Lific - Authorize</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body {{ font-family: system-ui, sans-serif; max-width: 400px; margin: 80px auto; padding: 0 20px; background: #0a0a0a; color: #e0e0e0; }}
        h1 {{ font-size: 1.4em; margin-bottom: 0.5em; }}
        p {{ color: #888; line-height: 1.5; }}
        .client {{ color: #fff; font-weight: 600; }}
        .destination {{ color: #ddd; overflow-wrap: anywhere; }}
        label {{ display: block; margin-top: 1em; color: #aaa; font-size: 0.9em; }}
        select, input {{ width: 100%%; padding: 10px; margin-top: 4px; border-radius: 6px; border: 1px solid #333; background: #141414; color: #e0e0e0; box-sizing: border-box; }}
        form {{ margin-top: 2em; }}
        button {{ background: #2563eb; color: white; border: none; padding: 12px 32px; border-radius: 6px; font-size: 1em; cursor: pointer; width: 100%; margin-top: 1.5em; }}
        button:hover {{ background: #1d4ed8; }}
    </style>
</head>
<body>
    <h1>Authorize access to Lific</h1>
    <p><span class="client">{client_name}</span> wants access to your Lific issue tracker.</p>
    <p>Capability requested: <span class="client">MCP issue-tracker access</span>.</p>
    <p>After approval, you will be redirected to:<br><span class="destination">{redirect_uri}</span></p>
    <p>Token lifetime: <span class="client">{token_lifetime}</span>.</p>
    <p>Approving identity: <span class="client">{approving_identity}</span>.</p>
    <form method="POST" action="/oauth/authorize">
        <input type="hidden" name="client_id" value="{client_id}">
        <input type="hidden" name="redirect_uri" value="{redirect_uri}">
        <input type="hidden" name="response_type" value="{response_type}">
        <input type="hidden" name="state" value="{state}">
        <input type="hidden" name="code_challenge" value="{code_challenge}">
        <input type="hidden" name="code_challenge_method" value="{code_challenge_method}">
        <input type="hidden" name="scope" value="{scope}">
        <input type="hidden" name="csrf_token" value="{csrf_token}">
        {tool_pick_list}
        <button type="submit" name="decision" value="approve">Approve</button>
        <button type="submit" name="decision" value="deny" style="background:#444">Deny</button>
    </form>
</body>
</html>"#,
        client_id = html_escape(&params.client_id),
        client_name = html_escape(&client_name),
        redirect_uri = html_escape(&params.redirect_uri),
        response_type = html_escape(&params.response_type),
        state = html_escape(params.state.as_deref().unwrap_or("")),
        code_challenge = html_escape(params.code_challenge.as_deref().unwrap_or("")),
        code_challenge_method =
            html_escape(params.code_challenge_method.as_deref().unwrap_or("S256")),
        scope = html_escape(requested_scope),
        csrf_token = html_escape(&csrf_token),
        token_lifetime = ACCESS_TOKEN_LIFETIME_LABEL,
        approving_identity = html_escape(&approving_identity),
        tool_pick_list = tool_pick_list,
        )),
    )
        .into_response()
}

#[derive(Deserialize)]
struct ApproveForm {
    client_id: String,
    redirect_uri: String,
    /// Round-tripped from the authorize form so the POST body stays a valid
    /// OAuth request, but the value is fixed at `code` and never branched on.
    #[allow(dead_code)]
    response_type: String,
    state: Option<String>,
    code_challenge: Option<String>,
    code_challenge_method: Option<String>,
    scope: Option<String>,
    csrf_token: Option<String>,
    /// LIFIC-13: which tool is connecting — a Connected Tools registry id, or
    /// empty meaning `tool_custom` holds a free-text name.
    tool: Option<String>,
    /// Free-text tool name when `tool` is unset (an unrecognized tool).
    tool_custom: Option<String>,
    decision: Option<String>,
}

#[derive(Clone, Copy)]
enum ConsentDecision {
    Approve,
    Deny,
}

impl ConsentDecision {
    fn parse(value: Option<&str>) -> Option<Self> {
        match value {
            Some("approve") => Some(Self::Approve),
            Some("deny") => Some(Self::Deny),
            _ => None,
        }
    }
}

fn invalid_decision_page() -> Response {
    (
        StatusCode::BAD_REQUEST,
        Html("<h1>Invalid decision</h1><p>Choose Approve or Deny.</p>".to_string()),
    )
        .into_response()
}

/// The one page both approval handlers render when the presented credential is
/// not a live browser session: absent, wrong shape, expired, or revoked out
/// from under the form between rendering and submitting. Deliberately one
/// message for all of those.
fn invalid_session_page() -> Response {
    (
        StatusCode::UNAUTHORIZED,
        Html("<h1>Invalid session</h1><p>Your session has expired or is invalid. <a href=\"/#/login\">Sign in again</a></p>".to_string()),
    )
        .into_response()
}

/// The page shown when the session is real but was not authenticated recently
/// enough to hand out a durable credential.
///
/// Distinct copy from [`invalid_session_page`] because the fix is different:
/// nothing is wrong with the session, it is simply older than the window.
/// Telling them "expired or invalid" would send them looking for a problem that
/// is not there.
///
/// The copy is deliberately literal about what has to happen, and deliberately
/// does not promise a retry. This request is a form POST carrying a PKCE
/// challenge, a redirect URI and a CSRF token bound to the presenting session.
/// Replaying it after a fresh sign-in would need a server-side continuation
/// store keyed on something the browser can carry back, which is a real feature
/// with its own security surface, not a redirect. It also does not send them to
/// `/#/login`, because a stored session that is merely old still satisfies the
/// login screen: it would show them the app, they would come back, and it would
/// be just as stale. Signing **out** is what actually clears it.
fn stale_session_page() -> Response {
    (
        StatusCode::UNAUTHORIZED,
        Html(
            "<h1>Your sign-in is too old to connect a tool</h1>\
             <p>Connecting a tool gives it lasting access to your account, so Lific requires a \
             sign-in from the last 15 minutes. Yours is older than that. Nothing has been \
             connected and nothing has changed.</p>\
             <p>To continue:</p>\
             <ol>\
             <li>Open Lific and <strong>sign out</strong>. Simply reloading or revisiting the \
             login page will not help, because your existing sign-in is still valid, just old.</li>\
             <li>Sign back in. (On an instance that signs in without a password, signing out and \
             reloading is enough.)</li>\
             <li>Start the connection again from your MCP client. This page cannot resume it for \
             you.</li>\
             </ol>\
             <p><a href=\"/#/settings\">Open Lific settings</a></p>"
                .to_string(),
        ),
    )
        .into_response()
}

/// Establish, on `conn`, that `token` is a live browser session authenticated
/// inside the recent-authentication window, and return whose it is.
///
/// Approving an OAuth grant mints a 30-day credential for a tool, which is the
/// same authority as minting an API key, so it carries the same 15-minute rule
/// that `POST /api/auth/keys` does. Without it a session token stolen from a
/// browser that was signed in last week is enough to attach a permanent tool
/// credential to the account.
///
/// Callers run this as the first statement of the write transaction that
/// resolves the bot and stores the grant, so a lockdown cannot land between
/// the check and the write.
fn recent_approver(
    conn: &rusqlite::Connection,
    token: &str,
) -> Result<crate::db::models::User, ApprovalRefusal> {
    let user = crate::db::queries::users::validate_session(conn, token)
        .map_err(|_| ApprovalRefusal::InvalidSession)?;
    match crate::db::queries::users::session_is_recent(conn, token) {
        Ok(true) => Ok(user),
        Ok(false) => Err(ApprovalRefusal::StaleSession),
        Err(e) => {
            tracing::error!(error = %e, "failed to check session recency");
            Err(ApprovalRefusal::Database)
        }
    }
}

/// Why an approval was refused before anything was written. Kept as a small
/// enum rather than a built `Response` so the error half of
/// [`recent_approver`]'s result stays cheap to move.
enum ApprovalRefusal {
    InvalidSession,
    StaleSession,
    Database,
}

impl ApprovalRefusal {
    fn into_response(self) -> Response {
        match self {
            Self::InvalidSession => invalid_session_page(),
            Self::StaleSession => stale_session_page(),
            Self::Database => (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response(),
        }
    }
}

async fn authorize_approve(
    State(oauth): State<OAuthState>,
    headers: axum::http::HeaderMap,
    axum::Form(form): axum::Form<ApproveForm>,
) -> Response {
    if !valid_authorize_request(
        &form.response_type,
        form.scope.as_deref(),
        form.code_challenge.as_deref(),
        form.code_challenge_method.as_deref(),
    ) {
        return (
            StatusCode::BAD_REQUEST,
            Html("<h1>Unsupported OAuth request</h1><p>Only authorization-code access to the MCP capability is supported.</p>".to_string()),
        )
            .into_response();
    }

    let decision = match ConsentDecision::parse(form.decision.as_deref()) {
        Some(decision) => decision,
        None => return invalid_decision_page(),
    };

    // The credential presented on this POST (Bearer header or lific_token
    // cookie). The CSRF token must have been minted for this same credential.
    let credential = session_credential(&headers);

    // Validate CSRF token, BOUND to the presenting session, to prevent
    // cross-site form submission attacks. A token harvested from the
    // unauthenticated authorize page (bound to no/attacker session) will not
    // match a victim's session presented here.
    let request = AuthorizationRequest {
        client_id: &form.client_id,
        redirect_uri: &form.redirect_uri,
        response_type: &form.response_type,
        state: form.state.as_deref(),
        code_challenge: form.code_challenge.as_deref(),
        code_challenge_method: form.code_challenge_method.as_deref(),
        scope: form.scope.as_deref(),
    };
    match &form.csrf_token {
        Some(token) if request.validates_csrf_token(token, &credential) => {}
        _ => {
            return (
                StatusCode::FORBIDDEN,
                Html("<h1>Invalid or expired form</h1><p>Please go back and try again. <a href=\"/#/\">Return to Lific</a></p>".to_string()),
            )
                .into_response();
        }
    }

    // Require authentication -- the person approving must be identified.
    let Some(token) = (!credential.is_empty()).then_some(credential) else {
        return (
            StatusCode::UNAUTHORIZED,
            Html("<h1>Authentication required</h1><p>You must be signed in to approve OAuth access. <a href=\"/#/login\">Sign in</a></p>".to_string()),
        )
            .into_response();
    };

    // Approving an OAuth grant is an account-level act, so it requires a
    // browser session and nothing else. An OAuth access token used to be
    // accepted here, which let one connected tool authorize another and
    // survive a lockdown by re-minting through the grant it already held.
    if !token.starts_with("lific_sess_") {
        return invalid_session_page();
    }

    // Validate the redirect_uri against the client's registered URIs
    let redirect_ok = validate_redirect_uri(&form.redirect_uri).is_ok()
        && if let Ok(conn) = oauth.db.read() {
            let registered: Result<String, _> = conn.query_row(
                "SELECT redirect_uris FROM oauth_clients WHERE client_id = ?1",
                params![form.client_id],
                |row| row.get(0),
            );
            match registered {
                Ok(uris_json) => {
                    let uris: Vec<String> = serde_json::from_str(&uris_json).unwrap_or_default();
                    uris.iter().any(|u| u == &form.redirect_uri)
                }
                Err(_) => false,
            }
        } else {
            false
        };

    if !redirect_ok {
        return (
            StatusCode::BAD_REQUEST,
            Html("Invalid client_id or redirect_uri does not match registered URIs.".to_string()),
        )
            .into_response();
    }

    // Denial must never create an authorization code. The redirect was already
    // checked against the registered client, and the CSRF check above binds
    // the browser action to the session that rendered the consent page.
    match decision {
        ConsentDecision::Deny => {
            let mut redirect_url = form.redirect_uri.clone();
            redirect_url.push_str(if redirect_url.contains('?') { "&" } else { "?" });
            redirect_url.push_str("error=access_denied");
            if let Some(state) = &form.state
                && !state.is_empty()
            {
                let encoded = urlencoding::encode(state);
                redirect_url.push_str(&format!("&state={encoded}"));
            }
            info!(client_id = %form.client_id, "OAuth authorization denied");
            return Redirect::to(&redirect_url).into_response();
        }
        ConsentDecision::Approve => {}
    }

    let code = uuid_v4();
    let expires = chrono::Utc::now() + chrono::Duration::minutes(10);
    let scope = form.scope.as_deref().unwrap_or("mcp");

    // One transaction for the authorization decision and everything it
    // produces: revalidate the approving session, mint or reuse the tool's
    // bot, and store the code. SQLite serializes writers, so an account
    // lockdown either commits first (and this transaction finds no session) or
    // commits after (and burns the code this one wrote). There is no order in
    // which an approval outlives the session that authorized it.
    let conn = match oauth.db.write() {
        Ok(c) => c,
        Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response(),
    };
    let tx = match rusqlite::Transaction::new_unchecked(&conn, TransactionBehavior::Immediate) {
        Ok(tx) => tx,
        Err(e) => {
            tracing::error!(error = %e, "failed to open OAuth authorization transaction");
            return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
        }
    };

    // Validated inside the transaction, not before it: anything checked
    // earlier can be revoked between the check and this write. The approving
    // user's identity is bound to the issued code (LIF-79), and the session
    // must have been authenticated recently, because what this hands out is a
    // durable credential.
    let approver = match recent_approver(&tx, &token) {
        Ok(user) => user,
        Err(refusal) => return refusal.into_response(),
    };

    // LIFIC-13: pick which tool is connecting, then ensure (or reuse) its bot
    // so the issued credential attributes to the tool, not the approving human.
    // The bot inherits the human's permissions via authz's bot→owner resolution.
    let bot_id = match resolve_approval_bot(
        &tx,
        &form.tool,
        &form.tool_custom,
        Some(approver.id),
        Some(&form.client_id),
    ) {
        Ok(id) => id,
        Err((status, msg)) => {
            return (status, Html(msg)).into_response();
        }
    };

    if let Err(e) = tx.execute(
        "INSERT INTO oauth_codes (code, client_id, redirect_uri, code_challenge, code_challenge_method, expires_at, scope, user_id)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
        params![
            code,
            form.client_id,
            form.redirect_uri,
            form.code_challenge.unwrap_or_default(),
            form.code_challenge_method.unwrap_or_else(|| "S256".into()),
            expires.to_rfc3339(),
            scope,
            bot_id,
        ],
    ) {
        tracing::error!(error = %e, "failed to store OAuth authorization code");
        return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
    }

    if let Err(e) = tx.commit() {
        tracing::error!(error = %e, "failed to commit OAuth authorization");
        return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
    }
    drop(conn);

    let mut redirect_url = form.redirect_uri.clone();
    redirect_url.push_str(if redirect_url.contains('?') { "&" } else { "?" });
    redirect_url.push_str(&format!("code={code}"));
    if let Some(state) = &form.state
        && !state.is_empty()
    {
        let encoded = urlencoding::encode(state);
        redirect_url.push_str(&format!("&state={encoded}"));
    }

    info!(client_id = %form.client_id, "OAuth authorization approved");
    Redirect::to(&redirect_url).into_response()
}

// ── Device Authorization (RFC 8628) ──────────────────────────────────────

/// The RFC 8628 device-code grant type string.
const DEVICE_CODE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";

/// Device code lifetime in seconds (RFC 8628 `expires_in`).
const DEVICE_CODE_EXPIRES_IN: u64 = 900;

/// Default minimum polling interval in seconds (RFC 8628 `interval`).
const DEVICE_CODE_INTERVAL: i64 = 5;

/// Unambiguous alphabet for the human-typed `user_code` — no vowels (avoids
/// spelling words), no 0/O/1/I/L-style confusables. 20 characters.
const USER_CODE_ALPHABET: &[u8] = b"BCDFGHJKLMNPQRSTVWXZ";

/// Generate an 8-character user code formatted `XXXX-XXXX`.
fn generate_user_code() -> String {
    let pick = |buf: &mut String| {
        for _ in 0..4 {
            let idx = (rand::random::<u8>() as usize) % USER_CODE_ALPHABET.len();
            buf.push(USER_CODE_ALPHABET[idx] as char);
        }
    };
    let mut out = String::with_capacity(9);
    pick(&mut out);
    out.push('-');
    pick(&mut out);
    out
}

/// Tool ids that a human can't claim as a free-text tool — they'd collide with
/// real internal identities (`admin`, `system`) or are meaningless.
const RESERVED_TOOL_IDS: &[&str] = &["admin", "system"];

/// Resolve the connecting tool from the approval form's choice, returning its
/// `(tool_id, display_name)`.
///
/// LIFIC-13: known tools come from the Connected Tools registry
/// (`cli::connect::clients::all_clients`) so the approval pick-list and the
/// bot's display name match what `lific connect` writes. Unknown tools fall to
/// free text: lowercased, non-alphanumerics collapsed to `-`, then rejected if
/// they hit a reserved id.
fn resolve_tool(raw: &str) -> Result<(String, String), LificError> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Err(LificError::BadRequest("tool cannot be empty".into()));
    }
    // Known registry client: keep its canonical display name.
    if let Some(client) = crate::cli::connect::clients::find_client(trimmed) {
        return Ok((client.id.to_string(), client.display.to_string()));
    }

    // Free text: sanitize down to a slug id, fall back to the humanized text.
    let slug: String = trimmed
        .to_lowercase()
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '-' })
        .collect::<String>()
        .split('-')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("-");
    if slug.is_empty() {
        return Err(LificError::BadRequest("tool id cannot be empty".into()));
    }
    if RESERVED_TOOL_IDS.contains(&slug.as_str()) {
        return Err(LificError::BadRequest(format!(
            "tool id '{slug}' is reserved"
        )));
    }
    Ok((slug, trimmed.to_string()))
}

/// HTML `<option>` value that means "this isn't a known tool — let me type it".
/// The approval form selects this to reveal the free-text tool-name field.
const CUSTOM_TOOL_OPTION: &str = "__custom__";

/// Render the whole "Which tool is connecting?" widget shared by the auth-code
/// and device approval pages: the Connected Tools pick-list (from the same
/// registry `lific connect` writes), a hidden free-text field for unrecognized
/// tools, and the small inline script that reveals that field when the
/// `Custom tool…` option is chosen. Known tools come first; the pick-list and
/// the free-text input are never both live at once.
///
/// The reveal script compares against [`CUSTOM_TOOL_OPTION`] interpolated from
/// the Rust constant, so the option value lives in exactly one place.
/// Render the shared Connected Tools pick-list widget, pre-selecting the given
/// remembered tool when present (LIFIC-15).
///
/// `preset_id` is the `tool_id` a registered client already maps to, from
/// [`client_tool_id`]. When it's a known registry tool, that option is
/// pre-selected; when it's a free-text tool (a slug not in the registry), the
/// `Custom tool…` option is pre-selected and the free-text field revealed and
/// pre-filled. When `preset_id` is `None` (new client, or the device flow which
/// keys no persistent client), the pick-list starts blank for a fresh choice.
fn tool_pick_list_html(preset_id: Option<&str>) -> String {
    // A remembered tool is "custom" iff it isn't a known Connected Tool (and
    // isn't the sentinel itself). One guard, used for both the option and the
    // reveal+fill decision, so they can't diverge.
    let is_custom = preset_id.is_some_and(|id| {
        id != CUSTOM_TOOL_OPTION && crate::cli::connect::clients::find_client(id).is_none()
    });

    let mut options = String::new();
    for c in crate::cli::connect::clients::all_clients() {
        let selected = preset_id == Some(c.id);
        let sel_attr = if selected { " selected" } else { "" };
        options.push_str(&format!(
            "<option value=\"{}\"{sel_attr}>{}</option>",
            html_escape(c.id),
            html_escape(c.display)
        ));
    }
    let custom_option = if is_custom { " selected" } else { "" };
    options.push_str(&format!(
        "<option value=\"{}\"{custom_option}>Custom tool&hellip;</option>",
        CUSTOM_TOOL_OPTION
    ));

    // The placeholder is only the selected placeholder when there's no remembered
    // tool — the remembered option (or Custom) must win, not the placeholder.
    let placeholder_sel = if preset_id.is_some() { "" } else { " selected" };
    let (custom_visible, custom_value) = if is_custom {
        ("block", html_escape(preset_id.unwrap_or_default()))
    } else {
        ("none", String::new())
    };

    format!(
        "<label for=\"tool\">Which tool is connecting?</label>
        <select name=\"tool\" id=\"tool\">
            <option value=\"\"{placeholder_sel} disabled>Select a tool&hellip;</option>
            {options}
        </select>
        <div id=\"custom_tool\" style=\"display:{custom_visible};\">
            <label for=\"tool_custom\">Custom tool name</label>
            <input type=\"text\" name=\"tool_custom\" id=\"tool_custom\" placeholder=\"e.g. my-agent\" value=\"{custom_value}\">
        </div>
        <script>
        var tool = document.getElementById('tool');
        var custom = document.getElementById('custom_tool');
        tool.addEventListener('change', function () {{
            custom.style.display = tool.value === '{custom_option_value}' ? 'block' : 'none';
        }});
        </script>",
        custom_option_value = CUSTOM_TOOL_OPTION,
    )
}

/// The shared LIFIC-13 tool-resolution + bot-mint step used by both the
/// auth-code and device approval doors.
///
/// Resolves which tool is connecting from the form's `(tool, tool_custom)`
/// pair, validates it, then mints (or reuses) the per-tool bot owned by the
/// approving human. Returns the bot's user id on success, or a small
/// `(StatusCode, message)` the caller renders as its error page (missing tool,
/// unsanitizable/reserved id, no resolvable owner, or DB failure).
///
/// Takes the caller's connection rather than reaching for the pool itself, so
/// the bot it mints lands in the same transaction as the grant that names it.
/// It used to take its own write lock, which forced both approval handlers to
/// resolve the bot *before* opening their own write and left a window where a
/// recovery could revoke the approver between the two.
///
/// When `client_id` is `Some`, the resolved `tool_id` is remembered on that
/// client (LIFIC-15) so a reconnect pre-fills the pick-list instead of
/// re-asking. The device flow passes `None` — it has no persistent client.
fn resolve_approval_bot(
    conn: &rusqlite::Connection,
    tool: &Option<String>,
    tool_custom: &Option<String>,
    approving_user_id: Option<i64>,
    client_id: Option<&str>,
) -> Result<i64, (StatusCode, String)> {
    let tool_text = match (tool, tool_custom) {
        // A specific known tool chosen from the pick-list.
        (Some(id), _) if !id.trim().is_empty() && id.trim() != CUSTOM_TOOL_OPTION => id.clone(),
        // "Custom tool…" chosen — the free-text name is required.
        (Some(id), Some(name)) if id.trim() == CUSTOM_TOOL_OPTION && !name.trim().is_empty() => {
            name.clone()
        }
        _ => {
            return Err((
                StatusCode::BAD_REQUEST,
                "Pick which tool is connecting".into(),
            ));
        }
    };
    let (tool_id, display_name) = match resolve_tool(&tool_text) {
        Ok(v) => v,
        Err(e) => return Err((StatusCode::BAD_REQUEST, e.to_string())),
    };
    let Some(owner_id) = approving_user_id else {
        return Err((
            StatusCode::BAD_REQUEST,
            "No operator to attribute to — sign in as a human first".into(),
        ));
    };
    // LIFIC-15: remember the tool on the client (same conn, best-effort).
    if let Some(client_id) = client_id
        && let Err(e) = conn.execute(
            "UPDATE oauth_clients SET tool_id = ?1 WHERE client_id = ?2",
            params![tool_id, client_id],
        )
    {
        tracing::error!(error = %e, client_id, "failed to remember client tool");
    }
    match crate::db::queries::users::ensure_bot(conn, owner_id, &tool_id, &display_name) {
        Ok(bot) => Ok(bot.id),
        Err(e) => {
            tracing::error!(error = %e, "failed to mint OAuth tool bot");
            Err((StatusCode::INTERNAL_SERVER_ERROR, "database error".into()))
        }
    }
}

/// Normalize a user code the human may have typed with lowercase letters,
/// spaces, or a missing dash: uppercase, strip everything but the alphabet,
/// then re-insert the dash after 4 chars. `bcdf ghjk` and `bcdfghjk` both
/// normalize to `BCDF-GHJK`.
fn normalize_user_code(input: &str) -> String {
    let cleaned: String = input
        .chars()
        .filter(|c| c.is_ascii_alphanumeric())
        .map(|c| c.to_ascii_uppercase())
        .collect();
    if cleaned.len() == 8 {
        format!("{}-{}", &cleaned[..4], &cleaned[4..])
    } else {
        cleaned
    }
}

/// Clean up expired device codes before admitting another device request.
fn cleanup_expired_device_codes(conn: &Connection) -> rusqlite::Result<usize> {
    conn.execute(
        // `datetime(expires_at)` parses the RFC 3339 values stored in this table;
        // raw text comparison mis-orders them within the same day.
        "DELETE FROM oauth_device_codes WHERE datetime(expires_at) <= datetime('now')",
        [],
    )
}

#[derive(Deserialize)]
struct DeviceAuthRequest {
    client_id: Option<String>,
    /// Lific supports one device capability and rejects omitted or expanded
    /// scopes instead of silently upgrading the request.
    #[serde(default)]
    scope: Option<String>,
}

/// `POST /oauth/device_authorization` (RFC 8628 §3.1/§3.2). Accepts form OR
/// JSON. Rate-limited per source IP like `/oauth/register`.
async fn device_authorization(
    State(state): State<OAuthState>,
    ConnectInfo(peer): ConnectInfo<SocketAddr>,
    headers: HeaderMap,
    body: axum::body::Bytes,
) -> Response {
    // ── Rate limit per source IP (reuse the register limiter) ──
    let ip = crate::ratelimit::client_ip(peer.ip(), &headers, &state.trusted_proxies);
    let key = format!("oauth_device_authorization:{ip}");
    if !state.register_limiter.check(&key) {
        let retry = state.register_limiter.retry_after(&key);
        warn!(ip = %ip, "oauth device authorization rate limited");
        let mut resp = (
            StatusCode::TOO_MANY_REQUESTS,
            Json(serde_json::json!({
                "error": "too_many_requests",
                "error_description": crate::ratelimit::retry_after_message(
                    "too many device authorization requests",
                    retry,
                )
            })),
        )
            .into_response();
        if retry > 0
            && let Ok(v) = retry.to_string().parse()
        {
            resp.headers_mut().insert("retry-after", v);
        }
        return resp;
    }

    // Parse client_id and scope from either form-encoded or JSON body.
    let content_type = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    let req: DeviceAuthRequest = if content_type.contains("application/json") {
        serde_json::from_slice(&body).unwrap_or(DeviceAuthRequest {
            client_id: None,
            scope: None,
        })
    } else {
        // application/x-www-form-urlencoded (default)
        serde_urlencoded::from_bytes(&body).unwrap_or(DeviceAuthRequest {
            client_id: None,
            scope: None,
        })
    };

    // RFC 8628 §3.1 makes `scope` OPTIONAL, so omitting it must not be an
    // error: a conforming client that asks for no particular capability gets
    // the only one Lific has. An explicitly *different* capability is still
    // refused rather than silently downgraded to `mcp`.
    let requested_scope = req.scope.as_deref().unwrap_or(OAUTH_SCOPE);
    if requested_scope != OAUTH_SCOPE {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({
                "error": "invalid_scope",
                "error_description": "only the mcp capability is supported"
            })),
        )
            .into_response();
    }

    // `client_id` is REQUIRED for public clients (RFC 8628 §3.1). Older Lific
    // CLIs sent a `client_name` instead and have no client to name, so the
    // description says what to do rather than just what is missing.
    let Some(client_id) = req.client_id.as_deref() else {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({
                "error": "invalid_request",
                "error_description": "missing client_id: register a client at /oauth/register \
                                      and pass its client_id (older Lific CLIs must be upgraded)"
            })),
        )
            .into_response();
    };
    let client_name: String = match state.db.read().ok().and_then(|conn| {
        conn.query_row(
            "SELECT client_name FROM oauth_clients WHERE client_id = ?1",
            params![client_id],
            |row| row.get(0),
        )
        .ok()
    }) {
        Some(name) => name,
        None => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({
                    "error": "invalid_client",
                    "error_description": "unknown client_id"
                })),
            )
                .into_response();
        }
    };

    // High-entropy device code — return raw once, store only its hash.
    let device_code = format!("{}{}", uuid_v4(), uuid_v4()).replace('-', "");
    let device_code_hash = sha256_hex(device_code.as_bytes());

    // Generate a unique user code (retry a few times on the rare collision).
    let mut user_code = generate_user_code();
    let expires_at = chrono::Utc::now() + chrono::Duration::seconds(DEVICE_CODE_EXPIRES_IN as i64);

    let conn = match state.db.write() {
        Ok(c) => c,
        Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response(),
    };
    if let Err(error) = cleanup_expired_device_codes(&conn) {
        warn!(%error, "failed to clean up expired OAuth device codes");
        return (StatusCode::SERVICE_UNAVAILABLE, "database cleanup error").into_response();
    }
    let device_count: i64 =
        match conn.query_row("SELECT COUNT(*) FROM oauth_device_codes", [], |row| {
            row.get(0)
        }) {
            Ok(count) => count,
            Err(error) => {
                warn!(%error, "failed to inspect OAuth device-code storage");
                return (StatusCode::SERVICE_UNAVAILABLE, "database error").into_response();
            }
        };
    if device_count >= MAX_DEVICE_CODE_ROWS {
        warn!("OAuth device-code storage limit reached");
        return (
            StatusCode::TOO_MANY_REQUESTS,
            Json(serde_json::json!({
                "error": "temporarily_unavailable",
                "error_description": "OAuth device authorization storage is temporarily full"
            })),
        )
            .into_response();
    }
    let mut inserted = false;
    for _ in 0..5 {
        let res = conn.execute(
            "INSERT INTO oauth_device_codes
                (device_code_hash, user_code, client_name, expires_at, interval_seconds, status, scope, client_id)
             VALUES (?1, ?2, ?3, ?4, ?5, 'pending', ?6, ?7)",
            params![
                device_code_hash,
                user_code,
                client_name,
                expires_at.to_rfc3339(),
                DEVICE_CODE_INTERVAL,
                OAUTH_SCOPE,
                client_id,
            ],
        );
        match res {
            Ok(_) => {
                inserted = true;
                break;
            }
            Err(_) => {
                // user_code UNIQUE collision — regenerate and retry.
                user_code = generate_user_code();
            }
        }
    }
    drop(conn);
    if !inserted {
        return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
    }

    let verification_uri = format!(
        "{}/oauth/device",
        effective_issuer(&state, &headers).trim_end_matches('/')
    );
    let verification_uri_complete = format!(
        "{verification_uri}?user_code={}",
        urlencoding::encode(&user_code)
    );

    info!(user_code = %user_code, "OAuth device authorization issued");

    (
        StatusCode::OK,
        Json(serde_json::json!({
            "device_code": device_code,
            "user_code": user_code,
            "verification_uri": verification_uri,
            "verification_uri_complete": verification_uri_complete,
            "scope": OAUTH_SCOPE,
            "expires_in": DEVICE_CODE_EXPIRES_IN,
            "interval": DEVICE_CODE_INTERVAL,
        })),
    )
        .into_response()
}

struct DeviceConsent {
    client_id: String,
    client_name: String,
    scope: String,
}

fn pending_device_consent(db: &DbPool, user_code: &str) -> Option<DeviceConsent> {
    let conn = db.read().ok()?;
    let (client_id, client_name, scope, expires_at, status): (
        String,
        String,
        String,
        String,
        String,
    ) = conn
        .query_row(
            "SELECT dc.client_id, clients.client_name, dc.scope, dc.expires_at, dc.status
             FROM oauth_device_codes dc
             JOIN oauth_clients clients ON clients.client_id = dc.client_id
             WHERE dc.user_code = ?1",
            params![user_code],
            |row| {
                Ok((
                    row.get(0)?,
                    row.get(1)?,
                    row.get(2)?,
                    row.get(3)?,
                    row.get(4)?,
                ))
            },
        )
        .ok()?;
    let expires_at = chrono::DateTime::parse_from_rfc3339(&expires_at)
        .ok()?
        .with_timezone(&chrono::Utc);
    if status != "pending" || chrono::Utc::now() >= expires_at {
        return None;
    }
    Some(DeviceConsent {
        client_id,
        client_name,
        scope,
    })
}

fn user_identity(db: &DbPool, user_id: i64) -> Option<String> {
    let conn = db.read().ok()?;
    conn.query_row(
        "SELECT COALESCE(NULLIF(display_name, ''), username) FROM users WHERE id = ?1",
        params![user_id],
        |row| row.get(0),
    )
    .ok()
}

/// `GET /oauth/device` — server-rendered code-entry page. It deliberately does
/// not look up the supplied code; the authenticated POST does that and renders
/// the client confirmation as a separate step.
async fn device_page(headers: HeaderMap, Query(q): Query<DevicePageQuery>) -> Html<String> {
    let csrf_token = generate_csrf_token(&session_credential(&headers));
    let prefill = q
        .user_code
        .as_deref()
        .map(normalize_user_code)
        .unwrap_or_default();
    // LIFIC-13's tool pick-list used to live here, on the code-entry form.
    // Approval is now two steps, and the confirmation page is where the tool
    // is actually read, so asking here as well posed the same question twice
    // and threw the first answer away. This step is only "which code?".
    Html(format!(
        r#"<!DOCTYPE html>
<html>
<head>
    <title>Lific - Device Login</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body {{ font-family: system-ui, sans-serif; max-width: 400px; margin: 80px auto; padding: 0 20px; background: #0a0a0a; color: #e0e0e0; }}
        h1 {{ font-size: 1.4em; margin-bottom: 0.5em; }}
        p {{ color: #888; line-height: 1.5; }}
        label {{ display: block; margin-top: 1.5em; color: #aaa; font-size: 0.9em; }}
        input[type=text], select {{ width: 100%%; box-sizing: border-box; margin-top: 0.4em; padding: 12px; border-radius: 6px; border: 1px solid #333; background: #111; color: #fff; }}
        input[type=text] {{ font-size: 1.2em; letter-spacing: 0.15em; text-align: center; text-transform: uppercase; }}
        .buttons {{ display: flex; gap: 12px; margin-top: 2em; }}
        button {{ flex: 1; color: white; border: none; padding: 12px 24px; border-radius: 6px; font-size: 1em; cursor: pointer; }}
        button.approve {{ background: #2563eb; }}
        button.approve:hover {{ background: #1d4ed8; }}
        button.deny {{ background: #444; }}
        button.deny:hover {{ background: #555; }}
    </style>
</head>
<body>
    <h1>Connect a device to Lific</h1>
    <p>Enter the code shown on the device or terminal that's signing in. You'll see what it is asking for before anything is approved.</p>
    <form method="POST" action="/oauth/device">
        <label for="user_code">Device code</label>
        <input type="text" id="user_code" name="user_code" value="{user_code}" autocomplete="off" autocapitalize="characters" spellcheck="false" required>
        <input type="hidden" name="csrf_token" value="{csrf_token}">
        <div class="buttons">
            <button type="submit" name="decision" value="approve" class="approve">Continue</button>
            <button type="submit" name="decision" value="deny" class="deny">Deny</button>
        </div>
    </form>
</body>
</html>"#,
        user_code = html_escape(&prefill),
        csrf_token = html_escape(&csrf_token),
    ))
}

#[derive(Deserialize)]
struct DevicePageQuery {
    #[serde(default)]
    user_code: Option<String>,
}

#[derive(Deserialize)]
struct DeviceApproveForm {
    user_code: String,
    decision: Option<String>,
    csrf_token: Option<String>,
    confirmation_token: Option<String>,
    /// LIFIC-13: which tool is connecting — a registry id, or empty meaning
    /// `tool_custom` holds a free-text name.
    tool: Option<String>,
    /// Free-text tool name when `tool` is unset.
    tool_custom: Option<String>,
}

/// Render the second, authenticated device-consent step.
fn device_confirmation_page(
    user_code: &str,
    csrf_token: &str,
    confirmation_token: &str,
    consent: &DeviceConsent,
    approving_identity: &str,
) -> Html<String> {
    let tool_pick_list = tool_pick_list_html(None);
    Html(format!(
        r#"<!DOCTYPE html>
<html>
<head>
    <title>Lific - Confirm Device Access</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body {{ font-family: system-ui, sans-serif; max-width: 400px; margin: 80px auto; padding: 0 20px; background: #0a0a0a; color: #e0e0e0; }}
        h1 {{ font-size: 1.4em; margin-bottom: 0.5em; }}
        p {{ color: #888; line-height: 1.5; }}
        .value {{ color: #fff; font-weight: 600; overflow-wrap: anywhere; }}
        label {{ display: block; margin-top: 1em; color: #aaa; font-size: 0.9em; }}
        select, input {{ width: 100%%; padding: 10px; margin-top: 4px; border-radius: 6px; border: 1px solid #333; background: #141414; color: #e0e0e0; box-sizing: border-box; }}
        form {{ margin-top: 2em; }}
        button {{ color: white; border: none; padding: 12px 24px; border-radius: 6px; font-size: 1em; cursor: pointer; width: 100%%; margin-top: 1em; }}
        button.approve {{ background: #2563eb; }}
        button.deny {{ background: #444; }}
    </style>
</head>
<body>
    <h1>Confirm device access</h1>
    <p><span class="value">{client_name}</span> is requesting access to Lific.</p>
    <p>Registered client ID: <span class="value">{client_id}</span>.</p>
    <p>Capability: <span class="value">{scope}</span>.</p>
    <p>Token lifetime: <span class="value">{token_lifetime}</span>.</p>
    <p>Approving identity: <span class="value">{approving_identity}</span>.</p>
    <form method="POST" action="/oauth/device">
        <input type="hidden" name="user_code" value="{user_code}">
        <input type="hidden" name="csrf_token" value="{csrf_token}">
        <input type="hidden" name="confirmation_token" value="{confirmation_token}">
        {tool_pick_list}
        <button type="submit" name="decision" value="approve" class="approve">Approve</button>
        <button type="submit" name="decision" value="deny" class="deny">Deny</button>
    </form>
</body>
</html>"#,
        client_name = html_escape(&consent.client_name),
        client_id = html_escape(&consent.client_id),
        scope = html_escape(oauth_scope_label(&consent.scope)),
        token_lifetime = ACCESS_TOKEN_LIFETIME_LABEL,
        approving_identity = html_escape(approving_identity),
        user_code = html_escape(user_code),
        csrf_token = html_escape(csrf_token),
        confirmation_token = html_escape(confirmation_token),
        tool_pick_list = tool_pick_list,
    ))
}

/// `POST /oauth/device` — authenticate and look up the code first, then require
/// a separate confirmation submission before changing its status.
async fn device_approve(
    State(oauth): State<OAuthState>,
    headers: HeaderMap,
    axum::Form(form): axum::Form<DeviceApproveForm>,
) -> Response {
    let credential = session_credential(&headers);

    // CSRF, bound to the presenting session (identical policy to authorize).
    match &form.csrf_token {
        Some(token) if validate_csrf_token(token, &credential) => {}
        _ => {
            return (
                StatusCode::FORBIDDEN,
                Html("<h1>Invalid or expired form</h1><p>Please go back and try again. <a href=\"/#/\">Return to Lific</a></p>".to_string()),
            )
                .into_response();
        }
    }

    // The approver must be signed in.
    let Some(token) = (!credential.is_empty()).then_some(credential) else {
        return (
            StatusCode::UNAUTHORIZED,
            Html("<h1>Authentication required</h1><p>You must be signed in to approve a device. <a href=\"/#/login\">Sign in</a></p>".to_string()),
        )
            .into_response();
    };

    // Same rule as the authorization-code flow: only a browser session may
    // approve a device. An OAuth access token is a tool's credential, not a
    // human at a keyboard.
    if !token.starts_with("lific_sess_") {
        return invalid_session_page();
    }

    let normalized = normalize_user_code(&form.user_code);
    let decision = match ConsentDecision::parse(form.decision.as_deref()) {
        Some(decision) => decision,
        None => return invalid_decision_page(),
    };

    match (decision, form.confirmation_token.as_deref()) {
        (ConsentDecision::Approve, None) => {
            let Some(approving_user_id) = authenticated_user_id(&oauth.db, &headers) else {
                return invalid_session_page();
            };
            let Some(consent) = pending_device_consent(&oauth.db, &normalized) else {
                return (
                    StatusCode::BAD_REQUEST,
                    Html(format!(
                        "<h1>Unknown or expired code</h1><p>The code <code>{}</code> was not found, has expired, or was already used. <a href=\"/oauth/device\">Try again</a></p>",
                        html_escape(&normalized)
                    )),
                )
                    .into_response();
            };
            let confirmation_token = device_confirmation_token(&token, &normalized);
            let approving_identity = user_identity(&oauth.db, approving_user_id)
                .unwrap_or_else(|| "Unknown authenticated identity".into());
            return device_confirmation_page(
                &normalized,
                form.csrf_token.as_deref().unwrap_or_default(),
                &confirmation_token,
                &consent,
                &approving_identity,
            )
            .into_response();
        }
        (ConsentDecision::Approve, Some(confirmation))
            if !validate_device_confirmation_token(confirmation, &token, &normalized) =>
        {
            return (
                StatusCode::FORBIDDEN,
                Html("<h1>Invalid or expired confirmation</h1><p>Start the device approval again.</p>".to_string()),
            )
                .into_response();
        }
        (ConsentDecision::Approve, Some(_)) | (ConsentDecision::Deny, _) => {}
    }

    // One transaction: revalidate the approving session, resolve the tool's
    // bot, and move the device code out of `pending`. `resolve_approval_bot`
    // used to take its own write lock, which is why this handler had to
    // resolve the bot before opening its own, and why a lockdown could land
    // between the two.
    let conn = match oauth.db.write() {
        Ok(c) => c,
        Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response(),
    };
    let tx = match rusqlite::Transaction::new_unchecked(&conn, TransactionBehavior::Immediate) {
        Ok(tx) => tx,
        Err(e) => {
            tracing::error!(error = %e, "failed to open device approval transaction");
            return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
        }
    };

    // Denying is a refusal, not a grant. It creates nothing, hands out
    // nothing, and is the thing a person does when a device they do not
    // recognise is asking for access, which is exactly the moment not to make
    // them sign in again first. So a *live* session is required either way,
    // and the 15-minute freshness rule applies only to approval.
    let (new_status, target_user_id) = match decision {
        ConsentDecision::Deny => {
            let approver = match crate::db::queries::users::validate_session(&tx, &token) {
                Ok(user) => user,
                Err(_) => return invalid_session_page(),
            };
            ("denied", approver.id)
        }
        ConsentDecision::Approve => {
            let approver = match recent_approver(&tx, &token) {
                Ok(user) => user,
                Err(refusal) => return refusal.into_response(),
            };
            let target_user_id = match resolve_approval_bot(
                &tx,
                &form.tool,
                &form.tool_custom,
                Some(approver.id),
                None,
            ) {
                Ok(id) => id,
                Err((status, msg)) => return (status, Html(msg)).into_response(),
            };
            ("approved", target_user_id)
        }
    };

    let updated = tx
        .execute(
            "UPDATE oauth_device_codes
             SET status = ?1, user_id = ?2
             WHERE user_code = ?3 AND status = 'pending'
               AND datetime(expires_at) > datetime('now')",
            params![new_status, target_user_id, normalized],
        )
        .unwrap_or(0);

    if updated == 0 {
        return (
            StatusCode::BAD_REQUEST,
            Html(format!(
                "<h1>Unknown or expired code</h1><p>The code <code>{}</code> was not found, has expired, or was already used. <a href=\"/oauth/device\">Try again</a></p>",
                html_escape(&normalized)
            )),
        )
            .into_response();
    }

    if let Err(e) = tx.commit() {
        tracing::error!(error = %e, "failed to commit device approval");
        return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
    }
    drop(conn);

    info!(user_code = %normalized, decision = %new_status, "OAuth device verification");

    match decision {
        ConsentDecision::Deny => (
            StatusCode::OK,
            Html("<h1>Access denied</h1><p>The device will not be connected. You can close this page.</p>".to_string()),
        )
            .into_response(),
        ConsentDecision::Approve => (
            StatusCode::OK,
            Html("<h1>Device approved</h1><p>You're all set. Return to the device or terminal — it will finish signing in automatically.</p>".to_string()),
        )
            .into_response(),
    }
}

// ── Token Exchange ───────────────────────────────────────────────────────

#[derive(Deserialize)]
struct TokenRequest {
    grant_type: String,
    code: Option<String>,
    redirect_uri: Option<String>,
    client_id: Option<String>,
    code_verifier: Option<String>,
    /// Parsed so a `refresh_token` grant deserializes rather than 422s, and
    /// is then refused by the `grant_type` match: we issue no refresh tokens.
    #[allow(dead_code)]
    refresh_token: Option<String>,
    /// RFC 8628 device grant: the opaque device_code returned by
    /// /oauth/device_authorization.
    device_code: Option<String>,
}

#[derive(Serialize)]
struct TokenResponse {
    access_token: String,
    token_type: String,
    expires_in: u64,
    scope: String,
}

async fn token_exchange(
    State(state): State<OAuthState>,
    axum::Form(req): axum::Form<TokenRequest>,
) -> Response {
    if req.grant_type == DEVICE_CODE_GRANT {
        return device_token_exchange(&state, &req);
    }
    if req.grant_type != "authorization_code" {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({"error": "unsupported_grant_type"})),
        )
            .into_response();
    }

    let Some(code) = &req.code else {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({"error": "invalid_request", "error_description": "missing code"})),
        )
            .into_response();
    };

    let Some(code_verifier) = &req.code_verifier else {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({"error": "invalid_request", "error_description": "missing code_verifier"})),
        )
            .into_response();
    };

    // The whole exchange is one transaction: read the code, validate it, check
    // that the identity it names may still authenticate, burn it, and insert
    // the token. Splitting the read from the burn is what let a recovery land
    // in between and hand out a 30-day token against a code it had already
    // invalidated.
    let conn = match state.db.write() {
        Ok(c) => c,
        Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response(),
    };
    let conn = match rusqlite::Transaction::new_unchecked(&conn, TransactionBehavior::Immediate) {
        Ok(tx) => tx,
        Err(e) => {
            tracing::error!(error = %e, "failed to open OAuth token transaction");
            return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
        }
    };

    // Named row type keeps the query_row result readable and avoids
    // clippy::type_complexity on the 7-column tuple (LIF-79 added user_id).
    struct AuthCodeRow {
        client_id: String,
        redirect_uri: String,
        code_challenge: String,
        challenge_method: String,
        used: i64,
        scope: String,
        user_id: Option<i64>,
    }

    let code_row: Result<AuthCodeRow, _> = conn.query_row(
        // `datetime(expires_at)` for the same reason as the device codes: the
        // column holds RFC 3339, and raw text comparison against
        // `datetime('now')` mis-orders it within the same day.
        "SELECT client_id, redirect_uri, code_challenge, code_challenge_method, used, scope, user_id \
         FROM oauth_codes WHERE code = ?1 AND datetime(expires_at) > datetime('now')",
        params![code],
        |row| {
            Ok(AuthCodeRow {
                client_id: row.get(0)?,
                redirect_uri: row.get(1)?,
                code_challenge: row.get(2)?,
                challenge_method: row.get(3)?,
                used: row.get(4)?,
                scope: row.get(5)?,
                user_id: row.get(6)?,
            })
        },
    );

    let AuthCodeRow {
        client_id: stored_client_id,
        redirect_uri: stored_redirect_uri,
        code_challenge,
        challenge_method,
        used,
        scope,
        user_id: code_user_id,
    } = match code_row {
        Ok(row) => row,
        Err(_) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({"error": "invalid_grant"})),
            )
                .into_response();
        }
    };

    if used != 0 {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({"error": "invalid_grant", "error_description": "code already used"})),
        )
            .into_response();
    }

    // Validate client_id — required per OAuth 2.1 for public clients
    let Some(client_id) = &req.client_id else {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({"error": "invalid_request", "error_description": "missing client_id"})),
        )
            .into_response();
    };
    if *client_id != stored_client_id {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({"error": "invalid_grant"})),
        )
            .into_response();
    }

    // Validate redirect_uri matches the one used during authorization (OAuth 2.1 Section 4.1.3)
    match &req.redirect_uri {
        Some(uri) if *uri != stored_redirect_uri => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({"error": "invalid_grant", "error_description": "redirect_uri mismatch"})),
            )
                .into_response();
        }
        None => {
            // redirect_uri is required when it was included in the authorization request
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({"error": "invalid_request", "error_description": "missing redirect_uri"})),
            )
                .into_response();
        }
        _ => {} // matches — continue
    }

    // Validate PKCE
    if !validate_pkce(code_verifier, &code_challenge, &challenge_method) {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({"error": "invalid_grant", "error_description": "PKCE verification failed"})),
        )
            .into_response();
    }

    // The code must name an identity, and that identity must still be one that
    // may authenticate.
    //
    // A NULL `user_id` is a pre-LIF-79 legacy row. Every approval since binds
    // the per-tool bot, so nothing issues one any more, and exchanging one
    // produced an *unbound* access token: a credential that names nobody,
    // which the caller resolution then treats as the operator. That is a
    // silent privilege escalation, and no lockdown can revoke it either, since
    // a lockdown scopes by user id. Fail closed instead.
    //
    // A bound code still has to resolve a live identity: the bot may have been
    // deleted between approval and exchange (PR #23 review), and its owner may
    // have been deactivated or locked down since. `credential_is_live` is the
    // same predicate every other bearer credential is judged by.
    let Some(code_user_id) = code_user_id else {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({"error": "invalid_grant", "error_description": "this authorization is not bound to an identity; reconnect to authorize again"})),
        )
            .into_response();
    };
    let live = crate::db::queries::users::get_user_by_id(&conn, code_user_id)
        .and_then(|user| crate::db::queries::users::credential_is_live(&conn, &user))
        .unwrap_or(false);
    if !live {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({"error": "invalid_grant", "error_description": "authorizing user is no longer active"})),
        )
            .into_response();
    }

    // Mark code as used
    if let Err(e) = conn.execute(
        "UPDATE oauth_codes SET used = 1 WHERE code = ?1",
        params![code],
    ) {
        tracing::error!(error = %e, "failed to mark OAuth code as used");
        return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
    }

    // Generate access token — store SHA-256 hash, return raw token only once
    let access_token = format!("lific_at_{}", uuid_v4());
    let token_hash = sha256_hex(access_token.as_bytes());
    let expires_in = ACCESS_TOKEN_EXPIRES_IN;
    let expires_at = chrono::Utc::now() + chrono::Duration::seconds(expires_in as i64);

    if let Err(e) = conn.execute(
        "INSERT INTO oauth_tokens (access_token, client_id, expires_at, scope, user_id) VALUES (?1, ?2, ?3, ?4, ?5)",
        params![token_hash, stored_client_id, expires_at.to_rfc3339(), scope, code_user_id],
    ) {
        tracing::error!(error = %e, "failed to store OAuth token");
        return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
    }

    if let Err(e) = conn.commit() {
        tracing::error!(error = %e, "failed to commit OAuth token exchange");
        return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
    }

    info!(client_id = %stored_client_id, scope = %scope, "OAuth token issued");

    Json(TokenResponse {
        access_token,
        token_type: "Bearer".into(),
        expires_in,
        scope,
    })
    .into_response()
}

/// RFC 8628 §3.4/§3.5 device-code token exchange. Looks up the device code by
/// hash, enforces the polling interval (`slow_down`), and returns the
/// per-status error (`authorization_pending` / `access_denied` /
/// `expired_token`) or, on approval, mints and returns an access token.
fn device_token_exchange(state: &OAuthState, req: &TokenRequest) -> Response {
    let Some(device_code) = req.device_code.as_deref().filter(|c| !c.is_empty()) else {
        return device_error(
            StatusCode::BAD_REQUEST,
            "invalid_request",
            Some("missing device_code"),
        );
    };
    let device_code_hash = sha256_hex(device_code.as_bytes());

    // LIF-370 extended: the read, the status decision, the liveness check, the
    // token insert and the consumed transition are all one transaction. The
    // approved-row read used to sit outside the transaction that consumed it,
    // so a recovery that denied the grant between the two still handed the
    // polling device a token.
    let conn = match state.db.write() {
        Ok(c) => c,
        Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response(),
    };
    let conn = match rusqlite::Transaction::new_unchecked(&conn, TransactionBehavior::Immediate) {
        Ok(tx) => tx,
        Err(e) => {
            tracing::error!(error = %e, "failed to open device token transaction");
            return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
        }
    };

    /// Commit the bookkeeping a non-issuing outcome still needs to persist
    /// (the expiry sweep, the poll timestamp) and hand back the response. A
    /// failed commit is not worth failing the poll over: the client simply
    /// retries, so log it and answer as decided.
    macro_rules! finish {
        ($conn:expr, $response:expr) => {{
            if let Err(e) = $conn.commit() {
                tracing::error!(error = %e, "failed to commit device poll bookkeeping");
            }
            return $response;
        }};
    }

    struct DeviceRow {
        client_id: Option<String>,
        status: String,
        user_id: Option<i64>,
        scope: String,
        expires_at: String,
        interval_seconds: i64,
        last_polled_at: Option<String>,
    }

    let row: Result<DeviceRow, _> = conn.query_row(
        "SELECT client_id, status, user_id, scope, expires_at, interval_seconds, last_polled_at
         FROM oauth_device_codes WHERE device_code_hash = ?1",
        params![device_code_hash],
        |r| {
            Ok(DeviceRow {
                client_id: r.get(0)?,
                status: r.get(1)?,
                user_id: r.get(2)?,
                scope: r.get(3)?,
                expires_at: r.get(4)?,
                interval_seconds: r.get(5)?,
                last_polled_at: r.get(6)?,
            })
        },
    );

    let row = match row {
        Ok(r) => r,
        // Unknown device_code → invalid_grant per RFC 8628 §3.5.
        Err(_) => return device_error(StatusCode::BAD_REQUEST, "invalid_grant", None),
    };

    let now = chrono::Utc::now();

    // Expiry check first (RFC 8628: expired_token).
    let expired = chrono::DateTime::parse_from_rfc3339(&row.expires_at)
        .map_or(true, |t| now >= t.with_timezone(&chrono::Utc));
    if expired {
        let _ = conn.execute(
            "DELETE FROM oauth_device_codes WHERE device_code_hash = ?1",
            params![device_code_hash],
        );
        finish!(
            conn,
            device_error(StatusCode::BAD_REQUEST, "expired_token", None)
        );
    }

    // slow_down: reject if polled faster than `interval` since the last poll.
    if let Some(last) = &row.last_polled_at
        && let Ok(last_t) = chrono::DateTime::parse_from_rfc3339(last)
    {
        let elapsed = now
            .signed_duration_since(last_t.with_timezone(&chrono::Utc))
            .num_seconds();
        if elapsed < row.interval_seconds {
            // Do NOT update last_polled_at here — an early poll shouldn't push
            // the window out; the client is told to slow down.
            finish!(
                conn,
                device_error(StatusCode::BAD_REQUEST, "slow_down", None)
            );
        }
    }

    // Record this poll time (used for the next slow_down check).
    let _ = conn.execute(
        "UPDATE oauth_device_codes SET last_polled_at = ?1 WHERE device_code_hash = ?2",
        params![now.to_rfc3339(), device_code_hash],
    );

    match row.status.as_str() {
        "pending" => finish!(
            conn,
            device_error(StatusCode::BAD_REQUEST, "authorization_pending", None)
        ),
        "denied" => finish!(
            conn,
            device_error(StatusCode::BAD_REQUEST, "access_denied", None)
        ),
        "consumed" => finish!(
            conn,
            device_error(
                StatusCode::BAD_REQUEST,
                "invalid_grant",
                Some("device code already used")
            )
        ),
        "approved" => {
            // Mint the access token bound to the approving user, then mark the
            // code consumed (single use).
            //
            // The approval must name an identity. A NULL `user_id` on an
            // approved row is a pre-LIF-79 legacy grant; exchanging it minted
            // an *unbound* access token, which resolves as the operator and
            // which no lockdown can revoke, because a lockdown scopes by user
            // id. Nothing issues one any more, so fail closed. Same reasoning
            // and same wording as the authorization-code path.
            //
            // A bound approval still has to resolve a live identity: the bot
            // may have been deleted between approval and this poll (PR #23
            // review), and its owner may have been deactivated or locked down
            // since. `credential_is_live` is the predicate every other bearer
            // credential is judged by.
            let Some(approved_user_id) = row.user_id else {
                finish!(
                    conn,
                    device_error(
                        StatusCode::BAD_REQUEST,
                        "invalid_grant",
                        Some(
                            "this authorization is not bound to an identity; reconnect to \
                             authorize again"
                        ),
                    )
                );
            };
            let live = crate::db::queries::users::get_user_by_id(&conn, approved_user_id)
                .and_then(|user| crate::db::queries::users::credential_is_live(&conn, &user))
                .unwrap_or(false);
            if !live {
                finish!(
                    conn,
                    device_error(
                        StatusCode::BAD_REQUEST,
                        "invalid_grant",
                        Some("authorizing user is no longer active"),
                    )
                );
            }
            let scope = row.scope.as_str();
            let Some(client_id) = row.client_id.as_deref() else {
                finish!(
                    conn,
                    device_error(
                        StatusCode::BAD_REQUEST,
                        "invalid_grant",
                        Some("device authorization has no registered client"),
                    )
                );
            };

            let access_token = format!("lific_at_{}", uuid_v4());
            let token_hash = sha256_hex(access_token.as_bytes());
            let expires_in = ACCESS_TOKEN_EXPIRES_IN;
            let expires_at = now + chrono::Duration::seconds(expires_in as i64);

            // LIF-370: minting the token and burning the device code are one
            // atomic step. Previously the consumed-UPDATE was `let _ =`, so a
            // failed write handed out a token while leaving the code
            // `approved` and replayable for as many tokens as the client cared
            // to poll for. Either both writes land or neither does, and since
            // LIF-PR32 the approved-row read is inside the same transaction, so
            // a denial that lands first wins cleanly instead of being read
            // stale.
            let tx = conn;

            if let Err(e) = tx.execute(
                "INSERT INTO oauth_tokens (access_token, client_id, expires_at, scope, user_id)
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                params![
                    token_hash,
                    client_id,
                    expires_at.to_rfc3339(),
                    scope,
                    approved_user_id
                ],
            ) {
                tracing::error!(error = %e, "failed to store device OAuth token");
                return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
            }

            // Single-use: mark consumed so a replay returns invalid_grant. The
            // `status = 'approved'` guard means exactly one exchange can win;
            // anything other than one row changed rolls the token back.
            match tx.execute(
                "UPDATE oauth_device_codes SET status = 'consumed'
                 WHERE device_code_hash = ?1 AND status = 'approved'",
                params![device_code_hash],
            ) {
                Ok(1) => {}
                Ok(n) => {
                    tracing::error!(
                        rows = n,
                        "device code not consumed exactly once; refusing to issue token"
                    );
                    return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
                }
                Err(e) => {
                    tracing::error!(error = %e, "failed to consume device code");
                    return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
                }
            }

            if let Err(e) = tx.commit() {
                tracing::error!(error = %e, "failed to commit device token exchange");
                return (StatusCode::INTERNAL_SERVER_ERROR, "database error").into_response();
            }

            info!(scope = %scope, "OAuth device token issued");
            Json(TokenResponse {
                access_token,
                token_type: "Bearer".into(),
                expires_in,
                scope: scope.into(),
            })
            .into_response()
        }
        _ => finish!(
            conn,
            device_error(StatusCode::BAD_REQUEST, "invalid_grant", None)
        ),
    }
}

/// Build an RFC 8628 §3.5 JSON error response body.
fn device_error(status: StatusCode, error: &str, description: Option<&str>) -> Response {
    let body = match description {
        Some(d) => serde_json::json!({"error": error, "error_description": d}),
        None => serde_json::json!({"error": error}),
    };
    (status, Json(body)).into_response()
}

// ── Token Revocation (RFC 7009) ──────────────────────────────────────────

#[derive(Deserialize)]
struct RevokeRequest {
    token: String,
    /// RFC 7009 explicitly makes this a hint the server MAY ignore. We do:
    /// there is only one revocable token store (`oauth_tokens`), so there is
    /// nothing for the hint to disambiguate.
    #[allow(dead_code)]
    token_type_hint: Option<String>,
}

async fn revoke_token(
    State(state): State<OAuthState>,
    headers: axum::http::HeaderMap,
    axum::Form(req): axum::Form<RevokeRequest>,
) -> Response {
    // Require authentication -- only authenticated users/tokens can revoke.
    let caller_token = headers
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .map(|s| s.trim().to_string());

    let is_authenticated = match &caller_token {
        Some(t) if t.starts_with("lific_sess_") => match state.db.read() {
            Ok(conn) => crate::db::queries::users::validate_session(&conn, t).is_ok(),
            Err(_) => false,
        },
        Some(t) if t.starts_with("lific_at_") => authenticate_oauth_token(&state.db, t).is_some(),
        // LIF-208: default-deny unknown bearer shapes. The previous
        // `Some(_) => true` treated *any* other string (including arbitrary
        // garbage) as authenticated, which is sloppier than the rest of the
        // file. The OAuth router doesn't run the API-key middleware and has no
        // key manager, so it can't validate `lific_sk` keys here; a legitimate
        // caller revoking a token presents a session or the OAuth token itself.
        Some(_) => false,
        None => false,
    };

    if !is_authenticated {
        return (StatusCode::UNAUTHORIZED, "authentication required").into_response();
    }

    // RFC 7009 says the server MUST respond with 200 even if the token
    // is invalid, already revoked, or unrecognized -- to prevent token scanning.
    // Hash the token before lookup since we store SHA-256 hashes.
    let token_hash = sha256_hex(req.token.as_bytes());
    // RFC 7009: always return 200, but log DB errors instead of silently discarding
    match state.db.write() {
        Ok(conn) => {
            if let Err(e) = conn.execute(
                "UPDATE oauth_tokens SET revoked = 1 WHERE access_token = ?1",
                params![token_hash],
            ) {
                tracing::error!(error = %e, "failed to revoke OAuth token");
            }
        }
        Err(e) => tracing::error!(error = %e, "failed to acquire DB lock for token revocation"),
    }

    StatusCode::OK.into_response()
}

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

fn valid_s256_challenge(challenge: &str) -> bool {
    challenge.len() == 43
        && challenge
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
}

fn validate_pkce(verifier: &str, challenge: &str, method: &str) -> bool {
    if !(43..=128).contains(&verifier.len())
        || !verifier
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~'))
        || challenge.is_empty()
    {
        return false;
    }
    match method {
        "S256" => {
            let hash = Sha256::digest(verifier.as_bytes());
            let computed = base64_url_encode(&hash);
            computed == challenge
        }
        _ => false, // Only S256 is accepted per OAuth 2.1
    }
}

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

    #[test]
    fn verifier_must_use_rfc7636_length_and_characters() {
        for verifier in [
            "a".repeat(42),
            "a".repeat(129),
            format!("{}:", "a".repeat(42)),
        ] {
            let challenge = base64_url_encode(&Sha256::digest(verifier.as_bytes()));
            assert!(!validate_pkce(&verifier, &challenge, "S256"));
        }

        let verifier = format!("{}-._~", "a".repeat(39));
        let challenge = base64_url_encode(&Sha256::digest(verifier.as_bytes()));
        assert!(validate_pkce(&verifier, &challenge, "S256"));
    }
}

/// Decode a lowercase/uppercase hex string into bytes. Returns `Err(())` on
/// odd length or any non-hex digit. Used to parse a presented CSRF MAC before
/// constant-time verification (LIF-208).
fn hex_decode(s: &str) -> Result<Vec<u8>, ()> {
    if !s.len().is_multiple_of(2) {
        return Err(());
    }
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(|_| ()))
        .collect()
}

fn base64_url_encode(bytes: &[u8]) -> String {
    use base64::Engine;
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    URL_SAFE_NO_PAD.encode(bytes)
}

fn uuid_v4() -> String {
    let bytes: [u8; 16] = rand::random();
    format!(
        "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",
        u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
        u16::from_be_bytes([bytes[4], bytes[5]]),
        u16::from_be_bytes([bytes[6], bytes[7]]) & 0x0fff,
        u16::from_be_bytes([bytes[8], bytes[9]]) & 0x3fff | 0x8000,
        u64::from_be_bytes([
            0, 0, bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]
        ])
    )
}

fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// What an OAuth bearer token resolved to.
///
/// The middleware used to answer this with three separate calls: "is it
/// valid", "whose is it", "is that user live". Each took its own pooled
/// connection, so the three answers came from three different snapshots of the
/// database. A token revoked between the first and the second read as valid,
/// then as unbound, and an unbound OAuth token is the operator: revoking a
/// tool's credential could *promote* it. That is the whole reason this is one
/// function and one connection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OAuthCredential {
    /// Valid, and bound to a user who may authenticate right now.
    Bound(AuthUser),
    /// Valid, and genuinely carries no user binding.
    ///
    /// Only rows issued before user binding existed (pre-LIF-79) can be in
    /// this state; every approval since binds the per-tool bot, and the token
    /// exchange refuses an unbound grant outright. It is kept because such
    /// rows may still exist in an upgraded database, and it resolves to the
    /// operator fallback, which is the documented pre-LIF-79 behaviour.
    LegacyUnbound,
}

/// Why an OAuth bearer token did not authenticate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OAuthReject {
    /// Wrong prefix, no such row, revoked, or expired.
    Invalid,
    /// The row is fine but names an identity that may not authenticate: the
    /// user is gone, deactivated, or is a bot whose owner is deactivated.
    ///
    /// Deliberately distinct from [`OAuthReject::Invalid`] at the type level so
    /// it can never be collapsed into "unbound". A dead binding is a dead
    /// credential, not an anonymous one.
    DeadBinding,
    /// The database could not be read. Fails closed.
    Unavailable,
}

/// Resolve an OAuth bearer token with one SQL statement.
///
/// A connection alone is not a snapshot in SQLite autocommit mode: each
/// statement starts its own read transaction. Keep token validity, its nullable
/// binding, the bound user, and the bot owner's liveness in one joined query so
/// revocation cannot land between those decisions.
pub fn resolve_oauth_credential(db: &DbPool, token: &str) -> Result<OAuthCredential, OAuthReject> {
    if !token.starts_with("lific_at_") {
        return Err(OAuthReject::Invalid);
    }
    let token_hash = sha256_hex(token.as_bytes());
    let conn = db.read().map_err(|error| {
        tracing::error!(%error, "OAuth token lookup could not read the database");
        OAuthReject::Unavailable
    })?;

    struct CredentialRow {
        bound_user_id: Option<i64>,
        user_id: Option<i64>,
        username: Option<String>,
        display_name: Option<String>,
        is_admin: Option<bool>,
        is_active: Option<bool>,
        is_bot: Option<bool>,
        owner_id: Option<i64>,
        owner_is_active: Option<bool>,
    }

    let row = conn
        .query_row(
            "SELECT token.user_id,
                    user.id, user.username, user.display_name, user.is_admin,
                    user.is_active, user.is_bot, user.owner_id, owner.is_active
             FROM oauth_tokens token
             LEFT JOIN users user ON user.id = token.user_id
             LEFT JOIN users owner ON owner.id = user.owner_id
             WHERE token.access_token = ?1 AND token.revoked = 0
               AND datetime(token.expires_at) > datetime('now')",
            params![token_hash],
            |row| {
                Ok(CredentialRow {
                    bound_user_id: row.get(0)?,
                    user_id: row.get(1)?,
                    username: row.get(2)?,
                    display_name: row.get(3)?,
                    is_admin: row.get(4)?,
                    is_active: row.get(5)?,
                    is_bot: row.get(6)?,
                    owner_id: row.get(7)?,
                    owner_is_active: row.get(8)?,
                })
            },
        )
        .optional()
        .map_err(|error| {
            tracing::error!(%error, "OAuth token lookup failed");
            OAuthReject::Unavailable
        })?
        .ok_or(OAuthReject::Invalid)?;

    let Some(bound_user_id) = row.bound_user_id else {
        return Ok(OAuthCredential::LegacyUnbound);
    };
    let (
        Some(user_id),
        Some(username),
        Some(display_name),
        Some(is_admin),
        Some(is_active),
        Some(is_bot),
    ) = (
        row.user_id,
        row.username,
        row.display_name,
        row.is_admin,
        row.is_active,
        row.is_bot,
    )
    else {
        return Err(OAuthReject::DeadBinding);
    };
    debug_assert_eq!(user_id, bound_user_id);

    // Match `credential_is_live`: an inactive user is dead; an owned bot is
    // dead when its owner exists and is inactive. Ownerless and dangling-owner
    // bots retain the existing fallback of being evaluated as themselves.
    if !is_active || (is_bot && row.owner_id.is_some() && row.owner_is_active == Some(false)) {
        return Err(OAuthReject::DeadBinding);
    }

    Ok(OAuthCredential::Bound(AuthUser {
        id: user_id,
        username,
        display_name,
        is_admin,
    }))
}

/// Authenticate an OAuth access token as an *approving identity*.
///
/// Returns:
/// - `None` when the token does not authenticate at all: invalid, revoked,
///   expired, or bound to a user who may no longer authenticate (deactivated,
///   or a bot whose owner is deactivated — LIF-214 follow-up, see
///   `queries::users::credential_is_live`).
/// - `Some(None)` for a valid legacy token carrying no user binding.
/// - `Some(Some(id))` for a valid token bound to a live user.
///
/// This is the OAuth-token twin of [`crate::db::queries::users::validate_session`],
/// which applies the same liveness rule to session tokens.
fn authenticate_oauth_token(db: &DbPool, token: &str) -> Option<Option<i64>> {
    match resolve_oauth_credential(db, token) {
        Ok(OAuthCredential::Bound(user)) => Some(Some(user.id)),
        Ok(OAuthCredential::LegacyUnbound) => Some(None),
        Err(_) => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::extract::connect_info::MockConnectInfo;
    use axum::http::{Request, StatusCode};
    use http_body_util::BodyExt;
    use tower::ServiceExt;

    fn test_oauth_app() -> (Router, DbPool) {
        test_oauth_app_with_register_limit(1000)
    }

    /// Build a test OAuth router with a configurable register-limit cap.
    /// Most tests need a generous cap so unrelated registrations don't
    /// trip the limiter; the rate-limit tests pass a small cap.
    fn test_oauth_app_with_register_limit(cap: usize) -> (Router, DbPool) {
        let db = crate::db::open_memory().expect("test db");
        let state = OAuthState {
            db: db.clone(),
            issuer: "https://example.com".into(),
            issuer_is_explicit: true,
            allowed_hosts: test_allowed_hosts(),
            register_limiter: Arc::new(RateLimiter::new(cap, std::time::Duration::from_secs(3600))),
            trusted_proxies: default_trusted_proxies(),
        };
        (
            router(state).layer(MockConnectInfo(SocketAddr::from(([127, 0, 0, 1], 4242)))),
            db,
        )
    }

    fn test_allowed_hosts() -> Arc<[String]> {
        vec![
            "localhost".to_string(),
            "127.0.0.1".to_string(),
            "::1".to_string(),
        ]
        .into()
    }

    fn default_trusted_proxies() -> Arc<[crate::ratelimit::IpNetwork]> {
        Arc::<[crate::ratelimit::IpNetwork]>::from(
            crate::ratelimit::parse_trusted_proxies(&["127.0.0.0/8".into()])
                .expect("test trusted proxy range must parse"),
        )
    }

    /// Build a test OAuth router the way `lific start` does when
    /// `server.public_url` is UNSET: bind-derived issuer, not explicit.
    /// Exercises the LIF-287 Host-derived issuer fallback.
    fn test_oauth_app_implicit_issuer() -> Router {
        let db = crate::db::open_memory().expect("test db");
        let state = OAuthState {
            db,
            issuer: "http://127.0.0.1:3456".into(),
            issuer_is_explicit: false,
            allowed_hosts: test_allowed_hosts(),
            register_limiter: Arc::new(RateLimiter::new(
                1000,
                std::time::Duration::from_secs(3600),
            )),
            trusted_proxies: default_trusted_proxies(),
        };
        router(state).layer(MockConnectInfo(SocketAddr::from(([127, 0, 0, 1], 4242))))
    }

    /// Register a client, returning the client_id.
    async fn register_named_client_helper(
        app: &Router,
        redirect_uri: &str,
        client_name: &str,
    ) -> String {
        let body = serde_json::json!({
            "redirect_uris": [redirect_uri],
            "client_name": client_name
        });
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/register")
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::CREATED);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let val: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        val["client_id"].as_str().unwrap().to_string()
    }

    async fn register_client_helper(app: &Router, redirect_uri: &str) -> String {
        register_named_client_helper(app, redirect_uri, "Test Client").await
    }

    /// The user an access token resolves to, or `None` for anything that does
    /// not authenticate as a bound identity.
    fn bound_user(db: &DbPool, token: &str) -> Option<i64> {
        match resolve_oauth_credential(db, token) {
            Ok(OAuthCredential::Bound(user)) => Some(user.id),
            _ => None,
        }
    }

    /// Create a user session for OAuth tests.
    fn create_test_session(db: &DbPool) -> String {
        let conn = db.write().unwrap();
        let user = crate::db::queries::users::create_user(
            &conn,
            &crate::db::models::CreateUser {
                username: "oauthtest".into(),
                email: "oauth@test.com".into(),
                password: "testpassword1".into(),
                display_name: None,
                is_admin: false,
                is_bot: false,
            },
        )
        .unwrap();
        let session = crate::db::queries::users::create_session(&conn, user.id, None).unwrap();
        session.token
    }

    /// Build the form body for an authorize POST, including a CSRF token bound
    /// to the complete authorization request and `binding` (the session
    /// credential the POST will carry: a Bearer token, a cookie value, or ""
    /// for the unauthenticated case).
    fn authorize_body(client_id: &str, redirect_uri: &str, binding: &str) -> String {
        let challenge = test_code_challenge();
        let request = AuthorizationRequest {
            client_id,
            redirect_uri,
            response_type: "code",
            state: None,
            code_challenge: Some(&challenge),
            code_challenge_method: Some("S256"),
            scope: Some("mcp"),
        };
        let csrf = request.csrf_token(binding);
        format!(
            "client_id={}&redirect_uri={}&response_type=code&code_challenge={}&code_challenge_method=S256&scope=mcp&csrf_token={}&tool=claude-code&decision=approve",
            client_id,
            urlencoding::encode(redirect_uri),
            urlencoding::encode(&challenge),
            urlencoding::encode(&csrf),
        )
    }

    fn test_code_challenge() -> String {
        base64_url_encode(&Sha256::digest(
            b"test_verifier_abcdefghijklmnopqrstuvwxyz_0123456789",
        ))
    }

    // ── Authorization approval validates tokens ─────────────

    #[tokio::test]
    async fn authorize_rejects_missing_auth() {
        let (app, _db) = test_oauth_app();
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let body = authorize_body(&client_id, "http://localhost/callback", "");
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn authorize_consent_identifies_client_and_capability() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let challenge = test_code_challenge();
        let uri = format!(
            "/oauth/authorize?client_id={client_id}&redirect_uri={}&response_type=code&scope=mcp&code_challenge={challenge}&code_challenge_method=S256",
            urlencoding::encode("http://localhost/callback"),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri(uri)
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = String::from_utf8(
            resp.into_body()
                .collect()
                .await
                .unwrap()
                .to_bytes()
                .to_vec(),
        )
        .unwrap();
        assert!(body.contains("Test Client"));
        assert!(body.contains("MCP issue-tracker access"));
        assert!(body.contains("http://localhost/callback"));
        assert!(body.contains("30 days"));
        assert!(body.contains("oauthtest"));
        assert!(!body.contains("An application wants"));
    }

    /// Consent names the approving account, so the page needs a session where
    /// it used to render for anyone. That makes arriving signed out the normal
    /// first case for every browser client that sends its user straight here,
    /// so the refusal has to offer a way forward instead of dead-ending.
    #[tokio::test]
    async fn authorize_consent_signed_out_offers_a_way_to_sign_in() {
        let (app, _db) = test_oauth_app();
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let challenge = test_code_challenge();
        let uri = format!(
            "/oauth/authorize?client_id={client_id}&redirect_uri={}&response_type=code&scope=mcp&code_challenge={challenge}&code_challenge_method=S256",
            urlencoding::encode("http://localhost/callback"),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri(uri)
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        let body = String::from_utf8(
            resp.into_body()
                .collect()
                .await
                .unwrap()
                .to_bytes()
                .to_vec(),
        )
        .unwrap();
        assert!(
            body.contains("/#/login"),
            "signed-out consent must link to sign-in: {body}"
        );
    }

    #[tokio::test]
    async fn authorize_consent_rejects_unknown_capability_or_client() {
        let (app, _db) = test_oauth_app();
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let challenge = test_code_challenge();
        let bad_scope = format!(
            "/oauth/authorize?client_id={client_id}&redirect_uri={}&response_type=code&scope=admin&code_challenge={challenge}&code_challenge_method=S256",
            urlencoding::encode("http://localhost/callback"),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri(bad_scope)
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

        let unknown = format!(
            "/oauth/authorize?client_id=unknown&redirect_uri=http%3A%2F%2Flocalhost%2Fcallback&response_type=code&scope=mcp&code_challenge={challenge}&code_challenge_method=S256"
        );
        let resp = app
            .oneshot(
                Request::builder()
                    .uri(unknown)
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn authorize_consent_rejects_missing_scope_or_pkce() {
        let (app, _db) = test_oauth_app();
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let challenge = test_code_challenge();
        let base = format!(
            "/oauth/authorize?client_id={client_id}&redirect_uri={}&response_type=code",
            urlencoding::encode("http://localhost/callback")
        );

        for suffix in [
            "&code_challenge=__CHALLENGE__&code_challenge_method=S256",
            "&scope=mcp&code_challenge_method=S256",
            "&scope=mcp&code_challenge=__CHALLENGE__",
            "&scope=mcp&code_challenge=&code_challenge_method=S256",
            "&scope=mcp&code_challenge=__CHALLENGE__&code_challenge_method=plain",
        ] {
            let suffix = suffix.replace("__CHALLENGE__", &challenge);
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .uri(format!("{base}{suffix}"))
                        .body(axum::body::Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "suffix={suffix}");
        }
    }

    #[tokio::test]
    async fn authorize_deny_redirects_without_issuing_code() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let challenge = test_code_challenge();
        let request = AuthorizationRequest {
            client_id: &client_id,
            redirect_uri: "http://localhost/callback",
            response_type: "code",
            state: Some("opaque-state"),
            code_challenge: Some(&challenge),
            code_challenge_method: Some("S256"),
            scope: Some("mcp"),
        };
        let csrf = request.csrf_token(&session_token);
        let body = format!(
            "client_id={client_id}&redirect_uri={}&response_type=code&scope=mcp&code_challenge={challenge}&code_challenge_method=S256&state=opaque-state&csrf_token={csrf}&decision=deny",
            urlencoding::encode("http://localhost/callback"),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        if !resp.status().is_redirection() {
            let status = resp.status();
            let body = resp.into_body().collect().await.unwrap().to_bytes();
            panic!(
                "deny status={status}, body={}",
                String::from_utf8_lossy(&body)
            );
        }
        let location = resp.headers().get("location").unwrap().to_str().unwrap();
        assert!(location.starts_with("http://localhost/callback?error=access_denied"));
        assert!(location.contains("state=opaque-state"));
        let conn = db.read().unwrap();
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM oauth_codes", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0, "denial must not mint an authorization code");
    }

    #[tokio::test]
    async fn authorize_rejects_a_tampered_request_binding() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let original_client = register_client_helper(&app, "http://localhost/original").await;
        let tampered_client = register_client_helper(&app, "http://localhost/tampered").await;
        let challenge = test_code_challenge();
        let request = AuthorizationRequest {
            client_id: &original_client,
            redirect_uri: "http://localhost/original",
            response_type: "code",
            state: None,
            code_challenge: Some(&challenge),
            code_challenge_method: Some("S256"),
            scope: Some("mcp"),
        };
        let csrf = request.csrf_token(&session_token);
        let body = format!(
            "client_id={tampered_client}&redirect_uri={}&response_type=code&scope=mcp&code_challenge={challenge}&code_challenge_method=S256&csrf_token={csrf}&decision=approve",
            urlencoding::encode("http://localhost/tampered")
        );
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn authorize_rejects_malformed_pkce_challenge() {
        let (app, _db) = test_oauth_app();
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let uri = format!(
            "/oauth/authorize?client_id={client_id}&redirect_uri={}&response_type=code&scope=mcp&code_challenge=abc&code_challenge_method=S256",
            urlencoding::encode("http://localhost/callback")
        );
        let resp = app
            .oneshot(
                Request::builder()
                    .uri(uri)
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn authorize_requires_an_explicit_approval_decision() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let client_id = register_client_helper(&app, "http://localhost/callback").await;

        for decision in [None, Some("maybe")] {
            let mut body = authorize_body(&client_id, "http://localhost/callback", &session_token);
            body = body.replace("&decision=approve", "");
            if let Some(decision) = decision {
                body.push_str(&format!("&decision={decision}"));
            }
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/authorize")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("cookie", format!("lific_token={session_token}"))
                        .body(axum::body::Body::from(body))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        }
    }

    #[tokio::test]
    async fn authorize_rejects_garbage_bearer_token() {
        let (app, _db) = test_oauth_app();
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        // CSRF bound to the (garbage) token actually presented, so we exercise
        // the session-validation path rather than tripping the CSRF check.
        let body = authorize_body(
            &client_id,
            "http://localhost/callback",
            "lific_sess_fake_garbage_token",
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("authorization", "Bearer lific_sess_fake_garbage_token")
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn authorize_rejects_fake_cookie_token() {
        let (app, _db) = test_oauth_app();
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let body = authorize_body(
            &client_id,
            "http://localhost/callback",
            "lific_sess_fake_garbage_token",
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", "lific_token=lific_sess_fake_garbage_token")
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn authorize_accepts_valid_session_token() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let body = authorize_body(&client_id, "http://localhost/callback", &session_token);
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("authorization", format!("Bearer {session_token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        // Should redirect (303 or 302), not reject
        assert!(
            resp.status().is_redirection() || resp.status() == StatusCode::SEE_OTHER,
            "expected redirect, got {}",
            resp.status()
        );
    }

    #[tokio::test]
    async fn authorize_accepts_valid_cookie_session() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let body = authorize_body(&client_id, "http://localhost/callback", &session_token);
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert!(
            resp.status().is_redirection(),
            "expected redirect, got {}",
            resp.status()
        );
    }

    /// CSRF regression: a token harvested from the unauthenticated authorize
    /// page (bound to no session, `binding=""`) must NOT validate when replayed
    /// against a victim's authenticated session. This is the exact cross-site
    /// attack the binding closes — without it, the harvested token would pass
    /// CSRF and the victim's cookie would drive an approval. Expect 403, not a
    /// redirect.
    #[tokio::test]
    async fn authorize_rejects_unbound_csrf_replayed_with_victim_session() {
        let (app, db) = test_oauth_app();
        let victim_session = create_test_session(&db);
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        // Attacker mints a CSRF from the public GET page → bound to "".
        let body = authorize_body(&client_id, "http://localhost/callback", "");
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    // Victim's session rides along (e.g. via cookie).
                    .header("cookie", format!("lific_token={victim_session}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::FORBIDDEN,
            "harvested unbound CSRF must be rejected against a victim session"
        );
    }

    /// The authorize page binds the CSRF token to the session that loaded it, so
    /// a CSRF minted for one session must not authorize a different one.
    #[tokio::test]
    async fn authorize_rejects_csrf_bound_to_a_different_session() {
        let (app, db) = test_oauth_app();
        let victim_session = create_test_session(&db);
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        // CSRF bound to some OTHER session value than the one presented.
        let body = authorize_body(
            &client_id,
            "http://localhost/callback",
            "lific_sess_some_other_session",
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("authorization", format!("Bearer {victim_session}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    /// Unit-level proof the binding is enforced in the token primitives.
    #[test]
    fn csrf_token_is_bound_to_its_session() {
        let t = generate_csrf_token("session-A");
        assert!(validate_csrf_token(&t, "session-A"));
        assert!(!validate_csrf_token(&t, "session-B"));
        assert!(!validate_csrf_token(&t, ""));
    }

    // ── LIF-208: constant-time CSRF MAC verification ─────────
    // The validator now hex-decodes the presented signature and verifies it
    // with the MAC's own constant-time compare. These guard the new decode
    // path: a valid token still round-trips, and tampered / malformed
    // signatures are rejected rather than panicking or short-circuiting.
    #[test]
    fn csrf_rejects_tampered_and_malformed_signatures() {
        let t = generate_csrf_token("sess");
        assert!(
            validate_csrf_token(&t, "sess"),
            "honest token must validate"
        );

        let (ts, sig) = t.split_once('.').unwrap();

        // Flip one hex nibble in the signature → MAC mismatch, must reject.
        let mut bad = sig.to_string();
        let first = bad.remove(0);
        let flipped = if first == '0' { '1' } else { '0' };
        bad.insert(0, flipped);
        assert!(!validate_csrf_token(&format!("{ts}.{bad}"), "sess"));

        // Non-hex characters in the signature → decode fails, must reject.
        assert!(!validate_csrf_token(&format!("{ts}.zzzz"), "sess"));

        // Odd-length hex → decode fails, must reject.
        assert!(!validate_csrf_token(&format!("{ts}.abc"), "sess"));

        // Empty signature → reject.
        assert!(!validate_csrf_token(&format!("{ts}."), "sess"));
    }

    #[test]
    fn hex_decode_roundtrips_and_rejects_bad_input() {
        assert_eq!(hex_decode("00ff10").unwrap(), vec![0x00, 0xff, 0x10]);
        assert_eq!(hex_decode(&hex_encode(b"lific")).unwrap(), b"lific");
        assert!(hex_decode("abc").is_err(), "odd length rejected");
        assert!(hex_decode("zz").is_err(), "non-hex rejected");
    }

    // ── LIF-49: metadata does not advertise refresh_token ────

    #[tokio::test]
    async fn metadata_does_not_advertise_refresh_token() {
        let (app, _) = test_oauth_app();
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/.well-known/oauth-authorization-server")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let val: serde_json::Value = serde_json::from_slice(&bytes).unwrap();

        let grants = val["grant_types_supported"].as_array().unwrap();
        assert!(
            !grants.iter().any(|g| g == "refresh_token"),
            "metadata should not advertise refresh_token grant"
        );
        assert!(grants.iter().any(|g| g == "authorization_code"));
    }

    #[tokio::test]
    async fn register_defaults_do_not_include_refresh_token() {
        let (app, _) = test_oauth_app();
        let body = serde_json::json!({
            "redirect_uris": ["http://localhost/callback"],
            "client_name": "Test"
        });
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/register")
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let val: serde_json::Value = serde_json::from_slice(&bytes).unwrap();

        let grants = val["grant_types"].as_array().unwrap();
        assert!(
            !grants.iter().any(|g| g == "refresh_token"),
            "client registration should not default to refresh_token"
        );
    }

    #[tokio::test]
    async fn registration_allows_no_redirect_only_for_device_clients() {
        let (app, _) = test_oauth_app();
        for (body, expected) in [
            (
                serde_json::json!({
                    "redirect_uris": [],
                    "client_name": "Device Client",
                    "grant_types": [DEVICE_CODE_GRANT],
                    "response_types": [],
                }),
                StatusCode::CREATED,
            ),
            (
                serde_json::json!({
                    "redirect_uris": [],
                    "client_name": "Authorization Client",
                }),
                StatusCode::BAD_REQUEST,
            ),
        ] {
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/register")
                        .header("content-type", "application/json")
                        .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), expected, "body={body}");
        }
    }

    // ── Dynamic clients are reclaimable once their grants are dead ──
    //
    // `oauth_clients` is referenced by `oauth_codes` and `oauth_tokens`, so a
    // client cannot be deleted while any row points at it. Device grants now
    // carry a real registered client rather than the old shared `device` row,
    // so without a way to clear dead grants every CLI login would consume one
    // of MAX_DYNAMIC_CLIENT_ROWS permanently and registration would
    // eventually fail for everyone.

    /// Insert a token row against `client_id` and age the client past the
    /// retention window, so the next registration considers it for reclaim.
    fn plant_aged_client_token(
        db: &DbPool,
        client_id: &str,
        access_token: &str,
        revoked: i64,
        expires_at: chrono::DateTime<chrono::Utc>,
    ) {
        let conn = db.write().unwrap();
        conn.execute(
            "INSERT INTO oauth_tokens (access_token, client_id, expires_at, scope, revoked)
             VALUES (?1, ?2, ?3, 'mcp', ?4)",
            params![access_token, client_id, expires_at.to_rfc3339(), revoked],
        )
        .unwrap();
        conn.execute(
            "UPDATE oauth_clients SET created_at = datetime('now', '-30 days')
             WHERE client_id = ?1",
            params![client_id],
        )
        .unwrap();
    }

    fn client_exists(db: &DbPool, client_id: &str) -> bool {
        db.read()
            .unwrap()
            .query_row(
                "SELECT COUNT(*) FROM oauth_clients WHERE client_id = ?1",
                params![client_id],
                |row| row.get::<_, i64>(0),
            )
            .unwrap()
            > 0
    }

    #[tokio::test]
    async fn a_revoked_grant_stops_pinning_its_client() {
        let (app, db) = test_oauth_app();
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        plant_aged_client_token(
            &db,
            &client_id,
            "revoked-hash",
            1,
            chrono::Utc::now() + chrono::Duration::days(30),
        );

        // Any later registration runs the reclaim.
        let _ = register_client_helper(&app, "http://localhost/other").await;

        assert!(
            !client_exists(&db, &client_id),
            "a revoked grant must not pin its client forever"
        );
    }

    /// `oauth_device_codes.client_id` is a foreign key with no ON DELETE, so
    /// an aged client with a leftover device row does not merely survive the
    /// reclaim: it fails the whole DELETE, and registration answers 503 for
    /// everyone. Expired device rows are only swept when someone starts a
    /// device flow, so on an instance that never runs one they last forever.
    #[tokio::test]
    async fn a_stale_device_grant_cannot_break_registration() {
        let (app, db) = test_oauth_app();
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        {
            let conn = db.write().unwrap();
            conn.execute(
                "INSERT INTO oauth_device_codes
                    (device_code_hash, user_code, client_name, expires_at, interval_seconds,
                     status, scope, client_id)
                 VALUES ('stale-hash', 'BCDF-GHJK', 'Stale', ?1, 5, 'pending', 'mcp', ?2)",
                params![
                    (chrono::Utc::now() - chrono::Duration::days(8)).to_rfc3339(),
                    client_id
                ],
            )
            .unwrap();
            conn.execute(
                "UPDATE oauth_clients SET created_at = datetime('now', '-30 days')
                 WHERE client_id = ?1",
                params![client_id],
            )
            .unwrap();
        }

        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/register")
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(
                        serde_json::json!({
                            "redirect_uris": ["http://localhost/other"],
                            "client_name": "Later Client",
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::CREATED,
            "a leftover device grant must not take registration down"
        );
        assert!(
            !client_exists(&db, &client_id),
            "the expired device grant should have been swept, freeing its client"
        );
    }

    /// The reclaim must not become a way to delete clients that are still in
    /// use. Connected Tools treats a bot as connected while it holds any
    /// unrevoked token regardless of OAuth expiry, so an expired-but-live
    /// token has to keep its client too.
    #[tokio::test]
    async fn a_live_or_merely_expired_grant_still_pins_its_client() {
        for (label, expires_at) in [
            ("live", chrono::Utc::now() + chrono::Duration::days(30)),
            ("expired", chrono::Utc::now() - chrono::Duration::days(30)),
        ] {
            let (app, db) = test_oauth_app();
            let client_id = register_client_helper(&app, "http://localhost/callback").await;
            plant_aged_client_token(&db, &client_id, "unrevoked-hash", 0, expires_at);

            let _ = register_client_helper(&app, "http://localhost/other").await;

            assert!(
                client_exists(&db, &client_id),
                "an unrevoked ({label}) grant must keep its client"
            );
        }
    }

    // ── LIF-415: only public-client auth is advertised ──────────
    //
    // No client secret is ever issued (registration returns a client_id and
    // nothing else) and `token_exchange` never looks for one, so advertising
    // `client_secret_post` promised an authentication method that does not
    // exist. A client that sent a secret would have it silently ignored.

    #[tokio::test]
    async fn metadata_advertises_only_public_client_auth() {
        let (app, _) = test_oauth_app();
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/.well-known/oauth-authorization-server")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let val: serde_json::Value = serde_json::from_slice(&bytes).unwrap();

        let methods = val["token_endpoint_auth_methods_supported"]
            .as_array()
            .unwrap();
        assert_eq!(
            methods,
            &vec![serde_json::Value::from("none")],
            "only `none` is implemented, so only `none` may be advertised"
        );
    }

    #[tokio::test]
    async fn register_reports_none_auth_method_even_when_a_secret_is_requested() {
        let (app, _) = test_oauth_app();
        let body = serde_json::json!({
            "redirect_uris": ["http://localhost/callback"],
            "client_name": "Test",
            "token_endpoint_auth_method": "client_secret_post"
        });
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/register")
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::CREATED);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let val: serde_json::Value = serde_json::from_slice(&bytes).unwrap();

        assert_eq!(
            val["token_endpoint_auth_method"], "none",
            "the response states what was registered, not what was asked for"
        );
        assert!(
            val.get("client_secret").is_none(),
            "no client secret is ever issued"
        );
    }

    // ── Protected-resource metadata advertises the /mcp resource ──
    // Claude.ai derives the RFC 8707 audience from the MCP URL the user enters
    // (`https://host/mcp`) and rejects the issued token if the protected-resource
    // metadata's `resource` is the bare origin. Both the root and the path-aware
    // well-known routes must advertise the path-qualified resource.
    #[tokio::test]
    async fn protected_resource_metadata_resource_includes_mcp_path() {
        let (app, _) = test_oauth_app();
        for path in [
            "/.well-known/oauth-protected-resource",
            "/.well-known/oauth-protected-resource/mcp",
        ] {
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .uri(path)
                        .body(axum::body::Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::OK, "path {path}");
            let bytes = resp.into_body().collect().await.unwrap().to_bytes();
            let val: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
            assert_eq!(val["resource"], "https://example.com/mcp", "path {path}");
            assert_eq!(
                val["authorization_servers"][0], "https://example.com",
                "path {path}"
            );
        }
    }

    // ── LIF-287: Host-derived issuer fallback ────────────────
    // When public_url is unset the advertised issuer may be replaced by the
    // request Host, but only for allowlisted (loopback) hosts. An explicit
    // public_url is never overridden, and forwarded headers are ignored.

    /// GET a metadata path and parse the JSON body.
    async fn get_metadata(app: &Router, path: &str, headers: &[(&str, &str)]) -> serde_json::Value {
        let mut builder = Request::builder().uri(path);
        for (name, value) in headers {
            builder = builder.header(*name, *value);
        }
        let resp = app
            .clone()
            .oneshot(builder.body(axum::body::Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK, "path {path}");
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        serde_json::from_slice(&bytes).unwrap()
    }

    #[tokio::test]
    async fn metadata_derives_issuer_from_allowlisted_host() {
        let app = test_oauth_app_implicit_issuer();

        let val = get_metadata(
            &app,
            "/.well-known/oauth-authorization-server",
            &[("host", "localhost:3456")],
        )
        .await;
        assert_eq!(val["issuer"], "http://localhost:3456");
        assert_eq!(val["token_endpoint"], "http://localhost:3456/oauth/token");

        let val = get_metadata(
            &app,
            "/.well-known/oauth-protected-resource",
            &[("host", "localhost:3456")],
        )
        .await;
        assert_eq!(val["resource"], "http://localhost:3456/mcp");
        assert_eq!(val["authorization_servers"][0], "http://localhost:3456");
    }

    #[tokio::test]
    async fn metadata_derives_issuer_from_ipv6_loopback_host() {
        let app = test_oauth_app_implicit_issuer();
        let val = get_metadata(
            &app,
            "/.well-known/oauth-authorization-server",
            &[("host", "[::1]:3456")],
        )
        .await;
        assert_eq!(val["issuer"], "http://[::1]:3456");
    }

    #[tokio::test]
    async fn metadata_falls_back_to_static_issuer_for_unallowlisted_host() {
        let app = test_oauth_app_implicit_issuer();
        let val = get_metadata(
            &app,
            "/.well-known/oauth-authorization-server",
            &[("host", "evil.example.com")],
        )
        .await;
        assert_eq!(
            val["issuer"], "http://127.0.0.1:3456",
            "unallowlisted Host must not control the advertised issuer"
        );

        let val = get_metadata(
            &app,
            "/.well-known/oauth-protected-resource",
            &[("host", "evil.example.com")],
        )
        .await;
        assert_eq!(val["resource"], "http://127.0.0.1:3456/mcp");
    }

    #[tokio::test]
    async fn metadata_ignores_forwarded_headers() {
        let app = test_oauth_app_implicit_issuer();
        let val = get_metadata(
            &app,
            "/.well-known/oauth-authorization-server",
            &[
                ("host", "localhost:3456"),
                ("x-forwarded-host", "evil.example.com"),
                ("x-forwarded-proto", "https"),
            ],
        )
        .await;
        assert_eq!(
            val["issuer"], "http://localhost:3456",
            "X-Forwarded-* must never influence the advertised issuer"
        );
    }

    #[tokio::test]
    async fn explicit_public_url_issuer_is_never_overridden_by_host() {
        // test_oauth_app() marks the issuer explicit (public_url set).
        let (app, _) = test_oauth_app();
        for host in ["localhost:3456", "evil.example.com"] {
            let val = get_metadata(
                &app,
                "/.well-known/oauth-authorization-server",
                &[("host", host)],
            )
            .await;
            assert_eq!(val["issuer"], "https://example.com", "host {host}");
        }
    }

    // ── LIF-50: token revocation ─────────────────────────────

    #[tokio::test]
    async fn revoke_token_invalidates_access() {
        let (app, db) = test_oauth_app();

        // Manually insert a token to revoke (stored as SHA-256 hash)
        let token = "lific_at_test-revoke-token";
        let token_hash = sha256_hex(token.as_bytes());
        let expires = (chrono::Utc::now() + chrono::Duration::hours(24)).to_rfc3339();
        {
            let conn = db.write().unwrap();
            // Need a client first
            conn.execute(
                "INSERT INTO oauth_clients (client_id, client_name, redirect_uris) VALUES ('test-client', 'Test', '[\"http://localhost\"]')",
                [],
            ).unwrap();
            conn.execute(
                "INSERT INTO oauth_tokens (access_token, client_id, expires_at, scope) VALUES (?1, 'test-client', ?2, 'mcp')",
                params![token_hash, expires],
            ).unwrap();
        }

        // Token should be valid
        assert!(resolve_oauth_credential(&db, token).is_ok());

        // Revoke it (must be authenticated)
        let body = format!("token={token}");
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/revoke")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("authorization", format!("Bearer {token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        // Token should now be invalid
        assert!(resolve_oauth_credential(&db, token).is_err());
    }

    #[tokio::test]
    async fn revoke_unauthenticated_returns_401() {
        let (app, _) = test_oauth_app();

        // Without auth, revoke should be rejected
        let body = "token=lific_at_nonexistent";
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/revoke")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn revoke_unknown_token_returns_200() {
        let (app, db) = test_oauth_app();

        // Create a valid token so we can authenticate the revoke request
        let auth_token = "lific_at_auth-for-revoke";
        let auth_hash = sha256_hex(auth_token.as_bytes());
        let expires = (chrono::Utc::now() + chrono::Duration::hours(24)).to_rfc3339();
        {
            let conn = db.write().unwrap();
            conn.execute(
                "INSERT INTO oauth_clients (client_id, client_name, redirect_uris) VALUES ('revoke-test', 'Test', '[\"http://localhost\"]')",
                [],
            ).unwrap();
            conn.execute(
                "INSERT INTO oauth_tokens (access_token, client_id, expires_at, scope) VALUES (?1, 'revoke-test', ?2, 'mcp')",
                params![auth_hash, expires],
            ).unwrap();
        }

        // RFC 7009: always return 200, even for unknown tokens (when authenticated)
        let body = "token=lific_at_nonexistent";
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/revoke")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("authorization", format!("Bearer {auth_token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    // ── LIF-51: metadata advertises revocation endpoint ──────

    #[tokio::test]
    async fn metadata_includes_revocation_endpoint() {
        let (app, _) = test_oauth_app();
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/.well-known/oauth-authorization-server")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let val: serde_json::Value = serde_json::from_slice(&bytes).unwrap();

        assert!(val["revocation_endpoint"].as_str().is_some());
        assert!(
            val["revocation_endpoint"]
                .as_str()
                .unwrap()
                .ends_with("/oauth/revoke")
        );
    }

    // ── LIF-51 / LIF-384: scope is stored and advertised, never enforced ──
    //
    // The two tests that lived here exercised `validate_oauth_token_with_scope`,
    // which is gone: nothing compared its return value against a required
    // scope. Revoked tokens failing validation is covered by
    // `revoke_token_invalidates_access`, and the `scope` field clients read off
    // the token response is pinned in
    // `device_consumed_code_cannot_mint_a_second_token`.

    // ── LIF-64: redirect_uri validation + register rate limit ─────────────

    #[test]
    fn validate_redirect_uri_accepts_http_and_https() {
        assert!(validate_redirect_uri("http://localhost/callback").is_ok());
        assert!(validate_redirect_uri("http://127.0.0.1:8080/cb").is_ok());
        assert!(validate_redirect_uri("https://app.example.com/oauth/callback").is_ok());
        assert!(validate_redirect_uri("HTTP://localhost/callback").is_ok());
        assert!(validate_redirect_uri("HTTPS://example.com/").is_ok());
    }

    #[test]
    fn validate_redirect_uri_rejects_dangerous_schemes() {
        for evil in [
            "javascript:alert(1)",
            "JavaScript:alert(1)",
            "data:text/html,<script>alert(1)</script>",
            "file:///etc/passwd",
            "vbscript:msgbox()",
            "about:blank",
            "blob:https://evil/x",
            "ftp://example.com/",
            "myapp://callback",
        ] {
            assert!(
                validate_redirect_uri(evil).is_err(),
                "should reject: {evil}"
            );
        }
    }

    #[test]
    fn validate_redirect_uri_rejects_log_injection_characters() {
        assert!(validate_redirect_uri(" http://localhost/callback").is_err());
        assert!(validate_redirect_uri("http://localhost/callback\nforged=entry").is_err());
    }

    #[test]
    fn validate_redirect_uri_rejects_malformed() {
        assert!(validate_redirect_uri("").is_err());
        assert!(validate_redirect_uri("   ").is_err());
        assert!(validate_redirect_uri("http:evil").is_err());
        assert!(validate_redirect_uri("not-a-url").is_err());
        assert!(validate_redirect_uri("https://").is_err());
        assert!(validate_redirect_uri("http:///path").is_err());
    }

    #[test]
    fn validate_redirect_uri_rejects_fragments() {
        assert!(validate_redirect_uri("https://example.com/callback#fragment").is_err());
        assert!(validate_redirect_uri("https://example.com/callback?mode=full").is_ok());
    }

    #[tokio::test]
    async fn register_rejects_javascript_redirect_uri() {
        let (app, _) = test_oauth_app();
        let body = serde_json::json!({
            "redirect_uris": ["javascript:alert(1)"],
            "client_name": "Evil"
        });
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/register")
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let val: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(val["error"], "invalid_redirect_uri");
    }

    #[tokio::test]
    async fn register_rejects_when_any_redirect_is_invalid() {
        // One good, one bad — must reject the whole request.
        let (app, _) = test_oauth_app();
        let body = serde_json::json!({
            "redirect_uris": ["http://localhost/cb", "data:text/html,x"],
            "client_name": "Mixed"
        });
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/register")
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn register_rejects_oversized_client_metadata() {
        let (app, _) = test_oauth_app();
        let body = serde_json::json!({
            "redirect_uris": ["http://localhost/callback"],
            "client_name": "x".repeat(MAX_CLIENT_NAME_BYTES + 1)
        });
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/register")
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn register_rejects_too_many_redirect_uris() {
        let (app, _) = test_oauth_app();
        let body = serde_json::json!({
            "redirect_uris": (0..=MAX_REDIRECT_URIS)
                .map(|_| "http://localhost/callback")
                .collect::<Vec<_>>()
        });
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/register")
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn register_storage_cap_is_persistent_and_global() {
        let (app, db) = test_oauth_app();
        {
            let conn = db.write().unwrap();
            for index in 0..MAX_DYNAMIC_CLIENT_ROWS {
                conn.execute(
                    "INSERT INTO oauth_clients (client_id, client_name, redirect_uris) VALUES (?1, 'Test', '[\"http://localhost/callback\"]')",
                    params![format!("cap-client-{index}")],
                )
                .unwrap();
            }
        }

        let body = serde_json::json!({
            "redirect_uris": ["http://localhost/callback"],
            "client_name": "After restart"
        });
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/register")
                    .header("content-type", "application/json")
                    .header("x-forwarded-for", "198.51.100.200")
                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
    }

    #[tokio::test]
    async fn register_storage_cap_counts_utf8_bytes() {
        let (app, db) = test_oauth_app();
        let multibyte_name = "é".repeat(7_000);
        {
            let conn = db.write().unwrap();
            for index in 0..512 {
                conn.execute(
                    "INSERT INTO oauth_clients (client_id, client_name, redirect_uris)
                     VALUES (?1, ?2, '[\"http://localhost/callback\"]')",
                    params![format!("utf8-cap-client-{index}"), &multibyte_name],
                )
                .unwrap();
            }
        }

        let body = serde_json::json!({
            "redirect_uris": ["http://localhost/callback"],
            "client_name": "After UTF-8 cap"
        });
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/register")
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
    }

    #[tokio::test]
    async fn device_storage_cap_rejects_new_sources() {
        let (app, db) = test_oauth_app();
        let expires_at = (chrono::Utc::now() + chrono::Duration::minutes(5)).to_rfc3339();
        {
            let conn = db.write().unwrap();
            conn.execute(
                "INSERT INTO oauth_clients (client_id, client_name, redirect_uris) VALUES ('device-cap-client', 'Device cap test', '[]')",
                [],
            )
            .unwrap();
            for index in 0..MAX_DEVICE_CODE_ROWS {
                conn.execute(
                    "INSERT INTO oauth_device_codes
                        (device_code_hash, user_code, expires_at, interval_seconds, status)
                     VALUES (?1, ?2, ?3, 5, 'pending')",
                    params![
                        format!("device-hash-{index}"),
                        format!("ABCD-{index:04}"),
                        expires_at
                    ],
                )
                .unwrap();
            }
        }

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/device_authorization")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("x-forwarded-for", "198.51.100.201")
                    .body(axum::body::Body::from(
                        "scope=mcp&client_id=device-cap-client",
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
    }

    #[test]
    fn rfc3339_expiry_is_rejected_even_before_utc_midnight() {
        let (_, db) = test_oauth_app();
        let token = "lific_at_expired-rfc3339";
        let token_hash = hex_encode(&Sha256::digest(token.as_bytes()));
        let expires = (chrono::Utc::now() - chrono::Duration::minutes(5)).to_rfc3339();
        let conn = db.write().unwrap();
        conn.execute(
            "INSERT INTO oauth_clients (client_id, client_name, redirect_uris) VALUES ('expiry-client', 'Test', '[\"http://localhost\"]')",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO oauth_tokens (access_token, client_id, expires_at, scope) VALUES (?1, 'expiry-client', ?2, 'mcp')",
            params![token_hash, expires],
        )
        .unwrap();
        drop(conn);
        assert!(matches!(
            resolve_oauth_credential(&db, token),
            Err(OAuthReject::Invalid)
        ));
    }

    #[tokio::test]
    async fn register_rate_limits_after_cap() {
        // Cap at 2 registrations per IP (window from test_oauth_app helper).
        let (app, _) = test_oauth_app_with_register_limit(2);
        let body = serde_json::json!({
            "redirect_uris": ["http://localhost/callback"],
            "client_name": "RL Test"
        });
        let send = || {
            let app = app.clone();
            let body = body.clone();
            async move {
                app.oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/register")
                        .header("content-type", "application/json")
                        .header("x-forwarded-for", "192.0.2.42")
                        .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                        .unwrap(),
                )
                .await
                .unwrap()
            }
        };

        assert_eq!(send().await.status(), StatusCode::CREATED);
        assert_eq!(send().await.status(), StatusCode::CREATED);
        let limited = send().await;
        assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS);
        assert!(limited.headers().get("retry-after").is_some());
    }

    #[tokio::test]
    async fn register_rate_limit_is_per_ip() {
        // Distinct X-Forwarded-For values should each get their own bucket.
        let (app, _) = test_oauth_app_with_register_limit(1);
        let body = serde_json::json!({
            "redirect_uris": ["http://localhost/callback"],
            "client_name": "Per-IP Test"
        });
        let send = |ip: &'static str| {
            let app = app.clone();
            let body = body.clone();
            async move {
                app.oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/register")
                        .header("content-type", "application/json")
                        .header("x-forwarded-for", ip)
                        .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                        .unwrap(),
                )
                .await
                .unwrap()
            }
        };

        // First IP: allowed.
        assert_eq!(send("198.51.100.1").await.status(), StatusCode::CREATED);
        // Same IP again: limited (cap=1).
        assert_eq!(
            send("198.51.100.1").await.status(),
            StatusCode::TOO_MANY_REQUESTS
        );
        // Different IP: allowed (independent bucket).
        assert_eq!(send("198.51.100.2").await.status(), StatusCode::CREATED);
    }

    // ── LIF-79: OAuth codes/tokens bound to approving user ───────────────

    #[tokio::test]
    async fn token_is_bound_to_approving_user() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db); // creates user "oauthtest"
        let client_id = register_client_helper(&app, "http://localhost/callback").await;

        let user_id: i64 = {
            let conn = db.read().unwrap();
            conn.query_row(
                "SELECT id FROM users WHERE username = 'oauthtest'",
                [],
                |r| r.get(0),
            )
            .unwrap()
        };

        // A real PKCE pair so the later token exchange passes verification.
        let verifier = "test_verifier_abcdefghijklmnopqrstuvwxyz_0123456789";
        let challenge = base64_url_encode(&Sha256::digest(verifier.as_bytes()));
        // CSRF bound to the complete request and session presented on approval.
        let request = AuthorizationRequest {
            client_id: &client_id,
            redirect_uri: "http://localhost/callback",
            response_type: "code",
            state: None,
            code_challenge: Some(&challenge),
            code_challenge_method: Some("S256"),
            scope: Some(OAUTH_SCOPE),
        };
        let csrf = request.csrf_token(&session_token);
        let body = format!(
            "client_id={}&redirect_uri={}&response_type=code&code_challenge={}&code_challenge_method=S256&scope=mcp&csrf_token={}&tool=claude-code&decision=approve",
            client_id,
            urlencoding::encode("http://localhost/callback"),
            urlencoding::encode(&challenge),
            urlencoding::encode(&csrf),
        );

        // Approve via the session cookie.
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert!(
            resp.status().is_redirection(),
            "approve should redirect, got {}",
            resp.status()
        );
        let location = resp
            .headers()
            .get("location")
            .unwrap()
            .to_str()
            .unwrap()
            .to_string();
        let code = location
            .split("code=")
            .nth(1)
            .unwrap()
            .split('&')
            .next()
            .unwrap()
            .to_string();

        // LIFIC-13: the issued credential binds to the per-tool BOT, not the
        // approving human, so the audit log distinguishes which tool acted.
        let (bot_id, bot_username): (i64, String) = {
            let conn = db.read().unwrap();
            conn.query_row(
                "SELECT id, username FROM users WHERE username = 'claude-code-oauthtest'",
                [],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .unwrap()
        };
        assert!(!bot_username.is_empty());
        {
            let conn = db.read().unwrap();
            let code_user: Option<i64> = conn
                .query_row(
                    "SELECT user_id FROM oauth_codes WHERE code = ?1",
                    params![code],
                    |r| r.get(0),
                )
                .unwrap();
            assert_eq!(
                code_user,
                Some(bot_id),
                "code should bind the tool bot, not the approver"
            );
        }

        // Exchange the code; the issued token must carry the same identity.
        let token_body = format!(
            "grant_type=authorization_code&code={}&redirect_uri={}&client_id={}&code_verifier={}",
            code,
            urlencoding::encode("http://localhost/callback"),
            client_id,
            verifier,
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/token")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(axum::body::Body::from(token_body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "token exchange should succeed"
        );
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let val: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        let access_token = val["access_token"].as_str().unwrap();

        // The middleware resolves this token to the tool bot, not the human.
        assert_eq!(bound_user(&db, access_token), Some(bot_id));
        assert_ne!(bot_id, user_id, "bot must differ from the approving human");
    }

    #[tokio::test]
    async fn reapproval_reuses_the_same_tool_bot() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db); // user "oauthtest"
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let challenge = test_code_challenge();

        let approve = |app: Router| {
            let request = AuthorizationRequest {
                client_id: &client_id,
                redirect_uri: "http://localhost/callback",
                response_type: "code",
                state: None,
                code_challenge: Some(&challenge),
                code_challenge_method: Some("S256"),
                scope: Some(OAUTH_SCOPE),
            };
            let csrf = request.csrf_token(&session_token);
            let body = format!(
                "client_id={}&redirect_uri={}&response_type=code&code_challenge={}&code_challenge_method=S256&scope=mcp&csrf_token={}&tool=opencode&decision=approve",
                client_id,
                urlencoding::encode("http://localhost/callback"),
                urlencoding::encode(&challenge),
                urlencoding::encode(&csrf),
            );
            app.oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
        };

        assert!(
            approve(app.clone())
                .await
                .unwrap()
                .status()
                .is_redirection()
        );
        let first_id: i64 = {
            let conn = db.read().unwrap();
            conn.query_row(
                "SELECT id FROM users WHERE username = 'opencode-oauthtest'",
                [],
                |r| r.get(0),
            )
            .unwrap()
        };
        // Re-approval of the same tool+owner must reuse the same bot.
        assert!(
            approve(app.clone())
                .await
                .unwrap()
                .status()
                .is_redirection()
        );
        let second_id: i64 = {
            let conn = db.read().unwrap();
            conn.query_row(
                "SELECT id FROM users WHERE username = 'opencode-oauthtest'",
                [],
                |r| r.get(0),
            )
            .unwrap()
        };
        assert_eq!(
            first_id, second_id,
            "re-approval must reuse the same bot, not mint a duplicate"
        );
    }

    // ── LIFIC-15: remember tool per client, pre-fill on reconnect ──

    #[tokio::test]
    async fn approve_persists_remembered_tool_on_client() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let client_id = register_client_helper(&app, "http://localhost/callback").await;

        let body = authorize_body(&client_id, "http://localhost/callback", &session_token);
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert!(resp.status().is_redirection());

        // The approved tool choice is remembered on the registered client.
        let tool_id: Option<String> = {
            let conn = db.read().unwrap();
            conn.query_row(
                "SELECT tool_id FROM oauth_clients WHERE client_id = ?1",
                params![client_id],
                |r| r.get(0),
            )
            .unwrap()
        };
        assert_eq!(tool_id.as_deref(), Some("claude-code"));
    }

    #[tokio::test]
    async fn authorize_page_prefills_remembered_known_tool() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let challenge = test_code_challenge();

        // Remember the tool on the client directly (as an approval would).
        {
            let conn = db.write().unwrap();
            conn.execute(
                "UPDATE oauth_clients SET tool_id = 'opencode' WHERE client_id = ?1",
                params![client_id],
            )
            .unwrap();
        }

        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri(format!("/oauth/authorize?client_id={client_id}&redirect_uri={}&response_type=code&scope=mcp&code_challenge={challenge}&code_challenge_method=S256", urlencoding::encode("http://localhost/callback")))
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = String::from_utf8_lossy(&bytes);
        // Reconnect: the known tool is pre-selected (real browser behavior —
        // the placeholder must NOT also carry selected, or it wins in tree order).
        assert!(
            html.contains("value=\"opencode\" selected"),
            "known tool should be pre-selected, html={html}"
        );
        assert!(
            !html.contains("value=\"\" selected"),
            "placeholder must not also be selected when a tool is remembered, html={html}"
        );
    }

    #[tokio::test]
    async fn authorize_page_prefills_remembered_custom_tool() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let challenge = test_code_challenge();

        // A free-text tool: stored tool_id is a slug not in the registry.
        {
            let conn = db.write().unwrap();
            conn.execute(
                "UPDATE oauth_clients SET tool_id = 'my-editor' WHERE client_id = ?1",
                params![client_id],
            )
            .unwrap();
        }

        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri(format!("/oauth/authorize?client_id={client_id}&redirect_uri={}&response_type=code&scope=mcp&code_challenge={challenge}&code_challenge_method=S256", urlencoding::encode("http://localhost/callback")))
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = String::from_utf8_lossy(&bytes);
        // Reconnect: the custom field is revealed and pre-filled with the slug.
        assert!(
            html.contains("display:block"),
            "custom tool field should be revealed, html={html}"
        );
        assert!(
            html.contains("value=\"my-editor\""),
            "custom field should prefill the remembered slug, html={html}"
        );
    }

    #[tokio::test]
    async fn authorize_requires_a_tool_choice() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let challenge = test_code_challenge();
        let request = AuthorizationRequest {
            client_id: &client_id,
            redirect_uri: "http://localhost/callback",
            response_type: "code",
            state: None,
            code_challenge: Some(&challenge),
            code_challenge_method: Some("S256"),
            scope: Some(OAUTH_SCOPE),
        };
        let csrf = request.csrf_token(&session_token);
        // No tool, no tool_custom → must be rejected, not silently attributed.
        let body = format!(
            "client_id={}&redirect_uri={}&response_type=code&code_challenge={}&code_challenge_method=S256&scope=mcp&csrf_token={}&decision=approve",
            client_id,
            urlencoding::encode("http://localhost/callback"),
            urlencoding::encode(&challenge),
            urlencoding::encode(&csrf),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn authorize_rejects_reserved_free_text_tool() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let challenge = test_code_challenge();
        let request = AuthorizationRequest {
            client_id: &client_id,
            redirect_uri: "http://localhost/callback",
            response_type: "code",
            state: None,
            code_challenge: Some(&challenge),
            code_challenge_method: Some("S256"),
            scope: Some(OAUTH_SCOPE),
        };
        let csrf = request.csrf_token(&session_token);
        let body = format!(
            "client_id={}&redirect_uri={}&response_type=code&code_challenge={}&code_challenge_method=S256&scope=mcp&csrf_token={}&tool=__custom__&tool_custom=admin&decision=approve",
            client_id,
            urlencoding::encode("http://localhost/callback"),
            urlencoding::encode(&challenge),
            urlencoding::encode(&csrf),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn authorize_custom_tool_choice_mints_a_sanitized_bot() {
        // Selecting "Custom tool…" reveals a free-text field; a real custom
        // tool name sanitizes into the bot's username and mints it.
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let challenge = test_code_challenge();
        let request = AuthorizationRequest {
            client_id: &client_id,
            redirect_uri: "http://localhost/callback",
            response_type: "code",
            state: None,
            code_challenge: Some(&challenge),
            code_challenge_method: Some("S256"),
            scope: Some(OAUTH_SCOPE),
        };
        let csrf = request.csrf_token(&session_token);
        let body = format!(
            "client_id={}&redirect_uri={}&response_type=code&code_challenge={}&code_challenge_method=S256&scope=mcp&csrf_token={}&tool=__custom__&tool_custom=My Editor&decision=approve",
            client_id,
            urlencoding::encode("http://localhost/callback"),
            urlencoding::encode(&challenge),
            urlencoding::encode(&csrf),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/authorize")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert!(
            resp.status().is_redirection(),
            "custom free-text tool should approve, got {}",
            resp.status()
        );
        let bot: (String, String) = {
            let conn = db.read().unwrap();
            conn.query_row(
                "SELECT username, display_name FROM users WHERE username = 'my-editor-oauthtest'",
                [],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .unwrap()
        };
        assert_eq!(bot.0, "my-editor-oauthtest");
        assert_eq!(bot.1, "My Editor");
    }

    #[tokio::test]
    async fn legacy_token_without_user_resolves_to_none() {
        // Tokens issued before LIF-79 have NULL user_id and must keep working,
        // resolving to no user (anonymous) rather than erroring.
        let (_, db) = test_oauth_app();
        let token = "lific_at_legacy-no-user-binding";
        let token_hash = sha256_hex(token.as_bytes());
        let expires = (chrono::Utc::now() + chrono::Duration::hours(1)).to_rfc3339();
        {
            let conn = db.write().unwrap();
            conn.execute(
                "INSERT INTO oauth_clients (client_id, client_name, redirect_uris) VALUES ('legacy-c', 'Test', '[\"http://localhost\"]')",
                [],
            )
            .unwrap();
            // user_id intentionally omitted → NULL
            conn.execute(
                "INSERT INTO oauth_tokens (access_token, client_id, expires_at, scope) VALUES (?1, 'legacy-c', ?2, 'mcp')",
                params![token_hash, expires],
            )
            .unwrap();
        }
        assert!(
            resolve_oauth_credential(&db, token).is_ok(),
            "token still valid"
        );
        assert_eq!(
            bound_user(&db, token),
            None,
            "legacy token has no bound user"
        );
    }

    // ── LIF-252: device authorization flow (RFC 8628) ────────────────────

    /// POST /oauth/device_authorization and return the parsed JSON.
    async fn request_device_code(app: &Router, client_name: Option<&str>) -> serde_json::Value {
        let client_id = register_named_client_helper(
            app,
            "http://localhost/callback",
            client_name.unwrap_or("Test Device Client"),
        )
        .await;
        let body = format!("scope=mcp&client_id={}", urlencoding::encode(&client_id));
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/device_authorization")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        serde_json::from_slice(&bytes).unwrap()
    }

    /// POST the device grant to /oauth/token and return (status, json).
    async fn poll_device_token(app: &Router, device_code: &str) -> (StatusCode, serde_json::Value) {
        let body = format!(
            "grant_type={}&device_code={}",
            urlencoding::encode("urn:ietf:params:oauth:grant-type:device_code"),
            urlencoding::encode(device_code),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/token")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        let status = resp.status();
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let val = serde_json::from_slice(&bytes).unwrap_or_else(|_| serde_json::json!({}));
        (status, val)
    }

    #[tokio::test]
    async fn device_authorization_returns_wellformed_response() {
        let (app, _db) = test_oauth_app();
        let v = request_device_code(&app, Some("My CLI")).await;
        assert!(v["device_code"].as_str().is_some());
        let user_code = v["user_code"].as_str().unwrap();
        // Format XXXX-XXXX from the unambiguous alphabet.
        assert_eq!(user_code.len(), 9);
        assert_eq!(&user_code[4..5], "-");
        for c in user_code.chars().filter(|c| *c != '-') {
            assert!(
                USER_CODE_ALPHABET.contains(&(c as u8)),
                "user_code char {c} not in alphabet"
            );
        }
        assert_eq!(v["expires_in"], 900);
        assert_eq!(v["interval"], 5);
        assert_eq!(v["scope"], OAUTH_SCOPE);
        let vuri = v["verification_uri"].as_str().unwrap();
        assert!(vuri.ends_with("/oauth/device"));
        let vuc = v["verification_uri_complete"].as_str().unwrap();
        assert!(vuc.contains("user_code="));
    }

    /// RFC 8628 §3.1 makes `scope` OPTIONAL. A conforming client that omits it
    /// is asking for whatever the server offers, and Lific offers exactly one
    /// capability, so the request must succeed and record `mcp` rather than
    /// being refused on a technicality.
    #[tokio::test]
    async fn device_authorization_defaults_an_omitted_scope_to_mcp() {
        let (app, db) = test_oauth_app();
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/device_authorization")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(axum::body::Body::from(format!(
                        "client_id={}",
                        urlencoding::encode(&client_id)
                    )))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let v: serde_json::Value =
            serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap();
        assert_eq!(v["scope"], OAUTH_SCOPE);

        let stored: String = db
            .read()
            .unwrap()
            .query_row(
                "SELECT scope FROM oauth_device_codes WHERE user_code = ?1",
                params![v["user_code"].as_str().unwrap()],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(stored, OAUTH_SCOPE);
    }

    /// Defaulting an omitted scope must not become silently upgrading a
    /// different one: asking for something Lific does not have is still an
    /// error, not a quiet downgrade to `mcp`.
    #[tokio::test]
    async fn device_authorization_rejects_an_unsupported_scope() {
        let (app, _db) = test_oauth_app();
        let client_id = register_client_helper(&app, "http://localhost/callback").await;
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/device_authorization")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(axum::body::Body::from(format!(
                        "client_id={}&scope=admin",
                        urlencoding::encode(&client_id)
                    )))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let v: serde_json::Value =
            serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap();
        assert_eq!(v["error"], "invalid_scope");
    }

    #[tokio::test]
    async fn device_authorization_requires_a_registered_client() {
        let (app, db) = test_oauth_app();
        let client_id = register_client_helper(&app, "http://localhost/callback").await;

        for body in [
            "scope=mcp".to_string(),
            "scope=mcp&client_id=unknown".to_string(),
        ] {
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/device_authorization")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .body(axum::body::Body::from(body))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        }

        let body = format!(
            "scope=mcp&client_id={}&client_name=Impostor",
            urlencoding::encode(&client_id)
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/device_authorization")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let response: serde_json::Value =
            serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap();
        let user_code = response["user_code"].as_str().unwrap();
        let consent = pending_device_consent(&db, user_code).unwrap();
        assert_eq!(consent.client_name, "Test Client");
        assert_eq!(consent.client_id, client_id);
    }

    #[tokio::test]
    async fn device_code_stored_only_as_hash() {
        let (app, db) = test_oauth_app();
        let v = request_device_code(&app, None).await;
        let device_code = v["device_code"].as_str().unwrap();
        let hash = sha256_hex(device_code.as_bytes());
        let conn = db.read().unwrap();
        // The raw code must NOT be in the table; only its hash.
        let by_hash: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM oauth_device_codes WHERE device_code_hash = ?1",
                params![hash],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(by_hash, 1);
        let by_raw: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM oauth_device_codes WHERE device_code_hash = ?1",
                params![device_code],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(by_raw, 0, "raw device_code must not be stored");
    }

    #[tokio::test]
    async fn device_metadata_advertises_endpoint_and_grant() {
        let (app, _) = test_oauth_app();
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/.well-known/oauth-authorization-server")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert!(
            v["device_authorization_endpoint"]
                .as_str()
                .unwrap()
                .ends_with("/oauth/device_authorization")
        );
        let grants = v["grant_types_supported"].as_array().unwrap();
        assert!(
            grants
                .iter()
                .any(|g| g == "urn:ietf:params:oauth:grant-type:device_code"),
            "metadata must advertise the device grant"
        );
    }

    #[tokio::test]
    async fn device_polling_pending_then_approved_end_to_end() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db); // user "oauthtest"
        let user_id: i64 = {
            let conn = db.read().unwrap();
            conn.query_row(
                "SELECT id FROM users WHERE username = 'oauthtest'",
                [],
                |r| r.get(0),
            )
            .unwrap()
        };

        let v = request_device_code(&app, Some("laptop <img>")).await;
        let device_code = v["device_code"].as_str().unwrap().to_string();
        let user_code = v["user_code"].as_str().unwrap().to_string();

        let device_hash = sha256_hex(device_code.as_bytes());

        // First poll: pending.
        let (status, body) = poll_device_token(&app, &device_code).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(body["error"], "authorization_pending");

        // Simulate the client having waited the interval before its next poll,
        // so the slow_down guard doesn't fire (this test drives polls
        // back-to-back with no real delay).
        let reset_last_poll = |db: &DbPool| {
            let conn = db.write().unwrap();
            conn.execute(
                "UPDATE oauth_device_codes SET last_polled_at = NULL WHERE device_code_hash = ?1",
                params![device_hash],
            )
            .unwrap();
        };

        // The first approval submission only resolves the code and renders a
        // confirmation page; it must not approve the device yet.
        let csrf = generate_csrf_token(&session_token);
        let approve_body = format!(
            "user_code={}&decision=approve&csrf_token={}&tool=claude-code",
            urlencoding::encode(&user_code),
            urlencoding::encode(&csrf),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/device")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(approve_body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK, "approval should succeed");
        let confirmation_page = String::from_utf8(
            resp.into_body()
                .collect()
                .await
                .unwrap()
                .to_bytes()
                .to_vec(),
        )
        .unwrap();
        let status: String = db
            .read()
            .unwrap()
            .query_row(
                "SELECT status FROM oauth_device_codes WHERE user_code = ?1",
                params![user_code],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(status, "pending", "looking up a device must not approve it");
        assert!(confirmation_page.contains("laptop &lt;img&gt;"));
        assert!(!confirmation_page.contains("laptop <img>"));
        assert!(confirmation_page.contains("MCP issue-tracker access"));
        assert!(confirmation_page.contains("30 days"));
        assert!(confirmation_page.contains("oauthtest"));
        assert!(confirmation_page.contains("name=\"confirmation_token\""));

        let confirmation_token = confirmation_page
            .split("name=\"confirmation_token\" value=\"")
            .nth(1)
            .and_then(|rest| rest.split('"').next())
            .expect("confirmation token")
            .to_string();
        let confirm_body = format!(
            "user_code={}&decision=approve&csrf_token={}&confirmation_token={}&tool=claude-code",
            urlencoding::encode(&user_code),
            urlencoding::encode(&csrf),
            urlencoding::encode(&confirmation_token),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/device")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(confirm_body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK, "confirmation should approve");

        // LIFIC-13: the device row binds the per-tool BOT, not the approver.
        let bot_id: i64 = {
            let conn = db.read().unwrap();
            conn.query_row(
                "SELECT id FROM users WHERE username = 'claude-code-oauthtest'",
                [],
                |r| r.get(0),
            )
            .unwrap()
        };
        {
            let conn = db.read().unwrap();
            let (st, uid): (String, Option<i64>) = conn
                .query_row(
                    "SELECT status, user_id FROM oauth_device_codes WHERE user_code = ?1",
                    params![user_code],
                    |r| Ok((r.get(0)?, r.get(1)?)),
                )
                .unwrap();
            assert_eq!(st, "approved");
            assert_eq!(uid, Some(bot_id));
        }

        // Next poll: approved → returns a token bound to the tool bot.
        reset_last_poll(&db);
        let (status, body) = poll_device_token(&app, &device_code).await;
        assert_eq!(status, StatusCode::OK, "expected token, got {body}");
        let access_token = body["access_token"].as_str().unwrap();
        assert!(access_token.starts_with("lific_at_"));
        assert_eq!(bound_user(&db, access_token), Some(bot_id));
        assert_ne!(bot_id, user_id, "bot must differ from the approving human");

        // Single-use: a replay poll now fails (consumed → invalid_grant).
        reset_last_poll(&db);
        let (status, body) = poll_device_token(&app, &device_code).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(body["error"], "invalid_grant");
    }

    #[tokio::test]
    async fn device_polling_slow_down_when_too_fast() {
        let (app, _db) = test_oauth_app();
        let v = request_device_code(&app, None).await;
        let device_code = v["device_code"].as_str().unwrap().to_string();

        // First poll registers last_polled_at (pending).
        let (_, body) = poll_device_token(&app, &device_code).await;
        assert_eq!(body["error"], "authorization_pending");

        // Immediate second poll (< interval seconds) → slow_down.
        let (status, body) = poll_device_token(&app, &device_code).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(body["error"], "slow_down");
    }

    #[tokio::test]
    async fn device_expired_token_after_expiry() {
        let (app, db) = test_oauth_app();
        let v = request_device_code(&app, None).await;
        let device_code = v["device_code"].as_str().unwrap().to_string();
        let hash = sha256_hex(device_code.as_bytes());

        // Force expiry by rewriting expires_at into the past.
        {
            let conn = db.write().unwrap();
            let past = (chrono::Utc::now() - chrono::Duration::minutes(1)).to_rfc3339();
            conn.execute(
                "UPDATE oauth_device_codes SET expires_at = ?1 WHERE device_code_hash = ?2",
                params![past, hash],
            )
            .unwrap();
        }

        let (status, body) = poll_device_token(&app, &device_code).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(body["error"], "expired_token");
    }

    #[tokio::test]
    async fn device_denied_path() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let v = request_device_code(&app, None).await;
        let device_code = v["device_code"].as_str().unwrap().to_string();
        let user_code = v["user_code"].as_str().unwrap().to_string();

        let csrf = generate_csrf_token(&session_token);
        let deny_body = format!(
            "user_code={}&decision=deny&csrf_token={}",
            urlencoding::encode(&user_code),
            urlencoding::encode(&csrf),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/device")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(deny_body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let (status, body) = poll_device_token(&app, &device_code).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(body["error"], "access_denied");
    }

    #[tokio::test]
    async fn device_requires_an_explicit_approval_decision() {
        let (app, db) = test_oauth_app();
        let session = create_test_session(&db);
        let response = request_device_code(&app, None).await;
        let user_code = response["user_code"].as_str().unwrap();
        let csrf = generate_csrf_token(&session);

        for decision in [None, Some("maybe")] {
            let mut body = format!(
                "user_code={}&csrf_token={}",
                urlencoding::encode(user_code),
                urlencoding::encode(&csrf),
            );
            if let Some(decision) = decision {
                body.push_str(&format!("&decision={decision}"));
            }
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/device")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("cookie", format!("lific_token={session}"))
                        .body(axum::body::Body::from(body))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        }

        let status: String = db
            .read()
            .unwrap()
            .query_row(
                "SELECT status FROM oauth_device_codes WHERE user_code = ?1",
                params![user_code],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(status, "pending");
    }

    #[tokio::test]
    async fn device_verification_requires_login() {
        let (app, _db) = test_oauth_app();
        let v = request_device_code(&app, None).await;
        let user_code = v["user_code"].as_str().unwrap().to_string();

        // CSRF bound to the empty (unauthenticated) session so we get past the
        // CSRF gate and exercise the auth-required branch.
        let csrf = generate_csrf_token("");
        let body = format!(
            "user_code={}&decision=approve&csrf_token={}",
            urlencoding::encode(&user_code),
            urlencoding::encode(&csrf),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/device")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn device_approve_rejects_unbound_csrf() {
        // A CSRF minted for no session must not approve with a victim cookie.
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let v = request_device_code(&app, None).await;
        let user_code = v["user_code"].as_str().unwrap().to_string();

        let csrf = generate_csrf_token(""); // unbound
        let body = format!(
            "user_code={}&decision=approve&csrf_token={}",
            urlencoding::encode(&user_code),
            urlencoding::encode(&csrf),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/device")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn device_invalid_user_code_returns_error_page() {
        let (app, db) = test_oauth_app();
        let session_token = create_test_session(&db);
        let csrf = generate_csrf_token(&session_token);
        let body = format!(
            "user_code={}&decision=approve&csrf_token={}",
            "ZZZZ-ZZZZ",
            urlencoding::encode(&csrf),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/device")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session_token}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn device_unknown_device_code_is_invalid_grant() {
        let (app, _db) = test_oauth_app();
        let (status, body) = poll_device_token(&app, "totally-unknown-device-code").await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(body["error"], "invalid_grant");
    }

    // ── LIF-370: token mint + code consumption are one transaction ───────

    /// Approve a device code directly in the DB (the verification-page dance
    /// is covered end-to-end above) and clear `last_polled_at` so the next
    /// poll isn't answered with `slow_down`.
    ///
    /// Binds a real user, because the real approval path always does and an
    /// approved row that names nobody is refused at exchange time (see
    /// `grant_lifetime::a_legacy_unbound_device_approval_cannot_be_exchanged`).
    /// These tests are about the consume/mint transaction, not about that.
    fn approve_device_code(db: &DbPool, device_hash: &str) {
        let conn = db.write().unwrap();
        let approver = crate::db::queries::users::create_user(
            &conn,
            &crate::db::models::CreateUser {
                username: "device-approver".into(),
                email: "device-approver@test.com".into(),
                password: "testpassword1".into(),
                display_name: None,
                is_admin: false,
                is_bot: false,
            },
        )
        .unwrap();
        conn.execute(
            "UPDATE oauth_device_codes
             SET status = 'approved', user_id = ?2, last_polled_at = NULL
             WHERE device_code_hash = ?1",
            params![device_hash, approver.id],
        )
        .unwrap();
    }

    fn device_status(db: &DbPool, device_hash: &str) -> String {
        let conn = db.read().unwrap();
        conn.query_row(
            "SELECT status FROM oauth_device_codes WHERE device_code_hash = ?1",
            params![device_hash],
            |r| r.get(0),
        )
        .unwrap()
    }

    fn token_count(db: &DbPool) -> i64 {
        let conn = db.read().unwrap();
        conn.query_row("SELECT COUNT(*) FROM oauth_tokens", [], |r| r.get(0))
            .unwrap()
    }

    #[tokio::test]
    async fn device_consumed_code_cannot_mint_a_second_token() {
        let (app, db) = test_oauth_app();
        let v = request_device_code(&app, None).await;
        let device_code = v["device_code"].as_str().unwrap().to_string();
        let hash = sha256_hex(device_code.as_bytes());

        approve_device_code(&db, &hash);
        let (status, body) = poll_device_token(&app, &device_code).await;
        assert_eq!(status, StatusCode::OK, "expected token, got {body}");
        // Clients read `scope` off the token response; it stays on the wire.
        assert_eq!(body["scope"], "mcp");
        assert_eq!(token_count(&db), 1);
        assert_eq!(device_status(&db, &hash), "consumed");

        // Replay the same code (interval waited): no second token, ever.
        {
            let conn = db.write().unwrap();
            conn.execute(
                "UPDATE oauth_device_codes SET last_polled_at = NULL WHERE device_code_hash = ?1",
                params![hash],
            )
            .unwrap();
        }
        let (status, body) = poll_device_token(&app, &device_code).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(body["error"], "invalid_grant");
        assert_eq!(token_count(&db), 1, "replay must not mint a second token");
    }

    #[tokio::test]
    async fn device_token_is_rolled_back_when_the_code_cannot_be_consumed() {
        // A failing consume-UPDATE used to be swallowed (`let _ = ...`),
        // handing out a token while leaving the code approved and replayable.
        // Now the whole exchange fails and nothing is written.
        let (app, db) = test_oauth_app();
        let v = request_device_code(&app, None).await;
        let device_code = v["device_code"].as_str().unwrap().to_string();
        let hash = sha256_hex(device_code.as_bytes());

        approve_device_code(&db, &hash);
        {
            let conn = db.write().unwrap();
            conn.execute_batch(
                "CREATE TRIGGER block_consume
                 BEFORE UPDATE OF status ON oauth_device_codes
                 WHEN NEW.status = 'consumed'
                 BEGIN SELECT RAISE(ABORT, 'consume blocked'); END;",
            )
            .unwrap();
        }

        let (status, _) = poll_device_token(&app, &device_code).await;
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(token_count(&db), 0, "no token may survive a failed consume");
        assert_eq!(device_status(&db, &hash), "approved");
    }

    #[tokio::test]
    async fn device_page_prefills_user_code_from_query() {
        let (app, _db) = test_oauth_app();
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/oauth/device?user_code=bcdfghjk")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let html = String::from_utf8_lossy(&bytes);
        // Normalized + uppercased + dash-inserted into the input value.
        assert!(
            html.contains("value=\"BCDF-GHJK\""),
            "prefill missing: {html}"
        );
    }

    /// Approval is two steps now, and the confirmation page is the one that
    /// reads the tool. Asking on the code-entry page as well put the same
    /// question twice and discarded the first answer.
    #[tokio::test]
    async fn device_code_entry_asks_only_for_the_code() {
        let (app, db) = test_oauth_app();
        let session = create_test_session(&db);
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/oauth/device")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let entry = String::from_utf8_lossy(&bytes).to_string();
        assert!(entry.contains("name=\"user_code\""));
        assert!(
            !entry.contains("name=\"tool\""),
            "code entry must not ask which tool is connecting: {entry}"
        );

        // The confirmation step still asks, because that is where it is read.
        let v = request_device_code(&app, Some("laptop")).await;
        let body = format!(
            "user_code={}&decision=approve&csrf_token={}",
            urlencoding::encode(v["user_code"].as_str().unwrap()),
            urlencoding::encode(&generate_csrf_token(&session)),
        );
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth/device")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("cookie", format!("lific_token={session}"))
                    .body(axum::body::Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let confirm = String::from_utf8_lossy(&bytes);
        assert!(
            confirm.contains("name=\"tool\""),
            "confirmation must ask which tool is connecting: {confirm}"
        );
    }

    #[test]
    fn normalize_user_code_handles_spacing_and_case() {
        assert_eq!(normalize_user_code("bcdf-ghjk"), "BCDF-GHJK");
        assert_eq!(normalize_user_code("bcdf ghjk"), "BCDF-GHJK");
        assert_eq!(normalize_user_code("BCDFGHJK"), "BCDF-GHJK");
        assert_eq!(normalize_user_code("  bcdfghjk  "), "BCDF-GHJK");
    }

    #[test]
    fn generate_user_code_is_wellformed() {
        for _ in 0..50 {
            let c = generate_user_code();
            assert_eq!(c.len(), 9);
            assert_eq!(&c[4..5], "-");
            for ch in c.chars().filter(|c| *c != '-') {
                assert!(USER_CODE_ALPHABET.contains(&(ch as u8)));
            }
        }
    }

    // ── resolve_tool (LIFIC-13) ────────────────────────────────

    #[test]
    fn resolve_tool_known_registry_id_keeps_display_name() {
        // A pick from the Connected Tools registry maps to its display name.
        let (id, display) = resolve_tool("claude-code").unwrap();
        assert_eq!(id, "claude-code");
        assert_eq!(display, "Claude Code");
    }

    #[test]
    fn resolve_tool_unregistered_tool_is_sanitized() {
        // Free text gets lowercased and stripped to the id, display falls back
        // to the same humanized text.
        let (id, display) = resolve_tool("My Editor").unwrap();
        assert_eq!(id, "my-editor");
        assert_eq!(display, "My Editor");
    }

    #[test]
    fn resolve_tool_rejects_reserved_words() {
        for reserved in ["admin", "system"] {
            assert!(
                resolve_tool(reserved).is_err(),
                "{reserved} is a reserved tool id"
            );
        }
    }

    #[test]
    fn resolve_tool_rejects_empty_or_only_symbols() {
        assert!(resolve_tool("").is_err());
        assert!(resolve_tool("   ").is_err());
    }

    /// One snapshot, one answer.
    ///
    /// The middleware used to ask three questions on three pooled connections:
    /// is the token valid, whose is it, is that user live. Between the first
    /// two, a revocation could land, and the pair then read "valid" and
    /// "unbound". An unbound OAuth token takes the operator fallback, so
    /// revoking a tool's credential could promote it to the first admin.
    /// `resolve_oauth_credential` makes that unrepresentable: the outcome is
    /// one value from one connection.
    mod credential_resolution {
        use super::*;

        struct Fixture {
            db: DbPool,
            owner_id: i64,
            bot_id: i64,
            token: String,
        }

        fn fixture() -> Fixture {
            let db = crate::db::open_memory().unwrap();
            let (owner_id, bot_id) = {
                let conn = db.write().unwrap();
                let owner = crate::db::queries::users::create_user(
                    &conn,
                    &crate::db::models::CreateUser {
                        username: "owner".into(),
                        email: "owner@test.local".into(),
                        password: "testpassword1".into(),
                        display_name: None,
                        is_admin: true,
                        is_bot: false,
                    },
                )
                .unwrap();
                let bot = crate::db::queries::users::create_bot_user(
                    &conn,
                    owner.id,
                    "zed-owner",
                    "Zed",
                    Some("zed"),
                )
                .unwrap();
                conn.execute(
                    "INSERT INTO oauth_clients (client_id, client_name, redirect_uris)
                     VALUES ('c', 'Test', '[\"http://localhost\"]')",
                    [],
                )
                .unwrap();
                (owner.id, bot.id)
            };
            let token = insert_token(&db, "bound", Some(bot_id));
            Fixture {
                db,
                owner_id,
                bot_id,
                token,
            }
        }

        fn insert_token(db: &DbPool, suffix: &str, user_id: Option<i64>) -> String {
            let token = format!("lific_at_{suffix}");
            let hash = sha256_hex(token.as_bytes());
            let expires = (chrono::Utc::now() + chrono::Duration::hours(1)).to_rfc3339();
            db.write()
                .unwrap()
                .execute(
                    "INSERT INTO oauth_tokens (access_token, client_id, expires_at, scope, user_id)
                     VALUES (?1, 'c', ?2, 'mcp', ?3)",
                    params![hash, expires, user_id],
                )
                .unwrap();
            token
        }

        #[test]
        fn a_live_bound_token_resolves_to_its_user() {
            let f = fixture();
            assert_eq!(
                resolve_oauth_credential(&f.db, &f.token),
                Ok(OAuthCredential::Bound(crate::db::models::AuthUser {
                    id: f.bot_id,
                    username: "zed-owner".into(),
                    display_name: "Zed".into(),
                    is_admin: false,
                })),
            );
        }

        /// The escalation this consolidation exists to prevent. Whatever the
        /// state, a bound token can never come back as unbound.
        #[test]
        fn a_bound_token_never_degrades_to_unbound() {
            for (label, mutate) in [
                (
                    "revoked",
                    Box::new(|f: &Fixture| {
                        f.db.write()
                            .unwrap()
                            .execute("UPDATE oauth_tokens SET revoked = 1", [])
                            .unwrap();
                    }) as Box<dyn Fn(&Fixture)>,
                ),
                (
                    "expired",
                    Box::new(|f: &Fixture| {
                        let past = (chrono::Utc::now() - chrono::Duration::minutes(1)).to_rfc3339();
                        f.db.write()
                            .unwrap()
                            .execute("UPDATE oauth_tokens SET expires_at = ?1", params![past])
                            .unwrap();
                    }),
                ),
                (
                    "bot deleted",
                    Box::new(|f: &Fixture| {
                        f.db.write()
                            .unwrap()
                            .execute("DELETE FROM users WHERE id = ?1", params![f.bot_id])
                            .unwrap();
                    }),
                ),
                (
                    "owner deactivated",
                    Box::new(|f: &Fixture| {
                        let conn = f.db.write().unwrap();
                        crate::db::queries::users::create_user(
                            &conn,
                            &crate::db::models::CreateUser {
                                username: "spare".into(),
                                email: "spare@test.local".into(),
                                password: "testpassword1".into(),
                                display_name: None,
                                is_admin: true,
                                is_bot: false,
                            },
                        )
                        .unwrap();
                        crate::db::queries::users::set_active(&conn, f.owner_id, false).unwrap();
                    }),
                ),
            ] {
                let f = fixture();
                mutate(&f);
                let outcome = resolve_oauth_credential(&f.db, &f.token);
                assert!(
                    outcome.is_err(),
                    "{label}: must not authenticate, got {outcome:?}"
                );
                assert_ne!(
                    outcome,
                    Ok(OAuthCredential::LegacyUnbound),
                    "{label}: a dead binding must never read as unbound, which is the operator"
                );
            }
        }

        /// The documented pre-LIF-79 behaviour, kept for rows that predate
        /// user binding. Nothing issued since can be in this state.
        #[test]
        fn a_genuinely_unbound_legacy_token_still_resolves_to_the_operator_fallback() {
            let f = fixture();
            let legacy = insert_token(&f.db, "legacy", None);
            assert_eq!(
                resolve_oauth_credential(&f.db, &legacy),
                Ok(OAuthCredential::LegacyUnbound)
            );
        }

        #[test]
        fn an_unknown_or_wrong_shaped_token_is_invalid() {
            let f = fixture();
            for token in ["lific_at_never-issued", "lific_sess_wrong-shape", ""] {
                assert_eq!(
                    resolve_oauth_credential(&f.db, token),
                    Err(OAuthReject::Invalid),
                    "{token}"
                );
            }
        }

        /// Through the real middleware, which is where the escalation would
        /// have happened: a revoked bot token must 401, not arrive as the
        /// first admin.
        #[tokio::test]
        async fn a_revoked_bot_token_is_refused_by_the_middleware_not_promoted() {
            use tower::ServiceExt;
            let f = fixture();
            let auth_state = crate::auth::AuthState {
                db: f.db.clone(),
                manager: crate::auth::create_key_manager().unwrap(),
                public_url: "https://example.com".into(),
                required: true,
            };
            let app = crate::api::router(f.db.clone(), &[])
                .layer(axum::Extension(crate::realtime::RealtimeHub::new()))
                .layer(axum::Extension(crate::config::AuthConfig {
                    allow_signup: true,
                    required: true,
                    secure_cookies: false,
                }))
                .layer(axum::middleware::from_fn_with_state(
                    auth_state,
                    crate::auth::require_api_key,
                ));

            let call = |token: String| {
                let app = app.clone();
                async move {
                    app.oneshot(
                        Request::builder()
                            .uri("/api/auth/me")
                            .header("authorization", format!("Bearer {token}"))
                            .body(axum::body::Body::empty())
                            .unwrap(),
                    )
                    .await
                    .unwrap()
                }
            };

            assert_eq!(call(f.token.clone()).await.status(), StatusCode::OK);

            f.db.write()
                .unwrap()
                .execute("UPDATE oauth_tokens SET revoked = 1", [])
                .unwrap();

            let resp = call(f.token.clone()).await;
            assert_eq!(
                resp.status(),
                StatusCode::UNAUTHORIZED,
                "a revoked token must not authenticate at all, let alone as the operator"
            );
        }
    }

    /// Every OAuth expiry column is written with `to_rfc3339`, and SQLite's
    /// `datetime('now')` is not that format. Compared as raw text they
    /// disagree within the same day: 'T' sorts after every digit, so
    /// '2026-08-20T11:59:00+00:00' reads as later than '2026-08-20 12:00:00'
    /// and an expired grant looks live. Every predicate wraps the column in
    /// `datetime()`; these prove it, a minute either side of now so nothing
    /// rests on a second boundary.
    mod expiry_is_compared_as_a_datetime {
        use super::*;

        fn rfc3339_from_now(minutes: i64) -> String {
            (chrono::Utc::now() + chrono::Duration::minutes(minutes)).to_rfc3339()
        }

        fn seeded_db() -> DbPool {
            let db = crate::db::open_memory().unwrap();
            db.write()
                .unwrap()
                .execute(
                    "INSERT INTO oauth_clients (client_id, client_name, redirect_uris)
                     VALUES ('c', 'Test', '[\"http://localhost\"]')",
                    [],
                )
                .unwrap();
            db
        }

        fn insert_token(db: &DbPool, name: &str, minutes: i64) -> String {
            let token = format!("lific_at_{name}");
            db.write()
                .unwrap()
                .execute(
                    "INSERT INTO oauth_tokens (access_token, client_id, expires_at, scope)
                     VALUES (?1, 'c', ?2, 'mcp')",
                    params![sha256_hex(token.as_bytes()), rfc3339_from_now(minutes)],
                )
                .unwrap();
            token
        }

        #[test]
        fn an_access_token_expiring_in_a_minute_is_still_valid() {
            let db = seeded_db();
            let token = insert_token(&db, "live", 1);
            assert!(resolve_oauth_credential(&db, &token).is_ok());
        }

        #[test]
        fn an_access_token_that_expired_a_minute_ago_is_refused() {
            let db = seeded_db();
            let token = insert_token(&db, "dead", -1);
            assert_eq!(
                resolve_oauth_credential(&db, &token),
                Err(OAuthReject::Invalid)
            );
        }

        fn insert_code(db: &DbPool, code: &str, minutes: i64) {
            db.write()
                .unwrap()
                .execute(
                    "INSERT INTO oauth_codes
                        (code, client_id, redirect_uri, code_challenge, expires_at, user_id)
                     VALUES (?1, 'c', 'http://localhost', 'x', ?2, NULL)",
                    params![code, rfc3339_from_now(minutes)],
                )
                .unwrap();
        }

        fn code_is_visible(db: &DbPool, code: &str) -> bool {
            db.read()
                .unwrap()
                .query_row(
                    "SELECT 1 FROM oauth_codes
                     WHERE code = ?1 AND datetime(expires_at) > datetime('now')",
                    params![code],
                    |_| Ok(()),
                )
                .is_ok()
        }

        #[test]
        fn an_authorization_code_expiring_in_a_minute_is_still_exchangeable() {
            let db = seeded_db();
            insert_code(&db, "live-code", 1);
            assert!(code_is_visible(&db, "live-code"));
        }

        #[test]
        fn an_authorization_code_that_expired_a_minute_ago_is_gone() {
            let db = seeded_db();
            insert_code(&db, "dead-code", -1);
            assert!(!code_is_visible(&db, "dead-code"));
        }

        fn insert_device_code(db: &DbPool, hash: &str, user_code: &str, minutes: i64) {
            db.write()
                .unwrap()
                .execute(
                    "INSERT INTO oauth_device_codes
                        (device_code_hash, user_code, expires_at, status)
                     VALUES (?1, ?2, ?3, 'pending')",
                    params![hash, user_code, rfc3339_from_now(minutes)],
                )
                .unwrap();
        }

        fn device_codes(db: &DbPool) -> i64 {
            db.read()
                .unwrap()
                .query_row("SELECT COUNT(*) FROM oauth_device_codes", [], |r| r.get(0))
                .unwrap()
        }

        /// The opportunistic sweep must remove the expired one and keep the
        /// live one. Reading these as text does the opposite within a day.
        #[test]
        fn the_device_code_sweep_removes_only_the_expired_one() {
            let db = seeded_db();
            insert_device_code(&db, "live", "BCDF-GHJK", 1);
            insert_device_code(&db, "dead", "BCDF-GHJL", -1);
            assert_eq!(device_codes(&db), 2);

            let conn = db.write().unwrap();
            cleanup_expired_device_codes(&conn).unwrap();

            assert_eq!(device_codes(&db), 1, "only the expired grant is swept");
            let survivor: String = db
                .read()
                .unwrap()
                .query_row("SELECT device_code_hash FROM oauth_device_codes", [], |r| {
                    r.get(0)
                })
                .unwrap();
            assert_eq!(survivor, "live");
        }

        /// Approval only acts on a code that has not expired.
        #[test]
        fn only_an_unexpired_device_code_can_be_approved() {
            let db = seeded_db();
            insert_device_code(&db, "live", "BCDF-GHJK", 1);
            insert_device_code(&db, "dead", "BCDF-GHJL", -1);

            let approve = |user_code: &str| -> usize {
                db.write()
                    .unwrap()
                    .execute(
                        "UPDATE oauth_device_codes SET status = 'approved'
                         WHERE user_code = ?1 AND status = 'pending'
                           AND datetime(expires_at) > datetime('now')",
                        params![user_code],
                    )
                    .unwrap()
            };
            assert_eq!(approve("BCDF-GHJK"), 1, "the live grant is approvable");
            assert_eq!(approve("BCDF-GHJL"), 0, "the expired grant is not");
        }
    }

    // ── Grants may not outlive the authorization that produced them ──
    //
    // Every test here is about ordering: a grant that was legitimately issued,
    // then invalidated by an account recovery before the client got round to
    // exchanging it. The approval and the exchange each run as one
    // transaction, so "before" and "after" are the only two orders that exist;
    // these pin what each one produces.
    mod grant_lifetime {
        use super::*;

        const VERIFIER: &str = "test_verifier_abcdefghijklmnopqrstuvwxyz_0123456789";

        fn challenge() -> String {
            base64_url_encode(&Sha256::digest(VERIFIER.as_bytes()))
        }

        fn authorization_approval_body(client_id: &str, credential: &str) -> String {
            let challenge = challenge();
            let csrf = AuthorizationRequest {
                client_id,
                redirect_uri: "http://localhost/callback",
                response_type: "code",
                state: None,
                code_challenge: Some(&challenge),
                code_challenge_method: Some("S256"),
                scope: Some(OAUTH_SCOPE),
            }
            .csrf_token(credential);
            format!(
                "client_id={}&redirect_uri={}&response_type=code&code_challenge={}&code_challenge_method=S256&scope=mcp&csrf_token={}&tool=claude-code&decision=approve",
                client_id,
                urlencoding::encode("http://localhost/callback"),
                urlencoding::encode(&challenge),
                urlencoding::encode(&csrf),
            )
        }

        fn owner_id(db: &DbPool) -> i64 {
            db.read()
                .unwrap()
                .query_row(
                    "SELECT id FROM users WHERE username = 'oauthtest'",
                    [],
                    |r| r.get(0),
                )
                .unwrap()
        }

        /// Run the authorize POST with a live session cookie and return the
        /// issued code from the redirect.
        async fn approve_code(app: &Router, client_id: &str, session: &str) -> String {
            let body = authorization_approval_body(client_id, session);
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/authorize")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("cookie", format!("lific_token={session}"))
                        .body(axum::body::Body::from(body))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert!(
                resp.status().is_redirection(),
                "approve should redirect, got {}",
                resp.status()
            );
            let location = resp
                .headers()
                .get("location")
                .unwrap()
                .to_str()
                .unwrap()
                .to_string();
            location
                .split("code=")
                .nth(1)
                .unwrap()
                .split('&')
                .next()
                .unwrap()
                .to_string()
        }

        async fn exchange_code(
            app: &Router,
            client_id: &str,
            code: &str,
        ) -> (StatusCode, serde_json::Value) {
            let body = format!(
                "grant_type=authorization_code&code={}&redirect_uri={}&client_id={}&code_verifier={}",
                code,
                urlencoding::encode("http://localhost/callback"),
                client_id,
                VERIFIER,
            );
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/token")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .body(axum::body::Body::from(body))
                        .unwrap(),
                )
                .await
                .unwrap();
            let status = resp.status();
            let bytes = resp.into_body().collect().await.unwrap().to_bytes();
            (
                status,
                serde_json::from_slice(&bytes).unwrap_or_else(|_| serde_json::json!({})),
            )
        }

        #[tokio::test]
        async fn an_ordinary_authorization_code_flow_still_works() {
            let (app, db) = test_oauth_app();
            let session = create_test_session(&db);
            let client_id = register_client_helper(&app, "http://localhost/callback").await;

            let code = approve_code(&app, &client_id, &session).await;
            let (status, body) = exchange_code(&app, &client_id, &code).await;
            assert_eq!(status, StatusCode::OK, "{body}");
            assert!(
                body["access_token"]
                    .as_str()
                    .unwrap()
                    .starts_with("lific_at_")
            );
        }

        #[tokio::test]
        async fn a_code_approved_before_a_lockdown_cannot_mint_after_it() {
            let (app, db) = test_oauth_app();
            let session = create_test_session(&db);
            let client_id = register_client_helper(&app, "http://localhost/callback").await;
            let code = approve_code(&app, &client_id, &session).await;

            {
                let conn = db.write().unwrap();
                crate::db::queries::users::lock_down_account(&conn, owner_id(&db)).unwrap();
            }

            let (status, body) = exchange_code(&app, &client_id, &code).await;
            assert_eq!(status, StatusCode::BAD_REQUEST);
            assert_eq!(body["error"], "invalid_grant");

            let tokens: i64 = db
                .read()
                .unwrap()
                .query_row("SELECT COUNT(*) FROM oauth_tokens", [], |r| r.get(0))
                .unwrap();
            assert_eq!(tokens, 0, "no token was minted");
        }

        #[tokio::test]
        async fn a_code_whose_bot_owner_went_inactive_cannot_be_exchanged() {
            let (app, db) = test_oauth_app();
            let session = create_test_session(&db);
            let client_id = register_client_helper(&app, "http://localhost/callback").await;
            let code = approve_code(&app, &client_id, &session).await;

            {
                let conn = db.write().unwrap();
                crate::db::queries::users::set_active(&conn, owner_id(&db), false).unwrap();
            }

            let (status, body) = exchange_code(&app, &client_id, &code).await;
            assert_eq!(status, StatusCode::BAD_REQUEST);
            assert_eq!(body["error"], "invalid_grant");
            assert_eq!(
                body["error_description"],
                "authorizing user is no longer active"
            );
        }

        /// A code with `user_id IS NULL` is a pre-LIF-79 legacy row. Nothing
        /// issues one any more; exchanging one used to mint an *unbound*
        /// access token, which resolves as the operator and which no account
        /// lockdown can revoke, because a lockdown scopes by user id.
        #[tokio::test]
        async fn a_legacy_unbound_code_cannot_be_exchanged() {
            let (app, db) = test_oauth_app();
            let client_id = register_client_helper(&app, "http://localhost/callback").await;

            // Otherwise valid in every respect: unexpired, unused, correct
            // client and redirect, and a PKCE challenge the verifier matches.
            db.write()
                .unwrap()
                .execute(
                    "INSERT INTO oauth_codes
                        (code, client_id, redirect_uri, code_challenge, code_challenge_method,
                         expires_at, scope, user_id)
                     VALUES ('legacy-code', ?1, 'http://localhost/callback', ?2, 'S256',
                             ?3, 'mcp', NULL)",
                    params![
                        client_id,
                        challenge(),
                        (chrono::Utc::now() + chrono::Duration::minutes(10)).to_rfc3339(),
                    ],
                )
                .unwrap();

            let (status, body) = exchange_code(&app, &client_id, "legacy-code").await;
            assert_eq!(status, StatusCode::BAD_REQUEST);
            assert_eq!(body["error"], "invalid_grant");

            let conn = db.read().unwrap();
            let tokens: i64 = conn
                .query_row("SELECT COUNT(*) FROM oauth_tokens", [], |r| r.get(0))
                .unwrap();
            assert_eq!(tokens, 0, "no unbound token was minted");
            let used: i64 = conn
                .query_row(
                    "SELECT used FROM oauth_codes WHERE code = 'legacy-code'",
                    [],
                    |r| r.get(0),
                )
                .unwrap();
            assert_eq!(used, 0, "the refused exchange rolled back cleanly");
        }

        /// The device twin of the above: an approved row that names nobody.
        #[tokio::test]
        async fn a_legacy_unbound_device_approval_cannot_be_exchanged() {
            let (app, db) = test_oauth_app();
            let v = request_device_code(&app, Some("My CLI")).await;
            db.write()
                .unwrap()
                .execute(
                    "UPDATE oauth_device_codes
                     SET status = 'approved', user_id = NULL, last_polled_at = NULL",
                    [],
                )
                .unwrap();

            let (status, body) = poll_device_token(&app, v["device_code"].as_str().unwrap()).await;
            assert_eq!(status, StatusCode::BAD_REQUEST);
            assert_eq!(body["error"], "invalid_grant");

            let conn = db.read().unwrap();
            let tokens: i64 = conn
                .query_row("SELECT COUNT(*) FROM oauth_tokens", [], |r| r.get(0))
                .unwrap();
            assert_eq!(tokens, 0, "no unbound token was minted");
            let status: String = conn
                .query_row("SELECT status FROM oauth_device_codes", [], |r| r.get(0))
                .unwrap();
            assert_eq!(
                status, "approved",
                "the grant is not consumed by a refused exchange"
            );
            // The poll bookkeeping the refusal still owes the client did
            // commit, so the next poll is rate-limited as usual rather than
            // being treated as a first poll.
            let polled: Option<String> = conn
                .query_row("SELECT last_polled_at FROM oauth_device_codes", [], |r| {
                    r.get(0)
                })
                .unwrap();
            assert!(polled.is_some());
        }

        /// Approving a connection mints a 30-day tool credential, so it needs
        /// the same recent sign-in `POST /api/auth/keys` needs. A session
        /// token lifted from a browser that signed in last week must not be
        /// enough to attach a permanent credential to the account.
        #[tokio::test]
        async fn an_aged_session_may_not_approve_an_authorization_request() {
            let (app, db) = test_oauth_app();
            let session = create_test_session(&db);
            let client_id = register_client_helper(&app, "http://localhost/callback").await;
            db.write()
                .unwrap()
                .execute(
                    "UPDATE sessions SET created_at = datetime('now', '-16 minutes')",
                    [],
                )
                .unwrap();

            let body = authorization_approval_body(&client_id, &session);
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/authorize")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("cookie", format!("lific_token={session}"))
                        .body(axum::body::Body::from(body))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
            let page = String::from_utf8(
                resp.into_body()
                    .collect()
                    .await
                    .unwrap()
                    .to_bytes()
                    .to_vec(),
            )
            .unwrap();
            // The copy has to be actionable and honest: name the window, say
            // that signing out is what clears the stale session, and say the
            // connection must be restarted from the client. It must NOT claim
            // the approval will be retried automatically, because it will not.
            for phrase in [
                "15 minutes",
                "sign out",
                "Sign back in",
                "Start the connection again from your MCP client",
                "nothing has changed",
            ] {
                assert!(
                    page.to_lowercase().contains(&phrase.to_lowercase()),
                    "the page must say {phrase:?}: {page}"
                );
            }
            for forbidden in ["automatically", "will be retried", "try again shortly"] {
                assert!(
                    !page.to_lowercase().contains(forbidden),
                    "the page must not promise a retry it does not do: {page}"
                );
            }

            let conn = db.read().unwrap();
            let codes: i64 = conn
                .query_row("SELECT COUNT(*) FROM oauth_codes", [], |r| r.get(0))
                .unwrap();
            assert_eq!(codes, 0, "no code was issued");
            let bots: i64 = conn
                .query_row("SELECT COUNT(*) FROM users WHERE is_bot = 1", [], |r| {
                    r.get(0)
                })
                .unwrap();
            assert_eq!(bots, 0, "no bot was minted either");
            // The session itself is untouched; only this action needed more.
            assert!(crate::db::queries::users::validate_session(&conn, &session).is_ok());
        }

        #[tokio::test]
        async fn an_aged_session_may_not_approve_a_device() {
            let (app, db) = test_oauth_app();
            let session = create_test_session(&db);
            let v = request_device_code(&app, Some("My CLI")).await;
            db.write()
                .unwrap()
                .execute(
                    "UPDATE sessions SET created_at = datetime('now', '-16 minutes')",
                    [],
                )
                .unwrap();

            let user_code = v["user_code"].as_str().unwrap();
            let (csrf, confirmation_token) = device_confirmation(&app, &session, user_code).await;
            let body = format!(
                "user_code={}&decision=approve&csrf_token={}&confirmation_token={}&tool=claude-code",
                urlencoding::encode(user_code),
                urlencoding::encode(&csrf),
                urlencoding::encode(&confirmation_token),
            );
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/device")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("cookie", format!("lific_token={session}"))
                        .body(axum::body::Body::from(body))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

            let conn = db.read().unwrap();
            let pending: i64 = conn
                .query_row(
                    "SELECT COUNT(*) FROM oauth_device_codes WHERE status = 'pending'",
                    [],
                    |r| r.get(0),
                )
                .unwrap();
            assert_eq!(pending, 1, "the grant is still waiting, not approved");
            let bots: i64 = conn
                .query_row("SELECT COUNT(*) FROM users WHERE is_bot = 1", [], |r| {
                    r.get(0)
                })
                .unwrap();
            assert_eq!(bots, 0);
        }
        /// Refusing a device is not a grant, so it must not be made harder
        /// than approving one. Someone who sees a code they do not recognise
        /// should be able to deny it immediately, from whatever session they
        /// already have open.
        #[tokio::test]
        async fn an_aged_session_may_still_deny_a_device() {
            let (app, db) = test_oauth_app();
            let session = create_test_session(&db);
            let v = request_device_code(&app, Some("Unknown device")).await;
            db.write()
                .unwrap()
                .execute(
                    "UPDATE sessions SET created_at = datetime('now', '-16 minutes')",
                    [],
                )
                .unwrap();

            let body = format!(
                "user_code={}&decision=deny&csrf_token={}",
                urlencoding::encode(v["user_code"].as_str().unwrap()),
                urlencoding::encode(&generate_csrf_token(&session)),
            );
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/device")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("cookie", format!("lific_token={session}"))
                        .body(axum::body::Body::from(body))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let conn = db.read().unwrap();
            let denied: i64 = conn
                .query_row(
                    "SELECT COUNT(*) FROM oauth_device_codes WHERE status = 'denied'",
                    [],
                    |r| r.get(0),
                )
                .unwrap();
            assert_eq!(denied, 1, "the grant is refused");
            let bots: i64 = conn
                .query_row("SELECT COUNT(*) FROM users WHERE is_bot = 1", [], |r| {
                    r.get(0)
                })
                .unwrap();
            assert_eq!(bots, 0, "denying resolves no tool and mints no bot");

            // The exchange sees the denial.
            drop(conn);
            db.write()
                .unwrap()
                .execute("UPDATE oauth_device_codes SET last_polled_at = NULL", [])
                .unwrap();
            let (status, body) = poll_device_token(&app, v["device_code"].as_str().unwrap()).await;
            assert_eq!(status, StatusCode::BAD_REQUEST);
            assert_eq!(body["error"], "access_denied");
        }

        /// A dead session may not deny either: the page still has to know who
        /// is refusing.
        #[tokio::test]
        async fn a_revoked_session_may_not_deny_a_device() {
            let (app, db) = test_oauth_app();
            let session = create_test_session(&db);
            let v = request_device_code(&app, None).await;
            db.write()
                .unwrap()
                .execute("DELETE FROM sessions", [])
                .unwrap();

            let body = format!(
                "user_code={}&decision=deny&csrf_token={}",
                urlencoding::encode(v["user_code"].as_str().unwrap()),
                urlencoding::encode(&generate_csrf_token(&session)),
            );
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/device")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("cookie", format!("lific_token={session}"))
                        .body(axum::body::Body::from(body))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
            let pending: i64 = db
                .read()
                .unwrap()
                .query_row(
                    "SELECT COUNT(*) FROM oauth_device_codes WHERE status = 'pending'",
                    [],
                    |r| r.get(0),
                )
                .unwrap();
            assert_eq!(pending, 1);
        }

        #[tokio::test]
        async fn an_oauth_token_may_not_approve_an_authorization_request() {
            let (app, db) = test_oauth_app();
            let session = create_test_session(&db);
            let client_id = register_client_helper(&app, "http://localhost/callback").await;

            // A perfectly valid access token for the same account.
            let access_token = {
                let token = "lific_at_tool-held-token".to_string();
                let hash = crate::auth::sha256_hex(token.as_bytes());
                let expires = (chrono::Utc::now() + chrono::Duration::hours(1)).to_rfc3339();
                let conn = db.write().unwrap();
                conn.execute(
                    "INSERT INTO oauth_tokens (access_token, client_id, expires_at, scope, user_id)
                     VALUES (?1, ?2, ?3, 'mcp', ?4)",
                    params![hash, client_id, expires, owner_id(&db)],
                )
                .unwrap();
                token
            };
            let _ = session;

            let body = authorization_approval_body(&client_id, &access_token);
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/authorize")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("authorization", format!("Bearer {access_token}"))
                        .body(axum::body::Body::from(body))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

            let codes: i64 = db
                .read()
                .unwrap()
                .query_row("SELECT COUNT(*) FROM oauth_codes", [], |r| r.get(0))
                .unwrap();
            assert_eq!(codes, 0, "no code was issued");
        }

        #[tokio::test]
        async fn a_revoked_session_cannot_approve_and_mints_no_bot() {
            let (app, db) = test_oauth_app();
            let session = create_test_session(&db);
            let client_id = register_client_helper(&app, "http://localhost/callback").await;
            db.write()
                .unwrap()
                .execute("DELETE FROM sessions", [])
                .unwrap();

            let body = authorization_approval_body(&client_id, &session);
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/authorize")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("cookie", format!("lific_token={session}"))
                        .body(axum::body::Body::from(body))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

            let conn = db.read().unwrap();
            let codes: i64 = conn
                .query_row("SELECT COUNT(*) FROM oauth_codes", [], |r| r.get(0))
                .unwrap();
            assert_eq!(codes, 0);
            let bots: i64 = conn
                .query_row("SELECT COUNT(*) FROM users WHERE is_bot = 1", [], |r| {
                    r.get(0)
                })
                .unwrap();
            assert_eq!(bots, 0, "a refused approval mints no bot either");
        }

        // ── Device grant ────────────────────────────────────────

        /// Resolve a device code through the first verification step and
        /// return the fields needed for the explicit confirmation step.
        async fn device_confirmation(
            app: &Router,
            session: &str,
            user_code: &str,
        ) -> (String, String) {
            let csrf = generate_csrf_token(session);
            let lookup_body = format!(
                "user_code={}&decision=approve&csrf_token={}&tool=claude-code",
                urlencoding::encode(user_code),
                urlencoding::encode(&csrf),
            );
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/device")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("cookie", format!("lific_token={session}"))
                        .body(axum::body::Body::from(lookup_body))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::OK);
            let page = String::from_utf8(
                resp.into_body()
                    .collect()
                    .await
                    .unwrap()
                    .to_bytes()
                    .to_vec(),
            )
            .unwrap();
            let confirmation_token = page
                .split("name=\"confirmation_token\" value=\"")
                .nth(1)
                .and_then(|rest| rest.split('"').next())
                .expect("confirmation token")
                .to_string();
            (csrf, confirmation_token)
        }

        /// Confirm a device approval, then clear `last_polled_at` so the next
        /// poll is not answered with `slow_down`.
        async fn approve_device(app: &Router, db: &DbPool, session: &str, user_code: &str) {
            let (csrf, confirmation_token) = device_confirmation(app, session, user_code).await;
            let confirm_body = format!(
                "user_code={}&decision=approve&csrf_token={}&confirmation_token={}&tool=claude-code",
                urlencoding::encode(user_code),
                urlencoding::encode(&csrf),
                urlencoding::encode(&confirmation_token),
            );
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/device")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("cookie", format!("lific_token={session}"))
                        .body(axum::body::Body::from(confirm_body))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::OK);
            db.write()
                .unwrap()
                .execute("UPDATE oauth_device_codes SET last_polled_at = NULL", [])
                .unwrap();
        }

        #[tokio::test]
        async fn an_ordinary_device_flow_still_works() {
            let (app, db) = test_oauth_app();
            let session = create_test_session(&db);
            let v = request_device_code(&app, Some("My CLI")).await;
            let client_id: String = db
                .read()
                .unwrap()
                .query_row(
                    "SELECT client_id FROM oauth_device_codes WHERE user_code = ?1",
                    params![v["user_code"].as_str().unwrap()],
                    |row| row.get(0),
                )
                .unwrap();
            approve_device(&app, &db, &session, v["user_code"].as_str().unwrap()).await;

            let (status, body) = poll_device_token(&app, v["device_code"].as_str().unwrap()).await;
            assert_eq!(status, StatusCode::OK, "{body}");
            assert!(
                body["access_token"]
                    .as_str()
                    .unwrap()
                    .starts_with("lific_at_")
            );
            let token_client_id: String = db
                .read()
                .unwrap()
                .query_row("SELECT client_id FROM oauth_tokens", [], |row| row.get(0))
                .unwrap();
            assert_eq!(token_client_id, client_id);
        }

        #[tokio::test]
        async fn a_device_approved_before_a_lockdown_is_denied_after_it() {
            let (app, db) = test_oauth_app();
            let session = create_test_session(&db);
            let v = request_device_code(&app, Some("My CLI")).await;
            approve_device(&app, &db, &session, v["user_code"].as_str().unwrap()).await;

            {
                let conn = db.write().unwrap();
                crate::db::queries::users::lock_down_account(&conn, owner_id(&db)).unwrap();
            }

            let (status, body) = poll_device_token(&app, v["device_code"].as_str().unwrap()).await;
            assert_eq!(status, StatusCode::BAD_REQUEST);
            assert_eq!(body["error"], "access_denied", "the denial wins cleanly");

            let tokens: i64 = db
                .read()
                .unwrap()
                .query_row("SELECT COUNT(*) FROM oauth_tokens", [], |r| r.get(0))
                .unwrap();
            assert_eq!(tokens, 0);
        }

        #[tokio::test]
        async fn a_device_bound_to_a_bot_with_an_inactive_owner_cannot_exchange() {
            let (app, db) = test_oauth_app();
            let session = create_test_session(&db);
            let v = request_device_code(&app, Some("My CLI")).await;
            approve_device(&app, &db, &session, v["user_code"].as_str().unwrap()).await;

            {
                let conn = db.write().unwrap();
                crate::db::queries::users::set_active(&conn, owner_id(&db), false).unwrap();
            }

            let (status, body) = poll_device_token(&app, v["device_code"].as_str().unwrap()).await;
            assert_eq!(status, StatusCode::BAD_REQUEST);
            assert_eq!(body["error"], "invalid_grant");
            assert_eq!(
                body["error_description"],
                "authorizing user is no longer active"
            );
        }

        #[tokio::test]
        async fn an_oauth_token_may_not_approve_a_device() {
            let (app, db) = test_oauth_app();
            let session = create_test_session(&db);
            let v = request_device_code(&app, Some("My CLI")).await;

            let access_token = {
                let token = "lific_at_device-approver".to_string();
                let hash = crate::auth::sha256_hex(token.as_bytes());
                let expires = (chrono::Utc::now() + chrono::Duration::hours(1)).to_rfc3339();
                let conn = db.write().unwrap();
                conn.execute(
                    "INSERT OR IGNORE INTO oauth_clients (client_id, client_name, redirect_uris)
                     VALUES ('device', 'Device Authorization', '[]')",
                    [],
                )
                .unwrap();
                conn.execute(
                    "INSERT INTO oauth_tokens (access_token, client_id, expires_at, scope, user_id)
                     VALUES (?1, 'device', ?2, 'mcp', ?3)",
                    params![hash, expires, owner_id(&db)],
                )
                .unwrap();
                token
            };
            let _ = session;

            let body = format!(
                "user_code={}&decision=approve&csrf_token={}&tool=claude-code",
                urlencoding::encode(v["user_code"].as_str().unwrap()),
                urlencoding::encode(&generate_csrf_token(&access_token)),
            );
            let resp = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/oauth/device")
                        .header("content-type", "application/x-www-form-urlencoded")
                        .header("authorization", format!("Bearer {access_token}"))
                        .body(axum::body::Body::from(body))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

            let still_pending: i64 = db
                .read()
                .unwrap()
                .query_row(
                    "SELECT COUNT(*) FROM oauth_device_codes WHERE status = 'pending'",
                    [],
                    |r| r.get(0),
                )
                .unwrap();
            assert_eq!(still_pending, 1);
        }
    }
}