pylon-router 0.3.20

Pylon — realtime backend as a single Rust binary. Schema, policies, server functions, live queries, auth — one process.
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
//! `/api/auth/*` routes — sessions, OAuth, magic-link, password,
//! email verification, /me, /providers, /sessions, refresh.
//!
//! Returns `Some((status, body))` if this module owns the route, or
//! `None` to fall through to the next module. Behavior is identical
//! to the pre-split inline handlers in `lib.rs`; this is a pure
//! mechanical extraction so security audits can scope to one file.

use crate::{
    complete_oauth_login_pkce, json_error, json_error_safe, json_error_with_hint, parse_query,
    redact_email, url_encode, RouterContext,
};
use pylon_http::HttpMethod;

pub(crate) fn handle(
    ctx: &RouterContext,
    method: HttpMethod,
    url: &str,
    body: &str,
    auth_token: Option<&str>,
) -> Option<(u16, String)> {
    // POST /api/auth/session
    //
    // Mints a session for an arbitrary user_id. This is a privileged operation
    // — there is NO credential check here, only an admin/dev gate. Production
    // code must go through `/api/auth/magic/verify` or the OAuth callback.
    // Historically this route was ungated and any caller could become any
    // user. Now: dev mode OR admin token required.
    if url == "/api/auth/session" && method == HttpMethod::Post {
        if !ctx.is_dev && !ctx.auth_ctx.is_admin {
            return Some((
                403,
                json_error(
                    "FORBIDDEN",
                    "/api/auth/session requires admin auth in non-dev mode",
                ),
            ));
        }
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => {
                return Some((
                    400,
                    json_error_safe(
                        "INVALID_JSON",
                        "Invalid request body",
                        &format!("Invalid JSON: {e}"),
                    ),
                ));
            }
        };
        let user_id = match data.get("user_id").and_then(|v| v.as_str()) {
            Some(id) => id.to_string(),
            None => return Some((400, json_error("MISSING_USER_ID", "user_id is required"))),
        };
        let session = ctx.session_store.create(user_id);
        return Some((
            201,
            serde_json::json!({"token": session.token, "user_id": session.user_id}).to_string(),
        ));
    }

    // GET /api/auth/me
    //
    // Cheap session/identity probe. Returns just the AuthContext
    // (`{ user_id, is_admin, roles, tenant_id }`) — no DB hit, no
    // entity fetch. Use this when all you need is "is the caller
    // signed in?" or "are they an admin?" — middleware, route gates,
    // permission checks. For the full `{ session, user }` payload
    // (with the User row from the DB), call /api/auth/session.
    //
    // AuthContext comes from the runtime's pre-route resolution —
    // calling session_store.resolve here would miss the
    // PYLON_ADMIN_TOKEN bearer-auth branch.
    if url == "/api/auth/me" && method == HttpMethod::Get {
        return Some((
            200,
            serde_json::to_string(ctx.auth_ctx).unwrap_or_else(|_| "{}".into()),
        ));
    }

    // GET /api/auth/session
    //
    // Better-auth's `getSession()` shape: returns both the session
    // (auth context) AND the User row in a single round-trip. The
    // SDK uses this for layout/dashboard reads; /api/auth/me stays
    // available for the cheap session-only probe.
    //
    // - User row is fetched by id from the manifest's User entity
    //   (conventionally named "User"; configurable user-entity is
    //   a follow-up).
    // - Sensitive fields stripped: `passwordHash` + anything starting
    //   with `_` (framework-internal columns). Apps wanting a custom
    //   projection can still expose a TS `getMe` function and call it
    //   alongside this endpoint.
    // - Returns `user: null` when the caller is anonymous, a guest,
    //   or the User row was deleted out from under the session.
    if url == "/api/auth/session" && method == HttpMethod::Get {
        let auth_cfg = &ctx.store.manifest().auth;
        let user_entity = &auth_cfg.user.entity;
        let mut body = serde_json::Map::new();
        let session_value = serde_json::to_value(ctx.auth_ctx).unwrap_or(serde_json::Value::Null);
        body.insert("session".into(), session_value);
        let user_value = ctx
            .auth_ctx
            .user_id
            .as_deref()
            .filter(|_| !ctx.auth_ctx.is_guest)
            .and_then(|uid| ctx.store.get_by_id(user_entity, uid).ok().flatten())
            .map(|row| project_user_row(row, &auth_cfg.user))
            .unwrap_or(serde_json::Value::Null);
        body.insert("user".into(), user_value);
        return Some((200, serde_json::Value::Object(body).to_string()));
    }

    // POST /api/auth/guest
    if url == "/api/auth/guest" && method == HttpMethod::Post {
        let session = ctx.session_store.create_guest();
        ctx.maybe_set_session_cookie(&session.token);
        return Some((
            201,
            serde_json::json!({"token": session.token, "user_id": session.user_id, "guest": true})
                .to_string(),
        ));
    }

    // POST /api/auth/upgrade
    //
    // Swap a guest session's anonymous id for a real user id. Same hole as
    // /api/auth/session if ungated: a caller holding a guest token can
    // upgrade to anyone. Gate: admin auth, or dev mode, with the same
    // rationale as session mint. Real upgrade should flow through magic-code
    // verify or OAuth callback, which consume the previous guest token and
    // issue a fresh user token server-side.
    if url == "/api/auth/upgrade" && method == HttpMethod::Post {
        if !ctx.is_dev && !ctx.auth_ctx.is_admin {
            return Some((
                403,
                json_error(
                    "FORBIDDEN",
                    "/api/auth/upgrade requires admin auth in non-dev mode",
                ),
            ));
        }
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => {
                return Some((
                    400,
                    json_error_safe(
                        "INVALID_JSON",
                        "Invalid request body",
                        &format!("Invalid JSON: {e}"),
                    ),
                ));
            }
        };
        let user_id = match data.get("user_id").and_then(|v| v.as_str()) {
            Some(id) => id.to_string(),
            None => return Some((400, json_error("MISSING_USER_ID", "user_id is required"))),
        };
        if let Some(token) = auth_token {
            if ctx.session_store.upgrade(token, user_id.clone()) {
                return Some((
                    200,
                    serde_json::json!({"upgraded": true, "user_id": user_id}).to_string(),
                ));
            }
        }
        return Some((
            400,
            json_error("UPGRADE_FAILED", "No valid session to upgrade"),
        ));
    }

    // POST /api/auth/select-org
    //
    // Switch the caller's active tenant (organization). The server does a
    // membership check against OrgMember before committing — a client can't
    // impersonate an org it doesn't belong to. Pass `{ orgId: null }` to
    // leave all orgs (back to the login lobby).
    if url == "/api/auth/select-org" && method == HttpMethod::Post {
        let token = match auth_token {
            Some(t) => t,
            None => return Some((401, json_error("UNAUTHENTICATED", "missing bearer token"))),
        };
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(id) => id,
            None => return Some((401, json_error("UNAUTHENTICATED", "anonymous session"))),
        };
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => {
                return Some((
                    400,
                    json_error_safe(
                        "INVALID_JSON",
                        "Invalid request body",
                        &format!("Invalid JSON: {e}"),
                    ),
                ));
            }
        };
        let target = data.get("orgId").and_then(|v| {
            if v.is_null() {
                Some(String::new())
            } else {
                v.as_str().map(String::from)
            }
        });
        let target = match target {
            Some(t) => t,
            None => {
                return Some((
                    400,
                    json_error("MISSING_ORG_ID", "orgId is required (or null)"),
                ));
            }
        };
        if target.is_empty() {
            // Clear the active org — the user is dropping out of all tenants.
            ctx.session_store.set_tenant(token, None);
            return Some((200, serde_json::json!({"tenantId": null}).to_string()));
        }
        // Look up an OrgMember row matching this user + target org.
        let filter = serde_json::json!({ "userId": user_id, "orgId": &target });
        match ctx.store.query_filtered("OrgMember", &filter) {
            Ok(rows) if !rows.is_empty() => {
                ctx.session_store.set_tenant(token, Some(target.clone()));
                return Some((200, serde_json::json!({"tenantId": target}).to_string()));
            }
            Ok(_) => {
                return Some((
                    403,
                    json_error(
                        "NOT_A_MEMBER",
                        "you are not a member of the target organization",
                    ),
                ));
            }
            Err(e) => {
                return Some((
                    500,
                    json_error_safe("LOOKUP_FAILED", "could not verify membership", &e.message),
                ));
            }
        }
    }

    // POST /api/auth/magic/send
    if url == "/api/auth/magic/send" && method == HttpMethod::Post {
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => {
                return Some((
                    400,
                    json_error_safe(
                        "INVALID_JSON",
                        "Invalid request body",
                        &format!("Invalid JSON: {e}"),
                    ),
                ));
            }
        };
        let email = match data.get("email").and_then(|v| v.as_str()) {
            Some(e) => e.to_string(),
            None => return Some((400, json_error("MISSING_EMAIL", "email is required"))),
        };
        // Optional CAPTCHA gate. When PYLON_CAPTCHA_PROVIDER+SECRET
        // are set, the request must include `captchaToken`. Skipped
        // entirely when unconfigured so existing apps keep working.
        if let Some(cfg) = pylon_auth::captcha::CaptchaConfig::from_env() {
            let token = data.get("captchaToken").and_then(|v| v.as_str()).unwrap_or("");
            if let Err(reason) = cfg.verify(token, Some(ctx.peer_ip)) {
                tracing::warn!("[captcha] magic/send rejected: {reason}");
                return Some((
                    400,
                    json_error("CAPTCHA_FAILED", "CAPTCHA verification failed"),
                ));
            }
        }
        let code = match ctx.magic_codes.try_create(&email) {
            Ok(c) => c,
            Err(pylon_auth::MagicCodeError::Throttled { retry_after_secs }) => {
                return Some((
                    429,
                    json_error_with_hint(
                        "RATE_LIMITED",
                        "A sign-in code was requested too recently.",
                        &format!("Try again in {retry_after_secs} seconds."),
                    ),
                ));
            }
            Err(e) => {
                return Some((
                    500,
                    json_error(
                        "EMAIL_SEND_FAILED",
                        &format!("Could not issue code: {:?}", e),
                    ),
                ));
            }
        };
        let subject = "Your sign-in code";
        let body_text =
            format!("Your sign-in code is: {code}\n\nThis code will expire in 10 minutes.");
        if let Err(e) = ctx.email.send(&email, subject, &body_text) {
            if !ctx.is_dev {
                tracing::warn!(
                    "[email] Failed to send magic code to {}: {e}",
                    redact_email(&email)
                );
                return Some((
                    500,
                    json_error("EMAIL_SEND_FAILED", "Could not send sign-in email"),
                ));
            }
        }
        if ctx.is_dev {
            return Some((
                200,
                serde_json::json!({"sent": true, "email": email, "dev_code": code}).to_string(),
            ));
        }
        return Some((
            200,
            serde_json::json!({"sent": true, "email": email}).to_string(),
        ));
    }

    // POST /api/auth/magic/verify
    if url == "/api/auth/magic/verify" && method == HttpMethod::Post {
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => {
                return Some((
                    400,
                    json_error_safe(
                        "INVALID_JSON",
                        "Invalid request body",
                        &format!("Invalid JSON: {e}"),
                    ),
                ));
            }
        };
        let email = match data.get("email").and_then(|v| v.as_str()) {
            Some(e) => e,
            None => return Some((400, json_error("MISSING_EMAIL", "email is required"))),
        };
        let code = match data.get("code").and_then(|v| v.as_str()) {
            Some(c) => c,
            None => return Some((400, json_error("MISSING_CODE", "code is required"))),
        };
        match ctx.magic_codes.try_verify(email, code) {
            Ok(()) => {
                let now = format!(
                    "{}Z",
                    std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_secs()
                );
                let user_id =
                    match ctx
                        .store
                        .lookup(&ctx.store.manifest().auth.user.entity, "email", email)
                    {
                        Ok(Some(row)) => {
                            let id = row["id"].as_str().unwrap_or("").to_string();
                            // Magic-link login implicitly verifies the
                            // email — the caller proved control by typing
                            // the code we sent there. Stamp emailVerified
                            // if not already set.
                            if row.get("emailVerified").map_or(true, |v| v.is_null()) {
                                let _ = ctx.store.update(
                                    &ctx.store.manifest().auth.user.entity,
                                    &id,
                                    &serde_json::json!({ "emailVerified": now }),
                                );
                            }
                            id
                        }
                        _ => ctx
                            .store
                            .insert(
                                &ctx.store.manifest().auth.user.entity,
                                &serde_json::json!({
                                    "email": email,
                                    "displayName": email,
                                    "emailVerified": now,
                                    "createdAt": now,
                                }),
                            )
                            .unwrap_or_else(|_| email.to_string()),
                    };
                let session = ctx.session_store.create(user_id.clone());
                ctx.maybe_set_session_cookie(&session.token);
                return Some((
                    200,
                    serde_json::json!({"token": session.token, "user_id": user_id, "expires_at": session.expires_at}).to_string(),
                ));
            }
            Err(pylon_auth::MagicCodeError::TooManyAttempts) => {
                return Some((
                    429,
                    json_error(
                        "RATE_LIMITED",
                        "Too many verification attempts. Request a new code.",
                    ),
                ));
            }
            Err(_) => {}
        }
        return Some((401, json_error("INVALID_CODE", "Invalid or expired code")));
    }

    // POST /api/auth/email/send-verification
    //
    // Issues a 6-digit code to the *current session's* email address and
    // ships it via the EmailSender hook. Authenticated only — the email
    // is read from the User row keyed by `ctx.auth_ctx.user_id`, never from
    // the request body, so a logged-in caller can't trigger a code for
    // someone else's address.
    if url == "/api/auth/email/send-verification" && method == HttpMethod::Post {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(id) => id,
            None => return Some((401, json_error("UNAUTHORIZED", "Sign in required"))),
        };
        let user = match ctx
            .store
            .get_by_id(&ctx.store.manifest().auth.user.entity, user_id)
        {
            Ok(Some(u)) => u,
            _ => return Some((404, json_error("USER_NOT_FOUND", "User not found"))),
        };
        let email = match user.get("email").and_then(|v| v.as_str()) {
            Some(e) => e.to_string(),
            None => {
                return Some((
                    400,
                    json_error("MISSING_EMAIL", "User has no email on file"),
                ));
            }
        };
        let code = match ctx.magic_codes.try_create(&email) {
            Ok(c) => c,
            Err(pylon_auth::MagicCodeError::Throttled { retry_after_secs }) => {
                return Some((
                    429,
                    json_error_with_hint(
                        "RATE_LIMITED",
                        "A verification code was requested too recently.",
                        &format!("Try again in {retry_after_secs} seconds."),
                    ),
                ));
            }
            Err(e) => {
                return Some((
                    500,
                    json_error(
                        "EMAIL_SEND_FAILED",
                        &format!("Could not issue code: {:?}", e),
                    ),
                ));
            }
        };
        let subject = "Verify your email address";
        let body_text = format!(
            "Your email verification code is: {code}\n\nThis code will expire in 10 minutes."
        );
        if let Err(e) = ctx.email.send(&email, subject, &body_text) {
            if !ctx.is_dev {
                tracing::warn!(
                    "[email] Failed to send verification code to {}: {e}",
                    redact_email(&email)
                );
                return Some((
                    500,
                    json_error("EMAIL_SEND_FAILED", "Could not send verification email"),
                ));
            }
        }
        if ctx.is_dev {
            return Some((
                200,
                serde_json::json!({"sent": true, "email": email, "dev_code": code}).to_string(),
            ));
        }
        return Some((
            200,
            serde_json::json!({"sent": true, "email": email}).to_string(),
        ));
    }

    // POST /api/auth/email/verify
    if url == "/api/auth/email/verify" && method == HttpMethod::Post {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(id) => id,
            None => return Some((401, json_error("UNAUTHORIZED", "Sign in required"))),
        };
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => {
                return Some((
                    400,
                    json_error_safe(
                        "INVALID_JSON",
                        "Invalid request body",
                        &format!("Invalid JSON: {e}"),
                    ),
                ));
            }
        };
        let code = match data.get("code").and_then(|v| v.as_str()) {
            Some(c) => c,
            None => return Some((400, json_error("MISSING_CODE", "code is required"))),
        };
        let user = match ctx
            .store
            .get_by_id(&ctx.store.manifest().auth.user.entity, user_id)
        {
            Ok(Some(u)) => u,
            _ => return Some((404, json_error("USER_NOT_FOUND", "User not found"))),
        };
        let email = match user.get("email").and_then(|v| v.as_str()) {
            Some(e) => e.to_string(),
            None => {
                return Some((
                    400,
                    json_error("MISSING_EMAIL", "User has no email on file"),
                ));
            }
        };
        match ctx.magic_codes.try_verify(&email, code) {
            Ok(()) => {
                let now = format!(
                    "{}Z",
                    std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_secs()
                );
                // Best-effort: ignore the result. Schemas without an
                // emailVerified field will reject the unknown column;
                // schemas with it will accept the update. Either way
                // the verification *intent* succeeded.
                let _ = ctx.store.update(
                    &ctx.store.manifest().auth.user.entity,
                    user_id,
                    &serde_json::json!({ "emailVerified": now }),
                );
                return Some((
                    200,
                    serde_json::json!({"verified": true, "emailVerified": now}).to_string(),
                ));
            }
            Err(pylon_auth::MagicCodeError::TooManyAttempts) => {
                return Some((
                    429,
                    json_error(
                        "RATE_LIMITED",
                        "Too many verification attempts. Request a new code.",
                    ),
                ));
            }
            Err(_) => {}
        }
        return Some((401, json_error("INVALID_CODE", "Invalid or expired code")));
    }

    // POST /api/auth/password/register
    if url == "/api/auth/password/register" && method == HttpMethod::Post {
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => {
                return Some((
                    400,
                    json_error_safe(
                        "INVALID_JSON",
                        "Invalid request body",
                        &format!("Invalid JSON: {e}"),
                    ),
                ));
            }
        };
        let email = match data.get("email").and_then(|v| v.as_str()) {
            Some(e) => e.trim().to_lowercase(),
            None => return Some((400, json_error("MISSING_EMAIL", "email is required"))),
        };
        if !email.contains('@') {
            return Some((
                400,
                json_error("INVALID_EMAIL", "email must be well-formed"),
            ));
        }
        let password = match data.get("password").and_then(|v| v.as_str()) {
            Some(p) => p,
            None => return Some((400, json_error("MISSING_PASSWORD", "password is required"))),
        };
        if let Err(e) = pylon_auth::password::validate_length(password) {
            return Some((400, json_error("WEAK_PASSWORD", &e.to_string())));
        }
        // CAPTCHA gate (no-op when unconfigured).
        if let Some(cfg) = pylon_auth::captcha::CaptchaConfig::from_env() {
            let token = data.get("captchaToken").and_then(|v| v.as_str()).unwrap_or("");
            if let Err(reason) = cfg.verify(token, Some(ctx.peer_ip)) {
                tracing::warn!("[captcha] password/register rejected: {reason}");
                return Some((
                    400,
                    json_error("CAPTCHA_FAILED", "CAPTCHA verification failed"),
                ));
            }
        }
        // HIBP check unless explicitly disabled (off in test/dev to keep
        // unit tests offline). Honors PYLON_DISABLE_HIBP=1.
        if std::env::var("PYLON_DISABLE_HIBP").ok().as_deref() != Some("1") {
            match pylon_auth::password::check_pwned(password) {
                Ok(0) => {}
                Ok(n) => {
                    return Some((
                        400,
                        json_error_safe(
                            "PWNED_PASSWORD",
                            "This password has appeared in known data breaches. Choose a different one.",
                            &format!("HIBP returned {n} occurrences"),
                        ),
                    ));
                }
                // Fail-open on HIBP outage — security-vs-availability
                // tradeoff favors not locking out registration when an
                // external service is down.
                Err(_) => {}
            }
        }
        let display_name = data
            .get("displayName")
            .and_then(|v| v.as_str())
            .unwrap_or(email.as_str())
            .to_string();

        if let Ok(Some(_)) =
            ctx.store
                .lookup(&ctx.store.manifest().auth.user.entity, "email", &email)
        {
            return Some((409, json_error("EMAIL_TAKEN", "Email already registered")));
        }

        let hash = pylon_auth::password::hash_password(password);
        let now = format!(
            "{}Z",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs()
        );

        let palette = [
            "#8b5cf6", "#6366f1", "#3b82f6", "#06b6d4", "#10b981", "#84cc16", "#eab308", "#f97316",
            "#ef4444", "#ec4899",
        ];
        let mut hash_val: i32 = 0;
        for b in email.as_bytes() {
            hash_val = hash_val.wrapping_mul(31).wrapping_add(*b as i32);
        }
        let avatar_color = palette[(hash_val.unsigned_abs() as usize) % palette.len()];

        let user_id = match ctx.store.insert(
            &ctx.store.manifest().auth.user.entity,
            &serde_json::json!({
                "email": email,
                "displayName": display_name,
                "avatarColor": avatar_color,
                "passwordHash": hash,
                "createdAt": now,
            }),
        ) {
            Ok(id) => id,
            Err(e) => return Some((400, json_error(&e.code, &e.message))),
        };

        let session = ctx.session_store.create(user_id.clone());
        ctx.maybe_set_session_cookie(&session.token);
        return Some((
            200,
            serde_json::json!({
                "token": session.token,
                "user_id": user_id,
                "expires_at": session.expires_at,
            })
            .to_string(),
        ));
    }

    // POST /api/auth/password/login
    if url == "/api/auth/password/login" && method == HttpMethod::Post {
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => {
                return Some((
                    400,
                    json_error_safe(
                        "INVALID_JSON",
                        "Invalid request body",
                        &format!("Invalid JSON: {e}"),
                    ),
                ));
            }
        };
        let email = match data.get("email").and_then(|v| v.as_str()) {
            Some(e) => e.trim().to_lowercase(),
            None => return Some((400, json_error("MISSING_EMAIL", "email is required"))),
        };
        let password = match data.get("password").and_then(|v| v.as_str()) {
            Some(p) => p,
            None => return Some((400, json_error("MISSING_PASSWORD", "password is required"))),
        };

        let row = ctx
            .store
            .lookup(&ctx.store.manifest().auth.user.entity, "email", &email)
            .ok()
            .flatten();
        let (user_id, stored_hash): (Option<String>, Option<String>) = match row {
            Some(r) => (
                r.get("id").and_then(|v| v.as_str()).map(String::from),
                r.get("passwordHash")
                    .and_then(|v| v.as_str())
                    .map(String::from),
            ),
            None => (None, None),
        };

        let matched = match &stored_hash {
            Some(h) if !h.is_empty() => pylon_auth::password::verify_password(password, h),
            _ => {
                let _ = pylon_auth::password::verify_password(
                    password,
                    pylon_auth::password::dummy_hash(),
                );
                false
            }
        };

        if !matched {
            return Some((
                401,
                json_error("INVALID_CREDENTIALS", "Email or password is incorrect"),
            ));
        }

        let user_id = match user_id {
            Some(id) => id,
            None => {
                return Some((
                    500,
                    json_error("USER_NOT_FOUND", "Authenticated but user missing"),
                ));
            }
        };
        let session = ctx.session_store.create(user_id.clone());
        ctx.maybe_set_session_cookie(&session.token);
        return Some((
            200,
            serde_json::json!({
                "token": session.token,
                "user_id": user_id,
                "expires_at": session.expires_at,
            })
            .to_string(),
        ));
    }

    // GET /api/auth/providers
    if url == "/api/auth/providers" && method == HttpMethod::Get {
        let registry = pylon_auth::OAuthRegistry::shared();
        // Iterate the configured ids — order isn't stable across calls
        // but the frontend doesn't need it to be (it sorts by display
        // name). Sorting here would mask provider-list churn that's
        // useful in logs, so keep it as-is.
        let mut providers: Vec<serde_json::Value> = registry
            .ids()
            .filter_map(|id| {
                registry.get(id).map(|c| {
                    serde_json::json!({
                        "provider": id,
                        "auth_url": c.auth_url(),
                    })
                })
            })
            .collect();
        // Stable order in the response so the FE list doesn't reshuffle
        // every login page hit (HashMap iteration is unspecified).
        providers.sort_by(|a, b| {
            a.get("provider").and_then(|v| v.as_str()).unwrap_or("")
                .cmp(b.get("provider").and_then(|v| v.as_str()).unwrap_or(""))
        });
        return Some((
            200,
            serde_json::to_string(&providers).unwrap_or_else(|_| "[]".into()),
        ));
    }

    // GET /api/auth/login/:provider?callback=<url>[&error_callback=<url>][&redirect=1]
    //
    // The frontend MUST pass `callback` — the URL pylon should 302 the
    // browser to after a successful OAuth handshake. Optional
    // `error_callback` is where failures land (defaults to `callback`,
    // with `?oauth_error=…&oauth_error_message=…` appended). Both URLs
    // must have origins listed in `PYLON_TRUSTED_ORIGINS` — same
    // pattern as better-auth's `trustedOrigins`. No env-var fallback;
    // an unconfigured trusted-origins list is a 400 from this route.
    if let Some(provider_raw) = url.strip_prefix("/api/auth/login/") {
        let provider = provider_raw.split('?').next().unwrap_or(provider_raw);
        if method == HttpMethod::Get {
            let registry = pylon_auth::OAuthRegistry::shared();
            let Some(config) = registry.get(provider) else {
                return Some((
                    404,
                    json_error_with_hint(
                        "PROVIDER_NOT_FOUND",
                        &format!("OAuth provider \"{provider}\" is not configured"),
                        &format!(
                            "Set PYLON_OAUTH_{}_CLIENT_ID + PYLON_OAUTH_{}_CLIENT_SECRET (and _REDIRECT). For OIDC IdPs (Auth0, Okta, Keycloak) also set PYLON_OAUTH_{}_OIDC_ISSUER.",
                            provider.to_ascii_uppercase(),
                            provider.to_ascii_uppercase(),
                            provider.to_ascii_uppercase(),
                        ),
                    ),
                ));
            };

            let query = provider_raw.split_once('?').map(|(_, q)| q).unwrap_or("");
            let params = parse_query(query);
            let callback = match params.get("callback").map(String::as_str) {
                Some(s) if !s.is_empty() => s.to_string(),
                _ => {
                    return Some((
                        400,
                        json_error_with_hint(
                            "MISSING_CALLBACK",
                            "GET /api/auth/login/:provider requires a `callback` query parameter",
                            "Add ?callback=<your-success-url>&error_callback=<your-failure-url>; both origins must be in PYLON_TRUSTED_ORIGINS",
                        ),
                    ));
                }
            };
            // error_callback defaults to callback — the frontend can
            // disambiguate via the `?oauth_error=` query param appended
            // on failure.
            let error_callback = params
                .get("error_callback")
                .filter(|s| !s.is_empty())
                .cloned()
                .unwrap_or_else(|| callback.clone());

            // Trusted-origins gate. Both URLs validated against the
            // same allowlist so an attacker can't sneak a redirect
            // through one parameter that they couldn't through the
            // other.
            for (kind, target) in [("callback", &callback), ("error_callback", &error_callback)] {
                if let Err(err) = pylon_auth::validate_trusted_redirect(target, ctx.trusted_origins)
                {
                    tracing::warn!(
                        "[oauth] rejected {kind}={target:?} for provider {provider}: {err}"
                    );
                    return Some((
                        403,
                        json_error_with_hint(
                            "UNTRUSTED_REDIRECT",
                            &format!("OAuth {kind} redirect rejected: {err}"),
                            "Add the redirect's origin (scheme://host[:port]) to PYLON_TRUSTED_ORIGINS (comma-separated)",
                        ),
                    ));
                }
            }

            // PKCE: when the provider requires it (Twitter/X, Kick), the
            // auth helper mints a verifier; we stash it on the state
            // record so the callback can replay it on token exchange.
            let (auth_url, pkce_verifier) = match config.auth_url_with_pkce("") {
                Ok((u, v)) => (u, v),
                Err(e) => {
                    return Some((
                        500,
                        json_error("OAUTH_PROVIDER_BROKEN", &format!("provider {provider} misconfigured: {e}")),
                    ));
                }
            };
            let state = ctx
                .oauth_state
                .create_with_pkce(provider, &callback, &error_callback, pkce_verifier);
            // auth_url_with_pkce was given an empty state placeholder
            // because we mint the random state token AFTER the URL.
            // Append it now.
            let auth_url = format!("{auth_url}&state={}", url_encode(&state));
            let want_redirect = params
                .get("redirect")
                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
                .unwrap_or(false);
            if want_redirect {
                ctx.add_response_header("Location", auth_url);
                return Some((302, String::new()));
            }
            return Some((
                200,
                serde_json::json!({"redirect": auth_url, "state": state}).to_string(),
            ));
        }
    }

    // /api/auth/callback/:provider
    if let Some(provider_raw) = url.strip_prefix("/api/auth/callback/") {
        let provider = provider_raw.split('?').next().unwrap_or(provider_raw);

        // POST: SDK / programmatic flow OR Apple's `response_mode=form_post`
        // browser callback (Apple POSTs the redirect URL with a
        // form-encoded body when name/email scopes are requested).
        // Detect Apple by Content-Type header — the SDK flow always
        // sends JSON, the Apple flow sends form-urlencoded.
        if method == HttpMethod::Post {
            let is_form_post = ctx
                .request_headers
                .iter()
                .any(|(k, v)| {
                    k.eq_ignore_ascii_case("content-type")
                        && v.to_ascii_lowercase()
                            .starts_with("application/x-www-form-urlencoded")
                });

            let (state, code, dev_email, dev_name, is_browser) = if is_form_post {
                // Apple form-post callback. Body is
                // `state=…&code=…&id_token=…[&user=…]`.
                let params = parse_query(body);
                let state = params.get("state").map(|s| s.as_str().to_string());
                let code = params.get("code").map(|s| s.as_str().to_string());
                (state, code, None, None, true)
            } else {
                let data: serde_json::Value = match serde_json::from_str(body) {
                    Ok(v) => v,
                    Err(e) => {
                        return Some((
                            400,
                            json_error_safe(
                                "INVALID_JSON",
                                "Invalid request body",
                                &format!("Invalid JSON: {e}"),
                            ),
                        ));
                    }
                };
                let state = data.get("state").and_then(|v| v.as_str()).map(String::from);
                let code = data.get("code").and_then(|v| v.as_str()).map(String::from);
                let dev_email = data.get("email").and_then(|v| v.as_str()).map(String::from);
                let dev_name = data.get("name").and_then(|v| v.as_str()).map(String::from);
                (state, code, dev_email, dev_name, false)
            };

            let state_record = match state
                .as_deref()
                .and_then(|s| ctx.oauth_state.validate(s, provider))
            {
                Some(r) => r,
                None => {
                    return Some((
                        403,
                        json_error(
                            "OAUTH_INVALID_STATE",
                            "Invalid or missing OAuth state parameter",
                        ),
                    ));
                }
            };

            let result = complete_oauth_login_pkce(
                ctx,
                provider,
                code.as_deref(),
                state_record.pkce_verifier.as_deref(),
                dev_email.as_deref(),
                dev_name.as_deref(),
            );

            // Browser-flow form_post callbacks (Apple) need to land
            // back on the user-supplied callback URL with a session
            // cookie set, just like the GET browser callback path.
            if is_browser {
                return Some(match result {
                    Ok((_user_id, session)) => {
                        let cookie_value = ctx.cookie_config.set_value(&session.token);
                        ctx.add_response_header("Set-Cookie", cookie_value);
                        ctx.add_response_header("Location", state_record.callback_url);
                        (302, String::new())
                    }
                    Err(err) => {
                        tracing::warn!(
                            "[oauth] form_post callback {} failed: {} {}",
                            provider,
                            err.code,
                            err.message
                        );
                        let sep = if state_record.error_callback_url.contains('?') {
                            '&'
                        } else {
                            '?'
                        };
                        let target = format!(
                            "{}{}oauth_error={}&oauth_error_message={}",
                            state_record.error_callback_url,
                            sep,
                            url_encode(err.code),
                            url_encode(&err.message)
                        );
                        ctx.add_response_header("Location", target);
                        (302, String::new())
                    }
                });
            }

            return Some(match result {
                Ok((user_id, session)) => {
                    ctx.maybe_set_session_cookie(&session.token);
                    (
                        200,
                        serde_json::json!({
                            "token": session.token,
                            "user_id": user_id,
                            "provider": provider,
                            "expires_at": session.expires_at,
                        })
                        .to_string(),
                    )
                }
                Err(err) => (err.status, json_error(err.code, &err.message)),
            });
        }

        // GET: browser flow. State validation gives us the callback
        // URLs the start endpoint stored. No env-var lookup needed.
        //
        // CRITICAL: every arm here must `return Some(...)` directly.
        // Earlier code built `Some((302, ...))` as the value of the
        // match without returning, then a stray `let _ = ...` line
        // discarded it — every browser OAuth callback fell through
        // silently and produced no response. (Caught by codex P1
        // review of 0.3.9.)
        if method == HttpMethod::Get {
            let query = provider_raw.split_once('?').map(|(_, q)| q).unwrap_or("");
            let params = parse_query(query);
            let state_token = params.get("state").map(String::as_str);
            let code = params.get("code").map(String::as_str);

            // Validate state ONCE (single-use take) and capture the
            // stored callback URLs. We use them for both the success
            // 302 and the failure 302 — the start endpoint already
            // validated both URLs against PYLON_TRUSTED_ORIGINS.
            let state_record = match state_token.and_then(|s| ctx.oauth_state.validate(s, provider))
            {
                Some(s) => s,
                None => {
                    return Some((
                        403,
                        json_error(
                            "OAUTH_INVALID_STATE",
                            "Invalid, expired, or already-consumed OAuth state. Restart the sign-in flow.",
                        ),
                    ));
                }
            };

            match complete_oauth_login_pkce(
                ctx,
                provider,
                code,
                state_record.pkce_verifier.as_deref(),
                None,
                None,
            ) {
                Ok((_user_id, session)) => {
                    let cookie_value = ctx.cookie_config.set_value(&session.token);
                    ctx.add_response_header("Set-Cookie", cookie_value);
                    ctx.add_response_header("Location", state_record.callback_url);
                    return Some((302, String::new()));
                }
                Err(err) => {
                    tracing::warn!(
                        "[oauth] callback {} failed: {} {}",
                        provider,
                        err.code,
                        err.message
                    );
                    let msg = if err.message.len() > 500 {
                        format!("{}", &err.message[..500])
                    } else {
                        err.message.clone()
                    };
                    let sep = if state_record.error_callback_url.contains('?') {
                        '&'
                    } else {
                        '?'
                    };
                    let target = format!(
                        "{}{}oauth_error={}&oauth_error_message={}",
                        state_record.error_callback_url,
                        sep,
                        url_encode(err.code),
                        url_encode(&msg)
                    );
                    ctx.add_response_header("Location", target);
                    return Some((302, String::new()));
                }
            }
        }
    }

    let _ = body; // Suppress unused-warning for arms that don't read body.

    // DELETE /api/auth/session
    if url == "/api/auth/session" && method == HttpMethod::Delete {
        if let Some(token) = auth_token {
            ctx.session_store.revoke(token);
        }
        ctx.add_response_header("Set-Cookie", ctx.cookie_config.clear_value());
        return Some((200, serde_json::json!({"revoked": true}).to_string()));
    }

    // POST /api/auth/jwt — exchange the current session for a JWT-shaped
    // token (HS256 signed with PYLON_JWT_SECRET). Useful for edge runtimes
    // that can't tolerate a session-store round-trip on every request.
    // Requires PYLON_JWT_SECRET to be set; 501 otherwise.
    if url == "/api/auth/jwt" && method == HttpMethod::Post {
        if !ctx.auth_ctx.is_authenticated() {
            return Some((401, json_error("AUTH_REQUIRED", "Login required")));
        }
        let secret = match std::env::var("PYLON_JWT_SECRET").ok() {
            Some(s) if !s.is_empty() => s,
            _ => {
                return Some((
                    501,
                    json_error_with_hint(
                        "JWT_NOT_CONFIGURED",
                        "JWT-shaped sessions are disabled",
                        "Set PYLON_JWT_SECRET (32+ random bytes) to enable; optional PYLON_JWT_ISSUER for validation",
                    ),
                ));
            }
        };
        let issuer = std::env::var("PYLON_JWT_ISSUER").unwrap_or_else(|_| "pylon".into());
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let lifetime = std::env::var("PYLON_JWT_LIFETIME_SECS")
            .ok()
            .and_then(|s| s.parse::<u64>().ok())
            .unwrap_or(60 * 60); // 1 hour default
        let claims = pylon_auth::jwt::JwtClaims {
            sub: ctx.auth_ctx.user_id.clone().unwrap_or_default(),
            iat: now,
            exp: now + lifetime,
            iss: issuer,
            tenant_id: ctx.auth_ctx.tenant_id.clone(),
            roles: ctx.auth_ctx.roles.clone(),
        };
        let token = pylon_auth::jwt::mint(secret.as_bytes(), &claims);
        return Some((
            200,
            serde_json::json!({"token": token, "expires_at": claims.exp}).to_string(),
        ));
    }

    // POST /api/auth/refresh
    if url == "/api/auth/refresh" && method == HttpMethod::Post {
        let old = match auth_token {
            Some(t) => t,
            None => return Some((401, json_error("AUTH_REQUIRED", "No session to refresh"))),
        };
        match ctx.session_store.refresh(old) {
            Some(session) => {
                return Some((
                    200,
                    serde_json::json!({
                        "token": session.token,
                        "user_id": session.user_id,
                        "expires_at": session.expires_at,
                    })
                    .to_string(),
                ));
            }
            None => {
                return Some((
                    401,
                    json_error("SESSION_EXPIRED", "Session is expired or invalid"),
                ));
            }
        }
    }

    // GET /api/auth/sessions
    if url == "/api/auth/sessions" && method == HttpMethod::Get {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u,
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        let list = ctx.session_store.list_for_user(user_id);
        let sanitized: Vec<serde_json::Value> = list
            .iter()
            .map(|s| {
                serde_json::json!({
                    "token_prefix": &s.token[..s.token.len().min(8)],
                    "user_id": s.user_id,
                    "device": s.device,
                    "created_at": s.created_at,
                    "expires_at": s.expires_at,
                })
            })
            .collect();
        return Some((
            200,
            serde_json::to_string(&sanitized).unwrap_or_else(|_| "[]".into()),
        ));
    }

    // DELETE /api/auth/sessions
    if url == "/api/auth/sessions" && method == HttpMethod::Delete {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u,
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        let n = ctx.session_store.revoke_all_for_user(user_id);
        return Some((200, serde_json::json!({"revoked_count": n}).to_string()));
    }

    // ─── API keys ───────────────────────────────────────────────────────
    //
    // POST /api/auth/api-keys           — mint a new key (returns the
    //                                     plaintext exactly once)
    // GET  /api/auth/api-keys           — list (no plaintext, prefix only)
    // DELETE /api/auth/api-keys/:id     — revoke
    if url == "/api/auth/api-keys" {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u,
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        // P2 fix (codex Wave-2): API-key-authenticated requests cannot
        // create / list / revoke API keys. Same posture as Stripe
        // restricted keys — the user must hold a real session to manage
        // their keys. Admin tokens (server-issued) bypass.
        if ctx.auth_ctx.is_api_key_auth() && !ctx.auth_ctx.is_admin {
            return Some((
                403,
                json_error(
                    "API_KEY_AUTH_FORBIDDEN",
                    "API key management requires a session, not an API key",
                ),
            ));
        }
        if method == HttpMethod::Post {
            let data: serde_json::Value = match serde_json::from_str(body) {
                Ok(v) => v,
                Err(e) => {
                    return Some((
                        400,
                        json_error_safe(
                            "INVALID_JSON",
                            "Invalid request body",
                            &format!("Invalid JSON: {e}"),
                        ),
                    ));
                }
            };
            let name = data
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or("untitled")
                .to_string();
            let scopes = data
                .get("scopes")
                .and_then(|v| v.as_str())
                .map(String::from);
            let expires_at = data
                .get("expires_at")
                .and_then(|v| v.as_u64());
            let (plaintext, key) =
                ctx.api_keys.create(user_id.to_string(), name, scopes, expires_at);
            return Some((
                200,
                serde_json::json!({
                    // ONLY shown here. Frontend MUST display & forget.
                    "key": plaintext,
                    "id": key.id,
                    "prefix": key.prefix,
                    "name": key.name,
                    "scopes": key.scopes,
                    "expires_at": key.expires_at,
                    "created_at": key.created_at,
                })
                .to_string(),
            ));
        }
        if method == HttpMethod::Get {
            let list = ctx.api_keys.list_for_user(user_id);
            let payload: Vec<serde_json::Value> = list
                .iter()
                .map(|k| {
                    serde_json::json!({
                        "id": k.id,
                        "prefix": k.prefix,
                        "name": k.name,
                        "scopes": k.scopes,
                        "expires_at": k.expires_at,
                        "last_used_at": k.last_used_at,
                        "created_at": k.created_at,
                    })
                })
                .collect();
            return Some((200, serde_json::to_string(&payload).unwrap_or_else(|_| "[]".into())));
        }
    }
    if let Some(id) = url.strip_prefix("/api/auth/api-keys/") {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u,
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        if method == HttpMethod::Delete {
            // Verify ownership before revoking — a compromised api-key
            // shouldn't let an attacker revoke arbitrary other users' keys.
            match ctx.api_keys.list_for_user(user_id).iter().find(|k| k.id == id) {
                Some(_) => {
                    let revoked = ctx.api_keys.revoke(id);
                    return Some((
                        200,
                        serde_json::json!({"revoked": revoked}).to_string(),
                    ));
                }
                None => return Some((404, json_error("NOT_FOUND", "API key not found"))),
            }
        }
    }

    // ─── Password change (logged in) ───────────────────────────────────
    if url == "/api/auth/password/change" && method == HttpMethod::Post {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u.to_string(),
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        // P2 fix (codex Wave-2): API key auth cannot change passwords —
        // a leaked key shouldn't be able to lock the user out by
        // changing the password. Real session required.
        if ctx.auth_ctx.is_api_key_auth() {
            return Some((
                403,
                json_error(
                    "API_KEY_AUTH_FORBIDDEN",
                    "Password change requires a session, not an API key",
                ),
            ));
        }
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => {
                return Some((
                    400,
                    json_error_safe(
                        "INVALID_JSON",
                        "Invalid request body",
                        &format!("Invalid JSON: {e}"),
                    ),
                ));
            }
        };
        let current = data
            .get("currentPassword")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let new_password = match data.get("newPassword").and_then(|v| v.as_str()) {
            Some(p) => p,
            None => {
                return Some((
                    400,
                    json_error("MISSING_PASSWORD", "newPassword is required"),
                ));
            }
        };
        // Pull current row to verify old password (security rule:
        // session compromise alone shouldn't let an attacker change
        // the password and lock the user out).
        let row = match ctx.store.get_by_id(
            &ctx.store.manifest().auth.user.entity,
            &user_id,
        ) {
            Ok(Some(r)) => r,
            _ => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        let stored_hash = row
            .get("passwordHash")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        if stored_hash.is_empty() {
            return Some((
                400,
                json_error(
                    "NO_PASSWORD_SET",
                    "This account has no password (signed in via OAuth). Set one first.",
                ),
            ));
        }
        if !pylon_auth::password::verify_password(current, stored_hash) {
            return Some((
                401,
                json_error("WRONG_PASSWORD", "Current password is incorrect"),
            ));
        }
        if let Err(e) = pylon_auth::password::validate_length(new_password) {
            return Some((400, json_error("WEAK_PASSWORD", &e.to_string())));
        }
        if std::env::var("PYLON_DISABLE_HIBP").ok().as_deref() != Some("1") {
            if let Ok(n) = pylon_auth::password::check_pwned(new_password) {
                if n > 0 {
                    return Some((
                        400,
                        json_error_safe(
                            "PWNED_PASSWORD",
                            "This password has appeared in known data breaches.",
                            &format!("HIBP returned {n} occurrences"),
                        ),
                    ));
                }
            }
        }
        let new_hash = pylon_auth::password::hash_password(new_password);
        match ctx.store.update(
            &ctx.store.manifest().auth.user.entity,
            &user_id,
            &serde_json::json!({"passwordHash": new_hash}),
        ) {
            Ok(_) => {}
            Err(e) => return Some((400, json_error(&e.code, &e.message))),
        }
        // P1 fix (codex Wave-2): revoke ALL other sessions on
        // password change — better-auth pattern. A stolen session
        // shouldn't survive the password change that's meant to
        // contain its blast radius. We then re-mint a fresh session
        // for THIS request so the user isn't logged out of their
        // own password-change tab.
        let total_revoked = ctx.session_store.revoke_all_for_user(&user_id);
        let session = ctx.session_store.create(user_id.clone());
        ctx.maybe_set_session_cookie(&session.token);
        return Some((
            200,
            serde_json::json!({
                "changed": true,
                "revoked_sessions": total_revoked,
                "token": session.token,
                "expires_at": session.expires_at,
            })
            .to_string(),
        ));
    }

    // ─── TOTP (RFC 6238 — 6-digit, 30-second, HMAC-SHA1) ──────────────
    //
    // Two-step enrollment: POST /enroll returns a fresh secret +
    // provisioning URL (NOT yet active); POST /verify with a code from
    // the user's authenticator app finalizes it. Subsequent password /
    // magic-code logins don't auto-enforce TOTP — apps gate that
    // themselves by checking `User.totpVerified`. This matches
    // better-auth's "you bring the gate" stance.
    if url == "/api/auth/totp/enroll" && method == HttpMethod::Post {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u.to_string(),
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        if ctx.auth_ctx.is_api_key_auth() {
            return Some((
                403,
                json_error("API_KEY_AUTH_FORBIDDEN", "TOTP enrollment requires a session"),
            ));
        }
        // Fetch user row to derive the QR account label (their email).
        let row = match ctx
            .store
            .get_by_id(&ctx.store.manifest().auth.user.entity, &user_id)
        {
            Ok(Some(r)) => r,
            _ => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        // If TOTP is already verified, require a current TOTP code to
        // re-enroll. Defends against a session-cookie-only attacker
        // silently rotating the secret to one they control. Same posture
        // as password change requiring the current password.
        let already_verified = row
            .get("totpVerified")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        if already_verified {
            let data: serde_json::Value = serde_json::from_str(body).unwrap_or_default();
            let code = data.get("code").and_then(|v| v.as_str()).unwrap_or("");
            let stored_blob = row
                .get("totpSecret")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let secret_b32 = pylon_auth::totp::unseal_secret(stored_blob).unwrap_or_default();
            let secret = pylon_auth::totp::base32_decode(&secret_b32).unwrap_or_default();
            if !pylon_auth::totp::verify_now(&secret, code) {
                return Some((
                    401,
                    json_error(
                        "INVALID_TOTP_CODE",
                        "TOTP is already enrolled — provide a current code to rotate the secret",
                    ),
                ));
            }
        }
        let account = row
            .get("email")
            .and_then(|v| v.as_str())
            .unwrap_or(&user_id)
            .to_string();
        let issuer = std::env::var("PYLON_TOTP_ISSUER")
            .unwrap_or_else(|_| ctx.store.manifest().name.clone());

        let secret = pylon_auth::totp::generate_secret();
        let secret_b32 = pylon_auth::totp::base32_encode(&secret);
        let url_otp = pylon_auth::totp::provisioning_url(&issuer, &account, &secret_b32);
        // Persist the secret as PENDING (totpVerified=false), encrypted
        // at rest with PYLON_TOTP_ENCRYPTION_KEY. The app's user
        // entity needs `totpSecret: string?` + `totpVerified: bool?`.
        let sealed = pylon_auth::totp::seal_secret(&secret_b32);
        match ctx.store.update(
            &ctx.store.manifest().auth.user.entity,
            &user_id,
            &serde_json::json!({
                "totpSecret": sealed,
                "totpVerified": false,
            }),
        ) {
            Ok(_) => {}
            Err(e) => return Some((400, json_error(&e.code, &e.message))),
        }
        return Some((
            200,
            serde_json::json!({
                "secret": secret_b32,
                "url": url_otp,
                // Apps MAY render the QR code themselves; expose the
                // raw bytes too for non-web clients.
                "issuer": issuer,
                "account": account,
            })
            .to_string(),
        ));
    }

    if url == "/api/auth/totp/verify" && method == HttpMethod::Post {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u.to_string(),
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => {
                return Some((
                    400,
                    json_error_safe("INVALID_JSON", "Invalid request body", &format!("{e}")),
                ));
            }
        };
        let code = data
            .get("code")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .trim()
            .to_string();
        let row = match ctx
            .store
            .get_by_id(&ctx.store.manifest().auth.user.entity, &user_id)
        {
            Ok(Some(r)) => r,
            _ => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        let secret_blob = match row.get("totpSecret").and_then(|v| v.as_str()) {
            Some(s) if !s.is_empty() => s,
            _ => {
                return Some((
                    400,
                    json_error("TOTP_NOT_ENROLLED", "Call /api/auth/totp/enroll first"),
                ));
            }
        };
        let secret_b32 = match pylon_auth::totp::unseal_secret(secret_blob) {
            Ok(s) => s,
            Err(_) => return Some((500, json_error("TOTP_BAD_SECRET", "Stored secret is corrupt or PYLON_TOTP_ENCRYPTION_KEY missing"))),
        };
        let secret = match pylon_auth::totp::base32_decode(&secret_b32) {
            Ok(s) => s,
            Err(_) => return Some((500, json_error("TOTP_BAD_SECRET", "Stored secret is corrupt"))),
        };
        if !pylon_auth::totp::verify_now(&secret, &code) {
            return Some((401, json_error("INVALID_TOTP_CODE", "Wrong code")));
        }
        let was_verified = row
            .get("totpVerified")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        if !was_verified {
            // Stamp on first successful verify so the app knows
            // enrollment is finalized.
            match ctx.store.update(
                &ctx.store.manifest().auth.user.entity,
                &user_id,
                &serde_json::json!({"totpVerified": true}),
            ) {
                Ok(_) => {}
                Err(e) => return Some((400, json_error(&e.code, &e.message))),
            }
        }
        return Some((
            200,
            serde_json::json!({"verified": true, "enrolled": !was_verified}).to_string(),
        ));
    }

    if url == "/api/auth/totp/disable" && method == HttpMethod::Post {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u.to_string(),
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        if ctx.auth_ctx.is_api_key_auth() {
            return Some((
                403,
                json_error("API_KEY_AUTH_FORBIDDEN", "TOTP disable requires a session"),
            ));
        }
        // Require a current code to disable — defends against a
        // session-cookie-only attacker silently turning off 2FA.
        let data: serde_json::Value = serde_json::from_str(body).unwrap_or_default();
        let code = data.get("code").and_then(|v| v.as_str()).unwrap_or("");
        let row = match ctx
            .store
            .get_by_id(&ctx.store.manifest().auth.user.entity, &user_id)
        {
            Ok(Some(r)) => r,
            _ => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        if let Some(secret_blob) = row.get("totpSecret").and_then(|v| v.as_str()) {
            if !secret_blob.is_empty() {
                let secret_b32 =
                    pylon_auth::totp::unseal_secret(secret_blob).unwrap_or_default();
                let secret = pylon_auth::totp::base32_decode(&secret_b32).unwrap_or_default();
                if !pylon_auth::totp::verify_now(&secret, code) {
                    return Some((
                        401,
                        json_error(
                            "INVALID_TOTP_CODE",
                            "Provide a current TOTP code to disable 2FA",
                        ),
                    ));
                }
            }
        }
        match ctx.store.update(
            &ctx.store.manifest().auth.user.entity,
            &user_id,
            &serde_json::json!({"totpSecret": null, "totpVerified": false}),
        ) {
            Ok(_) => {}
            Err(e) => return Some((400, json_error(&e.code, &e.message))),
        }
        return Some((200, serde_json::json!({"disabled": true}).to_string()));
    }

    // ─── Organizations + invites ───────────────────────────────────────
    //
    // POST   /api/auth/orgs                          create org
    // GET    /api/auth/orgs                          list user's orgs
    // GET    /api/auth/orgs/:id                      org details
    // DELETE /api/auth/orgs/:id                      delete (owner only)
    // GET    /api/auth/orgs/:id/members              list members
    // PUT    /api/auth/orgs/:id/members/:user_id     change role (admin+)
    // DELETE /api/auth/orgs/:id/members/:user_id     remove member (admin+)
    // POST   /api/auth/orgs/:id/invites              send email invite
    // GET    /api/auth/orgs/:id/invites              list pending invites
    // DELETE /api/auth/orgs/:id/invites/:invite_id   revoke invite
    // POST   /api/auth/invites/:token/accept         accept (sets membership)
    if url == "/api/auth/orgs" {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u.to_string(),
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        if method == HttpMethod::Post {
            let data: serde_json::Value = match serde_json::from_str(body) {
                Ok(v) => v,
                Err(e) => {
                    return Some((
                        400,
                        json_error_safe("INVALID_JSON", "Invalid request body", &format!("{e}")),
                    ));
                }
            };
            let name = data
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .trim();
            if name.is_empty() {
                return Some((400, json_error("MISSING_NAME", "name is required")));
            }
            let org = ctx.orgs.create(name, &user_id);
            return Some((
                200,
                serde_json::json!({
                    "id": org.id,
                    "name": org.name,
                    "created_at": org.created_at,
                    "role": "owner",
                })
                .to_string(),
            ));
        }
        if method == HttpMethod::Get {
            let list = ctx.orgs.list_for_user(&user_id);
            let payload: Vec<serde_json::Value> = list
                .iter()
                .map(|(o, role)| {
                    serde_json::json!({
                        "id": o.id,
                        "name": o.name,
                        "role": role.as_str(),
                        "created_at": o.created_at,
                    })
                })
                .collect();
            return Some((200, serde_json::to_string(&payload).unwrap_or_else(|_| "[]".into())));
        }
    }

    if let Some(rest) = url.strip_prefix("/api/auth/orgs/") {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u.to_string(),
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        let parts: Vec<&str> = rest.splitn(4, '/').collect();
        let org_id = parts[0];

        // Caller must be a member to do anything below.
        let caller_role = match ctx.orgs.role_of(org_id, &user_id) {
            Some(r) => r,
            None => return Some((404, json_error("ORG_NOT_FOUND", "Org not found"))),
        };

        match parts.as_slice() {
            // /api/auth/orgs/:id
            [_id] if method == HttpMethod::Get => {
                let org = ctx.orgs.get(org_id).expect("role implies org exists");
                return Some((
                    200,
                    serde_json::json!({
                        "id": org.id,
                        "name": org.name,
                        "created_at": org.created_at,
                        "role": caller_role.as_str(),
                    })
                    .to_string(),
                ));
            }
            [_id] if method == HttpMethod::Delete => {
                if !caller_role.can_delete_org() {
                    return Some((403, json_error("FORBIDDEN", "Only owners can delete an org")));
                }
                let removed = ctx.orgs.delete(org_id);
                return Some((200, serde_json::json!({"deleted": removed}).to_string()));
            }
            // /api/auth/orgs/:id/members
            [_id, "members"] if method == HttpMethod::Get => {
                let list = ctx.orgs.list_members(org_id);
                let payload: Vec<serde_json::Value> = list
                    .iter()
                    .map(|m| {
                        serde_json::json!({
                            "user_id": m.user_id,
                            "role": m.role.as_str(),
                            "joined_at": m.joined_at,
                        })
                    })
                    .collect();
                return Some((200, serde_json::to_string(&payload).unwrap_or_else(|_| "[]".into())));
            }
            // /api/auth/orgs/:id/members/:user_id
            [_id, "members", target_user] if method == HttpMethod::Put => {
                if !caller_role.can_manage_members() {
                    return Some((403, json_error("FORBIDDEN", "Insufficient role")));
                }
                let data: serde_json::Value = serde_json::from_str(body).unwrap_or_default();
                let role_str = data
                    .get("role")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let role = match pylon_auth::org::OrgRole::from_str(role_str) {
                    Some(r) => r,
                    None => return Some((400, json_error("BAD_ROLE", "role must be owner|admin|member"))),
                };
                let updated = ctx.orgs.set_role(org_id, target_user, role);
                if !updated {
                    return Some((404, json_error("NOT_A_MEMBER", "Target user is not a member")));
                }
                return Some((200, serde_json::json!({"updated": true}).to_string()));
            }
            [_id, "members", target_user] if method == HttpMethod::Delete => {
                if !caller_role.can_manage_members() && target_user != &user_id.as_str() {
                    return Some((403, json_error("FORBIDDEN", "Insufficient role")));
                }
                // Prevent removing the LAST owner — would orphan the org.
                if let Some(target_role) = ctx.orgs.role_of(org_id, target_user) {
                    if target_role == pylon_auth::org::OrgRole::Owner {
                        let owners = ctx
                            .orgs
                            .list_members(org_id)
                            .into_iter()
                            .filter(|m| m.role == pylon_auth::org::OrgRole::Owner)
                            .count();
                        if owners <= 1 {
                            return Some((
                                400,
                                json_error(
                                    "LAST_OWNER",
                                    "Cannot remove the last owner — promote someone else first",
                                ),
                            ));
                        }
                    }
                }
                let removed = ctx.orgs.remove_member(org_id, target_user);
                return Some((200, serde_json::json!({"removed": removed}).to_string()));
            }
            // /api/auth/orgs/:id/invites
            [_id, "invites"] if method == HttpMethod::Post => {
                if !caller_role.can_manage_members() {
                    return Some((403, json_error("FORBIDDEN", "Insufficient role")));
                }
                let data: serde_json::Value = match serde_json::from_str(body) {
                    Ok(v) => v,
                    Err(e) => {
                        return Some((
                            400,
                            json_error_safe("INVALID_JSON", "Invalid request body", &format!("{e}")),
                        ));
                    }
                };
                let email = data
                    .get("email")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .trim();
                if email.is_empty() || !email.contains('@') {
                    return Some((400, json_error("INVALID_EMAIL", "valid email required")));
                }
                let role_str = data
                    .get("role")
                    .and_then(|v| v.as_str())
                    .unwrap_or("member");
                let role = pylon_auth::org::OrgRole::from_str(role_str)
                    .unwrap_or(pylon_auth::org::OrgRole::Member);
                let invited = ctx.orgs.create_invite(org_id, email, role, &user_id);
                // Best-effort email — failure to send still returns
                // success because the inviter can copy the link from
                // the response (apps can hide it in production).
                let org = ctx.orgs.get(org_id).expect("role implies exists");
                let accept_url = format!(
                    "{}/api/auth/invites/{}/accept",
                    std::env::var("PYLON_PUBLIC_URL").unwrap_or_else(|_| String::new()),
                    invited.token
                );
                let subject = format!("You've been invited to {}", org.name);
                let body_text = format!(
                    "You've been invited to join {} on Pylon.\n\nAccept here: {}\n\nThis link expires in 7 days.",
                    org.name, accept_url
                );
                if let Err(e) = ctx.email.send(email, &subject, &body_text) {
                    tracing::warn!("[org] invite email to {} failed: {e}", redact_email(email));
                }
                return Some((
                    200,
                    serde_json::json!({
                        "id": invited.invite.id,
                        "email": invited.invite.email,
                        "role": invited.invite.role.as_str(),
                        "expires_at": invited.invite.expires_at,
                        "accept_url": accept_url,
                        // Plaintext token so the inviter can copy/paste
                        // when email isn't configured (dev mode).
                        "token": if ctx.is_dev { Some(&invited.token) } else { None },
                    })
                    .to_string(),
                ));
            }
            [_id, "invites"] if method == HttpMethod::Get => {
                if !caller_role.can_manage_members() {
                    return Some((403, json_error("FORBIDDEN", "Insufficient role")));
                }
                let list = ctx.orgs.list_invites(org_id);
                let payload: Vec<serde_json::Value> = list
                    .iter()
                    .map(|i| {
                        serde_json::json!({
                            "id": i.id,
                            "email": i.email,
                            "role": i.role.as_str(),
                            "token_prefix": i.token_prefix,
                            "invited_by": i.invited_by,
                            "created_at": i.created_at,
                            "expires_at": i.expires_at,
                        })
                    })
                    .collect();
                return Some((200, serde_json::to_string(&payload).unwrap_or_else(|_| "[]".into())));
            }
            [_id, "invites", invite_id] if method == HttpMethod::Delete => {
                if !caller_role.can_manage_members() {
                    return Some((403, json_error("FORBIDDEN", "Insufficient role")));
                }
                let revoked = ctx.orgs.revoke_invite(invite_id);
                return Some((200, serde_json::json!({"revoked": revoked}).to_string()));
            }
            _ => {}
        }
    }

    // POST /api/auth/invites/:token/accept
    if let Some(rest) = url.strip_prefix("/api/auth/invites/") {
        if let Some(token) = rest.strip_suffix("/accept") {
            if method == HttpMethod::Post {
                let user_id = match ctx.auth_ctx.user_id.as_deref() {
                    Some(u) => u.to_string(),
                    None => return Some((401, json_error("AUTH_REQUIRED", "Login required to accept an invite"))),
                };
                // Pull the user's email from their row to verify the invite.
                let row = match ctx
                    .store
                    .get_by_id(&ctx.store.manifest().auth.user.entity, &user_id)
                {
                    Ok(Some(r)) => r,
                    _ => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
                };
                let email = match row.get("email").and_then(|v| v.as_str()) {
                    Some(e) => e,
                    None => return Some((400, json_error("NO_EMAIL", "Account has no email"))),
                };
                match ctx.orgs.accept_invite(token, &user_id, email) {
                    Ok(m) => {
                        return Some((
                            200,
                            serde_json::json!({
                                "org_id": m.org_id,
                                "role": m.role.as_str(),
                            })
                            .to_string(),
                        ));
                    }
                    Err(e) => {
                        let code = match e {
                            pylon_auth::org::AcceptError::NotFound => "INVITE_NOT_FOUND",
                            pylon_auth::org::AcceptError::Expired => "INVITE_EXPIRED",
                            pylon_auth::org::AcceptError::AlreadyAccepted => "ALREADY_ACCEPTED",
                            pylon_auth::org::AcceptError::EmailMismatch => "WRONG_EMAIL",
                            pylon_auth::org::AcceptError::AlreadyMember => "ALREADY_MEMBER",
                        };
                        return Some((400, json_error(code, &e.to_string())));
                    }
                }
            }
        }
    }

    // ─── Phone / SMS sign-in ──────────────────────────────────────────
    if url == "/api/auth/phone/send-code" && method == HttpMethod::Post {
        let data: serde_json::Value = serde_json::from_str(body).unwrap_or_default();
        let phone = data.get("phone").and_then(|v| v.as_str()).unwrap_or("");
        if let Some(cfg) = pylon_auth::captcha::CaptchaConfig::from_env() {
            let token = data.get("captchaToken").and_then(|v| v.as_str()).unwrap_or("");
            if cfg.verify(token, Some(ctx.peer_ip)).is_err() {
                return Some((400, json_error("CAPTCHA_FAILED", "CAPTCHA failed")));
            }
        }
        let code = match ctx.phone_codes.try_create(phone) {
            Ok(c) => c,
            Err(pylon_auth::phone::PhoneCodeError::Throttled { retry_after_secs }) => {
                return Some((
                    429,
                    json_error_with_hint("RATE_LIMITED", "Code requested too recently",
                        &format!("Try again in {retry_after_secs}s")),
                ));
            }
            Err(pylon_auth::phone::PhoneCodeError::InvalidPhone) => {
                return Some((400, json_error("INVALID_PHONE", "Phone must be E.164 (+15551234567)")));
            }
            Err(e) => return Some((500, json_error("PHONE_CODE_FAILED", &e.to_string()))),
        };
        let mut sent = false;
        if let Some(twilio) = pylon_auth::phone::TwilioSmsTransport::from_env() {
            use pylon_auth::phone::SmsSender;
            let body_text = format!("Your sign-in code is: {code}\nExpires in 10 minutes.");
            if let Err(e) = twilio.send_sms(phone, &body_text) {
                tracing::warn!("[phone] twilio send failed: {e}");
            } else {
                sent = true;
            }
        }
        let mut response = serde_json::json!({"sent": sent, "phone": phone});
        if ctx.is_dev || !sent {
            response["dev_code"] = serde_json::Value::String(code);
        }
        return Some((200, response.to_string()));
    }

    if url == "/api/auth/phone/verify" && method == HttpMethod::Post {
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => return Some((400, json_error_safe("INVALID_JSON", "Invalid request body", &format!("{e}")))),
        };
        let phone = data.get("phone").and_then(|v| v.as_str()).unwrap_or("");
        let code = data.get("code").and_then(|v| v.as_str()).unwrap_or("");
        let display_name = data.get("displayName").and_then(|v| v.as_str()).map(String::from);
        if let Err(e) = ctx.phone_codes.try_verify(phone, code) {
            let http_code = match e {
                pylon_auth::phone::PhoneCodeError::TooManyAttempts => 429,
                pylon_auth::phone::PhoneCodeError::InvalidPhone => 400,
                _ => 401,
            };
            return Some((http_code, json_error("INVALID_CODE", &e.to_string())));
        }
        let normalized = pylon_auth::phone::normalize(phone).expect("verified above");
        let entity = &ctx.store.manifest().auth.user.entity;
        let user_id = match ctx.store.lookup(entity, "phone", &normalized) {
            Ok(Some(row)) => row.get("id").and_then(|v| v.as_str()).unwrap_or_default().to_string(),
            _ => {
                let now = format!("{}Z", std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs());
                let dn = display_name.unwrap_or_else(|| normalized.clone());
                match ctx.store.insert(entity, &serde_json::json!({
                    "phone": normalized,
                    "displayName": dn,
                    "phoneVerified": now.clone(),
                    "createdAt": now,
                })) {
                    Ok(id) => id,
                    Err(e) => return Some((400, json_error(&e.code, &e.message))),
                }
            }
        };
        let session = ctx.session_store.create(user_id.clone());
        ctx.maybe_set_session_cookie(&session.token);
        return Some((200, serde_json::json!({
            "token": session.token, "user_id": user_id, "expires_at": session.expires_at
        }).to_string()));
    }

    // ─── SIWE — Sign-In With Ethereum ─────────────────────────────────
    if let Some(rest) = url.strip_prefix("/api/auth/siwe/nonce") {
        if method == HttpMethod::Get {
            let q = rest.trim_start_matches('?');
            let params = parse_query(q);
            let addr = params.get("address").map(|s| s.as_str()).unwrap_or("");
            if !addr.starts_with("0x") || addr.len() != 42 {
                return Some((400, json_error("INVALID_ADDRESS", "address must be 0x + 40 hex chars")));
            }
            let nonce = ctx.siwe.issue(addr);
            return Some((200, serde_json::json!({"nonce": nonce}).to_string()));
        }
    }
    if url == "/api/auth/siwe/verify" && method == HttpMethod::Post {
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => return Some((400, json_error_safe("INVALID_JSON", "Invalid body", &format!("{e}")))),
        };
        let message_text = data.get("message").and_then(|v| v.as_str()).unwrap_or("");
        let sig_hex = data.get("signature").and_then(|v| v.as_str()).unwrap_or("");
        let display_name = data.get("displayName").and_then(|v| v.as_str()).map(String::from);
        let parsed = match pylon_auth::siwe::parse_message(message_text) {
            Ok(m) => m,
            Err(e) => return Some((400, json_error("SIWE_BAD_MESSAGE", &e.to_string()))),
        };
        let expected_domain = ctx.request_headers.iter()
            .find(|(k, _)| k.eq_ignore_ascii_case("host"))
            .map(|(_, v)| v.split(':').next().unwrap_or(v).to_string())
            .unwrap_or_else(|| parsed.domain.clone());
        let recovered = match pylon_auth::siwe::verify(ctx.siwe, &parsed, sig_hex, &expected_domain) {
            Ok(addr) => addr,
            Err(e) => return Some((401, json_error("SIWE_VERIFY_FAILED", &e.to_string()))),
        };
        let entity = &ctx.store.manifest().auth.user.entity;
        let user_id = match ctx.store.lookup(entity, "walletAddress", &recovered) {
            Ok(Some(row)) => row.get("id").and_then(|v| v.as_str()).unwrap_or_default().to_string(),
            _ => {
                let now = format!("{}Z", std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs());
                let dn = display_name.unwrap_or_else(|| {
                    format!("{}{}", &recovered[..6], &recovered[recovered.len() - 4..])
                });
                match ctx.store.insert(entity, &serde_json::json!({
                    "walletAddress": recovered,
                    "displayName": dn,
                    "createdAt": now,
                })) {
                    Ok(id) => id,
                    Err(e) => return Some((400, json_error(&e.code, &e.message))),
                }
            }
        };
        let session = ctx.session_store.create(user_id.clone());
        ctx.maybe_set_session_cookie(&session.token);
        return Some((200, serde_json::json!({
            "token": session.token, "user_id": user_id, "address": recovered,
            "expires_at": session.expires_at
        }).to_string()));
    }

    // ─── WebAuthn / passkeys ──────────────────────────────────────────
    if url == "/api/auth/passkey/register/begin" && method == HttpMethod::Post {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u.to_string(),
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        let row = ctx.store.get_by_id(&ctx.store.manifest().auth.user.entity, &user_id).ok().flatten();
        let user_name = row.as_ref().and_then(|r| r.get("email")).and_then(|v| v.as_str())
            .unwrap_or(&user_id).to_string();
        let challenge = ctx.passkeys.mint_challenge(user_id.clone(),
            pylon_auth::webauthn::ChallengeKind::Registration);
        let rp_id = std::env::var("PYLON_WEBAUTHN_RP_ID").unwrap_or_else(|_| "localhost".into());
        return Some((200, serde_json::json!({
            "challenge": challenge, "rpId": rp_id, "userId": user_id, "userName": user_name
        }).to_string()));
    }
    if url == "/api/auth/passkey/register/finish" && method == HttpMethod::Post {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u.to_string(),
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => return Some((400, json_error_safe("INVALID_JSON", "Invalid body", &format!("{e}")))),
        };
        let challenge = data.get("challenge").and_then(|v| v.as_str()).unwrap_or("");
        let cred_id = data.get("credentialId").and_then(|v| v.as_str()).unwrap_or("");
        let public_key_b64 = data.get("publicKey").and_then(|v| v.as_str()).unwrap_or("");
        let name = data.get("name").and_then(|v| v.as_str()).unwrap_or("passkey").to_string();
        if cred_id.is_empty() || public_key_b64.is_empty() {
            return Some((400, json_error("MISSING_FIELD", "credentialId + publicKey required")));
        }
        if ctx.passkeys.take_challenge(challenge,
            pylon_auth::webauthn::ChallengeKind::Registration).is_none() {
            return Some((401, json_error("BAD_CHALLENGE", "Challenge missing or expired")));
        }
        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
        let public_key = match URL_SAFE_NO_PAD.decode(public_key_b64) {
            Ok(b) => b,
            Err(e) => return Some((400, json_error("BAD_PUBKEY", &format!("not base64url: {e}")))),
        };
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
        ctx.passkeys.store_passkey(pylon_auth::webauthn::Passkey {
            id: cred_id.to_string(), user_id, public_key, sign_count: 0,
            name, created_at: now, last_used_at: None,
        });
        return Some((200, serde_json::json!({"registered": true, "id": cred_id}).to_string()));
    }
    if url == "/api/auth/passkey/login/begin" && method == HttpMethod::Post {
        let challenge = ctx.passkeys.mint_challenge(String::new(),
            pylon_auth::webauthn::ChallengeKind::Assertion);
        let rp_id = std::env::var("PYLON_WEBAUTHN_RP_ID").unwrap_or_else(|_| "localhost".into());
        return Some((200, serde_json::json!({"challenge": challenge, "rpId": rp_id}).to_string()));
    }
    if url == "/api/auth/passkey/login/finish" && method == HttpMethod::Post {
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => return Some((400, json_error_safe("INVALID_JSON", "Invalid body", &format!("{e}")))),
        };
        let cred_id = data.get("credentialId").and_then(|v| v.as_str()).unwrap_or("");
        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
        let auth_data = URL_SAFE_NO_PAD.decode(
            data.get("authenticatorData").and_then(|v| v.as_str()).unwrap_or("")).unwrap_or_default();
        let client_data = URL_SAFE_NO_PAD.decode(
            data.get("clientDataJSON").and_then(|v| v.as_str()).unwrap_or("")).unwrap_or_default();
        let sig = URL_SAFE_NO_PAD.decode(
            data.get("signature").and_then(|v| v.as_str()).unwrap_or("")).unwrap_or_default();
        let expected_origin = std::env::var("PYLON_WEBAUTHN_ORIGIN")
            .unwrap_or_else(|_| "https://localhost".into());
        let expected_rp_id = std::env::var("PYLON_WEBAUTHN_RP_ID")
            .unwrap_or_else(|_| "localhost".into());
        let input = pylon_auth::webauthn::AssertionInput {
            credential_id: cred_id, authenticator_data: &auth_data,
            client_data_json: &client_data, signature: &sig, user_handle: None,
        };
        let key = match pylon_auth::webauthn::verify_assertion(
            ctx.passkeys, &input, &expected_origin, &expected_rp_id, None) {
            Ok(k) => k,
            Err(e) => return Some((401, json_error("PASSKEY_VERIFY_FAILED", &e.to_string()))),
        };
        let session = ctx.session_store.create(key.user_id.clone());
        ctx.maybe_set_session_cookie(&session.token);
        return Some((200, serde_json::json!({
            "token": session.token, "user_id": key.user_id, "expires_at": session.expires_at
        }).to_string()));
    }
    if url == "/api/auth/passkey/keys" && method == HttpMethod::Get {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u.to_string(),
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        let payload: Vec<serde_json::Value> = ctx.passkeys.list_for_user(&user_id).iter()
            .map(|k| serde_json::json!({
                "id": k.id, "name": k.name, "created_at": k.created_at,
                "last_used_at": k.last_used_at,
            })).collect();
        return Some((200, serde_json::to_string(&payload).unwrap_or_else(|_| "[]".into())));
    }
    if let Some(id) = url.strip_prefix("/api/auth/passkey/keys/") {
        if method == HttpMethod::Delete {
            let user_id = match ctx.auth_ctx.user_id.as_deref() {
                Some(u) => u.to_string(),
                None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
            };
            match ctx.passkeys.get_passkey(id) {
                Some(k) if k.user_id == user_id => {
                    let removed = ctx.passkeys.delete(id);
                    return Some((200, serde_json::json!({"deleted": removed}).to_string()));
                }
                _ => return Some((404, json_error("NOT_FOUND", "Passkey not found"))),
            }
        }
    }

    // ─── SCIM 2.0 ─────────────────────────────────────────────────────
    // Bearer-token gated via PYLON_SCIM_TOKEN. Apps that don't
    // configure this env var get a 503 — refusing silently would
    // leave the surface looking broken.
    if let Some(rest) = url.strip_prefix("/scim/v2/") {
        let auth = ctx.request_headers.iter()
            .find(|(k, _)| k.eq_ignore_ascii_case("authorization"))
            .map(|(_, v)| v.as_str());
        if !pylon_auth::scim::check_bearer(auth) {
            return Some((401, serde_json::to_string(
                &pylon_auth::scim::ScimError::new(401, "missing or invalid SCIM bearer token")
            ).unwrap_or_default()));
        }
        let entity = &ctx.store.manifest().auth.user.entity;
        let parts: Vec<&str> = rest.splitn(2, '/').collect();
        match (parts.as_slice(), method) {
            // POST /scim/v2/Users
            (["Users"], HttpMethod::Post) => {
                let scim_user: pylon_auth::scim::ScimUser = match serde_json::from_str(body) {
                    Ok(u) => u,
                    Err(e) => return Some((400, serde_json::to_string(
                        &pylon_auth::scim::ScimError::new(400, &format!("invalid SCIM JSON: {e}"))
                    ).unwrap_or_default())),
                };
                let now = format!("{}Z", std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs());
                let row = serde_json::json!({
                    "email": scim_user.primary_email(),
                    "displayName": scim_user.pretty_display_name(),
                    "scimId": scim_user.id,
                    "scimActive": scim_user.active,
                    "createdAt": now,
                });
                match ctx.store.insert(entity, &row) {
                    Ok(id) => {
                        let mut response = scim_user;
                        response.id = Some(id);
                        return Some((201, serde_json::to_string(&response).unwrap_or_default()));
                    }
                    Err(e) => return Some((409, serde_json::to_string(
                        &pylon_auth::scim::ScimError::new(409, &e.message)
                    ).unwrap_or_default())),
                }
            }
            (["Users"], HttpMethod::Get) => {
                let list = ctx.store.list(entity).unwrap_or_default();
                let users: Vec<pylon_auth::scim::ScimUser> = list.iter().filter_map(|row| {
                    let email = row.get("email").and_then(|v| v.as_str())?.to_string();
                    let id = row.get("id").and_then(|v| v.as_str()).map(String::from);
                    let active = row.get("scimActive").and_then(|v| v.as_bool()).unwrap_or(true);
                    let display_name = row.get("displayName").and_then(|v| v.as_str()).map(String::from);
                    Some(pylon_auth::scim::ScimUser {
                        id, user_name: email.clone(), active,
                        name: None,
                        emails: vec![pylon_auth::scim::ScimEmail {
                            value: email, primary: Some(true), kind: Some("work".into()),
                        }],
                        display_name,
                        schemas: vec!["urn:ietf:params:scim:schemas:core:2.0:User".into()],
                    })
                }).collect();
                return Some((200, serde_json::to_string(
                    &pylon_auth::scim::ScimListResponse::new(users)
                ).unwrap_or_default()));
            }
            (["Users", id], HttpMethod::Get) => {
                let row = match ctx.store.get_by_id(entity, id) {
                    Ok(Some(r)) => r,
                    _ => return Some((404, serde_json::to_string(
                        &pylon_auth::scim::ScimError::new(404, "user not found")
                    ).unwrap_or_default())),
                };
                let email = row.get("email").and_then(|v| v.as_str()).unwrap_or("").to_string();
                let user = pylon_auth::scim::ScimUser {
                    id: Some(id.to_string()),
                    user_name: email.clone(),
                    active: row.get("scimActive").and_then(|v| v.as_bool()).unwrap_or(true),
                    name: None,
                    emails: vec![pylon_auth::scim::ScimEmail {
                        value: email, primary: Some(true), kind: Some("work".into()),
                    }],
                    display_name: row.get("displayName").and_then(|v| v.as_str()).map(String::from),
                    schemas: vec!["urn:ietf:params:scim:schemas:core:2.0:User".into()],
                };
                return Some((200, serde_json::to_string(&user).unwrap_or_default()));
            }
            (["Users", id], HttpMethod::Delete) => {
                // SCIM DELETE = soft delete (set scimActive=false). Hard
                // delete left to the host app's account-deletion flow.
                let _ = ctx.store.update(entity, id, &serde_json::json!({"scimActive": false}));
                return Some((204, String::new()));
            }
            _ => {}
        }
    }

    // ─── OIDC Provider — discovery + JWKS only (auth-code flow Wave 6) ─
    // Apps that want pylon as their IdP get the discovery doc + JWKS
    // for free. Token issuance reuses the existing JWT mint.
    if url == "/.well-known/openid-configuration" && method == HttpMethod::Get {
        let issuer = std::env::var("PYLON_OIDC_ISSUER").unwrap_or_else(|_| {
            ctx.request_headers.iter()
                .find(|(k, _)| k.eq_ignore_ascii_case("host"))
                .map(|(_, v)| format!("https://{v}"))
                .unwrap_or_else(|| "http://localhost:4321".into())
        });
        let doc = pylon_auth::oidc_provider::DiscoveryDoc::for_issuer(&issuer);
        return Some((200, serde_json::to_string(&doc).unwrap_or_default()));
    }
    if url == "/oidc/jwks" && method == HttpMethod::Get {
        // We mint HS256 JWTs (Wave 3); HS256 doesn't publish a public
        // key (symmetric). When PYLON_OIDC_JWKS_RSA_N + _E are set,
        // we publish them — apps that have rotated to RSA can drop the
        // PEM-encoded modulus + exponent into env at deploy.
        let n = std::env::var("PYLON_OIDC_JWKS_RSA_N").unwrap_or_default();
        let e = std::env::var("PYLON_OIDC_JWKS_RSA_E").unwrap_or_else(|_| "AQAB".into());
        let kid = std::env::var("PYLON_OIDC_JWKS_KID").unwrap_or_else(|_| "pylon-default".into());
        let keys = if n.is_empty() {
            // No RSA key configured → empty JWKS (correct OIDC response;
            // means "no asymmetric verification keys published").
            vec![]
        } else {
            vec![pylon_auth::oidc_provider::Jwk {
                kty: "RSA".into(), alg: "RS256".into(), use_: "sig".into(),
                kid, n, e,
            }]
        };
        return Some((200, serde_json::to_string(
            &pylon_auth::oidc_provider::Jwks { keys }
        ).unwrap_or_default()));
    }

    // ─── Stripe billing ────────────────────────────────────────────────
    //
    // POST /api/billing/checkout — mint a Stripe Checkout Session for
    //   the authenticated user. Body: `{ priceIds: [...], mode:
    //   "subscription"|"payment", successUrl, cancelUrl }`.
    // POST /api/billing/webhook — Stripe sends events here. Pylon
    //   verifies signature; an app-defined plugin hook
    //   (`plugin_hooks.on_billing_event`) handles the parsed event.
    if url == "/api/billing/checkout" && method == HttpMethod::Post {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u.to_string(),
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        let cfg = match pylon_auth::stripe::StripeConfig::from_env() {
            Some(c) => c,
            None => {
                return Some((
                    501,
                    json_error_with_hint(
                        "STRIPE_NOT_CONFIGURED",
                        "Stripe billing is disabled",
                        "Set PYLON_STRIPE_API_KEY (sk_test_… or sk_live_…) to enable",
                    ),
                ));
            }
        };
        let data: serde_json::Value = match serde_json::from_str(body) {
            Ok(v) => v,
            Err(e) => {
                return Some((
                    400,
                    json_error_safe("INVALID_JSON", "Invalid request body", &format!("{e}")),
                ));
            }
        };
        let price_ids: Vec<&str> = data
            .get("priceIds")
            .and_then(|v| v.as_array())
            .map(|a| a.iter().filter_map(|v| v.as_str()).collect())
            .unwrap_or_default();
        if price_ids.is_empty() {
            return Some((400, json_error("MISSING_PRICES", "priceIds is required")));
        }
        let mode = match data.get("mode").and_then(|v| v.as_str()).unwrap_or("subscription") {
            "payment" => pylon_auth::stripe::CheckoutMode::Payment,
            _ => pylon_auth::stripe::CheckoutMode::Subscription,
        };
        let success_url = data
            .get("successUrl")
            .and_then(|v| v.as_str())
            .unwrap_or("/billing/success");
        let cancel_url = data
            .get("cancelUrl")
            .and_then(|v| v.as_str())
            .unwrap_or("/billing/cancel");
        // Pull existing customer id from the user row (or create
        // one). Apps should add `stripeCustomerId: string?` to their
        // User entity.
        let row = ctx
            .store
            .get_by_id(&ctx.store.manifest().auth.user.entity, &user_id)
            .ok()
            .flatten();
        let mut customer_id = row
            .as_ref()
            .and_then(|r| r.get("stripeCustomerId"))
            .and_then(|v| v.as_str())
            .map(String::from);
        if customer_id.is_none() {
            let email = row
                .as_ref()
                .and_then(|r| r.get("email"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            match cfg.create_customer(email, None) {
                Ok(c) => {
                    let _ = ctx.store.update(
                        &ctx.store.manifest().auth.user.entity,
                        &user_id,
                        &serde_json::json!({"stripeCustomerId": c.id}),
                    );
                    customer_id = Some(c.id);
                }
                Err(e) => {
                    tracing::warn!("[stripe] customer create failed: {e}");
                    return Some((
                        502,
                        json_error("STRIPE_FAILED", "Could not create Stripe customer"),
                    ));
                }
            }
        }
        match cfg.create_checkout(
            customer_id.as_deref(),
            &price_ids,
            mode,
            success_url,
            cancel_url,
        ) {
            Ok(s) => return Some((
                200,
                serde_json::json!({"url": s.url, "id": s.id}).to_string(),
            )),
            Err(e) => {
                tracing::warn!("[stripe] checkout create failed: {e}");
                return Some((502, json_error("STRIPE_FAILED", "Could not create checkout session")));
            }
        }
    }
    if url == "/api/billing/webhook" && method == HttpMethod::Post {
        let cfg = match pylon_auth::stripe::StripeConfig::from_env() {
            Some(c) => c,
            None => return Some((501, json_error("STRIPE_NOT_CONFIGURED", "Stripe disabled"))),
        };
        let secret = match cfg.webhook_secret {
            Some(s) => s,
            None => return Some((501, json_error("WEBHOOK_NOT_CONFIGURED", "Set PYLON_STRIPE_WEBHOOK_SECRET"))),
        };
        let sig_header = ctx
            .request_headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case("stripe-signature"))
            .map(|(_, v)| v.as_str())
            .unwrap_or("");
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        // body.as_bytes() is safe here because Stripe webhooks are
        // always JSON, JSON is always UTF-8, and the upstream
        // read_to_string preserves UTF-8 byte-for-byte. If a future
        // protocol carries non-UTF-8 bodies past read_to_string,
        // this assumption breaks — switch the dispatcher to bytes.
        let event = match pylon_auth::stripe::verify_webhook(&secret, body.as_bytes(), sig_header, now) {
            Ok(e) => e,
            Err(e) => {
                tracing::warn!("[stripe] webhook verify failed: {e}");
                return Some((400, json_error("WEBHOOK_INVALID", &e.to_string())));
            }
        };
        // For now we just log + return 200. A future hook lets apps
        // react via plugin (`plugin_hooks.on_billing_event`).
        tracing::info!("[stripe] event: {event:?}");
        return Some((200, serde_json::json!({"received": true}).to_string()));
    }

    // ─── Account deletion ──────────────────────────────────────────────
    //
    // DELETE /api/auth/account — wipes the user row, revokes all
    // sessions, deletes all API keys, removes linked accounts. The
    // app-defined `User` entity is the source of truth so other tables
    // that reference it cascade through whatever FK story the schema
    // has set up.
    if url == "/api/auth/account" && method == HttpMethod::Delete {
        let user_id = match ctx.auth_ctx.user_id.as_deref() {
            Some(u) => u.to_string(),
            None => return Some((401, json_error("AUTH_REQUIRED", "Login required"))),
        };
        // P2 fix: API key auth cannot delete the account.
        if ctx.auth_ctx.is_api_key_auth() {
            return Some((
                403,
                json_error(
                    "API_KEY_AUTH_FORBIDDEN",
                    "Account deletion requires a session, not an API key",
                ),
            ));
        }
        // Revoke sessions first so a slow user-row delete doesn't
        // leave the attacker with a usable session.
        let revoked_sessions = ctx.session_store.revoke_all_for_user(&user_id);
        // Delete all api keys for this user.
        let mut revoked_keys = 0;
        for key in ctx.api_keys.list_for_user(&user_id) {
            if ctx.api_keys.revoke(&key.id) {
                revoked_keys += 1;
            }
        }
        // Remove all linked OAuth accounts (codex P2). App-owned
        // tables that reference the user are NOT cascade-deleted by
        // pylon — the host schema is the source of truth and must
        // declare its own deletion semantics. The /api/auth/account
        // docs call this out so apps register a `before-delete-user`
        // hook to purge their tables.
        let revoked_accounts = ctx.account_store.delete_for_user(&user_id);
        // Delete the user row.
        match ctx
            .store
            .delete(&ctx.store.manifest().auth.user.entity, &user_id)
        {
            Ok(_) => {}
            Err(e) => return Some((400, json_error(&e.code, &e.message))),
        }
        ctx.add_response_header("Set-Cookie", ctx.cookie_config.clear_value());
        return Some((
            200,
            serde_json::json!({
                "deleted": true,
                "revoked_sessions": revoked_sessions,
                "revoked_api_keys": revoked_keys,
                "unlinked_accounts": revoked_accounts,
            })
            .to_string(),
        ));
    }

    None
}

