ryuk 0.1.1

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
//! OAuth2 authorization server (RFC 6749 + PKCE 7636 + revocation 7009 + introspection 7662).
//!
//! Opaque tokens, hashed at rest (sha256 hex; the plaintext exists only in the response):
//! access `ryo_<43 chars>`, refresh `ryr_<43 chars>`, authorization codes `ryc_..`, client
//! secrets `rys_..`, all 256 bits from the OS RNG so a leak is greppable. Tables
//! (`oauth_clients`, `oauth_codes`, `oauth_tokens`) are self-created through portable SeaORM.
//!
//! Mounting: the app state `S` must provide `OAuthServer` (and, for the consent page,
//! `inertia::InertiaConfig`) through `axum::extract::FromRef`.
//!
//! ```ignore
//! let oauth = OAuthServer::new(db.clone());
//! oauth.ensure_tables().await?;
//! let c = oauth.create_client("My app", &["https://app.example/cb"], &["read"], false).await?;
//! // browser group:  App::web(OAuthServer::web_routes())     (GET/POST /oauth/authorize)
//! // public group:   App::public(OAuthServer::token_routes()) (POST /oauth/{token,revoke,introspect})
//! // api group:      App::api_verifier(oauth.clone())
//! ```
//! Pages the client app must provide: Inertia `OAuth/Authorize` (props `client.name`, `scopes[].name`,
//! `state`, `request_id`; POST `decision=allow|deny` + `request_id` to `/oauth/authorize`) and
//! `OAuth/Error` (prop `message`).
//!
//! First-party clients: register with [`ClientSpec`] (`.first_party()`) through
//! [`OAuthServer::create_client_spec`]; the flag cannot be set over HTTP. For a logged-in user,
//! `GET /oauth/authorize` of a first-party client runs the same validation (client, exact
//! `redirect_uri`, PKCE, scopes) and then skips the consent page: it issues the code and answers 303 to
//! `redirect_uri?code=..&state=..`. Add `prompt=consent` (alone or in a space-separated list) to force
//! the consent page. Logged-out users still go to `/login?next=`. The skip applies ONLY when the
//! requested `redirect_uri` is `https` (a verified app link / universal link): any other app on the
//! device can claim the same custom scheme (`myapp://callback`) and start the flow with the public
//! `client_id`, so silent approval there would hand it a code. A first-party client with a
//! custom-scheme redirect (any absolute `scheme:...` URI without fragment, matched exactly) always
//! shows the consent page; use https app links for silent sign-in.
//!
//! ```ignore
//! let spec = ClientSpec::new("Mobile").redirect("https://app.example.com/cb").scope("profile").first_party();
//! let c = oauth.create_client_spec(spec).await?; // c.client_secret is None (public)
//! ```
//!
//! Deviations from the RFCs (all stricter or simpler): `redirect_uri` is always required and must
//! match a registered one exactly; only `S256` PKCE (required for public clients); no `scope`
//! means no scopes; revoking an access or refresh token revokes the whole grant (family); HTTP
//! Basic credentials are not form-urlencoded-decoded (generated secrets never need it); no
//! `token_type_hint` handling (both columns are tried).
//!
//! Account hygiene: [`OAuthServer::revoke_user_tokens`], [`OAuthServer::list_grants`] /
//! [`OAuthServer::revoke_grant`] (one [`Grant`] per active token family) and a scheduled
//! [`OAuthServer::prune`].
//!
//! shortcut / notes: `ensure_tables` upgrades existing tables in place (`oauth_clients.first_party
//! boolean NOT NULL DEFAULT false`, `oauth_tokens.last_used_at`, the secondary indexes); it detects a
//! missing column by selecting it (`SchemaManager::has_column` is unsupported on SQLite). `prompt=none`/`login` are ignored. A
//! first-party client must have at least one redirect URI (`OAuthError::Invalid` otherwise).
//! A refresh re-reads the client: revoked clients fail, and the new token keeps only scopes the client
//! still allows (none left: `invalid_grant`).
//! Skipping consent also skips the pending-request/`request_id` round trip: the code is issued in the
//! GET itself, so the GET must not be triggered by third-party pages on behalf of a user; PKCE (required
//! for public clients) and the exact redirect match are what keep a stolen code useless.
use crate::api::{Principal, PrincipalKind, TokenVerifier};
use crate::health::BoxFuture;
use crate::inertia::{Inertia, InertiaConfig};
use crate::session::Session;
use axum::extract::rejection::FormRejection;
use axum::extract::{FromRef, OriginalUri, Query, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Form, Json, Router};
use base64::{Engine, engine::general_purpose::STANDARD, engine::general_purpose::URL_SAFE_NO_PAD};
use sea_orm::entity::prelude::*;
use sea_orm::sea_query::{Alias, ColumnDef, Expr, Query as SqlQuery, Table};
use sea_orm::{
    ActiveValue::Set, Condition, ConnectionTrait, DatabaseConnection, DbErr, QueryFilter,
    QuerySelect, Schema,
};
use sea_orm_migration::SchemaManager;
use serde::{Deserialize, Serialize};
use serde_json::json;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::time::Duration;

const SESSION_USER: &str = "user_id";
const SESSION_PENDING: &str = "oauth_pending";
const CODE_TTL: i64 = 600;

/// `oauth_clients` table.
pub mod clients {
    use sea_orm::entity::prelude::*;
    /// A registered client. `secret_hash` is `None` for public clients.
    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "oauth_clients")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i64,
        #[sea_orm(unique)]
        pub client_id: String,
        pub secret_hash: Option<String>,
        pub name: String,
        /// JSON array of exact-match redirect URIs.
        #[sea_orm(column_type = "Text")]
        pub redirect_uris: String,
        /// Space-separated scopes this client may request.
        #[sea_orm(column_type = "Text")]
        pub allowed_scopes: String,
        pub created_at: i64,
        pub revoked_at: Option<i64>,
        /// First-party clients skip the consent page for logged-in users (server-side flag only).
        #[sea_orm(default_value = false)]
        pub first_party: bool,
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}

/// `oauth_codes` table (authorization codes, single use).
pub mod codes {
    use sea_orm::entity::prelude::*;
    /// A hashed authorization code. `claim` is the nonce of the request that consumed it.
    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "oauth_codes")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i64,
        #[sea_orm(unique)]
        pub code_hash: String,
        pub client_id: String,
        #[sea_orm(indexed)]
        pub user_id: i64,
        #[sea_orm(column_type = "Text")]
        pub redirect_uri: String,
        #[sea_orm(column_type = "Text")]
        pub scopes: String,
        pub code_challenge: Option<String>,
        pub expires_at: i64,
        pub used_at: Option<i64>,
        pub claim: Option<String>,
        /// Set when a used code was presented again (its tokens are revoked).
        pub replayed_at: Option<i64>,
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}

/// `oauth_tokens` table: one row per access/refresh pair; a rotation adds a row to the same family.
pub mod tokens {
    use sea_orm::entity::prelude::*;
    /// Hashed access (and optional refresh) token.
    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "oauth_tokens")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i64,
        #[sea_orm(unique)]
        pub access_hash: String,
        #[sea_orm(unique)]
        pub refresh_hash: Option<String>,
        #[sea_orm(indexed)]
        pub client_id: String,
        /// `None` for client_credentials.
        #[sea_orm(indexed)]
        pub user_id: Option<i64>,
        #[sea_orm(column_type = "Text")]
        pub scopes: String,
        pub created_at: i64,
        pub access_expires_at: i64,
        pub refresh_expires_at: Option<i64>,
        pub revoked_at: Option<i64>,
        #[sea_orm(indexed)]
        pub family_id: String,
        /// The code that produced this grant (to revoke it on code replay).
        #[sea_orm(indexed)]
        pub code_id: Option<i64>,
        pub refresh_used_at: Option<i64>,
        pub refresh_claim: Option<String>,
        /// Last verified use of the access token (at most 60 s stale).
        pub last_used_at: Option<i64>,
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}

/// Storage, randomness or input failure from the management API.
#[derive(Debug, thiserror::Error)]
pub enum OAuthError {
    /// Database error.
    #[error("database: {0}")]
    Db(#[from] DbErr),
    /// The OS random number generator failed.
    #[error("OS random number generator failed")]
    Rng,
    /// Rejected input (the message says which).
    #[error("invalid: {0}")]
    Invalid(&'static str),
}

/// A freshly registered client. `client_secret` is shown once (confidential clients only).
#[derive(Clone)]
pub struct NewClient {
    /// Public identifier.
    pub client_id: String,
    /// Plaintext secret; only its hash is stored.
    pub client_secret: Option<String>,
}

/// Never prints the secret: a `{:?}` of a new client must be safe to log.
impl std::fmt::Debug for NewClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NewClient")
            .field("client_id", &self.client_id)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "<redacted>"),
            )
            .finish()
    }
}

/// What to register; build with [`ClientSpec::new`] and the chained setters, then pass it to
/// [`OAuthServer::create_client_spec`]. Public (no secret) unless [`confidential`](Self::confidential).
///
/// ```ignore
/// let spec = ClientSpec::new("Mobile app").redirect("myapp://callback").scope("profile").first_party();
/// let c = oauth.create_client_spec(spec).await?;
/// ```
#[derive(Clone, Debug)]
pub struct ClientSpec {
    /// Display name, 1..=100 chars.
    pub name: String,
    /// Exact-match redirect URIs (custom schemes such as `myapp://callback` are valid).
    pub redirect_uris: Vec<String>,
    /// Scopes the client may request.
    pub scopes: Vec<String>,
    /// Gets a secret (and may use `client_credentials`).
    pub confidential: bool,
    /// Skips the consent page for logged-in users. Only settable here, never over HTTP.
    pub first_party: bool,
}

impl ClientSpec {
    /// A public, third-party client with no redirect URIs or scopes yet.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            redirect_uris: vec![],
            scopes: vec![],
            confidential: false,
            first_party: false,
        }
    }
    /// Add a redirect URI.
    pub fn redirect(mut self, uri: impl Into<String>) -> Self {
        self.redirect_uris.push(uri.into());
        self
    }
    /// Add an allowed scope.
    pub fn scope(mut self, s: impl Into<String>) -> Self {
        self.scopes.push(s.into());
        self
    }
    /// Make it confidential (a secret is generated).
    pub fn confidential(mut self) -> Self {
        self.confidential = true;
        self
    }
    /// Mark it first-party: no consent screen for logged-in users on `https` redirects (`prompt=consent`
    /// forces it; custom-scheme redirects always show it).
    pub fn first_party(mut self) -> Self {
        self.first_party = true;
        self
    }
}

/// The authorization server. Cheap to clone; put it in the app state.
#[derive(Clone)]
pub struct OAuthServer {
    db: DatabaseConnection,
    access_ttl: Duration,
    refresh_ttl: Duration,
}

/// Add a column to an existing table when missing. shortcut: SchemaManager::has_column is
/// unsupported on SQLite, so probe by selecting the column (any error means "missing"; a real
/// outage then fails the ALTER with the actual cause).
async fn add_column_if_missing<E, C>(
    db: &DatabaseConnection,
    table: E,
    column: C,
    def: ColumnDef,
) -> Result<(), DbErr>
where
    E: sea_orm::sea_query::IntoTableRef + sea_orm::sea_query::IntoIden + Copy,
    C: sea_orm::sea_query::IntoIden,
{
    let probe = SqlQuery::select()
        .column((table, column)) // qualified: SQLite reads an unknown bare "name" as a string literal
        .from(table)
        .limit(1)
        .to_owned();
    if db.query_all(&probe).await.is_err() {
        let alter = Table::alter().table(table).add_column(def).to_owned();
        // A concurrent instance may have added it first: only fail if it is still missing.
        if let Err(e) = SchemaManager::new(db).alter_table(alter).await
            && db.query_all(&probe).await.is_err()
        {
            return Err(e);
        }
    }
    Ok(())
}

/// Does MySQL already have this index? (`SchemaManager::has_index` is unsupported there.)
async fn mysql_has_index(db: &DatabaseConnection, table: &str, index: &str) -> Result<bool, DbErr> {
    use sea_orm::ExprTrait;
    use sea_orm::sea_query::Func;
    let q = SqlQuery::select()
        .column(Alias::new("index_name"))
        .from((Alias::new("information_schema"), Alias::new("statistics")))
        .and_where(Expr::col(Alias::new("table_schema")).eq(Func::cust(Alias::new("DATABASE"))))
        .and_where(Expr::col(Alias::new("table_name")).eq(table))
        .and_where(Expr::col(Alias::new("index_name")).eq(index))
        .limit(1)
        .to_owned();
    Ok(!db.query_all(&q).await?.is_empty())
}

/// Whether the database rolled a statement back because it lost a deadlock (MySQL 1213, PostgreSQL 40P01) or hit a
/// serialization failure (40001). Nothing of that statement was applied.
fn is_deadlock(e: &DbErr) -> bool {
    let m = e.to_string();
    m.contains("Deadlock") || m.contains("40P01") || m.contains("40001")
}

/// Run one autocommit statement, repeating it when the database picked it as a deadlock victim. Safe because a
/// victim statement was rolled back whole; do NOT wrap several statements that depend on each other. Under
/// concurrent prune and refresh rotation MySQL does this routinely, and it must not surface as a 500.
async fn retried<T, Fut: std::future::Future<Output = Result<T, DbErr>>>(
    mut f: impl FnMut() -> Fut,
) -> Result<T, DbErr> {
    let mut tries = 0u64;
    loop {
        match f().await {
            Err(e) if tries < 5 && is_deadlock(&e) => {
                tries += 1;
                tokio::time::sleep(Duration::from_millis(5 * tries)).await;
            }
            r => return r,
        }
    }
}

/// Create the `#[sea_orm(indexed)]` indexes of `entity` if missing (also on an old table).
/// Postgres/SQLite have `CREATE INDEX IF NOT EXISTS`; MySQL does not, so ask the catalog first
/// and tolerate a concurrent creator.
async fn ensure_indexes<E: EntityTrait>(db: &DatabaseConnection, entity: E) -> Result<(), DbErr> {
    let b = db.get_database_backend();
    for mut i in Schema::new(b).create_index_from_entity(entity) {
        if b != sea_orm::DbBackend::MySql {
            if let Err(e) = db.execute(i.if_not_exists()).await {
                // Two instances creating the same index at once can collide inside PostgreSQL (duplicate key in
                // pg_class); the second attempt sees it and is a no-op.
                if db.execute(i.if_not_exists()).await.is_err() {
                    return Err(e);
                }
            }
            continue;
        }
        let name = i
            .get_index_spec()
            .get_name()
            .unwrap_or_default()
            .to_string();
        let table = entity.table_name();
        if mysql_has_index(db, table, &name).await? {
            continue;
        }
        if let Err(e) = db.execute(&i).await
            && !mysql_has_index(db, table, &name).await?
        {
            return Err(e);
        }
    }
    Ok(())
}

/// Outcome of [`OAuthServer::prune`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PruneReport {
    /// Authorization codes deleted.
    pub codes: u64,
    /// Token rows deleted.
    pub tokens: u64,
}

/// One active authorization (a token family) of a user, for a "connected apps" page.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Grant {
    /// The token family id; pass it to [`OAuthServer::revoke_grant`].
    pub id: String,
    /// OAuth client id.
    pub client_id: String,
    /// Client display name (empty if the client row is gone).
    pub client_name: String,
    /// Scopes of the newest token in the family.
    pub scopes: Vec<String>,
    /// Unix seconds the grant was first issued.
    pub created_at: i64,
    /// Last verified use of an access token (at most 60 s stale).
    pub last_used_at: Option<i64>,
    /// Unix seconds after which nothing in the family can be used or refreshed.
    pub expires_at: i64,
}

/// Rows deleted per statement by `prune`.
const PRUNE_BATCH: u64 = 500;
/// Expired rows are kept this long so a request that was mid-flight at expiry still finishes.
const PRUNE_GRACE: i64 = 60;
/// `last_used_at` is written at most this often per token.
const LAST_USED_EVERY: i64 = 60;

fn now() -> i64 {
    chrono::Utc::now().timestamp()
}

fn hash(s: &str) -> String {
    Sha256::digest(s.as_bytes())
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

/// Constant-time equality for equal-length secrets/hashes.
fn ct_eq(a: &str, b: &str) -> bool {
    a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |d, (x, y)| d | (x ^ y)) == 0
}

fn random(prefix: &str, n: usize) -> Result<String, OAuthError> {
    use rand::TryRng;
    let mut raw = vec![0u8; n];
    rand::rngs::SysRng
        .try_fill_bytes(&mut raw)
        .map_err(|_| OAuthError::Rng)?;
    Ok(format!("{prefix}{}", URL_SAFE_NO_PAD.encode(raw)))
}

fn split(s: &str) -> Vec<String> {
    let mut v: Vec<String> = Vec::new();
    for x in s.split(' ').filter(|x| !x.is_empty()) {
        if !v.iter().any(|y| y == x) {
            v.push(x.into());
        }
    }
    v
}

fn pct(s: &str) -> String {
    s.bytes()
        .map(|b| {
            if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
                (b as char).to_string()
            } else {
                format!("%{b:02X}")
            }
        })
        .collect()
}

fn with_query(base: &str, params: &[(&str, &str)]) -> String {
    let q: Vec<String> = params
        .iter()
        .map(|(k, v)| format!("{k}={}", pct(v)))
        .collect();
    let sep = if base.contains('?') { '&' } else { '?' };
    format!("{base}{sep}{}", q.join("&"))
}

fn scope_ok(s: &str) -> bool {
    !s.is_empty()
        && s.len() <= 100
        && s.bytes()
            .all(|b| b.is_ascii_graphic() && b != b'"' && b != b'\\')
}

fn pkce_ok(challenge: &str, verifier: &str) -> bool {
    (43..=128).contains(&verifier.len())
        && verifier
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b))
        && ct_eq(
            &URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())),
            challenge,
        )
}

fn challenge_ok(c: &str) -> bool {
    c.len() == 43
        && c.bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}

impl clients::Model {
    fn uris(&self) -> Vec<String> {
        serde_json::from_str(&self.redirect_uris).unwrap_or_default()
    }
    fn allowed(&self) -> Vec<String> {
        split(&self.allowed_scopes)
    }
}

impl OAuthServer {
    /// New server over `db`: access tokens 1 h, refresh tokens 30 d.
    pub fn new(db: DatabaseConnection) -> Self {
        Self {
            db,
            access_ttl: Duration::from_secs(3600),
            refresh_ttl: Duration::from_secs(30 * 86400),
        }
    }

    /// Access token lifetime.
    pub fn access_ttl(mut self, d: Duration) -> Self {
        self.access_ttl = d;
        self
    }

    /// Refresh token lifetime (restarts on every rotation).
    pub fn refresh_ttl(mut self, d: Duration) -> Self {
        self.refresh_ttl = d;
        self
    }

    /// Create the three tables and their indexes if missing, and upgrade tables created by an
    /// older version in place (`oauth_clients.first_party`, `oauth_tokens.last_used_at`, indexes).
    pub async fn ensure_tables(&self) -> Result<(), DbErr> {
        let s = Schema::new(self.db.get_database_backend());
        let mut a = s.create_table_from_entity(clients::Entity);
        self.db.execute(a.if_not_exists()).await?;
        let mut b = s.create_table_from_entity(codes::Entity);
        self.db.execute(b.if_not_exists()).await?;
        let mut c = s.create_table_from_entity(tokens::Entity);
        self.db.execute(c.if_not_exists()).await?;
        add_column_if_missing(
            &self.db,
            clients::Entity,
            clients::Column::FirstParty,
            ColumnDef::new(Alias::new("first_party"))
                .boolean()
                .not_null()
                .default(false)
                .to_owned(),
        )
        .await?;
        add_column_if_missing(
            &self.db,
            tokens::Entity,
            tokens::Column::LastUsedAt,
            ColumnDef::new(Alias::new("last_used_at"))
                .big_integer()
                .null()
                .to_owned(),
        )
        .await?;
        ensure_indexes(&self.db, codes::Entity).await?;
        ensure_indexes(&self.db, tokens::Entity).await
    }

    /// Register a third-party client (wrapper over [`create_client_spec`](Self::create_client_spec)).
    pub async fn create_client(
        &self,
        name: &str,
        redirect_uris: &[&str],
        scopes: &[&str],
        confidential: bool,
    ) -> Result<NewClient, OAuthError> {
        let mut spec = ClientSpec::new(name);
        spec.redirect_uris = redirect_uris.iter().map(|s| String::from(*s)).collect();
        spec.scopes = scopes.iter().map(|s| String::from(*s)).collect();
        spec.confidential = confidential;
        self.create_client_spec(spec).await
    }

    /// Register a client. Redirect URIs must be absolute (`scheme:...`), fragment-free and are
    /// matched exactly. Confidential clients get a secret, returned once. A first-party client
    /// needs at least one redirect URI.
    pub async fn create_client_spec(&self, spec: ClientSpec) -> Result<NewClient, OAuthError> {
        let ClientSpec {
            name,
            redirect_uris,
            scopes,
            confidential,
            first_party,
        } = spec;
        if name.is_empty() || name.chars().count() > 100 {
            return Err(OAuthError::Invalid("name must be 1..=100 chars"));
        }
        if redirect_uris.len() > 20 || scopes.len() > 50 {
            return Err(OAuthError::Invalid("too many redirect uris or scopes"));
        }
        if first_party && redirect_uris.is_empty() {
            return Err(OAuthError::Invalid(
                "a first-party client needs a redirect uri",
            ));
        }
        for u in &redirect_uris {
            let scheme_ok = u.split_once(':').is_some_and(|(s, _)| {
                s.starts_with(|c: char| c.is_ascii_alphabetic())
                    && s.chars()
                        .all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
            });
            if !scheme_ok || u.contains('#') || !u.bytes().all(|b| b.is_ascii_graphic()) {
                return Err(OAuthError::Invalid(
                    "redirect uri must be absolute, ASCII, without fragment",
                ));
            }
        }
        if !scopes.iter().all(|s| scope_ok(s)) {
            return Err(OAuthError::Invalid("bad scope"));
        }
        let client_id = random("", 16)?;
        let secret = if confidential {
            Some(random("rys_", 32)?)
        } else {
            None
        };
        clients::ActiveModel {
            client_id: Set(client_id.clone()),
            secret_hash: Set(secret.as_deref().map(hash)),
            name: Set(name),
            redirect_uris: Set(json!(redirect_uris).to_string()),
            allowed_scopes: Set(scopes.join(" ")),
            created_at: Set(now()),
            first_party: Set(first_party),
            ..Default::default()
        }
        .insert(&self.db)
        .await?;
        Ok(NewClient {
            client_id,
            client_secret: secret,
        })
    }

    /// Store a single-use code (10 min) for an approved request; returns the plaintext.
    async fn issue_code(
        &self,
        client_id: &str,
        user: i64,
        redirect_uri: &str,
        scopes: &[String],
        challenge: Option<String>,
    ) -> Result<String, OAuthError> {
        let code = random("ryc_", 32)?;
        codes::ActiveModel {
            code_hash: Set(hash(&code)),
            client_id: Set(client_id.into()),
            user_id: Set(user),
            redirect_uri: Set(redirect_uri.into()),
            scopes: Set(scopes.join(" ")),
            code_challenge: Set(challenge),
            expires_at: Set(now() + CODE_TTL),
            ..Default::default()
        }
        .insert(&self.db)
        .await?;
        Ok(code)
    }

    /// Disable a client and revoke all its tokens. `false` if it does not exist.
    pub async fn revoke_client(&self, client_id: &str) -> Result<bool, OAuthError> {
        let Some(c) = self.client(client_id).await? else {
            return Ok(false);
        };
        let t = now();
        clients::Entity::update_many()
            .col_expr(clients::Column::RevokedAt, Expr::value(t))
            .filter(clients::Column::Id.eq(c.id))
            .filter(clients::Column::RevokedAt.is_null())
            .exec(&self.db)
            .await?;
        self.revoke_where(tokens::Column::ClientId.eq(client_id))
            .await?;
        Ok(true)
    }

    /// Revoke every token (access and refresh) of `user_id` and void their unused authorization
    /// codes; a refresh token presented afterwards is `invalid_grant`. Returns the number of
    /// token families that still had an unrevoked token.
    pub async fn revoke_user_tokens(&self, user_id: i64) -> Result<u64, OAuthError> {
        let live: std::collections::HashSet<String> = tokens::Entity::find()
            .filter(tokens::Column::UserId.eq(user_id))
            .filter(tokens::Column::RevokedAt.is_null())
            .all(&self.db)
            .await?
            .into_iter()
            .map(|r| r.family_id)
            .collect();
        // Codes first: an exchange racing us then replays a used code, which revokes what it minted.
        codes::Entity::update_many()
            .col_expr(codes::Column::UsedAt, Expr::value(now()))
            .filter(codes::Column::UserId.eq(user_id))
            .filter(codes::Column::UsedAt.is_null())
            .exec(&self.db)
            .await?;
        self.revoke_where(tokens::Column::UserId.eq(user_id))
            .await?;
        Ok(live.len() as u64)
    }

    /// The user's active grants (one per token family with a usable access or refresh token),
    /// newest first.
    pub async fn list_grants(&self, user_id: i64) -> Result<Vec<Grant>, OAuthError> {
        let t = now();
        let rows = tokens::Entity::find()
            .filter(tokens::Column::UserId.eq(user_id))
            .filter(tokens::Column::RevokedAt.is_null())
            .all(&self.db)
            .await?;
        let mut fams: HashMap<String, Vec<tokens::Model>> = HashMap::new();
        for r in rows {
            fams.entry(r.family_id.clone()).or_default().push(r);
        }
        let mut out = Vec::new();
        for (id, rows) in fams {
            // A rotated row's refresh is spent: only its access token can still be live.
            let end = |r: &tokens::Model| match (r.refresh_expires_at, r.refresh_used_at) {
                (Some(e), None) => e.max(r.access_expires_at),
                _ => r.access_expires_at,
            };
            let Some(expires_at) = rows.iter().map(end).filter(|e| *e > t).max() else {
                continue;
            };
            let newest = rows.iter().max_by_key(|r| r.id).expect("non-empty");
            let client_id = newest.client_id.clone();
            let client_name = self
                .client(&client_id)
                .await?
                .map(|c| c.name)
                .unwrap_or_default();
            out.push(Grant {
                id,
                client_id,
                client_name,
                scopes: split(&newest.scopes),
                created_at: rows.iter().map(|r| r.created_at).min().unwrap_or(t),
                last_used_at: rows.iter().filter_map(|r| r.last_used_at).max(),
                expires_at,
            });
        }
        out.sort_by(|a, b| b.created_at.cmp(&a.created_at).then(a.id.cmp(&b.id)));
        Ok(out)
    }

    /// Revoke one grant (token family) of `user_id`; `false` if it is not theirs, unknown or
    /// already revoked.
    pub async fn revoke_grant(&self, user_id: i64, family_id: &str) -> Result<bool, OAuthError> {
        let live = tokens::Entity::find()
            .filter(tokens::Column::FamilyId.eq(family_id))
            .filter(tokens::Column::UserId.eq(user_id))
            .filter(tokens::Column::RevokedAt.is_null())
            .one(&self.db)
            .await?
            .is_some();
        if live {
            self.revoke_where(
                Condition::all()
                    .add(tokens::Column::FamilyId.eq(family_id))
                    .add(tokens::Column::UserId.eq(user_id)),
            )
            .await?;
        }
        Ok(live)
    }

    /// Delete finished rows; run it from a scheduled task.
    ///
    /// Codes: unused ones expired (plus a 60 s grace), and used ones used more than `retention`
    /// ago (a used code is kept for a while so a replay still revokes the tokens it issued).
    /// Tokens: revoked more than `retention` ago, or whose access token AND refresh token (if
    /// any) expired more than 60 s ago. A rotated token whose refresh is still unexpired stays, so
    /// reuse detection keeps working; a request mid-flight on a deleted row fails closed.
    /// Counts are the rows selected for deletion (concurrent pruners may overlap).
    pub async fn prune(&self, retention: Duration) -> Result<PruneReport, OAuthError> {
        let t = now();
        let keep = retention.as_secs().min(i64::MAX as u64 / 4) as i64;
        let (old, expired) = (t - keep, t - PRUNE_GRACE);
        let dead_codes = Condition::any()
            .add(
                Condition::all()
                    .add(codes::Column::UsedAt.is_null())
                    .add(codes::Column::ExpiresAt.lte(expired)),
            )
            .add(codes::Column::UsedAt.lte(old));
        let dead_tokens = Condition::any()
            .add(tokens::Column::RevokedAt.lte(old))
            .add(
                Condition::all()
                    .add(tokens::Column::AccessExpiresAt.lte(expired))
                    .add(
                        Condition::any()
                            .add(tokens::Column::RefreshExpiresAt.is_null())
                            .add(tokens::Column::RefreshExpiresAt.lte(expired)),
                    ),
            );
        let mut report = PruneReport::default();
        loop {
            let ids: Vec<i64> = codes::Entity::find()
                .filter(dead_codes.clone())
                .limit(PRUNE_BATCH)
                .all(&self.db)
                .await?
                .into_iter()
                .map(|r| r.id)
                .collect();
            report.codes += ids.len() as u64;
            let full = ids.len() as u64 == PRUNE_BATCH;
            retried(|| {
                codes::Entity::delete_many()
                    .filter(codes::Column::Id.is_in(ids.clone()))
                    .exec(&self.db)
            })
            .await?;
            if !full {
                break;
            }
        }
        loop {
            let ids: Vec<i64> = tokens::Entity::find()
                .filter(dead_tokens.clone())
                .limit(PRUNE_BATCH)
                .all(&self.db)
                .await?
                .into_iter()
                .map(|r| r.id)
                .collect();
            report.tokens += ids.len() as u64;
            let full = ids.len() as u64 == PRUNE_BATCH;
            retried(|| {
                tokens::Entity::delete_many()
                    .filter(tokens::Column::Id.is_in(ids.clone()))
                    .exec(&self.db)
            })
            .await?;
            if !full {
                break;
            }
        }
        Ok(report)
    }

    async fn client(&self, client_id: &str) -> Result<Option<clients::Model>, DbErr> {
        clients::Entity::find()
            .filter(clients::Column::ClientId.eq(client_id))
            .one(&self.db)
            .await
    }

    async fn active_client(&self, client_id: &str) -> Result<Option<clients::Model>, DbErr> {
        Ok(self
            .client(client_id)
            .await?
            .filter(|c| c.revoked_at.is_none()))
    }