/// Project a User row down to the fields safe for `/api/auth/session`.
///
/// Defaults strip `passwordHash` + anything starting with `_`
/// (framework-internal). The manifest's `auth.user.expose` /
/// `auth.user.hide` config refines this:
/// - `expose` (allowlist): when non-empty, ONLY listed fields appear
///   (`id` is always included). Useful for apps with strict client
///   schemas.
/// - `hide` (blocklist): additional fields to strip on top of defaults.
///   Use for app-specific secrets stored on the User row.
fn project_user_row(
    row: serde_json::Value,
    cfg: &pylon_kernel::ManifestAuthUserConfig,
) -> serde_json::Value {
    let serde_json::Value::Object(obj) = row else {
        return row;
    };
    let filtered: serde_json::Map<String, serde_json::Value> = obj
        .into_iter()
        .filter(|(k, _)| {
            if k == "id" {
                return true; // always include id
            }
            // Allowlist takes precedence: only `expose` fields pass.
            if !cfg.expose.is_empty() && !cfg.expose.iter().any(|f| f == k) {
                return false;
            }
            // Default + manifest blocklist.
            if k == "passwordHash" || k.starts_with('_') {
                return false;
            }
            if cfg.hide.iter().any(|f| f == k) {
                return false;
            }
            true
        })
        .collect();
    serde_json::Value::Object(filtered)
}