    /// Mark live tokens matching `cond` revoked (no reliance on affected-row counts).
    async fn revoke_where(&self, cond: impl Into<Condition>) -> Result<(), DbErr> {
        let cond: Condition = cond.into();
        retried(|| {
            tokens::Entity::update_many()
                .col_expr(tokens::Column::RevokedAt, Expr::value(now()))
                .filter(cond.clone())
                .filter(tokens::Column::RevokedAt.is_null())
                .exec(&self.db)
        })
        .await?;
        Ok(())
    }

    async fn revoke_family(&self, family: &str) -> Result<(), DbErr> {
        self.revoke_where(tokens::Column::FamilyId.eq(family)).await
    }

    /// Insert a token row; returns `(row, access, refresh)` plaintexts.
    async fn mint(
        &self,
        client: &str,
        user: Option<i64>,
        scopes: &str,
        family: Option<String>,
        code_id: Option<i64>,
        refresh: bool,
    ) -> Result<(tokens::Model, String, Option<String>), Fail> {
        let access = random("ryo_", 32)?;
        let refresh = if refresh {
            Some(random("ryr_", 32)?)
        } else {
            None
        };
        let t = now();
        let new_row = tokens::ActiveModel {
            access_hash: Set(hash(&access)),
            refresh_hash: Set(refresh.as_deref().map(hash)),
            client_id: Set(client.into()),
            user_id: Set(user),
            scopes: Set(scopes.into()),
            created_at: Set(t),
            access_expires_at: Set(t + self.access_ttl.as_secs() as i64),
            refresh_expires_at: Set(refresh
                .as_ref()
                .map(|_| t + self.refresh_ttl.as_secs() as i64)),
            family_id: Set(match family {
                Some(f) => f,
                None => random("", 16)?,
            }),
            code_id: Set(code_id),
            ..Default::default()
        };
        let row = retried(|| new_row.clone().insert(&self.db)).await?;
        Ok((row, access, refresh))
    }

    /// Winner-takes-all consumption without affected-row counts: every contender writes its own
    /// nonce with a conditional `UPDATE ... WHERE used IS NULL`; only the first match changes the
    /// row, and each contender then reads back whose nonce is there.
    async fn claim_code(&self, id: i64) -> Result<bool, DbErr> {
        let nonce = random("", 16).map_err(|_| DbErr::Custom("rng".into()))?;
        codes::Entity::update_many()
            .col_expr(codes::Column::UsedAt, Expr::value(now()))
            .col_expr(codes::Column::Claim, Expr::value(nonce.clone()))
            .filter(codes::Column::Id.eq(id))
            .filter(codes::Column::UsedAt.is_null())
            .exec(&self.db)
            .await?;
        let row = codes::Entity::find_by_id(id).one(&self.db).await?;
        Ok(row.is_some_and(|r| r.claim.as_deref() == Some(nonce.as_str())))
    }

    async fn claim_refresh(&self, id: i64) -> Result<bool, DbErr> {
        let nonce = random("", 16).map_err(|_| DbErr::Custom("rng".into()))?;
        retried(|| {
            tokens::Entity::update_many()
                .col_expr(tokens::Column::RefreshUsedAt, Expr::value(now()))
                .col_expr(tokens::Column::RefreshClaim, Expr::value(nonce.clone()))
                .filter(tokens::Column::Id.eq(id))
                .filter(tokens::Column::RefreshUsedAt.is_null())
                .exec(&self.db)
        })
        .await?;
        let row = tokens::Entity::find_by_id(id).one(&self.db).await?;
        Ok(row.is_some_and(|r| r.refresh_claim.as_deref() == Some(nonce.as_str())))
    }

    /// A used code came back: remember it and revoke everything it issued.
    async fn code_replayed(&self, code_id: i64) -> Result<(), DbErr> {
        codes::Entity::update_many()
            .col_expr(codes::Column::ReplayedAt, Expr::value(now()))
            .filter(codes::Column::Id.eq(code_id))
            .exec(&self.db)
            .await?;
        self.revoke_where(tokens::Column::CodeId.eq(code_id)).await
    }

    /// Validate an access token; `Some(row)` if live.
    async fn live_access(&self, token: &str) -> Result<Option<tokens::Model>, DbErr> {
        if !token.starts_with("ryo_") {
            return Ok(None);
        }
        let h = hash(token);
        let t = now();
        Ok(tokens::Entity::find()
            .filter(tokens::Column::AccessHash.eq(h.as_str()))
            .one(&self.db)
            .await?
            .filter(|r| {
                r.revoked_at.is_none() && r.access_expires_at > t && ct_eq(&r.access_hash, &h)
            }))
    }
}

impl TokenVerifier for OAuthServer {
    fn verify<'a>(&'a self, bearer: &'a str) -> BoxFuture<'a, Option<Principal>> {
        Box::pin(async move {
            let r = match self.live_access(bearer).await {
                Ok(Some(r)) => r,
                Ok(None) => return None,
                Err(e) => {
                    tracing::error!("oauth verify: {e}");
                    return None;
                }
            };
            let t = now();
            if r.last_used_at.is_none_or(|l| l <= t - LAST_USED_EVERY) {
                // Best effort; the row count is not used (MySQL reports matched rows).
                let touched = tokens::Entity::update_many()
                    .col_expr(tokens::Column::LastUsedAt, Expr::value(t))
                    .filter(tokens::Column::Id.eq(r.id))
                    .exec(&self.db)
                    .await;
                if let Err(e) = touched {
                    tracing::warn!("oauth last_used update failed: {e}");
                }
            }
            let client = r.user_id.is_none();
            Some(Principal {
                kind: if client {
                    PrincipalKind::OAuthClient
                } else {
                    PrincipalKind::OAuthToken
                },
                // Stable per grant (survives refresh rotation) so rate limits cannot be dodged by refreshing.
                id: if client {
                    r.client_id.clone()
                } else {
                    r.family_id
                },
                user_id: r.user_id,
                client_id: Some(r.client_id),
                scopes: split(&r.scopes),
                name: None,
            })
        })
    }
}

// ---------------------------------------------------------------------------------------------
// Token endpoints
// ---------------------------------------------------------------------------------------------

/// RFC 6749 section 5.2 error.
struct Fail {
    status: StatusCode,
    error: &'static str,
    desc: &'static str,
}

fn nostore(mut r: Response) -> Response {
    let h = r.headers_mut();
    h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
    h.insert(header::PRAGMA, HeaderValue::from_static("no-cache"));
    r
}

impl IntoResponse for Fail {
    fn into_response(self) -> Response {
        let mut r = (
            self.status,
            Json(json!({"error": self.error, "error_description": self.desc})),
        )
            .into_response();
        if self.status == StatusCode::UNAUTHORIZED {
            r.headers_mut().insert(
                header::WWW_AUTHENTICATE,
                HeaderValue::from_static("Basic realm=\"oauth\""),
            );
        }
        nostore(r)
    }
}

fn bad(error: &'static str, desc: &'static str) -> Fail {
    Fail {
        status: StatusCode::BAD_REQUEST,
        error,
        desc,
    }
}
fn grant() -> Fail {
    bad(
        "invalid_grant",
        "The grant is invalid, expired, revoked or already used.",
    )
}
impl From<DbErr> for Fail {
    fn from(e: DbErr) -> Self {
        tracing::error!("oauth: {e}");
        Fail {
            status: StatusCode::INTERNAL_SERVER_ERROR,
            error: "server_error",
            desc: "Internal error.",
        }
    }
}
impl From<OAuthError> for Fail {
    fn from(e: OAuthError) -> Self {
        tracing::error!("oauth: {e}");
        Fail {
            status: StatusCode::INTERNAL_SERVER_ERROR,
            error: "server_error",
            desc: "Internal error.",
        }
    }
}

type Params = HashMap<String, String>;
type Res<T> = Result<T, Fail>;

fn param<'a>(f: &'a Params, k: &str) -> Option<&'a str> {
    f.get(k).map(String::as_str).filter(|v| !v.is_empty())
}

impl OAuthServer {
    /// Authenticate the client: HTTP Basic or `client_id`/`client_secret` in the body.
    async fn authenticate(&self, headers: &HeaderMap, f: &Params) -> Res<clients::Model> {
        let invalid = || Fail {
            status: StatusCode::UNAUTHORIZED,
            error: "invalid_client",
            desc: "Client authentication failed.",
        };
        let (id, secret) = match headers
            .get(header::AUTHORIZATION)
            .and_then(|v| v.to_str().ok())
        {
            Some(h) if h.len() > 6 && h[..6].eq_ignore_ascii_case("basic ") => {
                if f.contains_key("client_secret") {
                    return Err(bad(
                        "invalid_request",
                        "Use one client authentication method.",
                    ));
                }
                let dec = STANDARD
                    .decode(h[6..].trim())
                    .ok()
                    .and_then(|b| String::from_utf8(b).ok());
                let (i, s) = dec
                    .as_deref()
                    .and_then(|d| d.split_once(':'))
                    .ok_or_else(invalid)?;
                if param(f, "client_id").is_some_and(|b| b != i) {
                    return Err(bad("invalid_request", "client_id mismatch."));
                }
                (i.to_string(), Some(s.to_string()))
            }
            _ => (
                param(f, "client_id")
                    .ok_or_else(|| bad("invalid_request", "client_id is required."))?
                    .to_string(),
                param(f, "client_secret").map(str::to_string),
            ),
        };
        let client = self.active_client(&id).await?;
        // Hash and compare even for unknown clients so timing does not reveal which ids exist.
        let given = hash(secret.as_deref().unwrap_or(""));
        let (stored, public) = match &client {
            Some(c) => (
                c.secret_hash.clone().unwrap_or_default(),
                c.secret_hash.is_none(),
            ),
            None => (hash("unknown-client"), false),
        };
        let secret_ok = if public {
            secret.is_none()
        } else {
            secret.is_some() && ct_eq(&given, &stored)
        };
        match client {
            Some(c) if secret_ok => Ok(c),
            _ => Err(invalid()),
        }
    }

    async fn grant(&self, headers: &HeaderMap, f: &Params) -> Res<Response> {
        let client = self.authenticate(headers, f).await?;
        let Some(gt) = param(f, "grant_type") else {
            return Err(bad("invalid_request", "grant_type is required."));
        };
        let (row, access, refresh) = match gt {
            "authorization_code" => self.code_grant(&client, f).await?,
            "refresh_token" => self.refresh_grant(&client, f).await?,
            "client_credentials" => {
                if client.secret_hash.is_none() {
                    return Err(Fail {
                        status: StatusCode::BAD_REQUEST,
                        error: "unauthorized_client",
                        desc: "Public clients cannot use client_credentials.",
                    });
                }
                let scopes = requested_scopes(&client, param(f, "scope"))?;
                self.mint(
                    &client.client_id,
                    None,
                    &scopes.join(" "),
                    None,
                    None,
                    false,
                )
                .await?
            }
            _ => return Err(bad("unsupported_grant_type", "Unsupported grant_type.")),
        };
        let mut body = json!({
            "access_token": access, "token_type": "Bearer",
            "expires_in": (row.access_expires_at - row.created_at).max(0), "scope": row.scopes,
        });
        if let Some(r) = refresh {
            body["refresh_token"] = r.into();
        }
        Ok(nostore(Json(body).into_response()))
    }

    async fn code_grant(
        &self,
        client: &clients::Model,
        f: &Params,
    ) -> Res<(tokens::Model, String, Option<String>)> {
        let code = param(f, "code").ok_or_else(|| bad("invalid_request", "code is required."))?;
        let redirect = param(f, "redirect_uri")
            .ok_or_else(|| bad("invalid_request", "redirect_uri is required."))?;
        let h = hash(code);
        let row = codes::Entity::find()
            .filter(codes::Column::CodeHash.eq(h.as_str()))
            .one(&self.db)
            .await?
            .filter(|r| ct_eq(&r.code_hash, &h))
            .ok_or_else(grant)?;
        if row.client_id != client.client_id {
            return Err(grant());
        }
        if row.used_at.is_some() {
            self.code_replayed(row.id).await?;
            return Err(grant());
        }
        if row.expires_at <= now() || row.redirect_uri != redirect {
            return Err(grant());
        }
        match (&row.code_challenge, param(f, "code_verifier")) {
            (Some(c), Some(v)) if pkce_ok(c, v) => {}
            (Some(_), _) => return Err(grant()),
            // A verifier for a code issued without a challenge is a downgrade attempt.
            (None, Some(_)) => return Err(grant()),
            (None, None) => {}
        }
        if !self.claim_code(row.id).await? {
            self.code_replayed(row.id).await?;
            return Err(grant());
        }
        let out = self
            .mint(
                &client.client_id,
                Some(row.user_id),
                &row.scopes,
                None,
                Some(row.id),
                true,
            )
            .await?;
        // A replay that raced the claim may have revoked before this insert landed.
        let again = codes::Entity::find_by_id(row.id).one(&self.db).await?;
        if again.is_none_or(|c| c.replayed_at.is_some()) {
            self.revoke_where(tokens::Column::CodeId.eq(row.id)).await?;
            return Err(grant());
        }
        Ok(out)
    }

    async fn refresh_grant(
        &self,
        client: &clients::Model,
        f: &Params,
    ) -> Res<(tokens::Model, String, Option<String>)> {
        let tok = param(f, "refresh_token")
            .ok_or_else(|| bad("invalid_request", "refresh_token is required."))?;
        let h = hash(tok);
        let row = tokens::Entity::find()
            .filter(tokens::Column::RefreshHash.eq(h.as_str()))
            .one(&self.db)
            .await?
            .filter(|r| r.refresh_hash.as_deref().is_some_and(|x| ct_eq(x, &h)))
            .ok_or_else(grant)?;
        if row.client_id != client.client_id || row.revoked_at.is_some() {
            return Err(grant());
        }
        if row.refresh_used_at.is_some() {
            // A rotated token came back: someone holds a stolen copy. Kill the whole grant.
            self.revoke_family(&row.family_id).await?;
            return Err(grant());
        }
        if row.refresh_expires_at.is_none_or(|e| e <= now()) {
            return Err(grant());
        }
        let scopes = match param(f, "scope") {
            None => row.scopes.clone(),
            Some(s) => {
                let (want, had) = (split(s), split(&row.scopes));
                if !want.iter().all(|w| had.contains(w)) {
                    return Err(bad("invalid_scope", "Scope exceeds the original grant."));
                }
                want.join(" ")
            }
        };
        // The client's CURRENT allowed scopes cap what a refresh may carry forward.
        let allowed = client.allowed();
        let kept = split(&scopes)
            .into_iter()
            .filter(|s| allowed.contains(s))
            .collect::<Vec<_>>();
        if kept.is_empty() && !scopes.is_empty() {
            return Err(grant());
        }
        let scopes = kept.join(" ");
        if !self.claim_refresh(row.id).await? {
            self.revoke_family(&row.family_id).await?;
            return Err(grant());
        }
        let out = self
            .mint(
                &client.client_id,
                row.user_id,
                &scopes,
                Some(row.family_id.clone()),
                row.code_id,
                true,
            )
            .await?;
        // A concurrent reuse/revoke of the family may have run before the new row existed.
        let old = tokens::Entity::find_by_id(row.id).one(&self.db).await?;
        if old.is_none_or(|o| o.revoked_at.is_some()) {
            self.revoke_family(&row.family_id).await?;
            return Err(grant());
        }
        Ok(out)
    }

    async fn find_token(&self, token: &str) -> Result<Option<(tokens::Model, bool)>, DbErr> {
        let h = hash(token);
        let row = tokens::Entity::find()
            .filter(
                Condition::any()
                    .add(tokens::Column::AccessHash.eq(h.as_str()))
                    .add(tokens::Column::RefreshHash.eq(h.as_str())),
            )
            .one(&self.db)
            .await?;
        Ok(row.and_then(|r| {
            if ct_eq(&r.access_hash, &h) {
                Some((r, true))
            } else if r.refresh_hash.as_deref().is_some_and(|x| ct_eq(x, &h)) {
                Some((r, false))
            } else {
                None
            }
        }))
    }
}

/// Requested scopes must all be in the client's allowed set.
fn requested_scopes(client: &clients::Model, s: Option<&str>) -> Res<Vec<String>> {
    let want = split(s.unwrap_or(""));
    let allowed = client.allowed();
    if want.len() > 50 || !want.iter().all(|w| scope_ok(w) && allowed.contains(w)) {
        return Err(bad("invalid_scope", "Unknown or disallowed scope."));
    }
    Ok(want)
}

fn form(f: Result<Form<Params>, FormRejection>) -> Res<Params> {
    f.map(|Form(p)| p).map_err(|_| {
        bad(
            "invalid_request",
            "Expected an application/x-www-form-urlencoded body.",
        )
    })
}

async fn token_h(
    State(o): State<OAuthServer>,
    headers: HeaderMap,
    f: Result<Form<Params>, FormRejection>,
) -> Response {
    match async { o.grant(&headers, &form(f)?).await }.await {
        Ok(r) => r,
        Err(e) => e.into_response(),
    }
}

async fn revoke_h(
    State(o): State<OAuthServer>,
    headers: HeaderMap,
    f: Result<Form<Params>, FormRejection>,
) -> Response {
    let run = async {
        let f = form(f)?;
        let client = o.authenticate(&headers, &f).await?;
        let tok = param(&f, "token").ok_or_else(|| bad("invalid_request", "token is required."))?;
        // Unknown or foreign tokens are indistinguishable from success (RFC 7009 section 2.2).
        if let Some((row, _)) = o
            .find_token(tok)
            .await?
            .filter(|(r, _)| r.client_id == client.client_id)
        {
            o.revoke_family(&row.family_id).await?;
        }
        Ok::<_, Fail>(nostore(StatusCode::OK.into_response()))
    };
    run.await.unwrap_or_else(IntoResponse::into_response)
}

async fn introspect_h(
    State(o): State<OAuthServer>,
    headers: HeaderMap,
    f: Result<Form<Params>, FormRejection>,
) -> Response {
    let run = async {
        let f = form(f)?;
        let client = o.authenticate(&headers, &f).await?;
        if client.secret_hash.is_none() {
            return Err(Fail {
                status: StatusCode::UNAUTHORIZED,
                error: "invalid_client",
                desc: "Introspection needs a confidential client.",
            });
        }
        let tok = param(&f, "token").ok_or_else(|| bad("invalid_request", "token is required."))?;
        let t = now();
        let live = o
            .find_token(tok)
            .await?
            .filter(|(r, _)| r.client_id == client.client_id && r.revoked_at.is_none());
        let active = live.and_then(|(r, is_access)| {
            if is_access && r.access_expires_at > t {
                Some((r.access_expires_at, "Bearer", r))
            } else if !is_access
                && r.refresh_used_at.is_none()
                && r.refresh_expires_at.is_some_and(|e| e > t)
            {
                Some((r.refresh_expires_at.unwrap_or(0), "refresh_token", r))
            } else {
                None
            }
        });
        let body = match active {
            None => json!({"active": false}),
            Some((exp, kind, r)) => {
                let mut v = json!({"active": true, "scope": r.scopes, "client_id": r.client_id, "token_type": kind, "exp": exp, "iat": r.created_at});
                if let Some(u) = r.user_id {
                    v["sub"] = u.to_string().into();
                }
                v
            }
        };
        Ok::<_, Fail>(nostore(Json(body).into_response()))
    };
    run.await.unwrap_or_else(IntoResponse::into_response)
}

// ---------------------------------------------------------------------------------------------
// Authorization endpoint (browser)
// ---------------------------------------------------------------------------------------------

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

#[derive(Deserialize)]
struct Decision {
    decision: String,
    request_id: String,
}

/// The consent decision as the client sends it: an Inertia page posts JSON, a plain HTML form (or
/// curl) posts urlencoded. The RFC endpoints (`/oauth/token` ...) stay form-only; this one is a
/// browser endpoint, and answering 415 to the Inertia client broke the consent screen.
struct DecisionBody(Decision);

impl<S: Send + Sync> axum::extract::FromRequest<S> for DecisionBody {
    type Rejection = Response;

    async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Response> {
        let json = req
            .headers()
            .get(header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .is_some_and(|v| v.starts_with("application/json"));
        let d = if json {
            Json::<Decision>::from_request(req, state)
                .await
                .map_err(IntoResponse::into_response)?
                .0
        } else {
            Form::<Decision>::from_request(req, state)
                .await
                .map_err(IntoResponse::into_response)?
                .0
        };
        Ok(DecisionBody(d))
    }
}

#[derive(Serialize, Deserialize)]
struct Pending {
    request_id: String,
    user_id: i64,
    client_id: String,
    redirect_uri: String,
    scopes: Vec<String>,
    state: Option<String>,
    challenge: Option<String>,
}

fn server_error<E: std::fmt::Display>(e: E) -> Response {
    tracing::error!("oauth authorize: {e}");
    StatusCode::INTERNAL_SERVER_ERROR.into_response()
}

/// Send the user to an external URL; Inertia XHRs cannot follow cross-origin 303s, so they get a 409 location.
fn leave(headers: &HeaderMap, to: &str) -> Response {
    match HeaderValue::from_str(to) {
        Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
        Ok(v) if headers.contains_key("x-inertia") => {
            (StatusCode::CONFLICT, [("x-inertia-location", v)]).into_response()
        }
        Ok(v) => (StatusCode::SEE_OTHER, [(header::LOCATION, v)]).into_response(),
    }
}

fn error_page(i: Inertia, msg: &str) -> Response {
    let mut r = i.render("OAuth/Error", json!({ "message": msg }));
    if r.status() == StatusCode::OK {
        *r.status_mut() = StatusCode::BAD_REQUEST;
    }
    r
}

fn redirect_error(h: &HeaderMap, uri: &str, code: &str, state: Option<&str>) -> Response {
    let mut p = vec![("error", code)];
    if let Some(s) = state {
        p.push(("state", s));
    }
    leave(h, &with_query(uri, &p))
}

async fn authorize_get<S>(
    State(o): State<OAuthServer>,
    session: Session,
    inertia: Inertia,
    headers: HeaderMap,
    OriginalUri(uri): OriginalUri,
    Query(q): Query<AuthzParams>,
) -> Response
where
    S: Send + Sync,
    OAuthServer: FromRef<S>,
    InertiaConfig: FromRef<S>,
{
    let client = match o.active_client(q.client_id.as_deref().unwrap_or("")).await {
        Ok(Some(c)) => c,
        Ok(None) => return error_page(inertia, "Unknown application."),
        Err(e) => return server_error(e),
    };
    // Never redirect to a URI that is not registered verbatim.
    let Some(ru) = q.redirect_uri.clone().filter(|u| client.uris().contains(u)) else {
        return error_page(inertia, "Invalid redirect URI.");
    };
    let state = q.state.as_deref();
    let fail = |c: &str| redirect_error(&headers, &ru, c, state);
    if q.response_type.as_deref() != Some("code") {
        return fail("unsupported_response_type");
    }
    let Ok(scopes) = requested_scopes(&client, q.scope.as_deref()) else {
        return fail("invalid_scope");
    };
    let challenge = match (
        q.code_challenge.as_deref(),
        q.code_challenge_method.as_deref(),
    ) {
        (Some(c), Some("S256")) if challenge_ok(c) => Some(c.to_string()),
        (Some(_), _) => return fail("invalid_request"),
        (None, _) if client.secret_hash.is_none() => return fail("invalid_request"),
        (None, _) => None,
    };
    let user = match session.get::<i64>(SESSION_USER).await {
        Ok(Some(u)) => u,
        Ok(None) => {
            let next = uri
                .path_and_query()
                .map_or("/oauth/authorize", |p| p.as_str());
            return crate::inertia::redirect(&format!("/login?next={}", pct(next)));
        }
        Err(e) => return server_error(e),
    };
    // First-party clients skip consent only over https (app links); a custom scheme can be claimed by
    // any app on the device, so it always sees the consent page. `prompt=consent` opts out.
    if client.first_party
        && ru.starts_with("https://")
        && !split(q.prompt.as_deref().unwrap_or("")).contains(&"consent".into())
    {
        return match o
            .issue_code(&client.client_id, user, &ru, &scopes, challenge)
            .await
        {
            Ok(code) => {
                let mut params = vec![("code", code.as_str())];
                if let Some(s) = state {
                    params.push(("state", s));
                }
                leave(&headers, &with_query(&ru, &params))
            }
            Err(e) => server_error(e),
        };
    }
    let request_id = match random("", 16) {
        Ok(r) => r,
        Err(e) => return server_error(e),
    };
    let pending = Pending {
        request_id: request_id.clone(),
        user_id: user,
        client_id: client.client_id.clone(),
        redirect_uri: ru,
        scopes: scopes.clone(),
        state: q.state.clone(),
        challenge,
    };
    if let Err(e) = session.insert(SESSION_PENDING, pending).await {
        return server_error(e);
    }
    inertia.render(
        "OAuth/Authorize",
        json!({
            "client": {"name": client.name},
            "scopes": scopes.iter().map(|s| json!({"name": s})).collect::<Vec<_>>(),
            "state": q.state, "request_id": request_id,
        }),
    )
}

async fn authorize_post<S>(
    State(o): State<OAuthServer>,
    session: Session,
    inertia: Inertia,
    headers: HeaderMap,
    DecisionBody(d): DecisionBody,
) -> Response
where
    S: Send + Sync,
    OAuthServer: FromRef<S>,
    InertiaConfig: FromRef<S>,
{
    let user = match session.get::<i64>(SESSION_USER).await {
        Ok(Some(u)) => u,
        Ok(None) => return crate::inertia::redirect("/login"),
        Err(e) => return server_error(e),
    };
    // Single use whatever the outcome.
    let p = match session.remove::<Pending>(SESSION_PENDING).await {
        Ok(Some(p)) if p.user_id == user && ct_eq(&p.request_id, &d.request_id) => p,
        Ok(_) => {
            return error_page(
                inertia,
                "This authorization request expired. Start again from the application.",
            );
        }
        Err(e) => return server_error(e),
    };
    let state = p.state.as_deref();
    if d.decision != "allow" {
        return redirect_error(&headers, &p.redirect_uri, "access_denied", state);
    }
    match o.active_client(&p.client_id).await {
        Ok(Some(_)) => {}
        Ok(None) => return error_page(inertia, "Unknown application."),
        Err(e) => return server_error(e),
    }
    let issue = o.issue_code(
        &p.client_id,
        user,
        &p.redirect_uri,
        &p.scopes,
        p.challenge.clone(),
    );
    match issue.await {
        Ok(code) => {
            let mut params = vec![("code", code.as_str())];
            if let Some(s) = state {
                params.push(("state", s));
            }
            leave(&headers, &with_query(&p.redirect_uri, &params))
        }
        Err(e) => server_error(e),
    }
}

impl OAuthServer {
    /// Browser routes `GET/POST /oauth/authorize` as a plain axum router (mount with `App::routes`).
    /// Needs `OAuthServer` and `InertiaConfig` in the state via `FromRef`.
    pub fn web_router<S>() -> Router<S>
    where
        S: Clone + Send + Sync + 'static,
        OAuthServer: FromRef<S>,
        InertiaConfig: FromRef<S>,
    {
        Router::new().route(
            "/oauth/authorize",
            get(authorize_get::<S>).post(authorize_post::<S>),
        )
    }

    /// Machine routes `POST /oauth/token`, `/oauth/revoke`, `/oauth/introspect` as a plain router.
    pub fn token_router<S>() -> Router<S>
    where
        S: Clone + Send + Sync + 'static,
        OAuthServer: FromRef<S>,
    {
        Router::new()
            .route("/oauth/token", post(token_h))
            .route("/oauth/revoke", post(revoke_h))
            .route("/oauth/introspect", post(introspect_h))
    }

    /// [`web_router`](Self::web_router) for `App::web`. Not documented in OpenAPI (plain routes).
    #[cfg(feature = "openapi")]
    pub fn web_routes<S>() -> utoipa_axum::router::OpenApiRouter<S>
    where
        S: Clone + Send + Sync + 'static,
        OAuthServer: FromRef<S>,
        InertiaConfig: FromRef<S>,
    {
        Self::web_router::<S>().into()
    }

    /// [`token_router`](Self::token_router) for `App::public`.
    #[cfg(feature = "openapi")]
    pub fn token_routes<S>() -> utoipa_axum::router::OpenApiRouter<S>
    where
        S: Clone + Send + Sync + 'static,
        OAuthServer: FromRef<S>,
    {
        Self::token_router::<S>().into()
    }
}

#[cfg(all(test, feature = "sqlite"))]
mod tests {
    #[test]
    fn debug_never_prints_a_client_secret() {
        let c = NewClient {
            client_id: "cid".into(),
            client_secret: Some("super-SECRET-value".into()),
        };
        let shown = format!("{c:?}");
        assert!(
            !shown.contains("SECRET-value") && shown.contains("cid"),
            "{shown}"
        );
    }

    use super::*;
    use axum::body::{Body, to_bytes};
    use axum::http::Request;
    use tower::ServiceExt;

    const CB: &str = "https://app.example/cb";
    const VERIFIER: &str = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";

    #[derive(Clone)]
    struct St {
        o: OAuthServer,
        i: InertiaConfig,
    }
    impl FromRef<St> for OAuthServer {
        fn from_ref(s: &St) -> Self {
            s.o.clone()
        }
    }
    impl FromRef<St> for InertiaConfig {
        fn from_ref(s: &St) -> Self {
            s.i.clone()
        }
    }

    async fn login(s: Session, axum::extract::Path(id): axum::extract::Path<i64>) -> &'static str {
        s.insert(SESSION_USER, id).await.unwrap();
        "ok"
    }

    async fn dbs() -> Vec<(&'static str, DatabaseConnection)> {
        let ns = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let path = std::env::temp_dir().join(format!("ryuk-oauth-{ns}.db"));
        let mut v = vec![(
            "sqlite",
            sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", path.display()))
                .await
                .unwrap(),
        )];
        for (name, var) in [
            ("postgres", "TEST_POSTGRES_URL"),
            ("mysql", "TEST_MYSQL_URL"),
        ] {
            if let Ok(url) = std::env::var(var) {
                v.push((name, sea_orm::Database::connect(url).await.unwrap()));
            }
        }
        v
    }

    struct Env {
        o: OAuthServer,
        app: Router,
        db: DatabaseConnection,
    }

    async fn env(db: DatabaseConnection) -> Env {
        let o = OAuthServer::new(db.clone());
        o.ensure_tables().await.unwrap();
        o.ensure_tables().await.unwrap();
        let app = Router::new()
            .route("/login-as/{id}", get(login))
            .merge(OAuthServer::web_router::<St>())
            .merge(OAuthServer::token_router::<St>())
            .layer(crate::session::session_layer())
            .with_state(St {
                o: o.clone(),
                i: crate::inertia::Config::dev(1, "x", false, "t"),
            });
        Env { o, app, db }
    }

    struct Resp {
        status: StatusCode,
        headers: HeaderMap,
        body: String,
    }
    impl Resp {
        fn json(&self) -> serde_json::Value {
            serde_json::from_str(&self.body).unwrap_or_else(|_| panic!("not json: {}", self.body))
        }
        fn err(&self) -> String {
            self.json()["error"].as_str().unwrap_or("").to_string()
        }
        fn loc(&self) -> String {
            self.headers
                .get("location")
                .map(|v| v.to_str().unwrap().to_string())
                .unwrap_or_default()
        }
    }

    async fn send(app: &Router, req: Request<Body>) -> Resp {
        let r = app.clone().oneshot(req).await.unwrap();
        let (p, b) = r.into_parts();
        Resp {
            status: p.status,
            headers: p.headers,
            body: String::from_utf8(to_bytes(b, usize::MAX).await.unwrap().to_vec()).unwrap(),
        }
    }

    async fn post_form(app: &Router, path: &str, body: &str, extra: &[(&str, &str)]) -> Resp {
        let mut r = Request::post(path).header("content-type", "application/x-www-form-urlencoded");
        for (k, v) in extra {
            r = r.header(*k, *v);
        }
        send(app, r.body(Body::from(body.to_string())).unwrap()).await
    }

    async fn session_for(app: &Router, uid: i64) -> String {
        let r = send(
            app,
            Request::get(format!("/login-as/{uid}"))
                .body(Body::empty())
                .unwrap(),
        )
        .await;
        r.headers["set-cookie"]
            .to_str()
            .unwrap()
            .split(';')
            .next()
            .unwrap()
            .to_string()
    }

    fn s256(v: &str) -> String {
        URL_SAFE_NO_PAD.encode(Sha256::digest(v.as_bytes()))
    }

    fn qp(url: &str, key: &str) -> Option<String> {
        let q = url.split_once('?')?.1;
        q.split('&')
            .find_map(|kv| kv.strip_prefix(&format!("{key}=")).map(str::to_string))
    }

    fn basic(id: &str, secret: &str) -> String {
        format!("Basic {}", STANDARD.encode(format!("{id}:{secret}")))
    }

    /// Browser steps: login -> GET authorize (Inertia JSON) -> POST consent. Returns the consent response.
    async fn authorize(e: &Env, query: &str, decision: &str) -> Resp {
        let cookie = session_for(&e.app, 42).await;
        let page = send(
            &e.app,
            Request::get(format!("/oauth/authorize?{query}"))
                .header("cookie", &cookie)
                .header("x-inertia", "true")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
        assert_eq!(page.status, StatusCode::OK, "{}", page.body);
        let rid = page.json()["props"]["request_id"]
            .as_str()
            .unwrap()
            .to_string();
        post_form(
            &e.app,
            "/oauth/authorize",
            &format!("decision={decision}&request_id={rid}"),
            &[("cookie", &cookie)],
        )
        .await
    }

    async fn get_code(e: &Env, cid: &str, scope: &str) -> String {
        let q = format!(
            "response_type=code&client_id={cid}&redirect_uri={}&scope={scope}&state=xyz&code_challenge={}&code_challenge_method=S256",
            pct(CB),
            s256(VERIFIER)
        );
        let r = authorize(e, &q, "allow").await;
        assert_eq!(r.status, StatusCode::SEE_OTHER);
        assert!(
            r.loc().starts_with(&format!("{CB}?code=ryc_")),
            "{}",
            r.loc()
        );
        assert_eq!(qp(&r.loc(), "state").as_deref(), Some("xyz"));
        qp(&r.loc(), "code").unwrap()
    }

    fn code_body(cid: &str, code: &str, verifier: &str) -> String {
        format!(
            "grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}&code_verifier={verifier}",
            pct(CB)
        )
    }

    async fn public_client(e: &Env) -> String {
        e.o.create_client("Test app", &[CB], &["read", "write"], false)
            .await
            .unwrap()
            .client_id
    }

    async fn tokens_for(e: &Env, cid: &str, scope: &str) -> serde_json::Value {
        let code = get_code(e, cid, scope).await;
        let r = post_form(
            &e.app,
            "/oauth/token",
            &code_body(cid, &code, VERIFIER),
            &[],
        )
        .await;
        assert_eq!(r.status, StatusCode::OK, "{}", r.body);
        r.json()
    }

    #[tokio::test]
    async fn auth_code_pkce_roundtrip_hashed_at_rest() {
        for (name, db) in dbs().await {
            let e = env(db).await;
            let cid = public_client(&e).await;
            // not logged in -> login redirect carrying the authorize URL
            let q = format!(
                "response_type=code&client_id={cid}&redirect_uri={}&scope=read&code_challenge={}&code_challenge_method=S256",
                pct(CB),
                s256(VERIFIER)
            );
            let r = send(
                &e.app,
                Request::get(format!("/oauth/authorize?{q}"))
                    .body(Body::empty())
                    .unwrap(),
            )
            .await;
            assert_eq!(r.status, StatusCode::SEE_OTHER, "{name}");
            assert!(
                r.loc()
                    .starts_with("/login?next=%2Foauth%2Fauthorize%3Fresponse_type%3Dcode"),
                "{name}: {}",
                r.loc()
            );

            let code = get_code(&e, &cid, "read%20write").await;
            let t = post_form(
                &e.app,
                "/oauth/token",
                &code_body(&cid, &code, VERIFIER),
                &[],
            )
            .await;
            assert_eq!(t.status, StatusCode::OK, "{name}: {}", t.body);
            assert_eq!(t.headers["cache-control"], "no-store");
            let j = t.json();
            assert_eq!(j["token_type"], "Bearer");
            assert_eq!(j["scope"], "read write");
            assert_eq!(j["expires_in"], 3600);
            let (at, rt) = (
                j["access_token"].as_str().unwrap(),
                j["refresh_token"].as_str().unwrap(),
            );
            assert!(at.starts_with("ryo_") && rt.starts_with("ryr_") && at.len() == 47);

            let p = e.o.verify(at).await.expect(name);
            assert_eq!(
                (p.kind, p.user_id, p.client_id.as_deref()),
                (PrincipalKind::OAuthToken, Some(42), Some(cid.as_str()))
            );
            assert_eq!(p.scopes, ["read", "write"]);
            assert!(e.o.verify("ryo_nope").await.is_none() && e.o.verify(rt).await.is_none());

            // hash at rest
            let rows = format!(
                "{:?}{:?}{:?}",
                tokens::Entity::find().all(&e.db).await.unwrap(),
                codes::Entity::find().all(&e.db).await.unwrap(),
                clients::Entity::find().all(&e.db).await.unwrap()
            );
            assert!(
                !rows.contains(at) && !rows.contains(rt) && !rows.contains(&code),
                "{name}"
            );

            // replay of the code: rejected, and the tokens it issued die
            let again = post_form(
                &e.app,
                "/oauth/token",
                &code_body(&cid, &code, VERIFIER),
                &[],
            )
            .await;
            assert_eq!(
                (again.status, again.err()),
                (StatusCode::BAD_REQUEST, "invalid_grant".into()),
                "{name}"
            );
            assert!(e.o.verify(at).await.is_none(), "{name}: replay must revoke");
            let rr = post_form(
                &e.app,
                "/oauth/token",
                &format!("grant_type=refresh_token&client_id={cid}&refresh_token={rt}"),
                &[],
            )
            .await;
            assert_eq!(rr.err(), "invalid_grant", "{name}");
        }
    }

    #[tokio::test]
    async fn authorize_and_exchange_rejections() {
        for (name, db) in dbs().await {
            let e = env(db).await;
            let cid = public_client(&e).await;
            let ch = s256(VERIFIER);
            let base = |extra: &str| {
                format!(
                    "response_type=code&client_id={cid}&redirect_uri={}&code_challenge={ch}&code_challenge_method=S256{extra}",
                    pct(CB)
                )
            };
            let page = |q: String| {
                let app = e.app.clone();
                async move {
                    let c = session_for(&app, 1).await;
                    send(
                        &app,
                        Request::get(format!("/oauth/authorize?{q}"))
                            .header("cookie", c)
                            .header("x-inertia", "true")
                            .body(Body::empty())
                            .unwrap(),
                    )
                    .await
                }
            };
            // bad redirect_uri / unknown client: error page, never a redirect
            for q in [
                format!(
                    "response_type=code&client_id={cid}&redirect_uri={}",
                    pct("https://evil.example/cb")
                ),
                format!(
                    "response_type=code&client_id={cid}&redirect_uri={}",
                    pct("https://app.example/cb/")
                ),
                format!("response_type=code&client_id={cid}"),
                format!("response_type=code&client_id=nope&redirect_uri={}", pct(CB)),
            ] {
                let r = page(q.clone()).await;
                assert_eq!(r.status, StatusCode::BAD_REQUEST, "{name}: {q}");
                assert!(
                    r.headers.get("location").is_none()
                        && r.headers.get("x-inertia-location").is_none()
                );
                assert_eq!(r.json()["component"], "OAuth/Error");
            }
            // errors after redirect_uri validation go back to the client with state
            for (q, err) in [
                (base("&scope=admin&state=s1"), "invalid_scope"),
                (
                    format!(
                        "response_type=code&client_id={cid}&redirect_uri={}&state=s1",
                        pct(CB)
                    ),
                    "invalid_request", // public client without PKCE
                ),
                (
                    format!(
                        "response_type=code&client_id={cid}&redirect_uri={}&code_challenge={ch}&code_challenge_method=plain&state=s1",
                        pct(CB)
                    ),
                    "invalid_request",
                ),
                (
                    base("&state=s1").replace("response_type=code", "response_type=token"),
                    "unsupported_response_type",
                ),
            ] {
                let r = page(q.clone()).await;
                assert_eq!(r.status, StatusCode::CONFLICT, "{name}: {q}"); // Inertia XHR: 409 + location
                let l = r.headers["x-inertia-location"]
                    .to_str()
                    .unwrap()
                    .to_string();
                assert!(
                    l.starts_with(CB)
                        && qp(&l, "error").as_deref() == Some(err)
                        && qp(&l, "state").as_deref() == Some("s1"),
                    "{name}: {l}"
                );
            }
            // plain browser: 303
            let c = session_for(&e.app, 1).await;
            let r = send(
                &e.app,
                Request::get(format!("/oauth/authorize?{}", base("&scope=admin")))
                    .header("cookie", c)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await;
            assert_eq!(r.status, StatusCode::SEE_OTHER);
            assert_eq!(qp(&r.loc(), "error").as_deref(), Some("invalid_scope"));

            // deny
            let r = authorize(&e, &base("&state=s2"), "deny").await;
            assert_eq!(r.status, StatusCode::SEE_OTHER);
            assert_eq!(qp(&r.loc(), "error").as_deref(), Some("access_denied"));
            assert!(qp(&r.loc(), "code").is_none());

            // consent POST without a matching pending request
            let c = session_for(&e.app, 1).await;
            let r = post_form(
                &e.app,
                "/oauth/authorize",
                "decision=allow&request_id=guess",
                &[("cookie", &c)],
            )
            .await;
            assert_eq!(r.status, StatusCode::BAD_REQUEST, "{name}");
            assert!(r.loc().is_empty());
            let r = post_form(
                &e.app,
                "/oauth/authorize",
                "decision=allow&request_id=guess",
                &[],
            )
            .await;
            assert_eq!(
                (r.status, r.loc().as_str()),
                (StatusCode::SEE_OTHER, "/login")
            );

            // token side: wrong verifier / redirect_uri do not burn the code; wrong client rejected
            let code = get_code(&e, &cid, "read").await;
            for body in [
                code_body(&cid, &code, &"A".repeat(43)),
                code_body(&cid, &code, "short"),
                format!(
                    "grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}",
                    pct(CB)
                ),
                format!(
                    "grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}&code_verifier={VERIFIER}",
                    pct("https://app.example/other")
                ),
            ] {
                let r = post_form(&e.app, "/oauth/token", &body, &[]).await;
                assert_eq!(
                    (r.status, r.err()),
                    (StatusCode::BAD_REQUEST, "invalid_grant".into()),
                    "{name}: {body}"
                );
            }
            let other = public_client(&e).await;
            let r = post_form(
                &e.app,
                "/oauth/token",
                &code_body(&other, &code, VERIFIER),
                &[],
            )
            .await;
            assert_eq!(r.err(), "invalid_grant", "{name}: other client");
            let r = post_form(
                &e.app,
                "/oauth/token",
                &code_body(&cid, &code, VERIFIER),
                &[],
            )
            .await;
            assert_eq!(
                r.status,
                StatusCode::OK,
                "{name}: still redeemable by the right client: {}",
                r.body
            );

            // expired code
            let code = get_code(&e, &cid, "read").await;
            codes::Entity::update_many()
                .col_expr(codes::Column::ExpiresAt, Expr::value(now() - 1))
                .filter(codes::Column::CodeHash.eq(hash(&code)))
                .exec(&e.db)
                .await
                .unwrap();
            let r = post_form(
                &e.app,
                "/oauth/token",
                &code_body(&cid, &code, VERIFIER),
                &[],
            )
            .await;
            assert_eq!(r.err(), "invalid_grant", "{name}: expired");

            // protocol errors
            let r = post_form(
                &e.app,
                "/oauth/token",
                &format!("grant_type=password&client_id={cid}"),
                &[],
            )
            .await;
            assert_eq!(
                (r.status, r.err()),
                (StatusCode::BAD_REQUEST, "unsupported_grant_type".into())
            );
            let r = post_form(&e.app, "/oauth/token", &format!("client_id={cid}"), &[]).await;
            assert_eq!(r.err(), "invalid_request");
            let r = post_form(&e.app, "/oauth/token", "grant_type=authorization_code", &[]).await;
            assert_eq!(r.err(), "invalid_request");
            let r = post_form(
                &e.app,
                "/oauth/token",
                "grant_type=client_credentials&client_id=nope&client_secret=x",
                &[],
            )
            .await;
            assert_eq!(
                (r.status, r.err()),
                (StatusCode::UNAUTHORIZED, "invalid_client".into())
            );
            assert_eq!(r.headers["cache-control"], "no-store");
            let r = send(
                &e.app,
                Request::post("/oauth/token")
                    .header("content-type", "application/json")
                    .body(Body::from("{}"))
                    .unwrap(),
            )
            .await;
            assert_eq!(r.err(), "invalid_request");
        }
    }

    #[tokio::test]
    async fn refresh_rotation_and_reuse_detection() {
        for (name, db) in dbs().await {
            let e = env(db).await;
            let cid = public_client(&e).await;
            let t = tokens_for(&e, &cid, "read%20write").await;
            let (a1, r1) = (
                t["access_token"].as_str().unwrap().to_string(),
                t["refresh_token"].as_str().unwrap().to_string(),
            );
            let refresh = |r: &str, extra: &str| {
                format!("grant_type=refresh_token&client_id={cid}&refresh_token={r}{extra}")
            };

            // scope may only narrow
            let r = post_form(&e.app, "/oauth/token", &refresh(&r1, "&scope=admin"), &[]).await;
            assert_eq!(r.err(), "invalid_scope", "{name}");
            let t2 = post_form(&e.app, "/oauth/token", &refresh(&r1, "&scope=read"), &[]).await;
            assert_eq!(t2.status, StatusCode::OK, "{name}: {}", t2.body);
            let t2 = t2.json();
            assert_eq!(t2["scope"], "read");
            let (a2, r2) = (
                t2["access_token"].as_str().unwrap().to_string(),
                t2["refresh_token"].as_str().unwrap().to_string(),
            );
            assert!(a2 != a1 && r2 != r1);
            assert!(e.o.verify(&a2).await.is_some(), "{name}");
            // another client cannot use it
            let other = public_client(&e).await;
            let r = post_form(
                &e.app,
                "/oauth/token",
                &format!("grant_type=refresh_token&client_id={other}&refresh_token={r2}"),
                &[],
            )
            .await;
            assert_eq!(r.err(), "invalid_grant", "{name}");
            // reuse of the rotated token kills the whole family
            let r = post_form(&e.app, "/oauth/token", &refresh(&r1, ""), &[]).await;
            assert_eq!(r.err(), "invalid_grant", "{name}");
            assert!(
                e.o.verify(&a2).await.is_none() && e.o.verify(&a1).await.is_none(),
                "{name}: family revoked"
            );
            let r = post_form(&e.app, "/oauth/token", &refresh(&r2, ""), &[]).await;
            assert_eq!(r.err(), "invalid_grant", "{name}: newest refresh dead too");

            // refresh expiry
            let t = tokens_for(&e, &cid, "read").await;
            tokens::Entity::update_many()
                .col_expr(tokens::Column::RefreshExpiresAt, Expr::value(now() - 1))
                .filter(tokens::Column::AccessHash.eq(hash(t["access_token"].as_str().unwrap())))
                .exec(&e.db)
                .await
                .unwrap();
            let r = post_form(
                &e.app,
                "/oauth/token",
                &refresh(t["refresh_token"].as_str().unwrap(), ""),
                &[],
            )
            .await;
            assert_eq!(r.err(), "invalid_grant", "{name}: expired");
        }
    }

    #[tokio::test]
    async fn client_credentials_revoke_introspect_expiry() {
        for (name, db) in dbs().await {
            let e = env(db).await;
            let c =
                e.o.create_client("Svc", &[], &["read", "write"], true)
                    .await
                    .unwrap();
            let (id, secret) = (c.client_id.clone(), c.client_secret.clone().unwrap());
            assert!(secret.starts_with("rys_"));
            let (ok, wrong) = (basic(&id, &secret), basic(&id, "wrong"));

            let r = post_form(
                &e.app,
                "/oauth/token",
                "grant_type=client_credentials&scope=read",
                &[("authorization", &ok)],
            )
            .await;
            assert_eq!(r.status, StatusCode::OK, "{name}: {}", r.body);
            let j = r.json();
            assert!(j.get("refresh_token").is_none() && j["scope"] == "read");
            let at = j["access_token"].as_str().unwrap().to_string();
            let p = e.o.verify(&at).await.expect(name);
            assert_eq!(
                (p.kind, p.user_id, p.id),
                (PrincipalKind::OAuthClient, None, id.clone())
            );

            // body credentials work too; wrong secret / no secret / bad Basic fail; both methods rejected
            let r = post_form(
                &e.app,
                "/oauth/token",
                &format!("grant_type=client_credentials&client_id={id}&client_secret={secret}"),
                &[],
            )
            .await;
            assert_eq!(r.status, StatusCode::OK, "{name}");
            for (body, h) in [
                (
                    format!("grant_type=client_credentials&client_id={id}&client_secret=wrong"),
                    vec![],
                ),
                (
                    format!("grant_type=client_credentials&client_id={id}"),
                    vec![],
                ),
                (
                    "grant_type=client_credentials".to_string(),
                    vec![("authorization", wrong.as_str())],
                ),
            ] {
                let r = post_form(&e.app, "/oauth/token", &body, &h).await;
                assert_eq!(
                    (r.status, r.err()),
                    (StatusCode::UNAUTHORIZED, "invalid_client".into()),
                    "{name}: {body}"
                );
            }
            let r = post_form(
                &e.app,
                "/oauth/token",
                &format!("grant_type=client_credentials&client_secret={secret}"),
                &[("authorization", &ok)],
            )
            .await;
            assert_eq!(r.err(), "invalid_request", "{name}");
            let r = post_form(
                &e.app,
                "/oauth/token",
                "grant_type=client_credentials&scope=admin",
                &[("authorization", &ok)],
            )
            .await;
            assert_eq!(r.err(), "invalid_scope", "{name}");
            // public clients: unauthorized_client
            let pubc = public_client(&e).await;
            let r = post_form(
                &e.app,
                "/oauth/token",
                &format!("grant_type=client_credentials&client_id={pubc}"),
                &[],
            )
            .await;
            assert_eq!(r.err(), "unauthorized_client", "{name}");

            // introspect
            let r = post_form(
                &e.app,
                "/oauth/introspect",
                &format!("token={at}"),
                &[("authorization", &ok)],
            )
            .await;
            let j = r.json();
            assert_eq!(j["active"], true, "{name}");
            assert_eq!(
                (
                    j["client_id"].as_str(),
                    j["scope"].as_str(),
                    j["token_type"].as_str()
                ),
                (Some(id.as_str()), Some("read"), Some("Bearer"))
            );
            assert!(j["exp"].as_i64().unwrap() > now() && j.get("sub").is_none());
            assert_eq!(r.headers["cache-control"], "no-store");
            let r = post_form(
                &e.app,
                "/oauth/introspect",
                &format!("token={at}"),
                &[("authorization", &wrong)],
            )
            .await;
            assert_eq!(r.status, StatusCode::UNAUTHORIZED);
            let r = post_form(
                &e.app,
                "/oauth/introspect",
                &format!("token={at}&client_id={pubc}"),
                &[],
            )
            .await;
            assert_eq!(
                r.status,
                StatusCode::UNAUTHORIZED,
                "{name}: public clients cannot introspect"
            );
            let other =
                e.o.create_client("Other", &[], &["read"], true)
                    .await
                    .unwrap();
            let ob = basic(&other.client_id, &other.client_secret.unwrap());
            let r = post_form(
                &e.app,
                "/oauth/introspect",
                &format!("token={at}"),
                &[("authorization", &ob)],
            )
            .await;
            assert_eq!(
                r.json(),
                json!({"active": false}),
                "{name}: other client's token"
            );
            let r = post_form(
                &e.app,
                "/oauth/introspect",
                "token=garbage",
                &[("authorization", &ok)],
            )
            .await;
            assert_eq!(r.json(), json!({"active": false}));

            // revoke: a foreign client is a silent no-op, the owner kills it, unknown token is still 200
            let r = post_form(
                &e.app,
                "/oauth/revoke",
                &format!("token={at}"),
                &[("authorization", &ob)],
            )
            .await;
            assert_eq!(r.status, StatusCode::OK);
            assert!(
                e.o.verify(&at).await.is_some(),
                "{name}: foreign revoke ignored"
            );
            let r = post_form(
                &e.app,
                "/oauth/revoke",
                &format!("token={at}"),
                &[("authorization", &ok)],
            )
            .await;
            assert_eq!((r.status, r.body.as_str()), (StatusCode::OK, ""), "{name}");
            assert_eq!(r.headers["cache-control"], "no-store");
            assert!(e.o.verify(&at).await.is_none(), "{name}");
            let r = post_form(
                &e.app,
                "/oauth/introspect",
                &format!("token={at}"),
                &[("authorization", &ok)],
            )
            .await;
            assert_eq!(r.json(), json!({"active": false}), "{name}");
            let r = post_form(
                &e.app,
                "/oauth/revoke",
                "token=ryo_unknown",
                &[("authorization", &ok)],
            )
            .await;
            assert_eq!(r.status, StatusCode::OK);

            // access expiry
            let t = post_form(
                &e.app,
                "/oauth/token",
                "grant_type=client_credentials",
                &[("authorization", &ok)],
            )
            .await
            .json();
            let at = t["access_token"].as_str().unwrap();
            tokens::Entity::update_many()
                .col_expr(tokens::Column::AccessExpiresAt, Expr::value(now() - 1))
                .filter(tokens::Column::AccessHash.eq(hash(at)))
                .exec(&e.db)
                .await
                .unwrap();
            assert!(e.o.verify(at).await.is_none(), "{name}: expired");
            let r = post_form(
                &e.app,
                "/oauth/introspect",
                &format!("token={at}"),
                &[("authorization", &ok)],
            )
            .await;
            assert_eq!(r.json(), json!({"active": false}));

            // revoke_client kills tokens and blocks new ones
            let t = post_form(
                &e.app,
                "/oauth/token",
                "grant_type=client_credentials",
                &[("authorization", &ok)],
            )
            .await
            .json();
            let at = t["access_token"].as_str().unwrap();
            assert!(
                e.o.revoke_client(&id).await.unwrap() && !e.o.revoke_client("nope").await.unwrap()
            );
            assert!(e.o.verify(at).await.is_none(), "{name}");
            let r = post_form(
                &e.app,
                "/oauth/token",
                "grant_type=client_credentials",
                &[("authorization", &ok)],
            )
            .await;
            assert_eq!(r.status, StatusCode::UNAUTHORIZED, "{name}");
        }
    }

    async fn join(hs: Vec<tokio::task::JoinHandle<Resp>>) -> Vec<Resp> {
        let mut v = vec![];
        for h in hs {
            v.push(h.await.unwrap());
        }
        v
    }

    #[tokio::test]
    async fn single_winner_under_concurrency() {
        for (name, db) in dbs().await {
            let e = env(db).await;
            let cid = public_client(&e).await;
            for round in 0..3 {
                let code = get_code(&e, &cid, "read").await;
                let rs = join(
                    (0..12)
                        .map(|_| {
                            let (app, b) = (e.app.clone(), code_body(&cid, &code, VERIFIER));
                            tokio::spawn(
                                async move { post_form(&app, "/oauth/token", &b, &[]).await },
                            )
                        })
                        .collect(),
                )
                .await;
                let n = rs.iter().filter(|r| r.status == StatusCode::OK).count();
                assert!(n <= 1, "{name} code round {round}: {n} winners");
                // losers also revoke the winner's tokens (replay), so 0 or 1 live tokens; never 2
                let live = tokens::Entity::find()
                    .filter(tokens::Column::ClientId.eq(cid.as_str()))
                    .filter(tokens::Column::RevokedAt.is_null())
                    .all(&e.db)
                    .await
                    .unwrap();
                assert!(live.len() <= 1, "{name} round {round}: {} live", live.len());
            }
            // refresh: of N racing rotations at most one succeeds
            let t = tokens_for(&e, &cid, "read").await;
            let rt = t["refresh_token"].as_str().unwrap().to_string();
            let rs = join(
                (0..12)
                    .map(|_| {
                        let (app, b) = (
                            e.app.clone(),
                            format!("grant_type=refresh_token&client_id={cid}&refresh_token={rt}"),
                        );
                        tokio::spawn(async move { post_form(&app, "/oauth/token", &b, &[]).await })
                    })
                    .collect(),
            )
            .await;
            let n = rs.iter().filter(|r| r.status == StatusCode::OK).count();
            assert!(n <= 1, "{name} refresh: {n} winners");
            let fam = tokens::Entity::find()
                .filter(tokens::Column::AccessHash.eq(hash(t["access_token"].as_str().unwrap())))
                .one(&e.db)
                .await
                .unwrap()
                .unwrap()
                .family_id;
            let live = tokens::Entity::find()
                .filter(tokens::Column::FamilyId.eq(fam))
                .filter(tokens::Column::RevokedAt.is_null())
                .all(&e.db)
                .await
                .unwrap();
            assert!(
                live.is_empty(),
                "{name}: losers detected reuse, family must be dead ({n} won)"
            );
        }
    }

    #[tokio::test]
    async fn exactly_one_winner_without_replay_signal() {
        // Same race at the claim level (no revocation side effects): exactly one claimer.
        for (name, db) in dbs().await {
            let e = env(db).await;
            let cid = public_client(&e).await;
            let code = get_code(&e, &cid, "read").await;
            let id = codes::Entity::find()
                .filter(codes::Column::CodeHash.eq(hash(&code)))
                .one(&e.db)
                .await
                .unwrap()
                .unwrap()
                .id;
            let hs: Vec<_> = (0..16)
                .map(|_| {
                    let o = e.o.clone();
                    tokio::spawn(async move { o.claim_code(id).await.unwrap() })
                })
                .collect();
            let mut wins = 0;
            for h in hs {
                wins += h.await.unwrap() as u32;
            }
            assert_eq!(wins, 1, "{name}");
        }
    }

    #[tokio::test]
    async fn client_validation_and_long_uris() {
        for (name, db) in dbs().await {
            let e = env(db).await;
            for uri in [
                "/relative",
                "https://a.example/cb#frag",
                "javascript",
                "https://a b",
                "",
            ] {
                assert!(
                    e.o.create_client("x", &[uri], &[], false).await.is_err(),
                    "{name}: {uri}"
                );
            }
            assert!(e.o.create_client("", &[], &[], false).await.is_err());
            assert!(
                e.o.create_client("x", &[], &["bad scope"], false)
                    .await
                    .is_err()
            );
            let long = format!("https://a.example/{}", "x".repeat(600));
            let c =
                e.o.create_client("long", &[long.as_str(), "myapp:/cb"], &[], false)
                    .await
                    .unwrap();
            let row = e.o.client(&c.client_id).await.unwrap().unwrap();
            assert_eq!(
                row.uris(),
                [long, "myapp:/cb".to_string()],
                "{name}: Text column"
            );
            assert!(c.client_secret.is_none() && row.secret_hash.is_none());
        }
    }

    const APP_CB: &str = "myapp://callback";
    const HTTPS_CB: &str = "https://app.example.com/cb";

    async fn fp_client(e: &Env, uri: &str, first_party: bool) -> String {
        let mut spec = ClientSpec::new("Mobile").redirect(uri).scope("read");
        if first_party {
            spec = spec.first_party();
        }
        e.o.create_client_spec(spec).await.unwrap().client_id
    }

    fn authz_query(cid: &str, uri: &str, extra: &str) -> String {
        format!(
            "response_type=code&client_id={cid}&redirect_uri={}&scope=read&state=st&code_challenge={}&code_challenge_method=S256{extra}",
            pct(uri),
            s256(VERIFIER)
        )
    }

    async fn authz_get(e: &Env, q: &str, cookie: Option<&str>) -> Resp {
        let mut r = Request::get(format!("/oauth/authorize?{q}"));
        if let Some(c) = cookie {
            r = r.header("cookie", c);
        }
        send(&e.app, r.body(Body::empty()).unwrap()).await
    }

    #[tokio::test]
    async fn consent_accepts_json_bodies_like_the_inertia_client() {
        for (name, db) in dbs().await {
            let e = env(db).await;
            let cid = fp_client(&e, APP_CB, true).await;
            let cookie = session_for(&e.app, 7).await;
            // `prompt=consent` shows the consent page even for a first-party client.
            let q = authz_query(&cid, APP_CB, "&prompt=consent");
            let page = send(
                &e.app,
                Request::get(format!("/oauth/authorize?{q}"))
                    .header("cookie", &cookie)
                    .header("x-inertia", "true")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await;
            assert_eq!(page.status, StatusCode::OK, "{name}: {}", page.body);
            let rid = page.json()["props"]["request_id"]
                .as_str()
                .unwrap()
                .to_string();
            // `router.post` of the Svelte page sends JSON: this used to answer 415.
            let body = serde_json::json!({ "decision": "allow", "request_id": rid }).to_string();
            let r = send(
                &e.app,
                Request::post("/oauth/authorize")
                    .header("cookie", &cookie)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await;
            assert_eq!(r.status, StatusCode::SEE_OTHER, "{name}: {}", r.body);
            assert!(
                r.loc().starts_with("myapp://callback?code=ryc_"),
                "{name}: {}",
                r.loc()
            );
            // Garbage JSON is a client error, not a crash.
            let r = send(
                &e.app,
                Request::post("/oauth/authorize")
                    .header("cookie", &cookie)
                    .header("content-type", "application/json")
                    .body(Body::from("{not json"))
                    .unwrap(),
            )
            .await;
            assert!(r.status.is_client_error(), "{name}: {}", r.status);
        }
    }

    #[tokio::test]
    async fn first_party_skips_consent_over_https_roundtrip() {
        for (name, db) in dbs().await {
            let e = env(db).await;
            let cid = fp_client(&e, HTTPS_CB, true).await;
            let row = e.o.client(&cid).await.unwrap().unwrap();
            assert!(row.first_party && row.uris() == [HTTPS_CB], "{name}");
            let cookie = session_for(&e.app, 7).await;
            let q = authz_query(&cid, HTTPS_CB, "");

            // logged out: still the login redirect, no code
            let r = authz_get(&e, &q, None).await;
            assert!(r.loc().starts_with("/login?next="), "{name}: {}", r.loc());

            let r = authz_get(&e, &q, Some(&cookie)).await;
            assert_eq!(r.status, StatusCode::SEE_OTHER, "{name}: {}", r.body);
            let loc = r.loc();
            assert!(
                loc.starts_with("https://app.example.com/cb?code=ryc_"),
                "{name}: {loc}"
            );
            assert!(loc.ends_with("&state=st"), "{name}: {loc}");
            let code = qp(&loc, "code").unwrap();
            let body = format!(
                "grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}&code_verifier={VERIFIER}",
                pct(HTTPS_CB)
            );
            let t = post_form(&e.app, "/oauth/token", &body, &[]).await;
            assert_eq!(t.status, StatusCode::OK, "{name}: {}", t.body);
            let p = e.o.verify(t.json()["access_token"].as_str().unwrap()).await;
            assert_eq!(p.and_then(|p| p.user_id), Some(7), "{name}");
            // single use
            let again = post_form(&e.app, "/oauth/token", &body, &[]).await;
            assert_eq!(again.err(), "invalid_grant", "{name}");

            // prompt=consent forces the consent page (and no code is issued for it)
            let n = codes::Entity::find().all(&e.db).await.unwrap().len();
            let hdr = |q: String| {
                Request::get(format!("/oauth/authorize?{q}"))
                    .header("cookie", &cookie)
                    .header("x-inertia", "true")
                    .body(Body::empty())
                    .unwrap()
            };
            let r = send(
                &e.app,
                hdr(authz_query(&cid, HTTPS_CB, "&prompt=login%20consent")),
            )
            .await;
            assert_eq!(r.status, StatusCode::OK, "{name}");
            assert_eq!(r.json()["component"], "OAuth/Authorize");
            assert_eq!(codes::Entity::find().all(&e.db).await.unwrap().len(), n);

            // Inertia XHR gets the 409 external redirect for the skip
            let r = send(&e.app, hdr(authz_query(&cid, HTTPS_CB, ""))).await;
            assert_eq!(r.status, StatusCode::CONFLICT, "{name}");
            assert!(
                r.headers["x-inertia-location"]
                    .to_str()
                    .unwrap()
                    .starts_with(HTTPS_CB)
            );

            // third-party client with the same shape still shows consent
            let tp = fp_client(&e, HTTPS_CB, false).await;
            assert!(!e.o.client(&tp).await.unwrap().unwrap().first_party);
            let r = send(&e.app, hdr(authz_query(&tp, HTTPS_CB, ""))).await;
            assert_eq!(r.json()["component"], "OAuth/Authorize", "{name}");
        }
    }

    #[tokio::test]
    async fn first_party_custom_scheme_shows_consent_then_works() {
        for (name, db) in dbs().await {
            let e = env(db).await;
            let cid = fp_client(&e, APP_CB, true).await;
            let cookie = session_for(&e.app, 7).await;
            let n = codes::Entity::find().all(&e.db).await.unwrap().len();
            let page = send(
                &e.app,
                Request::get(format!(
                    "/oauth/authorize?{}",
                    authz_query(&cid, APP_CB, "")
                ))
                .header("cookie", &cookie)
                .header("x-inertia", "true")
                .body(Body::empty())
                .unwrap(),
            )
            .await;
            assert_eq!(page.status, StatusCode::OK, "{name}: {}", page.body);
            assert_eq!(page.json()["component"], "OAuth/Authorize", "{name}");
            assert_eq!(codes::Entity::find().all(&e.db).await.unwrap().len(), n);
            let rid = page.json()["props"]["request_id"]
                .as_str()
                .unwrap()
                .to_string();
            let r = post_form(
                &e.app,
                "/oauth/authorize",
                &format!("decision=allow&request_id={rid}"),
                &[("cookie", &cookie)],
            )
            .await;
            let code = qp(&r.loc(), "code").expect(name);
            let body = format!(
                "grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}&code_verifier={VERIFIER}",
                pct(APP_CB)
            );
            let t = post_form(&e.app, "/oauth/token", &body, &[]).await;
            assert_eq!(t.status, StatusCode::OK, "{name}: {}", t.body);
        }
    }

    #[tokio::test]
    async fn refresh_rechecks_the_client() {
        for (name, db) in dbs().await {
            let e = env(db).await;
            let set = |cid: String, v: &'static str| {
                clients::Entity::update_many()
                    .col_expr(clients::Column::AllowedScopes, Expr::value(v))
                    .filter(clients::Column::ClientId.eq(cid))
                    .exec(&e.db)
            };
            let cid = public_client(&e).await;
            let t = tokens_for(&e, &cid, "read%20write").await;
            // shrink to `read`: the refreshed token keeps the intersection
            set(cid.clone(), "read").await.unwrap();
            let r = refresh(&e, &cid, t["refresh_token"].as_str().unwrap()).await;
            assert_eq!(r.status, StatusCode::OK, "{name}: {}", r.body);
            assert_eq!(r.json()["scope"], "read", "{name}");
            // shrink to nothing in common: invalid_grant
            set(cid.clone(), "other").await.unwrap();
            let r = refresh(&e, &cid, r.json()["refresh_token"].as_str().unwrap()).await;
            assert_eq!(r.err(), "invalid_grant", "{name}");
            // revoked client (flag only, tokens untouched) cannot refresh
            let cid = public_client(&e).await;
            let t = tokens_for(&e, &cid, "read").await;
            clients::Entity::update_many()
                .col_expr(clients::Column::RevokedAt, Expr::value(now()))
                .filter(clients::Column::ClientId.eq(cid.as_str()))
                .exec(&e.db)
                .await
                .unwrap();
            let r = refresh(&e, &cid, t["refresh_token"].as_str().unwrap()).await;
            assert!(r.status.is_client_error(), "{name}: {}", r.body);
        }
    }

    #[tokio::test]
    async fn first_party_keeps_every_validation() {
        for (name, db) in dbs().await {
            let e = env(db).await;
            let cid = fp_client(&e, HTTPS_CB, true).await;
            let cookie = session_for(&e.app, 7).await;
            let n = codes::Entity::find().all(&e.db).await.unwrap().len();
            // redirect mismatch / unknown client: error page, no Location, no code
            for q in [
                authz_query(&cid, "https://app.example.com/evil", ""),
                authz_query(&cid, "https://app.example.com/cb/", ""),
                authz_query("nope", HTTPS_CB, ""),
            ] {
                let r = authz_get(&e, &q, Some(&cookie)).await;
                assert!(r.headers.get("location").is_none(), "{name}: {q}");
                assert_eq!(r.status, StatusCode::BAD_REQUEST, "{name}: {q}");
            }
            // PKCE missing / plain / bad scope: error redirect to the registered URI, no code
            let ok = authz_query(&cid, HTTPS_CB, "");
            for (q, err) in [
                (
                    format!(
                        "response_type=code&client_id={cid}&redirect_uri={}&scope=read&state=st",
                        pct(HTTPS_CB)
                    ),
                    "invalid_request",
                ),
                (ok.replace("S256", "plain"), "invalid_request"),
                (ok.replace("scope=read", "scope=admin"), "invalid_scope"),
                (
                    ok.replace("response_type=code", "response_type=token"),
                    "unsupported_response_type",
                ),
            ] {
                let r = authz_get(&e, &q, Some(&cookie)).await;
                assert_eq!(r.status, StatusCode::SEE_OTHER, "{name}: {q}");
                assert!(
                    r.loc().starts_with("https://app.example.com/cb?error=")
                        && qp(&r.loc(), "error").as_deref() == Some(err)
                        && qp(&r.loc(), "code").is_none(),
                    "{name}: {}",
                    r.loc()
                );
            }
            assert_eq!(
                codes::Entity::find().all(&e.db).await.unwrap().len(),
                n,
                "{name}"
            );
            // a wrong verifier does not redeem a skip-consent code
            let r = authz_get(&e, &ok, Some(&cookie)).await;
            let code = qp(&r.loc(), "code").unwrap();
            let body = format!(
                "grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}&code_verifier={}",
                pct(HTTPS_CB),
                "A".repeat(43)
            );
            assert_eq!(
                post_form(&e.app, "/oauth/token", &body, &[]).await.err(),
                "invalid_grant",
                "{name}"
            );
        }
    }

    #[tokio::test]
    async fn client_spec_validation() {
        for (name, db) in dbs().await {
            let e = env(db).await;
            let s = ClientSpec::new("x").redirect(APP_CB);
            assert!(
                e.o.create_client_spec(s.clone().first_party())
                    .await
                    .is_ok(),
                "{name}"
            );
            for bad in [
                ClientSpec::new("x").first_party(), // first-party without redirect
                ClientSpec::new(""),
                s.clone().redirect("/relative"),
                s.clone().redirect("myapp://cb#f"),
                s.clone().scope("bad scope"),
            ] {
                assert!(e.o.create_client_spec(bad).await.is_err(), "{name}");
            }
            let c =
                e.o.create_client_spec(s.confidential().first_party())
                    .await
                    .unwrap();
            assert!(c.client_secret.is_some(), "{name}");
            // the wrapper never sets the flag
            let c = e.o.create_client("w", &[APP_CB], &[], false).await.unwrap();
            assert!(!e.o.client(&c.client_id).await.unwrap().unwrap().first_party);
        }
    }

    #[tokio::test]
    async fn old_schema_is_upgraded() {
        use sea_orm::sea_query::Query;
        for (name, db) in dbs().await {
            // oauth_clients as the previous version created it (no first_party column).
            let drop = Table::drop()
                .table(Alias::new("oauth_clients"))
                .if_exists()
                .to_owned();
            db.execute(&drop).await.unwrap();
            let col = |n: &str| ColumnDef::new(Alias::new(n));
            let old = Table::create()
                .table(Alias::new("oauth_clients"))
                .col(
                    col("id")
                        .big_integer()
                        .not_null()
                        .auto_increment()
                        .primary_key(),
                )
                .col(col("client_id").string().not_null().unique_key())
                .col(col("secret_hash").string().null())
                .col(col("name").string().not_null())
                .col(col("redirect_uris").text().not_null())
                .col(col("allowed_scopes").text().not_null())
                .col(col("created_at").big_integer().not_null())
                .col(col("revoked_at").big_integer().null())
                .to_owned();
            db.execute(&old).await.unwrap();
            let ins = Query::insert()
                .into_table(Alias::new("oauth_clients"))
                .columns(
                    [
                        "client_id",
                        "name",
                        "redirect_uris",
                        "allowed_scopes",
                        "created_at",
                    ]
                    .map(Alias::new),
                )
                .values_panic([
                    "legacy".into(),
                    "Old".into(),
                    "[]".into(),
                    "read".into(),
                    1i64.into(),
                ])
                .to_owned();
            db.execute(&ins).await.unwrap();
            let e = env(db).await; // runs ensure_tables twice
            let c = e.o.client("legacy").await.unwrap().expect(name);
            assert!(!c.first_party && c.name == "Old", "{name}");
            let id = fp_client(&e, APP_CB, true).await;
            assert!(
                e.o.client(&id).await.unwrap().unwrap().first_party,
                "{name}"
            );
        }
    }

    fn uniq() -> i64 {
        chrono::Utc::now().timestamp_nanos_opt().unwrap()
    }

    async fn minted(e: &Env, cid: &str, uid: i64) -> (tokens::Model, String, String) {
        let (row, at, rt) =
            e.o.mint(cid, Some(uid), "read", None, None, true)
                .await
                .map_err(|_| "mint")
                .unwrap();
        (row, at, rt.unwrap())
    }

    async fn refresh(e: &Env, cid: &str, rt: &str) -> Resp {
        refresh_via(&e.app, cid, rt).await
    }

    async fn refresh_via(app: &Router, cid: &str, rt: &str) -> Resp {
        post_form(
            app,
            "/oauth/token",
            &format!("grant_type=refresh_token&client_id={cid}&refresh_token={rt}"),
            &[],
        )
        .await
    }

    async fn set_tok(db: &DatabaseConnection, id: i64, col: tokens::Column, v: Option<i64>) {
        tokens::Entity::update_many()
            .col_expr(col, Expr::value(v))
            .filter(tokens::Column::Id.eq(id))
            .exec(db)
            .await
            .unwrap();
    }

    async fn gone(db: &DatabaseConnection, id: i64) -> bool {
        tokens::Entity::find_by_id(id)
            .one(db)
            .await
            .unwrap()
            .is_none()
    }

    #[tokio::test]
    async fn grants_listing_revocation_and_last_used() {
        for (name, db) in dbs().await {
            let e = env(db.clone()).await;
            let cid = public_client(&e).await;
            let (uid, other) = (uniq(), uniq() + 1);
            let (g1, at1, _rt1) = minted(&e, &cid, uid).await;
            let (g2, at2, rt2) = minted(&e, &cid, uid).await;
            let (_g3, at3, _) = minted(&e, &cid, other).await;

            // last_used_at: set on first verify, then at most once per 60 s
            assert!(g1.last_used_at.is_none());
            e.o.verify(&at1).await.expect(name);
            let used = |id: i64| {
                let db = db.clone();
                async move {
                    tokens::Entity::find_by_id(id)
                        .one(&db)
                        .await
                        .unwrap()
                        .unwrap()
                        .last_used_at
                }
            };
            let first = used(g1.id).await.expect("set on first verify");
            set_tok(&db, g1.id, tokens::Column::LastUsedAt, Some(first - 10)).await;
            e.o.verify(&at1).await.unwrap();
            assert_eq!(used(g1.id).await, Some(first - 10), "{name}: within 60s");
            set_tok(&db, g1.id, tokens::Column::LastUsedAt, Some(first - 100)).await;
            e.o.verify(&at1).await.unwrap();
            assert!(used(g1.id).await.unwrap() >= first, "{name}: refreshed");

            // one row per active family
            let l = e.o.list_grants(uid).await.unwrap();
            assert_eq!(l.len(), 2, "{name}");
            let a = l.iter().find(|g| g.id == g1.family_id).unwrap();
            assert_eq!(
                (a.client_id.as_str(), a.client_name.as_str()),
                (cid.as_str(), "Test app")
            );
            assert_eq!(a.scopes, ["read"]);
            assert!(a.last_used_at.is_some() && a.expires_at > now() && a.created_at <= now());
            assert!(
                l.iter()
                    .find(|g| g.id == g2.family_id)
                    .unwrap()
                    .last_used_at
                    .is_none()
            );
            assert!(!format!("{l:?}").contains(&at1), "{name}: no secrets");
            assert_eq!(e.o.list_grants(other).await.unwrap().len(), 1, "{name}");

            // rotation keeps one grant per family
            let r = refresh(&e, &cid, &rt2).await;
            assert_eq!(r.status, StatusCode::OK, "{name} {}", r.body);
            let (at2b, rt2b) = (
                r.json()["access_token"].as_str().unwrap().to_string(),
                r.json()["refresh_token"].as_str().unwrap().to_string(),
            );
            assert_eq!(e.o.list_grants(uid).await.unwrap().len(), 2, "{name}");

            // owner-checked single revoke
            assert!(
                !e.o.revoke_grant(other, &g1.family_id).await.unwrap(),
                "{name}"
            );
            assert!(e.o.verify(&at1).await.is_some());
            assert!(
                e.o.revoke_grant(uid, &g1.family_id).await.unwrap(),
                "{name}"
            );
            assert!(
                !e.o.revoke_grant(uid, &g1.family_id).await.unwrap(),
                "{name}"
            );
            assert!(!e.o.revoke_grant(uid, "nope").await.unwrap());
            assert!(e.o.verify(&at1).await.is_none(), "{name}");
            let l = e.o.list_grants(uid).await.unwrap();
            assert_eq!(
                (l.len(), l[0].id.as_str()),
                (1, g2.family_id.as_str()),
                "{name}"
            );

            // an expired family is not listed
            let (x, _, _) = minted(&e, &cid, uid).await;
            assert_eq!(e.o.list_grants(uid).await.unwrap().len(), 2);
            set_tok(&db, x.id, tokens::Column::AccessExpiresAt, Some(now() - 5)).await;
            set_tok(&db, x.id, tokens::Column::RefreshExpiresAt, Some(now() - 5)).await;
            assert_eq!(e.o.list_grants(uid).await.unwrap().len(), 1, "{name}");

            // an unused authorization code is voided too
            let code =
                e.o.issue_code(&cid, uid, CB, &["read".into()], None)
                    .await
                    .unwrap();
            let body = format!(
                "grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}",
                pct(CB)
            );

            // revoke everything: access AND refresh tokens, old and rotated
            assert_eq!(e.o.revoke_user_tokens(uid).await.unwrap(), 2, "{name}");
            assert_eq!(e.o.revoke_user_tokens(uid).await.unwrap(), 0, "{name}");
            assert!(e.o.verify(&at2).await.is_none() && e.o.verify(&at2b).await.is_none());
            for rt in [&rt2, &rt2b] {
                let r = refresh(&e, &cid, rt).await;
                assert_eq!(
                    (r.status, r.err()),
                    (StatusCode::BAD_REQUEST, "invalid_grant".into()),
                    "{name}"
                );
            }
            let r = post_form(&e.app, "/oauth/token", &body, &[]).await;
            assert_eq!(r.err(), "invalid_grant", "{name}: code voided");
            assert!(e.o.list_grants(uid).await.unwrap().is_empty(), "{name}");
            // another user is untouched
            assert!(e.o.verify(&at3).await.is_some(), "{name}");
            assert_eq!(e.o.list_grants(other).await.unwrap().len(), 1);
        }
    }

    #[tokio::test]
    async fn prune_deletes_only_finished_rows() {
        for (name, db) in dbs().await {
            let e = env(db.clone()).await;
            let cid = public_client(&e).await;
            let uid = uniq();
            let t = now();
            let hour = Duration::from_secs(3600);
            let row = || async { minted(&e, &cid, uid).await.0 };
            let (live, revoked_old, revoked_new, expired, rotated_live, access_only) = (
                row().await,
                row().await,
                row().await,
                row().await,
                row().await,
                e.o.mint(&cid, Some(uid), "read", None, None, false)
                    .await
                    .map_err(|_| "mint")
                    .unwrap()
                    .0,
            );
            set_tok(
                &db,
                revoked_old.id,
                tokens::Column::RevokedAt,
                Some(t - 7200),
            )
            .await;
            set_tok(&db, revoked_new.id, tokens::Column::RevokedAt, Some(t - 5)).await;
            for c in [
                tokens::Column::AccessExpiresAt,
                tokens::Column::RefreshExpiresAt,
            ] {
                set_tok(&db, expired.id, c, Some(t - 120)).await;
            }
            // rotated: access long expired, refresh still live (kept for reuse detection)
            set_tok(
                &db,
                rotated_live.id,
                tokens::Column::AccessExpiresAt,
                Some(t - 5000),
            )
            .await;
            set_tok(
                &db,
                rotated_live.id,
                tokens::Column::RefreshUsedAt,
                Some(t - 4000),
            )
            .await;
            set_tok(
                &db,
                access_only.id,
                tokens::Column::AccessExpiresAt,
                Some(t - 120),
            )
            .await;

            let mk_code = |used: Option<i64>, exp: i64| {
                let db = db.clone();
                let cid = cid.clone();
                async move {
                    codes::ActiveModel {
                        code_hash: Set(hash(&format!("c{}", uniq()))),
                        client_id: Set(cid),
                        user_id: Set(uid),
                        redirect_uri: Set(CB.into()),
                        scopes: Set("read".into()),
                        expires_at: Set(exp),
                        used_at: Set(used),
                        ..Default::default()
                    }
                    .insert(&db)
                    .await
                    .unwrap()
                    .id
                }
            };
            let (c_live, c_exp, c_used_old, c_used_new) = (
                mk_code(None, t + 500).await,
                mk_code(None, t - 120).await,
                mk_code(Some(t - 7200), t - 7000).await,
                mk_code(Some(t - 5), t + 500).await,
            );

            let rep = e.o.prune(hour).await.unwrap();
            assert!(rep.tokens >= 3 && rep.codes >= 2, "{name}: {rep:?}");
            for (id, kept) in [
                (live.id, true),
                (revoked_old.id, false),
                (revoked_new.id, true),
                (expired.id, false),
                (rotated_live.id, true),
                (access_only.id, false),
            ] {
                assert_eq!(!gone(&db, id).await, kept, "{name}: token {id}");
            }
            for (id, kept) in [
                (c_live, true),
                (c_exp, false),
                (c_used_old, false),
                (c_used_new, true),
            ] {
                let there = codes::Entity::find_by_id(id)
                    .one(&db)
                    .await
                    .unwrap()
                    .is_some();
                assert_eq!(there, kept, "{name}: code {id}");
            }
            // a pruned-away user keeps working tokens
            assert_eq!(
                e.o.prune(hour).await.unwrap().tokens,
                0,
                "{name}: idempotent"
            );
            // retention zero also drops the freshly revoked one
            e.o.prune(Duration::ZERO).await.unwrap();
            assert!(gone(&db, revoked_new.id).await, "{name}");
            assert!(
                !gone(&db, live.id).await && !gone(&db, rotated_live.id).await,
                "{name}"
            );
        }
    }

    #[tokio::test]
    async fn prune_racing_verify_and_rotation_keeps_single_winner() {
        for (name, db) in dbs().await {
            let e = env(db.clone()).await;
            let cid = public_client(&e).await;
            let uid = uniq();
            let mut grants = Vec::new();
            for _ in 0..12 {
                let (_, at, rt) = minted(&e, &cid, uid).await;
                grants.push((at, rt));
            }
            // garbage for prune to chew on while the race runs
            for _ in 0..30 {
                let (r, _, _) = minted(&e, &cid, uid).await;
                set_tok(
                    &db,
                    r.id,
                    tokens::Column::AccessExpiresAt,
                    Some(now() - 600),
                )
                .await;
                set_tok(
                    &db,
                    r.id,
                    tokens::Column::RefreshExpiresAt,
                    Some(now() - 600),
                )
                .await;
            }
            let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
            let pruner = {
                let (o, stop) = (e.o.clone(), stop.clone());
                tokio::spawn(async move {
                    while !stop.load(std::sync::atomic::Ordering::Relaxed) {
                        o.prune(Duration::ZERO).await.unwrap();
                        tokio::task::yield_now().await;
                    }
                })
            };
            let mut hs = Vec::new();
            let mut solo_hs = Vec::new();
            for _ in 0..12 {
                let (_, _, rt) = minted(&e, &cid, uid).await;
                let (app, cid) = (e.app.clone(), cid.clone());
                solo_hs.push(tokio::spawn(
                    async move { refresh_via(&app, &cid, &rt).await },
                ));
            }
            for (at, rt) in &grants {
                for _ in 0..3 {
                    let (app, cid, rt) = (e.app.clone(), cid.clone(), rt.clone());
                    hs.push(tokio::spawn(async move {
                        post_form(
                            &app,
                            "/oauth/token",
                            &format!("grant_type=refresh_token&client_id={cid}&refresh_token={rt}"),
                            &[],
                        )
                        .await
                    }));
                }
                let (o, at) = (e.o.clone(), at.clone());
                hs.push(tokio::spawn(async move {
                    // verify during the race must never panic or error out
                    let _ = o.verify(&at).await;
                    Resp {
                        status: StatusCode::OK,
                        headers: HeaderMap::new(),
                        body: "{}".into(),
                    }
                }));
            }
            let rs = join(hs).await;
            stop.store(true, std::sync::atomic::Ordering::Relaxed);
            pruner.await.unwrap();
            for chunk in rs.chunks(4) {
                let wins = chunk[..3]
                    .iter()
                    .filter(|r| r.status == StatusCode::OK)
                    .count();
                assert!(wins <= 1, "{name}: {wins} winners");
                assert!(
                    chunk[..3]
                        .iter()
                        .all(|r| r.status == StatusCode::OK || r.err() == "invalid_grant"),
                    "{name}: {:?}",
                    chunk[..3]
                        .iter()
                        .map(|r| (r.status, r.body.clone()))
                        .collect::<Vec<_>>()
                );
            }
            // uncontended rotations under the same prune pressure must all succeed
            for r in join(solo_hs).await {
                assert_eq!(r.status, StatusCode::OK, "{name}: {}", r.body);
            }
        }
    }

    #[tokio::test]
    async fn old_token_tables_are_upgraded_with_indexes() {
        for (name, db) in dbs().await {
            for t in ["oauth_tokens", "oauth_codes"] {
                let drop = Table::drop().table(Alias::new(t)).if_exists().to_owned();
                db.execute(&drop).await.unwrap();
            }
            // previous schema: no last_used_at, no secondary indexes
            let col = |n: &str| ColumnDef::new(Alias::new(n));
            let old = Table::create()
                .table(Alias::new("oauth_tokens"))
                .col(
                    col("id")
                        .big_integer()
                        .not_null()
                        .auto_increment()
                        .primary_key(),
                )
                .col(col("access_hash").string().not_null().unique_key())
                .col(col("refresh_hash").string().null().unique_key())
                .col(col("client_id").string().not_null())
                .col(col("user_id").big_integer().null())
                .col(col("scopes").text().not_null())
                .col(col("created_at").big_integer().not_null())
                .col(col("access_expires_at").big_integer().not_null())
                .col(col("refresh_expires_at").big_integer().null())
                .col(col("revoked_at").big_integer().null())
                .col(col("family_id").string().not_null())
                .col(col("code_id").big_integer().null())
                .col(col("refresh_used_at").big_integer().null())
                .col(col("refresh_claim").string().null())
                .to_owned();
            db.execute(&old).await.unwrap();
            let mut c =
                Schema::new(db.get_database_backend()).create_table_from_entity(codes::Entity);
            db.execute(c.if_not_exists()).await.unwrap();
            let (uid, access) = (uniq(), format!("ryo_old{}", uniq()));
            let t = now();
            let ins = SqlQuery::insert()
                .into_table(Alias::new("oauth_tokens"))
                .columns(
                    [
                        "access_hash",
                        "client_id",
                        "user_id",
                        "scopes",
                        "created_at",
                        "access_expires_at",
                        "family_id",
                    ]
                    .map(Alias::new),
                )
                .values_panic([
                    hash(&access).into(),
                    "legacy-no-client".into(),
                    uid.into(),
                    "read".into(),
                    t.into(),
                    (t + 3600).into(),
                    "fam-old".into(),
                ])
                .to_owned();
            db.execute(&ins).await.unwrap();

            let o = OAuthServer::new(db.clone());
            let hs: Vec<_> = (0..3)
                .map(|_| {
                    let o = o.clone();
                    tokio::spawn(async move { o.ensure_tables().await })
                })
                .collect();
            for h in hs {
                h.await.unwrap().unwrap_or_else(|e| panic!("{name}: {e}"));
            }
            o.ensure_tables().await.unwrap();

            // the old row still works, and gets the new column written
            let p = o.verify(&access).await.expect(name);
            assert_eq!((p.user_id, p.id.as_str()), (Some(uid), "fam-old"), "{name}");
            let row = tokens::Entity::find()
                .filter(tokens::Column::AccessHash.eq(hash(&access)))
                .one(&db)
                .await
                .unwrap()
                .unwrap();
            assert!(row.last_used_at.is_some(), "{name}");
            let g = o.list_grants(uid).await.unwrap();
            assert_eq!(
                (g.len(), g[0].id.as_str(), g[0].client_name.as_str()),
                (1, "fam-old", ""),
                "{name}"
            );
            assert!(o.revoke_grant(uid, "fam-old").await.unwrap());
            assert!(o.verify(&access).await.is_none());

            // the indexes exist
            for (table, col) in [
                ("oauth_tokens", "family_id"),
                ("oauth_tokens", "code_id"),
                ("oauth_tokens", "client_id"),
                ("oauth_tokens", "user_id"),
                ("oauth_codes", "user_id"),
            ] {
                let idx = format!("idx-{table}-{col}");
                let found = if name == "mysql" {
                    mysql_has_index(&db, table, &idx).await.unwrap()
                } else {
                    // catalog views, built with the query builder
                    let (view, col) = if name == "sqlite" {
                        ("sqlite_master", "name")
                    } else {
                        ("pg_indexes", "indexname")
                    };
                    let q = SqlQuery::select()
                        .column(Alias::new(col))
                        .from(Alias::new(view))
                        .and_where(sea_orm::ExprTrait::eq(
                            Expr::col(Alias::new(col)),
                            idx.as_str(),
                        ))
                        .to_owned();
                    !db.query_all(&q).await.unwrap().is_empty()
                };
                assert!(found, "{name}: missing {idx}");
            }
        }
    }

    #[test]
    fn primitives() {
        assert!(ct_eq("abc", "abc") && !ct_eq("abc", "abd") && !ct_eq("abc", "ab"));
        // RFC 7636 appendix B
        assert_eq!(
            s256(VERIFIER),
            "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
        );
        assert!(pkce_ok(
            "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
            VERIFIER
        ));
        assert!(!pkce_ok("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", "x"));
        assert_eq!(pct("a b/?&=\u{e9}"), "a%20b%2F%3F%26%3D%C3%A9");
        assert_eq!(
            with_query("https://a/cb?x=1", &[("code", "c d")]),
            "https://a/cb?x=1&code=c%20d"
        );
        assert_eq!(split("a  b a"), ["a", "b"]);
        let (a, b) = (random("ryo_", 32).unwrap(), random("ryo_", 32).unwrap());
        assert!(a.len() == 47 && a != b);
    }
}