nyx-scanner 0.5.0

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

pub fn collect_top_level_units(
    root: Node<'_>,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
    model: &mut AuthorizationModel,
) {
    let file_meta = FileMeta::scan(root, bytes);
    for idx in 0..root.named_child_count() {
        let Some(child) = root.named_child(idx as u32) else {
            continue;
        };
        collect_top_level_from_node(child, bytes, rules, model, &file_meta);
    }
}

fn collect_top_level_from_node(
    node: Node<'_>,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
    model: &mut AuthorizationModel,
    file_meta: &FileMeta,
) {
    match node.kind() {
        "function_declaration"
        | "function_definition"
        | "method_declaration"
        | "function_item"
        | "method"
        | "singleton_method" => {
            model.units.push(build_function_unit_with_meta(
                node,
                AnalysisUnitKind::Function,
                function_name(node, bytes),
                bytes,
                rules,
                Some(file_meta),
            ));
        }
        "decorated_definition"
            if decorated_definition_child(node)
                .is_some_and(|definition| definition.kind() == "function_definition") =>
        {
            model.units.push(build_function_unit_with_meta(
                node,
                AnalysisUnitKind::Function,
                function_name(node, bytes),
                bytes,
                rules,
                Some(file_meta),
            ));
        }
        "lexical_declaration" | "variable_declaration" => {
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                if child.kind() == "variable_declarator"
                    && let Some(unit) =
                        function_unit_from_var_declarator(child, bytes, rules, Some(file_meta))
                {
                    model.units.push(unit);
                }
            }
        }
        "export_statement" => {
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                if child.is_named() {
                    collect_top_level_from_node(child, bytes, rules, model, file_meta);
                }
            }
        }
        "program" | "source_file" | "module" | "class" | "class_declaration" | "class_body"
        | "body_statement" => {
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                collect_top_level_from_node(child, bytes, rules, model, file_meta);
            }
        }
        _ => {}
    }
}

fn function_unit_from_var_declarator(
    node: Node<'_>,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
    file_meta: Option<&FileMeta>,
) -> Option<AnalysisUnit> {
    let value = node.child_by_field_name("value")?;
    if !is_function_like(value) {
        return None;
    }
    let name = node
        .child_by_field_name("name")
        .map(|n| text(n, bytes))
        .filter(|s| !s.is_empty());
    Some(build_function_unit_with_meta(
        value,
        AnalysisUnitKind::Function,
        name,
        bytes,
        rules,
        file_meta,
    ))
}

pub struct ResolvedHandler {
    pub unit_idx: usize,
    pub span: (usize, usize),
    pub params: Vec<String>,
    pub line: usize,
}

pub fn visit_named_nodes(node: Node<'_>, visit: &mut impl FnMut(Node<'_>)) {
    visit(node);
    for child in named_children(node) {
        visit_named_nodes(child, visit);
    }
}

pub fn attach_route_handler(
    root: Node<'_>,
    handler_expr: Node<'_>,
    route_name: String,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
    model: &mut AuthorizationModel,
) -> Option<ResolvedHandler> {
    let handler_node = resolve_handler_node(root, handler_expr, bytes)?;
    let unit_idx = model.units.len();
    // `attach_route_handler` is called by route-aware extractors (express,
    // koa, fastify, axum, …) which already hold the file root.  Build
    // the FileMeta once here so the JS/TS TRPC pre-scan only walks the
    // top-level decl set per file (instead of per route).
    let file_meta = FileMeta::scan(root, bytes);
    let unit = build_function_unit_with_meta(
        handler_node,
        AnalysisUnitKind::RouteHandler,
        Some(route_name),
        bytes,
        rules,
        Some(&file_meta),
    );
    let params = unit.params.clone();
    let line = handler_node.start_position().row + 1;
    let span = span(handler_node);
    model.units.push(unit);
    Some(ResolvedHandler {
        unit_idx,
        span,
        params,
        line,
    })
}

/// Per-file metadata gathered once at the top of
/// [`collect_top_level_units`] / [`attach_route_handler`] and passed
/// down through unit construction.  Currently carries the set of TS
/// type-alias names whose body references a TRPC-marker type; future
/// fields can be added without changing the per-unit signature.
#[derive(Default, Debug, Clone)]
pub struct FileMeta {
    pub trpc_alias_names: HashSet<String>,
}

impl FileMeta {
    pub fn scan(root: Node<'_>, bytes: &[u8]) -> Self {
        let mut trpc_alias_names = HashSet::new();
        scan_trpc_aliases_visit(root, bytes, &mut trpc_alias_names);
        Self { trpc_alias_names }
    }
}

pub fn push_route_registration(
    model: &mut AuthorizationModel,
    framework: Framework,
    method: HttpMethod,
    path: String,
    file: &Path,
    handler: ResolvedHandler,
    middleware_calls: Vec<CallSite>,
) {
    model.routes.push(RouteRegistration {
        framework,
        method,
        path,
        middleware: middleware_names(&middleware_calls),
        handler_span: handler.span,
        handler_params: handler.params,
        file: file.to_path_buf(),
        line: handler.line,
        unit_idx: handler.unit_idx,
        middleware_calls,
    });
}

pub fn middleware_names(middleware_calls: &[CallSite]) -> Vec<String> {
    middleware_calls
        .iter()
        .map(|call| call.name.clone())
        .collect()
}

pub fn resolve_handler_node<'tree>(
    root: Node<'tree>,
    handler_expr: Node<'tree>,
    bytes: &[u8],
) -> Option<Node<'tree>> {
    if is_function_like(handler_expr) {
        return Some(handler_expr);
    }

    if !is_handler_reference(handler_expr) {
        return None;
    }

    let candidate = callee_name(handler_expr, bytes);
    let name = candidate.rsplit('.').next().unwrap_or(&candidate);
    if name.is_empty() {
        return None;
    }
    find_top_level_function_node(root, name, bytes)
}

fn find_top_level_function_node<'tree>(
    root: Node<'tree>,
    name: &str,
    bytes: &[u8],
) -> Option<Node<'tree>> {
    for idx in 0..root.named_child_count() {
        let Some(child) = root.named_child(idx as u32) else {
            continue;
        };
        if let Some(found) = find_top_level_function_node_in_child(child, name, bytes) {
            return Some(found);
        }
    }
    None
}

fn find_top_level_function_node_in_child<'tree>(
    node: Node<'tree>,
    name: &str,
    bytes: &[u8],
) -> Option<Node<'tree>> {
    match node.kind() {
        "function_declaration" | "function_definition" | "method_declaration" => {
            if function_name(node, bytes).as_deref() == Some(name) {
                Some(node)
            } else {
                None
            }
        }
        "function_item" => {
            if function_name(node, bytes).as_deref() == Some(name) {
                Some(node)
            } else {
                None
            }
        }
        "decorated_definition" => {
            let definition = decorated_definition_child(node)?;
            if definition.kind() == "function_definition"
                && function_name(node, bytes).as_deref() == Some(name)
            {
                Some(node)
            } else {
                None
            }
        }
        "lexical_declaration" | "variable_declaration" => {
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                if child.kind() != "variable_declarator" {
                    continue;
                }
                let Some(var_name) = child.child_by_field_name("name") else {
                    continue;
                };
                if text(var_name, bytes) != name {
                    continue;
                }
                let Some(value) = child.child_by_field_name("value") else {
                    continue;
                };
                if is_function_like(value) {
                    return Some(value);
                }
            }
            None
        }
        "export_statement" => {
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                if child.is_named()
                    && let Some(found) = find_top_level_function_node_in_child(child, name, bytes)
                {
                    return Some(found);
                }
            }
            None
        }
        "program" | "source_file" | "class_declaration" | "class_body" => {
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                if let Some(found) = find_top_level_function_node_in_child(child, name, bytes) {
                    return Some(found);
                }
            }
            None
        }
        _ => None,
    }
}

pub fn build_function_unit(
    node: Node<'_>,
    kind: AnalysisUnitKind,
    name: Option<String>,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
) -> AnalysisUnit {
    build_function_unit_with_meta(node, kind, name, bytes, rules, None)
}

/// Internal variant of [`build_function_unit`] that accepts a
/// pre-computed file-level [`FileMeta`].  When `file_meta` is
/// `Some`, its `trpc_alias_names` set is copied into `UnitState`
/// once per unit so the per-parameter pre-pass doesn't re-scan the
/// source-file root.  Pre-built `FileMeta` is required to keep
/// `tests/hostile_input_tests::many_small_functions_do_not_explode`
/// inside its 15s budget on N×N files.
pub fn build_function_unit_with_meta(
    node: Node<'_>,
    kind: AnalysisUnitKind,
    name: Option<String>,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
    file_meta: Option<&FileMeta>,
) -> AnalysisUnit {
    let definition = function_definition_node(node);
    let params = function_params(definition, bytes);
    let line = node.start_position().row + 1;
    let mut state = UnitState::default();
    // Seed Go's method-receiver name (`func (c *Cache) ...` → `c`) into
    // `non_sink_vars` so calls of the form `c.foo(..)` /
    // `c.field.foo(..)` route through the in-memory-local sink class
    // and skip the verb-name fallback.  These are intra-struct
    // dispatches; without type tracking, the auth analyser cannot tell
    // a `*Cache` field-call from a `*sql.DB` call by name alone, so we
    // err on the safe side per the deferred memo
    // (`project_realrepo_hugo.md`).  Only Go's `method_declaration`
    // exposes a `receiver` field — Rust/Java instance methods route
    // through `self`/`this` keywords and are unaffected.
    if let Some(receiver_name) = method_receiver_name(definition, bytes) {
        state.non_sink_vars.insert(receiver_name);
    }
    if let Some(meta) = file_meta {
        state.trpc_alias_names = meta.trpc_alias_names.clone();
    }
    collect_unit_state(node, bytes, rules, &mut state);
    dedup_value_refs(&mut state.value_refs);
    let context_inputs: Vec<ValueRef> = state
        .value_refs
        .iter()
        .filter(|value| {
            matches!(
                value.source_kind,
                ValueSourceKind::RequestParam
                    | ValueSourceKind::RequestBody
                    | ValueSourceKind::RequestQuery
                    | ValueSourceKind::Session
            )
        })
        .cloned()
        .collect();

    AnalysisUnit {
        kind,
        name,
        span: span(node),
        params,
        context_inputs,
        call_sites: state.call_sites,
        auth_checks: state.auth_checks,
        operations: state.operations,
        value_refs: state.value_refs,
        condition_texts: state.condition_texts,
        line,
        row_field_vars: state.row_field_vars,
        var_alias_chain: state.var_alias_chain,
        row_population_data: state.row_population_data,
        self_actor_vars: state.self_actor_vars,
        self_actor_id_vars: state.self_actor_id_vars,
        authorized_sql_vars: state.authorized_sql_vars,
        const_bound_vars: state.const_bound_vars,
        typed_bounded_vars: HashSet::new(),
        typed_bounded_dto_fields: std::collections::HashMap::new(),
        self_scoped_session_bases: state.self_scoped_session_bases,
    }
}

#[derive(Default)]
struct UnitState {
    call_sites: Vec<CallSite>,
    auth_checks: Vec<AuthCheck>,
    operations: Vec<SensitiveOperation>,
    value_refs: Vec<ValueRef>,
    condition_texts: Vec<String>,
    /// Local variable names bound to a known non-sink collection
    /// (e.g. `HashMap::new()`, `Vec::with_capacity(_)`, `vec![]`,
    /// or via an explicit type annotation).  Consulted by
    /// `collect_call` so method calls on these bindings
    /// (`map.insert(…)`, `set.remove(…)`) aren't classified as
    /// auth-relevant Read/Mutation operations.
    non_sink_vars: HashSet<String>,
    /// Map from local variable name to the row binding it was read
    /// from (`let owner_id = existing.get("user_id")` → `owner_id →
    /// existing`). Powers A2's row-level ownership-equality check so
    /// downstream uses of fields from the same row are implicitly
    /// covered by a check on the row's owner column.
    row_field_vars: HashMap<String, String>,
    /// Full chain text for `let X = BASE.FIELD` shapes (or
    /// transitively through method calls / try / await wrappers when
    /// the value resolves to a member access). Stored alongside
    /// `row_field_vars` so the row-population reverse-walk can match
    /// plain-identifier sink subjects against population args by
    /// their original chain text. See
    /// [`crate::auth_analysis::model::AnalysisUnit::var_alias_chain`].
    var_alias_chain: HashMap<String, String>,
    /// Per row-binding metadata from the `let ROW = CALL(...)` site:
    /// the declaration line and the set of `ValueRef`s appearing in
    /// the call's arguments. When an A2 AuthCheck fires against
    /// `ROW`, we back-date the check to this line and merge these
    /// argument value-refs into its subjects so the original fetch
    /// (e.g. `db.query_one(..., &[doc_id])`) is also covered.
    row_population_data: HashMap<String, (usize, Vec<ValueRef>)>,
    /// A3: local variables bound to the authenticated actor.
    /// Populated from `let V = require_auth(..).await?` (or any call
    /// matching `rules.is_login_guard` / `rules.is_authorization_check`)
    /// and from typed route-handler parameters whose type names the
    /// authenticated user (`CurrentUser`, `AuthUser`, …). Copied onto
    /// `AnalysisUnit.self_actor_vars` so `checks.rs` can recognize
    /// `V.id` as actor context rather than a foreign scoped id.
    self_actor_vars: HashSet<String>,
    /// Transitive copies of the authenticated actor's id field
    /// (`let X = V.id` / `let X = (V.id as ..).into()` /
    /// `let X = V.user_id` / `V.uid`).  Populated by
    /// `collect_self_actor_id_binding`.  Copied onto
    /// `AnalysisUnit.self_actor_id_vars` so subjects whose name appears
    /// here count as actor context — closes the FP where a route
    /// handler does `let uid = user.id; query_all(.., &[uid])` and the
    /// engine sees `uid` only as a plain scoped id.
    self_actor_id_vars: HashSet<String>,
    /// B3: local variables bound (directly or transitively) to a
    /// SQL query whose literal text is auth-gated.  Populated by
    /// `collect_sql_authorized_binding` and the `for ROW in X` /
    /// `let Y = ROW.method(..)` propagation paths inside
    /// `collect_row_field_binding` and `collect_for_row_binding`.
    authorized_sql_vars: HashSet<String>,
    /// Local variables whose declaration binds them to a string,
    /// numeric, or boolean literal — `id := "id"` / `let id = "1"` /
    /// `String id = "id";`.  These cannot be user-controlled and so
    /// must not be treated as scoped-identifier subjects by
    /// `is_relevant_target_subject`.  Closes the gin/context_test.go
    /// FP where `id := "id"; c.AddParam(id, value)` triggered
    /// `go.auth.missing_ownership_check` because the local `id`
    /// matched `is_id_like` but had no actor-context exemption.
    const_bound_vars: HashSet<String>,
    /// Dynamic per-unit session-base set lifted into the
    /// `AnalysisUnit` of the same name.  Populated by
    /// [`collect_trpc_ctx_param`] when a TS parameter's type
    /// references a TRPC-shaped Options alias.  See the field doc on
    /// [`crate::auth_analysis::model::AnalysisUnit::self_scoped_session_bases`].
    self_scoped_session_bases: HashSet<String>,
    /// File-level set of TS type-alias names whose body references a
    /// TRPC-marker type (`TrpcSessionUser` etc.).  Populated once per
    /// unit at the top of [`build_function_unit`] by walking up to
    /// the source-file root and scanning every
    /// `type_alias_declaration` / `interface_declaration`.  Read by
    /// [`collect_trpc_ctx_param`] to decide whether a parameter's
    /// type annotation (often just an alias name like `GetOptions`)
    /// resolves to a TRPC handler signature.  Empty for non-TS
    /// languages — the scanner only matches TS-grammar node kinds.
    trpc_alias_names: HashSet<String>,
}

fn collect_unit_state(
    node: Node<'_>,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
    state: &mut UnitState,
) {
    match node.kind() {
        "call_expression" | "call" | "method_invocation" | "method_call_expression" => {
            collect_call(node, bytes, rules, state)
        }
        "if_statement" | "elif_clause" | "while_statement" | "do_statement" | "if" | "unless"
        | "if_modifier" | "unless_modifier" | "while_modifier" | "until_modifier"
        | "while_expression" => {
            if let Some(condition) = node.child_by_field_name("condition") {
                collect_condition(condition, bytes, rules, state);
            }
        }
        "if_expression" => {
            if let Some(condition) = node.child_by_field_name("condition") {
                collect_condition(condition, bytes, rules, state);
            }
            detect_ownership_equality_check(node, bytes, state);
        }
        "conditional_expression" => collect_condition(node, bytes, rules, state),
        "let_declaration" => {
            collect_non_sink_binding(node, bytes, rules, state);
            collect_row_field_binding(node, bytes, state);
            collect_member_alias_binding(node, bytes, state);
            collect_row_population(node, bytes, state);
            collect_self_actor_binding(node, bytes, rules, state);
            collect_self_actor_id_binding(node, bytes, state);
            collect_sql_authorized_binding(node, bytes, rules, state);
            propagate_sql_authorized_through_field_read(node, bytes, state);
            collect_const_string_binding(node, bytes, state);
        }
        // JS/TS `variable_declarator` inside `lexical_declaration`
        // (`const X = ...`, `let X = ...`) — exposes `name` + `value`
        // fields. Run the same self-actor / self-actor-id binding
        // recognition as the Rust `let_declaration` arm above so the
        // session-self-actor copy chain (`const session = await
        // getServerSession(...)`; `const userId = session.user.id`)
        // populates `self_actor_vars` / `self_actor_id_vars`.
        "variable_declarator" => {
            collect_self_actor_binding(node, bytes, rules, state);
            collect_self_actor_id_binding(node, bytes, state);
            collect_const_string_binding(node, bytes, state);
        }
        // Go `id := "id"` / Python `id = "id"` / Java `String id = "id";` /
        // Ruby `id = "id"` — language-specific binding nodes that the
        // let_declaration arm above doesn't catch.  Const-only — never
        // marks self_actor / row_field / sql vars (those need richer
        // right-hand-side analysis already provided by the
        // let_declaration arm).
        "short_var_declaration"
        | "const_declaration"
        | "var_declaration"
        | "var_spec"
        | "lexical_declaration"
        | "local_variable_declaration"
        | "assignment"
        | "assignment_expression"
        | "augmented_assignment"
        | "expression_statement" => {
            collect_const_string_binding(node, bytes, state);
            // Ruby `@issue = Issue.find(params[:id])` is the canonical
            // controller idiom: instance-variable assignment whose RHS
            // is a row-fetch call.  The let_declaration arm above
            // doesn't fire for this kind, so register the row
            // population separately.  `collect_row_population` reads
            // either `pattern`/`value` or `left`/`right`, so it works
            // unchanged for Ruby `assignment` once the LHS recognises
            // `instance_variable`.
            if matches!(node.kind(), "assignment" | "assignment_expression") {
                collect_row_population(node, bytes, state);
            }
        }
        "for_expression" => {
            collect_for_row_binding(node, bytes, state);
        }
        "parameter" => {
            collect_typed_extractor_self_actor(node, bytes, state);
        }
        // TS `required_parameter` / `optional_parameter` — the analogous
        // arm to Rust's `parameter`.  Recognise TRPC-shaped Options
        // params (`{ ctx, input }: GetOptions`) and add the destructured
        // ctx-base to `self_scoped_session_bases` so downstream
        // `ctx.user.id` accesses count as actor context.
        "required_parameter" | "optional_parameter" => {
            collect_trpc_ctx_param(node, bytes, state);
        }
        _ => {}
    }

    for value in extract_value_refs(node, bytes) {
        state.value_refs.push(value);
    }

    for idx in 0..node.named_child_count() {
        let Some(child) = node.named_child(idx as u32) else {
            continue;
        };
        collect_unit_state(child, bytes, rules, state);
    }
}

fn collect_call(node: Node<'_>, bytes: &[u8], rules: &AuthAnalysisRules, state: &mut UnitState) {
    let callee = call_name(node, bytes);
    if callee.is_empty() {
        return;
    }

    let args = node
        .child_by_field_name("arguments")
        .map(named_children)
        .unwrap_or_default();
    let mut subjects: Vec<ValueRef> = call_receiver_subjects(node, bytes);
    subjects.extend(
        args.iter()
            .flat_map(|arg| extract_value_refs(*arg, bytes))
            .collect::<Vec<_>>(),
    );
    let line = node.start_position().row + 1;
    let string_args: Vec<String> = args.iter().map(|arg| text(*arg, bytes)).collect();
    let args_value_refs: Vec<Vec<ValueRef>> = args
        .iter()
        .map(|arg| extract_value_refs(*arg, bytes))
        .collect();
    let node_text = text(node, bytes);
    state.call_sites.push(CallSite {
        name: callee.clone(),
        args: string_args.clone(),
        span: span(node),
        args_value_refs,
    });

    if rules.is_authorization_check(&callee) {
        state.auth_checks.push(AuthCheck {
            kind: classify_auth_check(&callee, rules),
            callee: callee.clone(),
            subjects: subjects.clone(),
            span: span(node),
            line,
            args: string_args,
            condition_text: None,
        });
    }

    // Split classification into OperationKind (what verb?) and
    // SinkClass (what resource?).  The sink class drives the
    // ownership gate; OperationKind is kept for partial-batch / stale-
    // session checks that care about read-vs-mutation semantics.
    let (op_kind, sink_class) = if rules.is_token_lookup_call(&callee, &node_text) {
        (Some(OperationKind::TokenLookup), None)
    } else if let Some(class) = rules.classify_sink_class(&callee, &state.non_sink_vars) {
        let op = match class {
            SinkClass::DbCrossTenantRead => OperationKind::Read,
            // InMemoryLocal: keep the verb for telemetry but the
            // ownership gate ignores this class.
            SinkClass::InMemoryLocal => {
                if rules.is_mutation(&callee) {
                    OperationKind::Mutation
                } else {
                    OperationKind::Read
                }
            }
            // Publish / outbound / cache / DB mutation — treat as
            // write-shaped by default unless the callee name is a
            // read verb (e.g. `cache.get(tenant_id)`).
            _ => {
                if rules.is_read(&callee) && !rules.is_mutation(&callee) {
                    OperationKind::Read
                } else {
                    OperationKind::Mutation
                }
            }
        };
        (Some(op), Some(class))
    } else {
        (None, None)
    };

    if let Some(kind) = op_kind {
        state.operations.push(SensitiveOperation {
            kind,
            sink_class,
            callee,
            subjects,
            span: span(node),
            line,
            text: node_text,
        });
    }
}

fn collect_condition(
    node: Node<'_>,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
    state: &mut UnitState,
) {
    let condition_text = text(node, bytes);
    if condition_text.is_empty() {
        return;
    }
    state.condition_texts.push(condition_text.clone());

    let subjects = extract_value_refs(node, bytes);
    let line = node.start_position().row + 1;

    if rules.has_expiry_field(&condition_text) {
        state.auth_checks.push(AuthCheck {
            kind: AuthCheckKind::TokenExpiry,
            callee: "(condition)".into(),
            subjects: subjects.clone(),
            span: span(node),
            line,
            args: Vec::new(),
            condition_text: Some(condition_text.clone()),
        });
    }

    if rules.has_recipient_field(&condition_text) {
        state.auth_checks.push(AuthCheck {
            kind: AuthCheckKind::TokenRecipient,
            callee: "(condition)".into(),
            subjects,
            span: span(node),
            line,
            args: Vec::new(),
            condition_text: Some(condition_text),
        });
    }
}

/// Detect `let` bindings that produce a known non-sink collection
/// (e.g. `HashMap::new()`, `Vec::with_capacity(_)`, `vec![]`, or an
/// explicit type annotation like `: HashMap<_, _>`).  Registered
/// variable names are consulted by `collect_call` so later method
/// calls on those bindings (`map.insert(..)`, `set.remove(..)`)
/// aren't treated as auth-relevant Read/Mutation operations.
///
/// Rust-oriented in practice; JS/TS/Python/etc. use different
/// declaration node kinds and are unaffected.
fn collect_non_sink_binding(
    node: Node<'_>,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
    state: &mut UnitState,
) {
    let Some(pattern) = node.child_by_field_name("pattern") else {
        return;
    };
    let Some(var_name) = first_identifier_name(pattern, bytes) else {
        return;
    };
    if var_name.is_empty() {
        return;
    }

    if let Some(ty_node) = node.child_by_field_name("type") {
        let ty_text = text(ty_node, bytes);
        if rules.is_non_sink_receiver_type(&ty_text) {
            state.non_sink_vars.insert(var_name);
            return;
        }
    }

    if let Some(value) = node.child_by_field_name("value")
        && value_is_non_sink_constructor(value, bytes, rules)
    {
        state.non_sink_vars.insert(var_name);
    }
}

fn first_identifier_name(node: Node<'_>, bytes: &[u8]) -> Option<String> {
    if matches!(
        node.kind(),
        "identifier"
            | "shorthand_property_identifier_pattern"
            // Ruby `@foo` instance vars and `@@foo` class vars:
            // Rails controllers populate the row via `@issue =
            // Issue.find(...)`, so the row var is the *full* `@issue`
            // text — chain_root in checks.rs strips on `.` only, so an
            // auth check on `@issue.visible?` resolves to root `@issue`,
            // matching the row var.
            | "instance_variable"
            | "class_variable"
            // Ruby globals `$foo` are unusual but match the same
            // handler-state idiom — kept symmetric with @-vars.
            | "global_variable"
    ) {
        let value = text(node, bytes);
        if !value.is_empty() {
            return Some(value);
        }
    }
    for idx in 0..node.named_child_count() {
        let Some(child) = node.named_child(idx as u32) else {
            continue;
        };
        if let Some(found) = first_identifier_name(child, bytes) {
            return Some(found);
        }
    }
    None
}

fn value_is_non_sink_constructor(node: Node<'_>, bytes: &[u8], rules: &AuthAnalysisRules) -> bool {
    match node.kind() {
        "call_expression" | "call" | "method_invocation" | "method_call_expression" => {
            let callee = call_name(node, bytes);
            rules.is_non_sink_constructor_callee(&callee)
        }
        "macro_invocation" => {
            let name = node
                .child_by_field_name("macro")
                .map(|m| text(m, bytes))
                .unwrap_or_default();
            let last = name.rsplit("::").next().unwrap_or(&name);
            matches!(last, "vec" | "smallvec")
        }
        "try_expression" | "await_expression" | "reference_expression" => {
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                if value_is_non_sink_constructor(child, bytes, rules) {
                    return true;
                }
            }
            false
        }
        _ => false,
    }
}

/// Track `let V = ROW.method(..)` or `let V = ROW.field` so later
/// row-level ownership-equality checks on `V` (or on another var read
/// from the same `ROW`) can be attributed back to `ROW`. See
/// `detect_ownership_equality_check` for the consumer.
fn collect_row_field_binding(node: Node<'_>, bytes: &[u8], state: &mut UnitState) {
    let Some(pattern) = node.child_by_field_name("pattern") else {
        return;
    };
    let Some(var_name) = first_identifier_name(pattern, bytes) else {
        return;
    };
    if var_name.is_empty() {
        return;
    }
    let Some(value) = node.child_by_field_name("value") else {
        return;
    };
    let Some(row_name) = extract_row_receiver_name(value, bytes) else {
        return;
    };
    state.row_field_vars.insert(var_name, row_name);
}

/// Track `let X = BASE.FIELD` (or `BASE.FIELD?` / `(BASE.FIELD).await`)
/// so a downstream sink whose subject is the bare identifier `X` can be
/// matched against row-population args that recorded the original
/// chain text.  Distinct from `collect_row_field_binding`, which only
/// records the receiver name (loses the field).
///
/// Only fires when the value resolves to a member-access node and the
/// resulting chain has at least two segments (`req.community_id`,
/// `data.user.id`, …) — single-ident receivers are uninteresting and a
/// chain of length one would just duplicate the binding's own name.
///
/// Defensive: never overwrites an existing entry — first writer wins.
/// Re-binding the same local name (rare in idiomatic Rust) is treated
/// as a separate variable scope; the rest of the analysis already
/// works on the first binding seen during a top-down walk.
fn collect_member_alias_binding(node: Node<'_>, bytes: &[u8], state: &mut UnitState) {
    let Some(pattern) = node.child_by_field_name("pattern") else {
        return;
    };
    let Some(var_name) = first_identifier_name(pattern, bytes) else {
        return;
    };
    if var_name.is_empty() {
        return;
    }
    let Some(value) = node.child_by_field_name("value") else {
        return;
    };
    let target = unwrap_try_like(value);
    if !matches!(
        target.kind(),
        "member_expression"
            | "attribute"
            | "selector_expression"
            | "field_expression"
            | "field_access"
    ) {
        return;
    }
    let chain = member_chain(target, bytes);
    if chain.len() < 2 {
        return;
    }
    let chain_text = chain.join(".");
    state.var_alias_chain.entry(var_name).or_insert(chain_text);
}

/// Record the line and argument value-refs of a `let ROW = CALL(..)`.
/// When A2 synthesises an `AuthCheck` on `ROW` later, we back-date the
/// check to this line and merge the args into its subjects so the
/// original fetch (e.g. `db.query_one(.., &[doc_id])`) is also covered.
///
/// The recorded line is the **call**'s start line, not the
/// `let_declaration`'s.  These differ for multi-line bindings such as
///
/// ```ignore
/// let orig =                         // let_declaration starts here
///     CommentView::read(&mut pool, comment_id, ..).await?;  // call starts here
/// ```
///
/// `has_row_fetch_exemption` looks for a row var "declared at this
/// op's line", where `op.line` is the call site.  Recording the
/// let-line caused the multi-line shape to fall through the exemption
/// — surfaced on lemmy's `comment/lock.rs:31`, where every fetch-then-
/// check route handler that wraps the read across two lines was
/// flagged despite a textual auth check on the resulting row.
fn collect_row_population(node: Node<'_>, bytes: &[u8], state: &mut UnitState) {
    // Most languages expose `pattern`/`value` on let / const / var
    // declarations.  Ruby `assignment` uses `left`/`right` instead, so
    // accept either.  When both fields are missing, the node isn't an
    // RHS-bound binding and we skip.
    let Some(pattern) = node
        .child_by_field_name("pattern")
        .or_else(|| node.child_by_field_name("left"))
    else {
        return;
    };
    let Some(var_name) = first_identifier_name(pattern, bytes) else {
        return;
    };
    if var_name.is_empty() {
        return;
    }
    let Some(value) = node
        .child_by_field_name("value")
        .or_else(|| node.child_by_field_name("right"))
    else {
        return;
    };
    let call_node = unwrap_try_like(value);
    if !matches!(
        call_node.kind(),
        "call_expression" | "call" | "method_invocation" | "method_call_expression"
    ) {
        return;
    }
    let args = call_node
        .child_by_field_name("arguments")
        .map(named_children)
        .unwrap_or_default();
    let mut arg_refs: Vec<ValueRef> = Vec::new();
    for arg in args {
        arg_refs.extend(extract_value_refs(arg, bytes));
    }
    let call_line = call_node.start_position().row + 1;
    state
        .row_population_data
        .insert(var_name, (call_line, arg_refs));
}

/// A3: record `let V = CALL(..)` (or `.await?` / `?` / reference
/// chains wrapping such a call) where `CALL` matches a configured
/// login-guard or authorization-check name. `V` is then treated as the
/// authenticated actor — `V.id`-shaped subjects are actor context and
/// shouldn't be flagged as foreign scoped IDs.
fn collect_self_actor_binding(
    node: Node<'_>,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
    state: &mut UnitState,
) {
    // Rust `let_declaration` exposes `pattern`; JS/TS
    // `variable_declarator` exposes `name`. Try both so the same
    // recognition fires across languages.
    let Some(pattern) = node
        .child_by_field_name("pattern")
        .or_else(|| node.child_by_field_name("name"))
    else {
        return;
    };
    let Some(value) = node.child_by_field_name("value") else {
        return;
    };

    // Destructuring: `const { user } = ctx.session;` /
    // `const { user } = await getServerSession();` /
    // `const { id } = req.user;`.  These bind LOCAL variables that are
    // semantically the actor (or the actor's id), and the existing
    // single-ident path can't see them because `first_identifier_name`
    // either picks the wrong key when several are destructured or
    // misses the session-container RHS shape entirely.
    if pattern.kind() == "object_pattern" {
        collect_destructured_self_actor_binding(pattern, value, bytes, rules, state);
        return;
    }

    let Some(var_name) = first_identifier_name(pattern, bytes) else {
        return;
    };
    if var_name.is_empty() {
        return;
    }
    if value_is_self_actor_call(value, bytes, rules) {
        state.self_actor_vars.insert(var_name);
    }
}

/// Pattern is `object_pattern` (JS/TS destructure).  Walk the keys and
/// classify the RHS to decide what each destructured local should
/// register as:
///
/// * `const { user } = ctx.session` / `const { user } = await
///   getServerSession()` — RHS is a session container, so a
///   destructured `user` (or `currentUser`) becomes the unit's
///   self-actor binding.
/// * `const { id } = req.user` / `const { userId } = session.user` —
///   RHS is the canonical authed-user base from
///   `is_self_scoped_session_base_text`, so a destructured `id` /
///   `userId` / `user_id` / `uid` becomes a self-actor-id binding.
/// * `const { user } = await loginGuardCall()` — also accepted
///   because `value_is_self_actor_call` already covers the
///   `let user = require_auth(..)` shape; we lift that recognition
///   into the destructure case so callers can extract the actor in a
///   single statement.
///
/// Each `pair_pattern` entry distinguishes the destructured KEY (the
/// shape of the RHS source) from the bound LOCAL (what we add to the
/// state set).  Shorthand patterns reuse the key as the local.
fn collect_destructured_self_actor_binding(
    pattern: Node<'_>,
    value: Node<'_>,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
    state: &mut UnitState,
) {
    // Two recognition paths run in sequence:
    //   1. Static classify_destructure_rhs: hard-coded session-container
    //      / self-actor-base / self-actor-call shapes.
    //   2. Dynamic self_scoped_session_bases lookup: if the RHS is a
    //      chain (or bare identifier) `<X>` and `<X>.user` was added to
    //      `self_scoped_session_bases` by an earlier TRPC param scan,
    //      the destructured `user` key is the actor.  Closes the
    //      cal.com `({ ctx, input }: Options) => { const { user } = ctx; }`
    //      shape where ctx is the TRPC-typed param.
    let kind = classify_destructure_rhs(value, bytes, rules);
    let trpc_ctx_path = lookup_trpc_ctx_destructure_match(value, bytes, state);

    if kind == DestructureRhsKind::None && trpc_ctx_path.is_none() {
        return;
    }

    for idx in 0..pattern.named_child_count() {
        let Some(child) = pattern.named_child(idx as u32) else {
            continue;
        };
        let (key, local) = match child.kind() {
            // `{ user }` — key and local are the same identifier.
            "shorthand_property_identifier_pattern" => {
                let name = text(child, bytes);
                (name.clone(), name)
            }
            // `{ user = default }` — left is the shorthand key/local.
            "object_assignment_pattern" => {
                let Some(left) = child.child_by_field_name("left") else {
                    continue;
                };
                let name = if matches!(
                    left.kind(),
                    "identifier" | "shorthand_property_identifier_pattern"
                ) {
                    text(left, bytes)
                } else {
                    first_identifier_name(left, bytes).unwrap_or_default()
                };
                (name.clone(), name)
            }
            // `{ user: localName }` — `key` and `value` fields are
            // distinct (key from RHS source, local in our scope).
            "pair_pattern" => {
                let key_node = child.child_by_field_name("key");
                let local_node = child.child_by_field_name("value");
                let (Some(k), Some(v)) = (key_node, local_node) else {
                    continue;
                };
                let key = text(k, bytes);
                let local = first_identifier_name(v, bytes).unwrap_or_default();
                (key, local)
            }
            _ => continue,
        };
        if kind != DestructureRhsKind::None {
            process_destructure_entry(&key, &local, kind, state);
        }
        // Dynamic-set lift: when the RHS resolves to an `<X>` whose
        // `<X>.user` was added to `self_scoped_session_bases`, the
        // destructured `user` key is the actor.  This closes the
        // chained TRPC shape `({ ctx }: Options) => { const { user }
        // = ctx; }` where the param-level pre-pass marked `ctx.user`
        // earlier in the unit.
        if let Some(rhs_path) = trpc_ctx_path.as_deref()
            && key.eq_ignore_ascii_case("user")
            && !local.is_empty()
        {
            let _ = rhs_path; // path itself is not stored; presence is the signal
            state.self_actor_vars.insert(local);
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DestructureRhsKind {
    /// RHS is a session container — the destructured `user` field
    /// resolves to the authenticated actor.  Examples: `ctx.session`,
    /// `req.session`, `session`, `await getServerSession()`,
    /// `getSession()`.
    SessionContainer,
    /// RHS is the authed-user base itself (`req.user`, `session.user`,
    /// `ctx.session.user`).  A destructured `id` field is the actor's
    /// own id.
    SelfActorBase,
    /// RHS is not a session/actor source — destructure is irrelevant
    /// for self-actor recognition.
    None,
}

/// When the destructure RHS is `<chain>` (an identifier or member
/// chain), return `Some(chain_text)` if `<chain_text>.user` was added
/// to `state.self_scoped_session_bases` by an earlier
/// `collect_trpc_ctx_param` call.  Used to mark the destructured
/// `user` shorthand as a self-actor binding when extracting it from a
/// TRPC ctx param's local — `({ ctx }: Options) => { const { user }
/// = ctx; }`.
fn lookup_trpc_ctx_destructure_match(
    node: Node<'_>,
    bytes: &[u8],
    state: &UnitState,
) -> Option<String> {
    if state.self_scoped_session_bases.is_empty() {
        return None;
    }
    let chain_text = chain_text_from_value(node, bytes)?;
    if chain_text.is_empty() {
        return None;
    }
    let candidate = format!("{chain_text}.user");
    if state.self_scoped_session_bases.contains(&candidate) {
        Some(chain_text)
    } else {
        None
    }
}

/// Reduce an RHS expression to its dotted chain text, walking through
/// `await`/parens/non-null wrappers.  Returns `None` for shapes that
/// aren't a pure identifier/member-chain (e.g. a call result, a
/// template literal, an object-literal expression).
fn chain_text_from_value(node: Node<'_>, bytes: &[u8]) -> Option<String> {
    match node.kind() {
        "identifier" => {
            let t = text(node, bytes);
            if t.is_empty() { None } else { Some(t) }
        }
        "field_expression" | "member_expression" | "field_access" | "scoped_identifier" => {
            let chain = member_chain(node, bytes);
            if chain.is_empty() {
                None
            } else {
                Some(chain.join("."))
            }
        }
        "type_cast_expression"
        | "as_expression"
        | "cast_expression"
        | "parenthesized_expression"
        | "non_null_expression"
        | "await_expression"
        | "try_expression" => {
            let inner = node
                .child_by_field_name("value")
                .or_else(|| node.child_by_field_name("expression"));
            if let Some(v) = inner
                && let Some(t) = chain_text_from_value(v, bytes)
            {
                return Some(t);
            }
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                if let Some(t) = chain_text_from_value(child, bytes) {
                    return Some(t);
                }
            }
            None
        }
        _ => None,
    }
}

fn classify_destructure_rhs(
    node: Node<'_>,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
) -> DestructureRhsKind {
    if value_is_self_actor_call(node, bytes, rules) {
        return DestructureRhsKind::SessionContainer;
    }
    if value_is_session_provider_chain(node, bytes) {
        return DestructureRhsKind::SessionContainer;
    }
    if value_is_self_actor_base_chain(node, bytes) {
        return DestructureRhsKind::SelfActorBase;
    }
    DestructureRhsKind::None
}

fn process_destructure_entry(
    key: &str,
    local: &str,
    kind: DestructureRhsKind,
    state: &mut UnitState,
) {
    if key.is_empty() || local.is_empty() {
        return;
    }
    let key_lower = key.to_ascii_lowercase();
    match kind {
        DestructureRhsKind::SessionContainer => {
            if matches!(key_lower.as_str(), "user" | "currentuser" | "current_user") {
                state.self_actor_vars.insert(local.to_string());
            }
        }
        DestructureRhsKind::SelfActorBase => {
            if matches!(key_lower.as_str(), "id" | "userid" | "user_id" | "uid") {
                state.self_actor_id_vars.insert(local.to_string());
            }
        }
        DestructureRhsKind::None => {}
    }
}

/// True when `node` (after walking through `await`/parens/non-null
/// wrappers) is a session-container expression — a chain ending in
/// `.session` / `.state.session` / a bare `session` identifier, or a
/// call to a known session-getter (`getServerSession()`,
/// `getSession()`).  Distinct from `value_is_self_actor_call` which
/// matches login-guard / authorization-check callees configured per
/// language.
fn value_is_session_provider_chain(node: Node<'_>, bytes: &[u8]) -> bool {
    match node.kind() {
        "field_expression" | "member_expression" | "field_access" | "scoped_identifier" => {
            let chain = member_chain(node, bytes);
            if chain.is_empty() {
                return false;
            }
            let joined = chain.join(".");
            // Bare session containers — `ctx.session`, `req.session`,
            // `request.session`, plus the Koa `ctx.state` shape.
            matches!(
                joined.as_str(),
                "ctx.session" | "ctx.state" | "req.session" | "request.session" | "session"
            )
        }
        "identifier" => {
            let name = text(node, bytes);
            matches!(name.as_str(), "session")
        }
        // Known session-getter calls.  Conservative list — only
        // recogniser shapes that are unambiguously session-providing
        // in the JS/TS ecosystem (NextAuth's `getServerSession` is the
        // dominant one).  `auth()` and `useSession()` are deliberately
        // omitted because their meaning is ambiguous outside of a
        // server-component context and adding them risks
        // over-suppression in non-NextAuth code.
        "call_expression" | "call" => {
            let callee = call_name(node, bytes);
            let last = bare_method_name(&callee);
            matches!(
                last,
                "getServerSession"
                    | "getSession"
                    | "getServerSideSession"
                    | "unstable_getServerSession"
            )
        }
        "type_cast_expression"
        | "as_expression"
        | "cast_expression"
        | "parenthesized_expression"
        | "non_null_expression"
        | "await_expression"
        | "try_expression" => {
            let inner = node
                .child_by_field_name("value")
                .or_else(|| node.child_by_field_name("expression"));
            if let Some(v) = inner
                && value_is_session_provider_chain(v, bytes)
            {
                return true;
            }
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                if value_is_session_provider_chain(child, bytes) {
                    return true;
                }
            }
            false
        }
        _ => false,
    }
}

/// True when `node` is the canonical authed-user base from
/// `is_self_scoped_session_base_text` (e.g. `req.user`, `session.user`,
/// `ctx.session.user`).  Used to recognise `const { id } = req.user`
/// so the destructured `id` becomes a self-actor-id.
fn value_is_self_actor_base_chain(node: Node<'_>, bytes: &[u8]) -> bool {
    match node.kind() {
        "field_expression" | "member_expression" | "field_access" | "scoped_identifier" => {
            let chain = member_chain(node, bytes);
            if chain.is_empty() {
                return false;
            }
            let joined = chain.join(".");
            is_self_scoped_session_base_text(&joined)
        }
        "type_cast_expression"
        | "as_expression"
        | "cast_expression"
        | "parenthesized_expression"
        | "non_null_expression"
        | "await_expression"
        | "try_expression" => {
            let inner = node
                .child_by_field_name("value")
                .or_else(|| node.child_by_field_name("expression"));
            if let Some(v) = inner
                && value_is_self_actor_base_chain(v, bytes)
            {
                return true;
            }
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                if value_is_self_actor_base_chain(child, bytes) {
                    return true;
                }
            }
            false
        }
        _ => false,
    }
}

/// Recognise variable bindings whose right-hand side is a literal
/// constant — string, integer, float, or boolean.  A subject backed
/// by a constant binding cannot be user-controlled and so must not
/// trigger `<lang>.auth.missing_ownership_check` even when the
/// variable name happens to match `is_id_like` (e.g.
/// `id := "id"` in a Go test fixture).
///
/// Walks the binding's RHS through common wrappers
/// (`parenthesized_expression`, `type_cast_expression`,
/// reference/borrow expressions) before checking for a leaf literal
/// kind.  Conservative: any non-literal subexpression on the RHS
/// (a call, identifier, field-access) skips the binding — that var
/// might still hold attacker-controlled data.
///
/// Handles the per-language declaration kinds wired in
/// `collect_unit_state`: Go `short_var_declaration` (`x := "foo"`),
/// JS `lexical_declaration` (`const x = "foo"`), Java
/// `local_variable_declaration`, Rust `let_declaration`, and bare
/// `assignment_expression`.
fn collect_const_string_binding(node: Node<'_>, bytes: &[u8], state: &mut UnitState) {
    // `assignment` / `assignment_expression`: `x = "foo"` — populate
    // the LHS (`name` / `left`) when the RHS is a literal.
    if matches!(
        node.kind(),
        "assignment" | "assignment_expression" | "augmented_assignment"
    ) {
        let lhs = node
            .child_by_field_name("left")
            .or_else(|| node.child_by_field_name("name"))
            .or_else(|| node.child_by_field_name("target"));
        let rhs = node
            .child_by_field_name("right")
            .or_else(|| node.child_by_field_name("value"));
        if let (Some(lhs), Some(rhs)) = (lhs, rhs)
            && rhs_is_pure_literal(rhs)
        {
            for var in collect_lhs_idents(lhs, bytes) {
                state.const_bound_vars.insert(var);
            }
        }
        return;
    }

    // Go `short_var_declaration` / `var_declaration` /
    // `const_declaration`: `id := "id"` or `var id string = "id"`.
    // Tree-sitter-go uses `left:expression_list` and
    // `right:expression_list`.
    if matches!(
        node.kind(),
        "short_var_declaration" | "var_spec" | "const_spec"
    ) {
        let left = node.child_by_field_name("left").or_else(|| {
            // Some tree-sitter grammars expose name(s) instead of left
            node.child_by_field_name("name")
        });
        let right = node.child_by_field_name("right").or_else(|| {
            node.child_by_field_name("value")
                .or_else(|| node.child_by_field_name("default"))
        });
        if let (Some(left), Some(right)) = (left, right) {
            // expression_list parallel — pair LHS idents with RHS exprs.
            let lhs_idents = collect_lhs_idents(left, bytes);
            let rhs_exprs: Vec<Node<'_>> = if right.kind() == "expression_list" {
                let mut cursor = right.walk();
                right
                    .children(&mut cursor)
                    .filter(|c| !matches!(c.kind(), "," | "(" | ")"))
                    .collect()
            } else {
                vec![right]
            };
            for (idx, var) in lhs_idents.into_iter().enumerate() {
                if let Some(expr) = rhs_exprs.get(idx)
                    && rhs_is_pure_literal(*expr)
                {
                    state.const_bound_vars.insert(var);
                }
            }
        }
        return;
    }

    // `var_declaration` / `const_declaration` (Go top-level wrappers
    // around var_spec/const_spec): recurse into children handled above.
    if matches!(node.kind(), "var_declaration" | "const_declaration") {
        for idx in 0..node.named_child_count() {
            if let Some(child) = node.named_child(idx as u32) {
                collect_const_string_binding(child, bytes, state);
            }
        }
        return;
    }

    // Rust `let_declaration` / Python `expression_statement` wrapping a
    // top-level assignment / JS `lexical_declaration` / Java
    // `local_variable_declaration` — all expose the binding via
    // `pattern`/`name` + `value`.
    let pattern = node
        .child_by_field_name("pattern")
        .or_else(|| node.child_by_field_name("name"));
    let value = node.child_by_field_name("value");
    if let (Some(pattern), Some(value)) = (pattern, value)
        && rhs_is_pure_literal(value)
    {
        for var in collect_lhs_idents(pattern, bytes) {
            state.const_bound_vars.insert(var);
        }
        return;
    }

    // JS `lexical_declaration` / Java `local_variable_declaration` /
    // Python `expression_statement` — the binding child is a wrapper
    // (`variable_declarator`).  Recurse into wrappers; the
    // `variable_declarator` arm in `collect_unit_state` handles them.
    for idx in 0..node.named_child_count() {
        let Some(child) = node.named_child(idx as u32) else {
            continue;
        };
        if matches!(
            child.kind(),
            "variable_declarator"
                | "init_declarator"
                | "var_spec"
                | "const_spec"
                | "assignment"
                | "assignment_expression"
        ) {
            collect_const_string_binding(child, bytes, state);
        }
    }
}

/// Returns true if `node` (after unwrapping common wrappers) is a
/// pure literal — string, integer, float, boolean, or null.  Returns
/// false for any expression that could carry attacker-controlled data
/// (calls, identifiers, field access, template strings with
/// interpolations).
fn rhs_is_pure_literal(node: Node<'_>) -> bool {
    // Unwrap wrappers that don't change taint provenance.
    let inner = match node.kind() {
        "parenthesized_expression"
        | "type_cast_expression"
        | "as_expression"
        | "cast_expression"
        | "reference_expression" => {
            let value = node
                .child_by_field_name("value")
                .or_else(|| node.child_by_field_name("expression"));
            value.unwrap_or(node)
        }
        _ => node,
    };
    matches!(
        inner.kind(),
        "string_literal"
            | "raw_string_literal"
            | "string"
            | "interpreted_string_literal"
            | "rune_literal"
            | "integer_literal"
            | "int_literal"
            | "float_literal"
            | "true"
            | "false"
            | "boolean_literal"
            | "nil"
            | "null"
            | "null_literal"
            | "none"
            | "character_literal"
    ) || (inner.kind() == "template_string" && !template_has_interpolation(inner))
        || (inner.kind() == "template_literal" && !template_has_interpolation(inner))
}

/// Returns true if a template literal/string contains any
/// interpolation segment (which carries dynamic data).  Pure
/// hard-coded template strings without `${...}` are still constants.
fn template_has_interpolation(node: Node<'_>) -> bool {
    for idx in 0..node.named_child_count() {
        let Some(child) = node.named_child(idx as u32) else {
            continue;
        };
        if matches!(
            child.kind(),
            "template_substitution" | "interpolation" | "string_interpolation"
        ) {
            return true;
        }
    }
    false
}

/// Collect identifier names from an LHS pattern: a bare `identifier`,
/// a `tuple_pattern`, a Go `expression_list`, or a Rust `tuple_pattern`
/// / `let_pattern`.  Returns the bound variable names.  Ignores
/// destructured field accesses (we only track plain locals).
fn collect_lhs_idents(node: Node<'_>, bytes: &[u8]) -> Vec<String> {
    let mut out = Vec::new();
    if node.kind() == "identifier" {
        out.push(text(node, bytes));
        return out;
    }
    // Walk children, picking up identifiers; recurse into list/tuple
    // wrappers commonly seen on LHS of multi-binding declarations.
    for idx in 0..node.named_child_count() {
        let Some(child) = node.named_child(idx as u32) else {
            continue;
        };
        match child.kind() {
            "identifier" => out.push(text(child, bytes)),
            "tuple_pattern"
            | "expression_list"
            | "pattern_list"
            | "list_pattern"
            | "field_identifier"
            | "shorthand_field_identifier" => {
                out.extend(collect_lhs_idents(child, bytes));
            }
            _ => {}
        }
    }
    out
}

/// Detect `let X = V.id` (or `(V.id as ..).into()`, `V.id.into()`,
/// `V.user_id`, `V.uid`, `V.userId`) where `V` is in `self_actor_vars`.
/// `X` is then a transitive copy of the authenticated actor's id and
/// is recorded in `self_actor_id_vars` so subjects of that name count
/// as actor context, not as foreign scoped IDs.
///
/// Closes a real-repo FP cluster: route handlers idiomatically reduce
/// the authed user to a scalar id and reuse it across many SQL params
/// (`let uid = user.id; query_all(.., &[uid]); query_all(.., &[uid])`).
/// The original `V.id`-shape recognition only covered direct subject
/// expressions; this captures the common copy-and-pass shape.
fn collect_self_actor_id_binding(node: Node<'_>, bytes: &[u8], state: &mut UnitState) {
    // Rust `let_declaration` exposes `pattern`; JS/TS
    // `variable_declarator` exposes `name`.
    let Some(pattern) = node
        .child_by_field_name("pattern")
        .or_else(|| node.child_by_field_name("name"))
    else {
        return;
    };
    let Some(var_name) = first_identifier_name(pattern, bytes) else {
        return;
    };
    if var_name.is_empty() {
        return;
    }
    let Some(value) = node.child_by_field_name("value") else {
        return;
    };
    if value_is_self_actor_id_field(value, bytes, &state.self_actor_vars)
        || value_is_self_scoped_session_id_chain(value, bytes)
    {
        state.self_actor_id_vars.insert(var_name);
    }
}

/// Does `node` resolve to a `V.id` / `V.user_id` / `V.uid` / `V.userId`
/// field access where `V` is in `actor_vars`?  Walks through common
/// wrappers: `try_expression`, `await_expression`, `parenthesized_expression`,
/// `reference_expression`, `type_cast_expression` (`v.id as i64`),
/// and `call_expression` for chained `.into()` / `.to_string()` etc.
fn value_is_self_actor_id_field(
    node: Node<'_>,
    bytes: &[u8],
    actor_vars: &HashSet<String>,
) -> bool {
    match node.kind() {
        "field_expression" | "member_expression" | "field_access" | "scoped_identifier" => {
            let receiver = node
                .child_by_field_name("value")
                .or_else(|| node.child_by_field_name("object"));
            let field = node
                .child_by_field_name("field")
                .or_else(|| node.child_by_field_name("property"))
                .or_else(|| node.child_by_field_name("name"));
            let (Some(receiver), Some(field)) = (receiver, field) else {
                return false;
            };
            let receiver_name = text(receiver, bytes);
            let field_name = text(field, bytes);
            actor_vars.contains(&receiver_name) && is_self_actor_id_field_name(&field_name)
        }
        "type_cast_expression"
        | "as_expression"
        | "cast_expression"
        | "parenthesized_expression"
        | "try_expression"
        | "await_expression"
        | "reference_expression" => {
            let value = node
                .child_by_field_name("value")
                .or_else(|| node.child_by_field_name("expression"));
            if let Some(v) = value
                && value_is_self_actor_id_field(v, bytes, actor_vars)
            {
                return true;
            }
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                if value_is_self_actor_id_field(child, bytes, actor_vars) {
                    return true;
                }
            }
            false
        }
        // `(v.id as i64).into()` / `v.id.to_string()` / `v.id.clone()` —
        // call on a self-actor id field still propagates self-actor-id.
        "call_expression" | "call" | "method_invocation" | "method_call_expression" => {
            let receiver = node
                .child_by_field_name("function")
                .or_else(|| node.child_by_field_name("object"));
            if let Some(r) = receiver {
                // Function field of a method call is `receiver.method` —
                // walk the receiver subtree for the self-actor id field.
                if value_is_self_actor_id_field(r, bytes, actor_vars) {
                    return true;
                }
                // Also check the receiver of a method-style chain:
                // `(v.id as i64).into()` — `function` is the
                // `field_expression` `(...).into`, whose `value` child
                // is the cast expression.
                if let Some(inner) = r
                    .child_by_field_name("value")
                    .or_else(|| r.child_by_field_name("object"))
                    && value_is_self_actor_id_field(inner, bytes, actor_vars)
                {
                    return true;
                }
            }
            false
        }
        _ => false,
    }
}

fn is_self_actor_id_field_name(field: &str) -> bool {
    let lower = field.to_ascii_lowercase();
    matches!(
        lower.as_str(),
        "id" | "user_id" | "userid" | "uid" | "email" | "username" | "handle"
    )
}

/// Recognise `let X = session.user.id` (or
/// `req.session.user.id` / `ctx.session.user.id` / `req.user.id` /
/// `request.user.id`, etc.) — a copy of the authenticated actor's
/// own id field through one of the canonical session-context chains
/// (the same set `is_self_scoped_session_subject` accepts at use
/// time). Walks through wrappers (`await`, `?.`, parens, casts,
/// trivial method chains like `.toString()`).
///
/// Closes a real-repo FP cluster (cal.com Next.js handlers): the
/// idiomatic shape is `if (session?.user?.id) { const userId =
/// session.user.id; await repo.get(userId); }`. The use site sees
/// a plain `userId` subject, so without binding-time recognition the
/// classifier can't tell it's actor context.
fn value_is_self_scoped_session_id_chain(node: Node<'_>, bytes: &[u8]) -> bool {
    match node.kind() {
        "field_expression" | "member_expression" | "field_access" | "scoped_identifier" => {
            // Build the dotted chain and reuse the same predicate the
            // subject classifier uses (`matches_session_context` +
            // self-scoped-base check). Doing it via the chain avoids
            // re-implementing the session-context grammar here.
            let chain = member_chain(node, bytes);
            if chain.len() < 2 {
                return false;
            }
            let field = chain.last().expect("len >= 2");
            if !is_self_actor_id_field_name(field) {
                return false;
            }
            let base_chain = &chain[..chain.len() - 1];
            let base = base_chain.join(".");
            classify_member_chain(base_chain) == ValueSourceKind::Session
                && is_self_scoped_session_base_text(&base)
        }
        "type_cast_expression"
        | "as_expression"
        | "cast_expression"
        | "parenthesized_expression"
        | "try_expression"
        | "await_expression"
        | "reference_expression"
        | "non_null_expression" => {
            let value = node
                .child_by_field_name("value")
                .or_else(|| node.child_by_field_name("expression"));
            if let Some(v) = value
                && value_is_self_scoped_session_id_chain(v, bytes)
            {
                return true;
            }
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                if value_is_self_scoped_session_id_chain(child, bytes) {
                    return true;
                }
            }
            false
        }
        // `(req.user.id as number).toString()` / `session.user.id.toString()`
        "call_expression" | "call" | "method_invocation" | "method_call_expression" => {
            let receiver = node
                .child_by_field_name("function")
                .or_else(|| node.child_by_field_name("object"));
            if let Some(r) = receiver {
                if value_is_self_scoped_session_id_chain(r, bytes) {
                    return true;
                }
                if let Some(inner) = r
                    .child_by_field_name("value")
                    .or_else(|| r.child_by_field_name("object"))
                    && value_is_self_scoped_session_id_chain(inner, bytes)
                {
                    return true;
                }
            }
            false
        }
        _ => false,
    }
}

/// String-level analogue of `is_self_scoped_session_base` from
/// `checks.rs`. Kept here in the extract layer to avoid a layer
/// dependency; the two lists must stay in sync.
fn is_self_scoped_session_base_text(base: &str) -> bool {
    matches!(
        base,
        "req.session.user"
            | "request.session.user"
            | "session.user"
            | "req.session.currentUser"
            | "request.session.currentUser"
            | "session.currentUser"
            | "req.user"
            | "request.user"
            | "req.currentUser"
            | "request.currentUser"
            | "ctx.session.user"
            | "ctx.session.currentUser"
            | "ctx.state.user"
            | "ctx.state.currentUser"
    )
}

/// Does `node` (possibly wrapped in `?`/`.await`/`&`/`match`) resolve
/// to a call whose callee matches `is_login_guard` or
/// `is_authorization_check`? Used to detect `let user =
/// auth::require_auth(..).await?`-style bindings, including the
/// `let user = match require_auth() { Ok(u) => u, Err(_) => return ... }`
/// shape used by Worker / Cloudflare-style handlers that propagate
/// the auth failure response instead of using `?`.
fn value_is_self_actor_call(node: Node<'_>, bytes: &[u8], rules: &AuthAnalysisRules) -> bool {
    match node.kind() {
        "call_expression" | "call" | "method_invocation" | "method_call_expression" => {
            let callee = call_name(node, bytes);
            !callee.is_empty()
                && (rules.is_login_guard(&callee) || rules.is_authorization_check(&callee))
        }
        "try_expression"
        | "await_expression"
        | "reference_expression"
        | "parenthesized_expression"
        | "match_expression" => {
            // For `match SCRUTINEE { ... }`, the scrutinee is the
            // call we care about — if `require_auth().await` is being
            // matched, the `Ok(u) => u` arm gives us a self-actor
            // binding even when `?` isn't usable.  Walk all named
            // children — tree-sitter exposes both the scrutinee and
            // the arms.
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                if value_is_self_actor_call(child, bytes, rules) {
                    return true;
                }
            }
            false
        }
        _ => false,
    }
}

/// A3: typed route-handler parameters whose declared type names the
/// authenticated user (e.g. `user: CurrentUser`, `admin: AdminUser`)
/// count as self-actor bindings. Recognized type last-segments:
/// `CurrentUser`, `SessionUser`, `AuthUser`, `AdminUser`,
/// `AuthenticatedUser`, `RequireAuth`, `RequireLogin`, `Authenticated`.
fn collect_typed_extractor_self_actor(node: Node<'_>, bytes: &[u8], state: &mut UnitState) {
    let Some(pattern) = node.child_by_field_name("pattern") else {
        return;
    };
    let Some(var_name) = first_identifier_name(pattern, bytes) else {
        return;
    };
    if var_name.is_empty() {
        return;
    }
    let Some(ty_node) = node.child_by_field_name("type") else {
        return;
    };
    let ty_text = text(ty_node, bytes);
    if is_self_actor_type_text(&ty_text) {
        state.self_actor_vars.insert(var_name);
    }
}

/// B3: detect `let X = …prepare(LIT)…` / `let X = …query(LIT)…`
/// where the SQL literal classifies as authorization-gated.  When
/// matched: insert `X` into `state.authorized_sql_vars` and synthesise
/// a `Membership` `AuthCheck` at the `let`'s line whose subjects
/// include `X` and the value-refs from the SQL call's bind args
/// (e.g. `user.id` in `.bind(user.id)`).  Downstream uses of `X`'s
/// columns are then transitively covered through `row_field_vars`.
fn collect_sql_authorized_binding(
    node: Node<'_>,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
    state: &mut UnitState,
) {
    if rules.acl_tables.is_empty() && !sql_direct_user_id_enabled() {
        return;
    }
    let Some(pattern) = node.child_by_field_name("pattern") else {
        return;
    };
    let Some(var_name) = first_identifier_name(pattern, bytes) else {
        return;
    };
    if var_name.is_empty() {
        return;
    }
    let Some(value) = node.child_by_field_name("value") else {
        return;
    };
    let Some((sql_call, bind_arg_refs)) = find_authorized_sql_call_in_chain(value, bytes, rules)
    else {
        return;
    };

    state.authorized_sql_vars.insert(var_name.clone());

    let mut subjects = bind_arg_refs;
    subjects.push(ValueRef {
        source_kind: ValueSourceKind::Identifier,
        name: var_name,
        base: None,
        field: None,
        index: None,
        span: span(node),
    });
    let line = node.start_position().row + 1;
    state.auth_checks.push(AuthCheck {
        kind: AuthCheckKind::Membership,
        callee: "(sql ACL)".into(),
        subjects,
        span: span(sql_call),
        line,
        args: Vec::new(),
        condition_text: None,
    });
}

/// Always true — the direct-user-id-predicate path in
/// `sql_semantics::classify_sql_query` doesn't depend on the ACL
/// table list, so we still want to walk `let X = …query(LIT)…`
/// chains even when the user hasn't configured any ACL tables.
/// Kept as a function so future tuning can disable this path.
fn sql_direct_user_id_enabled() -> bool {
    true
}

/// Walk down a chain of method calls (`a.b().c().d()`) looking for a
/// call whose method matches a SQL prepare/query verb and whose first
/// argument is a string literal classifying as auth-gated.  Returns
/// the matching call node along with the value-refs collected from
/// the *outer* chain's argument list (the call that bound the user
/// id, e.g. `.bind(user.id)`).
fn find_authorized_sql_call_in_chain<'tree>(
    value: Node<'tree>,
    bytes: &[u8],
    rules: &AuthAnalysisRules,
) -> Option<(Node<'tree>, Vec<ValueRef>)> {
    let mut bind_arg_refs: Vec<ValueRef> = Vec::new();
    let mut cur = unwrap_try_like(value);
    let mut steps = 0;
    while steps < 16 {
        steps += 1;
        if !matches!(
            cur.kind(),
            "call_expression" | "call" | "method_invocation" | "method_call_expression"
        ) {
            return None;
        }
        // Collect any non-literal arg value-refs from this call —
        // these typically include the bound user id (e.g.
        // `.bind(user.id)` → adds `user.id` as a subject).
        if let Some(args_node) = cur.child_by_field_name("arguments") {
            for arg in named_children(args_node) {
                if matches!(
                    arg.kind(),
                    "string_literal" | "raw_string_literal" | "string"
                ) {
                    continue;
                }
                bind_arg_refs.extend(extract_value_refs(arg, bytes));
            }
        }

        let callee = call_name(cur, bytes);
        let last_segment = bare_method_name(&callee);
        if is_sql_prepare_method(last_segment) {
            // Check first arg is a string literal that classifies
            // as authorized.
            let args = cur
                .child_by_field_name("arguments")
                .map(named_children)
                .unwrap_or_default();
            if let Some(first_arg) = args.first().copied()
                && let Some(literal) = collect_string_literal_text(first_arg, bytes)
                && crate::auth_analysis::sql_semantics::classify_sql_query(
                    &literal,
                    &rules.acl_tables,
                )
                .is_some()
            {
                return Some((cur, bind_arg_refs));
            }
            // Method matched but arg isn't a literal we recognise
            // as authorized — bail.
            return None;
        }

        // Descend through the receiver/object of this call to look
        // for an inner SQL prepare.
        let next = cur
            .child_by_field_name("receiver")
            .or_else(|| {
                cur.child_by_field_name("function").and_then(|fun| {
                    fun.child_by_field_name("object")
                        .or_else(|| fun.child_by_field_name("operand"))
                        .or_else(|| fun.child_by_field_name("argument"))
                        .or_else(|| fun.child_by_field_name("value"))
                })
            })
            .or_else(|| cur.child_by_field_name("object"));
        let next = next?;
        cur = unwrap_try_like(next);
    }
    None
}

/// Recognised SQL prepare/query method names. Matched against the
/// last segment of the callee.  String comparison only — we don't
/// constrain the receiver to a specific type; known DB connection
/// receivers are classified by the sink-class type gate, and this
/// list is the orthogonal verb axis.
fn is_sql_prepare_method(method: &str) -> bool {
    matches!(
        method,
        "prepare"
            | "query"
            | "query_one"
            | "query_all"
            | "query_as"
            | "query_map"
            | "query_row"
            | "query_scalar"
            | "fetch"
            | "fetch_one"
            | "fetch_all"
            | "fetch_optional"
            | "fetch_scalar"
            | "execute"
            | "exec"
    )
}

/// Extract the string content from a Rust string literal node, joining
/// adjacent fragments (e.g. `"a" "b"` becomes `"ab"`).  Returns `None`
/// when the node isn't a string literal at all.
fn collect_string_literal_text(node: Node<'_>, bytes: &[u8]) -> Option<String> {
    match node.kind() {
        "string_literal" | "raw_string_literal" => {
            let mut buf = String::new();
            let mut found = false;
            for child in named_children(node) {
                if child.kind() == "string_content" {
                    buf.push_str(&text(child, bytes));
                    found = true;
                }
            }
            if found {
                Some(buf)
            } else {
                Some(strip_quotes(&text(node, bytes)))
            }
        }
        "string" | "template_string" | "interpreted_string_literal" => {
            Some(strip_quotes(&text(node, bytes)))
        }
        _ => None,
    }
}

/// B3: `for ROW in X { … }` — when `X` (the iterator value) names a
/// SQL-authorized variable, mark `ROW` authorized too AND record
/// `row_field_vars[ROW] = X` so transitive subject coverage works
/// for column reads inside the loop body.
fn collect_for_row_binding(node: Node<'_>, bytes: &[u8], state: &mut UnitState) {
    let Some(pattern) = node.child_by_field_name("pattern") else {
        return;
    };
    let Some(var_name) = first_identifier_name(pattern, bytes) else {
        return;
    };
    if var_name.is_empty() {
        return;
    }
    let Some(value) = node.child_by_field_name("value") else {
        return;
    };
    // The iterated expression is often `&X`, `X.iter()`, `X.into_iter()`,
    // etc.  Walk through reference / common iterator-method wrappers
    // to recover the underlying var name.
    let Some(source_var) = single_iter_source_name(value, bytes) else {
        return;
    };
    state
        .row_field_vars
        .insert(var_name.clone(), source_var.clone());
    if state.authorized_sql_vars.contains(&source_var) {
        state.authorized_sql_vars.insert(var_name);
    }
}

/// Recover the source identifier under common iteration-shape
/// wrappers: `X`, `&X`, `&mut X`, `X.iter()`, `X.iter_mut()`,
/// `X.into_iter()`, `X.values()`, `X.keys()`.  Returns `None` for
/// arbitrary expressions (`fetch_rows()`, `make_iter() + 1`, …).
fn single_iter_source_name(node: Node<'_>, bytes: &[u8]) -> Option<String> {
    match node.kind() {
        "identifier" => {
            let value = text(node, bytes);
            if value.is_empty() { None } else { Some(value) }
        }
        "reference_expression" | "parenthesized_expression" => {
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                if let Some(name) = single_iter_source_name(child, bytes) {
                    return Some(name);
                }
            }
            None
        }
        "call_expression" | "call" | "method_invocation" | "method_call_expression" => {
            let callee = call_name(node, bytes);
            let last = bare_method_name(&callee);
            if !matches!(
                last,
                "iter" | "iter_mut" | "into_iter" | "values" | "keys" | "drain"
            ) {
                return None;
            }
            let receiver = node
                .child_by_field_name("receiver")
                .or_else(|| {
                    node.child_by_field_name("function").and_then(|fun| {
                        fun.child_by_field_name("object")
                            .or_else(|| fun.child_by_field_name("operand"))
                            .or_else(|| fun.child_by_field_name("argument"))
                            .or_else(|| fun.child_by_field_name("value"))
                    })
                })
                .or_else(|| node.child_by_field_name("object"))?;
            single_iter_source_name(receiver, bytes)
        }
        _ => None,
    }
}

/// B3: `let Y = ROW.method(..)` / `let Y = ROW.field` where `ROW` is
/// SQL-authorized — propagate authorized status to `Y` so any
/// downstream use (e.g. as a sink subject) is treated as covered.
/// `row_field_vars[Y] = ROW` is already populated by
/// `collect_row_field_binding`; this helper just propagates the
/// authorized-vars set along that edge.
fn propagate_sql_authorized_through_field_read(
    node: Node<'_>,
    bytes: &[u8],
    state: &mut UnitState,
) {
    let Some(pattern) = node.child_by_field_name("pattern") else {
        return;
    };
    let Some(var_name) = first_identifier_name(pattern, bytes) else {
        return;
    };
    if var_name.is_empty() {
        return;
    }
    let Some(value) = node.child_by_field_name("value") else {
        return;
    };
    let Some(source) = extract_row_receiver_name(value, bytes) else {
        return;
    };
    if state.authorized_sql_vars.contains(&source) {
        state.authorized_sql_vars.insert(var_name);
    }
}

/// Recognise type names that semantically mean "the authenticated
/// actor" as the type of a function parameter.  Used by
/// `collect_typed_extractor_self_actor` to seed `self_actor_vars` so
/// that downstream `V.id`-shaped subjects on a parameter of one of
/// these types count as actor context, not foreign scoped IDs.
///
/// The recogniser is intentionally type-only — no name heuristic on
/// the variable.  A handler signature
/// `pub async fn handler(.., local_user_view: LocalUserView)` is
/// recognised because the type name matches, not because the
/// parameter is conventionally named `local_user_view`.
///
/// **Two acceptance forms:**
///
/// 1. *Tight exact set* — names whose entire identity is "auth
///    subject": `Authenticated`, `Identity`, `Principal`.  Adding new
///    bare names to this set should be done sparingly; framework
///    types that include `User` should go through the structural
///    form instead.
///
/// 2. *Structural form* — a CamelCase identifier of the shape
///    `<PREFIX>User<SUFFIX>?` where `PREFIX` is one of `Local`,
///    `Current`, `Session`, `Auth`, `Authenticated`, `LoggedIn`,
///    `Admin`, and `SUFFIX` (optional) is one of `View`, `Info`,
///    `Context`, `Session`, `Token`.  Catches `LocalUserView`
///    (lemmy), `LocalUser`, `CurrentUser`, `LoggedInUser`,
///    `AuthenticatedUserContext`, etc.
///
/// **Deliberately *not* matched:**
/// * Bare `User` — too loose; `User` parameters are very often
///   deserialised payloads, not actor extractors.
/// * `UserView`, `UserPreferences` — same reason; the prefix is what
///   carries the auth signal, not the bare `User` segment.
fn is_self_actor_type_text(ty: &str) -> bool {
    let trimmed = ty
        .trim()
        .trim_start_matches('&')
        .trim_start_matches("mut ")
        .trim();
    let after_colons = trimmed.rsplit("::").next().unwrap_or(trimmed);
    let base = after_colons
        .split('<')
        .next()
        .unwrap_or(after_colons)
        .trim();
    if matches!(base, "Authenticated" | "Identity" | "Principal") {
        return true;
    }
    matches_self_actor_user_form(base)
}

/// Structural form: `<PREFIX>User<SUFFIX>?` where PREFIX is in the
/// authority-prefix vocabulary and SUFFIX is in the
/// auth-context-suffix vocabulary (or absent).
///
/// Implementation: strip a leading PREFIX, require the remainder to
/// start with `User`, and accept either an exact `User` match or a
/// `User`+SUFFIX match.  Case-sensitive on the segment boundaries
/// because we want CamelCase types only — `localuser` wouldn't be a
/// real Rust type name and matching it would create ambiguity with
/// payload identifiers.
fn matches_self_actor_user_form(base: &str) -> bool {
    const PREFIXES: &[&str] = &[
        "Local",
        "Current",
        "Session",
        "Authenticated",
        "Auth",
        "LoggedIn",
        "Admin",
    ];
    const SUFFIXES: &[&str] = &["View", "Info", "Context", "Session", "Token"];
    for prefix in PREFIXES {
        let Some(rest) = base.strip_prefix(prefix) else {
            continue;
        };
        let Some(after_user) = rest.strip_prefix("User") else {
            continue;
        };
        if after_user.is_empty() {
            return true;
        }
        if SUFFIXES.contains(&after_user) {
            return true;
        }
    }
    false
}

/// Extract a single-segment receiver name for a value node of the shape
/// `ROW.method(..)` or `ROW.field`. Returns `None` when the receiver
/// isn't a simple identifier (e.g. deeper chains like `ctx.db.get(..)`).
fn extract_row_receiver_name(node: Node<'_>, bytes: &[u8]) -> Option<String> {
    let node = unwrap_try_like(node);
    match node.kind() {
        "call_expression" | "call" | "method_invocation" | "method_call_expression" => {
            let function = node
                .child_by_field_name("function")
                .or_else(|| node.child_by_field_name("method"));
            let function = function?;
            single_ident_receiver(function, bytes)
                .or_else(|| single_ident_from_call_receiver(node, bytes))
        }
        "field_expression"
        | "member_expression"
        | "attribute"
        | "selector_expression"
        | "field_access" => single_ident_receiver(node, bytes),
        _ => None,
    }
}

fn single_ident_receiver(node: Node<'_>, bytes: &[u8]) -> Option<String> {
    let object = node
        .child_by_field_name("value")
        .or_else(|| node.child_by_field_name("object"))
        .or_else(|| node.child_by_field_name("operand"))
        .or_else(|| node.child_by_field_name("receiver"))?;
    single_ident_text(object, bytes)
}

fn single_ident_from_call_receiver(node: Node<'_>, bytes: &[u8]) -> Option<String> {
    let receiver = node
        .child_by_field_name("receiver")
        .or_else(|| node.child_by_field_name("object"))?;
    single_ident_text(receiver, bytes)
}

fn single_ident_text(node: Node<'_>, bytes: &[u8]) -> Option<String> {
    if matches!(
        node.kind(),
        "identifier" | "shorthand_property_identifier" | "field_identifier"
    ) {
        let value = text(node, bytes);
        if value.is_empty() { None } else { Some(value) }
    } else {
        None
    }
}

/// Strip `?` / `.await` / `&` / `&mut` wrappers from a value node,
/// returning the underlying call/field expression when present.
fn unwrap_try_like(node: Node<'_>) -> Node<'_> {
    let mut cur = node;
    loop {
        match cur.kind() {
            "try_expression"
            | "await_expression"
            | "reference_expression"
            | "parenthesized_expression" => {
                let Some(inner) = cur
                    .child_by_field_name("expression")
                    .or_else(|| cur.named_child(0))
                else {
                    return cur;
                };
                cur = inner;
            }
            _ => return cur,
        }
    }
}

/// Detect the `if OWNER != SELF { return ... }` (or `==` with `else`
/// early-exit) row-level ownership-equality pattern and emit a
/// synthetic `AuthCheck { kind: Ownership }`.  The AuthCheck is
/// back-dated to the row's `let` line — and populated with the row's
/// original fetch arguments as subjects — so the row-fetching call
/// (e.g. `db.query_one(.., &[doc_id])`) is also covered.
fn detect_ownership_equality_check(if_node: Node<'_>, bytes: &[u8], state: &mut UnitState) {
    let Some(condition_raw) = if_node.child_by_field_name("condition") else {
        return;
    };
    let Some(consequence) = if_node.child_by_field_name("consequence") else {
        return;
    };
    let alternative = if_node.child_by_field_name("alternative");
    let condition = unwrap_parens_local(condition_raw);
    if condition.kind() != "binary_expression" {
        return;
    }
    let Some(operator) = binary_operator_text(condition, bytes) else {
        return;
    };
    let is_ne = matches!(operator.as_str(), "!=" | "ne");
    let is_eq = matches!(operator.as_str(), "==" | "eq");
    if !is_ne && !is_eq {
        return;
    }
    let Some((left, right)) = binary_operands(condition) else {
        return;
    };

    let fail_branch = if is_ne {
        consequence
    } else if let Some(alt) = alternative {
        resolve_else_block(alt)
    } else {
        return;
    };

    if !branch_has_early_exit(fail_branch) {
        return;
    }

    let left_refs = extract_value_refs(left, bytes);
    let right_refs = extract_value_refs(right, bytes);

    let (owner_ref, _self_ref) = match (
        pick_owner_field_ref(&left_refs),
        pick_self_actor_ref(&right_refs),
    ) {
        (Some(o), Some(s)) => (o, s),
        _ => match (
            pick_owner_field_ref(&right_refs),
            pick_self_actor_ref(&left_refs),
        ) {
            (Some(o), Some(s)) => (o, s),
            _ => return,
        },
    };

    let row_binding = state.row_field_vars.get(&owner_ref.name).cloned();
    let if_line = if_node.start_position().row + 1;
    let if_span = span(if_node);
    let condition_text = text(condition, bytes);

    let (check_line, mut subjects) = match row_binding
        .as_ref()
        .and_then(|row| state.row_population_data.get(row).map(|v| (row, v)))
    {
        Some((row, (row_line, arg_refs))) => {
            let mut subjects = arg_refs.clone();
            subjects.push(ValueRef {
                source_kind: ValueSourceKind::Identifier,
                name: row.clone(),
                base: None,
                field: None,
                index: None,
                span: if_span,
            });
            (*row_line, subjects)
        }
        None => match row_binding.as_ref() {
            Some(row) => (
                if_line,
                vec![ValueRef {
                    source_kind: ValueSourceKind::Identifier,
                    name: row.clone(),
                    base: None,
                    field: None,
                    index: None,
                    span: if_span,
                }],
            ),
            None => (if_line, Vec::new()),
        },
    };
    subjects.push(owner_ref);

    state.auth_checks.push(AuthCheck {
        kind: AuthCheckKind::Ownership,
        callee: "(row ownership equality)".into(),
        subjects,
        span: if_span,
        line: check_line,
        args: Vec::new(),
        condition_text: Some(condition_text),
    });
}

fn unwrap_parens_local(node: Node<'_>) -> Node<'_> {
    if node.kind() == "parenthesized_expression"
        && let Some(inner) = node.named_child(0)
    {
        return unwrap_parens_local(inner);
    }
    node
}

fn binary_operator_text(node: Node<'_>, bytes: &[u8]) -> Option<String> {
    if let Some(op) = node.child_by_field_name("operator") {
        let value = text(op, bytes);
        if !value.is_empty() {
            return Some(value);
        }
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if !child.is_named() {
            let value = text(child, bytes);
            if !value.is_empty() {
                return Some(value);
            }
        }
    }
    None
}

fn binary_operands<'tree>(node: Node<'tree>) -> Option<(Node<'tree>, Node<'tree>)> {
    if let (Some(left), Some(right)) = (
        node.child_by_field_name("left"),
        node.child_by_field_name("right"),
    ) {
        return Some((left, right));
    }
    let children = named_children(node);
    match children.as_slice() {
        [left, right] => Some((*left, *right)),
        _ => None,
    }
}

fn resolve_else_block(alt: Node<'_>) -> Node<'_> {
    // Rust wraps the else branch in an `else_clause` with the block
    // as a named child. Other grammars differ, so we walk defensively.
    if alt.kind() == "else_clause"
        && let Some(block) = named_children(alt).into_iter().next()
    {
        return block;
    }
    alt
}

fn branch_has_early_exit(branch: Node<'_>) -> bool {
    named_children(branch).into_iter().any(node_is_early_exit)
}

fn node_is_early_exit(node: Node<'_>) -> bool {
    match node.kind() {
        "return_expression" | "return_statement" => true,
        "expression_statement" => named_children(node).into_iter().any(node_is_early_exit),
        _ => false,
    }
}

pub(super) fn is_owner_field_subject(subject: &ValueRef) -> bool {
    let raw = match subject.source_kind {
        ValueSourceKind::ArrayIndex => subject.base.as_deref().unwrap_or(&subject.name),
        _ => subject
            .field
            .as_deref()
            .or(subject.base.as_deref())
            .unwrap_or(&subject.name),
    };
    let key = canonical_name(raw);
    matches!(
        key.as_str(),
        "userid"
            | "ownerid"
            | "authorid"
            | "createdby"
            | "uploaderid"
            | "updatedby"
            | "submittedby"
            | "assignedto"
            | "creatorid"
            | "postedby"
    )
}

pub(super) fn is_self_actor_subject(subject: &ValueRef) -> bool {
    // `req.user.id`, `session.user.id`, `ctx.session.user.id`, etc.
    if subject.source_kind == ValueSourceKind::Session
        && subject
            .base
            .as_deref()
            .is_some_and(is_self_session_base_local)
    {
        return true;
    }
    // Plain member chains that name the caller directly: `user.id`,
    // `current_user.id`, `actor.id`. A3 widens this set via
    // `self_actor_vars`.
    let Some(field) = subject.field.as_deref() else {
        return false;
    };
    if !field.eq_ignore_ascii_case("id") {
        return false;
    }
    let Some(base) = subject.base.as_deref() else {
        return false;
    };
    let last = base.rsplit('.').next().unwrap_or(base);
    matches!(
        last,
        "user" | "current_user" | "currentUser" | "actor" | "current_actor"
    )
}

fn is_self_session_base_local(base: &str) -> bool {
    matches!(
        base,
        "req.session.user"
            | "request.session.user"
            | "session.user"
            | "req.session.currentUser"
            | "request.session.currentUser"
            | "session.currentUser"
            | "req.user"
            | "request.user"
            | "req.currentUser"
            | "request.currentUser"
            | "ctx.session.user"
            | "ctx.session.currentUser"
            | "ctx.state.user"
            | "ctx.state.currentUser"
    )
}

fn pick_owner_field_ref(refs: &[ValueRef]) -> Option<ValueRef> {
    refs.iter().find(|v| is_owner_field_subject(v)).cloned()
}

fn pick_self_actor_ref(refs: &[ValueRef]) -> Option<ValueRef> {
    refs.iter().find(|v| is_self_actor_subject(v)).cloned()
}

fn classify_auth_check(callee: &str, rules: &AuthAnalysisRules) -> AuthCheckKind {
    if rules.is_admin_guard(callee, &[]) || matches_name(callee, "isAdmin") {
        AuthCheckKind::AdminGuard
    } else if rules.is_login_guard(callee) {
        AuthCheckKind::LoginGuard
    } else if matches_name(callee, "checkMembership")
        || matches_name(callee, "hasWorkspaceMembership")
        || matches_name(callee, "isMember")
        || matches_name(callee, "requireMembership")
        || matches_name(callee, "check_membership")
        || matches_name(callee, "has_membership")
        || matches_name(callee, "has_membership?")
        || matches_name(callee, "require_membership")
        || matches_name(callee, "ensure_membership")
        || matches_name(callee, "member_of?")
        || matches_name(callee, "member?")
    {
        AuthCheckKind::Membership
    } else if matches_name(callee, "checkOwnership")
        || matches_name(callee, "isOwner")
        || matches_name(callee, "requireOwnership")
        || matches_name(callee, "check_ownership")
        || matches_name(callee, "has_ownership")
        || matches_name(callee, "require_ownership")
        || matches_name(callee, "ensure_ownership")
        || matches_name(callee, "is_owner")
        || matches_name(callee, "owner?")
        || matches_name(callee, "owns?")
    {
        AuthCheckKind::Ownership
    } else {
        AuthCheckKind::Other
    }
}

pub fn function_name(node: Node<'_>, bytes: &[u8]) -> Option<String> {
    function_definition_node(node)
        .child_by_field_name("name")
        .map(|name| text(name, bytes))
        .filter(|name| !name.is_empty())
}

fn function_params(node: Node<'_>, bytes: &[u8]) -> Vec<String> {
    let Some(params_node) = node.child_by_field_name("parameters") else {
        return Vec::new();
    };
    let mut params = Vec::new();
    collect_param_names(params_node, bytes, &mut params);
    params
}

/// Walk the tree starting at `node` and gather TS type-alias /
/// interface names whose body references a TRPC-marker type
/// (`TrpcSessionUser`, `TRPCContext`, …).  Recurses only through
/// container kinds that legitimately host top-level type aliases
/// (`program` / `module` / `export_statement` / namespace bodies);
/// stops at function or class bodies to avoid an O(units × tree)
/// blowup on files with many small functions.
///
/// No-op for non-TS files — the matched node kinds only exist in
/// the TS grammar.  Used by [`FileMeta::scan`] (called once per file
/// in `collect_top_level_units` / `attach_route_handler`) to amortise
/// the alias scan across all units in the same source file.
fn scan_trpc_aliases_visit(node: Node<'_>, bytes: &[u8], out: &mut HashSet<String>) {
    match node.kind() {
        "type_alias_declaration" | "interface_declaration" => {
            let body = node
                .child_by_field_name("value")
                .or_else(|| node.child_by_field_name("body"));
            if let Some(body) = body {
                let body_text = text(body, bytes);
                if body_text_references_trpc_marker(&body_text)
                    && let Some(name_node) = node.child_by_field_name("name")
                {
                    let name = text(name_node, bytes);
                    if !name.is_empty() {
                        out.insert(name);
                    }
                }
            }
            return;
        }
        // Recurse only through container kinds that legitimately host
        // top-level type aliases.  Skipping into function bodies /
        // class bodies / call arguments avoids an O(unit × tree)
        // blowup when `build_function_unit` triggers this scan once
        // per unit on files with thousands of small functions
        // (`tests/hostile_input_tests::many_small_functions_do_not_explode`).
        "program"
        | "source_file"
        | "module"
        | "export_statement"
        | "namespace_declaration"
        | "module_declaration"
        | "internal_module"
        | "ambient_declaration"
        | "lexical_declaration"
        | "variable_declaration"
        | "statement_block" => {}
        _ => return,
    }
    for idx in 0..node.named_child_count() {
        let Some(child) = node.named_child(idx as u32) else {
            continue;
        };
        scan_trpc_aliases_visit(child, bytes, out);
    }
}

fn body_text_references_trpc_marker(body_text: &str) -> bool {
    body_text.contains("TrpcSessionUser")
        || body_text.contains("TRPCContext")
        || body_text.contains("ProtectedTRPCContext")
        || body_text.contains("TrpcContext")
}

/// Recognise a TS `required_parameter` / `optional_parameter` whose
/// type annotation refers to a TRPC-shaped Options alias (or
/// inlines `TrpcSessionUser` directly), and add the destructured /
/// declared `ctx`-base to `self_scoped_session_bases` so subjects
/// rooted at `ctx.user.<id-like>` count as actor context downstream.
///
/// Three pattern shapes are handled:
///   1. Destructured shorthand: `({ ctx, input }: GetOptions)` →
///      add `"ctx.user"`.
///   2. Destructured rename: `({ ctx: c, input }: GetOptions)` →
///      add `"c.user"`.
///   3. Plain identifier: `(opts: GetOptions)` → add `"opts.ctx.user"`.
///
/// The rule is principled: we only fire when the param's type either
/// IS one of the file-level TRPC aliases (`state.trpc_alias_names`,
/// populated by [`scan_trpc_aliases_from_node_root`]) or its annotation
/// text inlines `TrpcSessionUser` directly.  Bare `ctx.user` is never
/// added to the static session-base list — that would over-suppress
/// in non-TRPC code.  Instead, the dynamic per-unit set
/// `self_scoped_session_bases` carries the lift.
fn collect_trpc_ctx_param(node: Node<'_>, bytes: &[u8], state: &mut UnitState) {
    let Some(pattern) = node.child_by_field_name("pattern") else {
        return;
    };
    let Some(ty_node) = node.child_by_field_name("type") else {
        return;
    };
    let ty_text = text(ty_node, bytes);
    if !type_text_is_trpc_options(&ty_text, &state.trpc_alias_names) {
        return;
    }

    if pattern.kind() == "object_pattern" {
        for idx in 0..pattern.named_child_count() {
            let Some(child) = pattern.named_child(idx as u32) else {
                continue;
            };
            match child.kind() {
                "shorthand_property_identifier_pattern" => {
                    let name = text(child, bytes);
                    if name.eq_ignore_ascii_case("ctx") {
                        state
                            .self_scoped_session_bases
                            .insert(format!("{name}.user"));
                    }
                }
                "object_assignment_pattern" => {
                    if let Some(left) = child.child_by_field_name("left") {
                        let name = if matches!(
                            left.kind(),
                            "identifier" | "shorthand_property_identifier_pattern"
                        ) {
                            text(left, bytes)
                        } else {
                            first_identifier_name(left, bytes).unwrap_or_default()
                        };
                        if name.eq_ignore_ascii_case("ctx") {
                            state
                                .self_scoped_session_bases
                                .insert(format!("{name}.user"));
                        }
                    }
                }
                "pair_pattern" => {
                    let key_node = child.child_by_field_name("key");
                    let local_node = child.child_by_field_name("value");
                    if let (Some(k), Some(v)) = (key_node, local_node) {
                        let key = text(k, bytes);
                        let local = first_identifier_name(v, bytes).unwrap_or_default();
                        if !local.is_empty() && key.eq_ignore_ascii_case("ctx") {
                            state
                                .self_scoped_session_bases
                                .insert(format!("{local}.user"));
                        }
                    }
                }
                _ => {}
            }
        }
        return;
    }

    if let Some(name) = first_identifier_name(pattern, bytes)
        && !name.is_empty()
    {
        state
            .self_scoped_session_bases
            .insert(format!("{name}.ctx.user"));
    }
}

/// True when the type-annotation text identifies a TRPC-shaped Options
/// type: it contains `TrpcSessionUser` directly (inline object type
/// literal), or it references one of the file-level TRPC alias names
/// from the pre-scan.
fn type_text_is_trpc_options(ty_text: &str, trpc_alias_names: &HashSet<String>) -> bool {
    if body_text_references_trpc_marker(ty_text) {
        return true;
    }
    let trimmed = ty_text.trim_start_matches(':').trim();
    if trimmed.is_empty() {
        return false;
    }
    // Match the leading identifier of the type (dropping any generic
    // suffix `<...>`).  This covers `GetOptions` and
    // `NonNullable<GetOptions>` shapes alike.
    let head = trimmed.split('<').next().unwrap_or(trimmed).trim();
    if trpc_alias_names.contains(head) {
        return true;
    }
    // Also accept the bare alias name appearing anywhere in the
    // annotation text — handles `Promise<GetOptions>` and other
    // wrappers without enumerating every shape.  Word-boundary check
    // avoids matching aliases that are substrings of longer
    // identifiers.
    for alias in trpc_alias_names {
        if alias.is_empty() {
            continue;
        }
        if let Some(idx) = ty_text.find(alias.as_str()) {
            let before_ok = idx == 0
                || !ty_text.as_bytes()[idx - 1].is_ascii_alphanumeric()
                    && ty_text.as_bytes()[idx - 1] != b'_';
            let end = idx + alias.len();
            let after_ok = end >= ty_text.len()
                || !ty_text.as_bytes()[end].is_ascii_alphanumeric()
                    && ty_text.as_bytes()[end] != b'_';
            if before_ok && after_ok {
                return true;
            }
        }
    }
    false
}

/// Extract the receiver-variable name from a Go `method_declaration`
/// (`func (c *Cache) ...` → `Some("c")`).  Returns `None` for any node
/// that doesn't expose a `receiver` field (Rust `function_item`,
/// Java `method_declaration`, JS arrow-functions, …).
///
/// Tree-sitter-go shape: `method_declaration` has a `receiver` field
/// whose value is a `parameter_list` containing a single
/// `parameter_declaration` with a `name` field (identifier) and a
/// `type` field (often `pointer_type`).  We only need the name.
pub fn method_receiver_name(node: Node<'_>, bytes: &[u8]) -> Option<String> {
    let receiver = node.child_by_field_name("receiver")?;
    extract_receiver_param_name(receiver, bytes)
}

fn extract_receiver_param_name(node: Node<'_>, bytes: &[u8]) -> Option<String> {
    if let Some(name_node) = node.child_by_field_name("name") {
        let name = text(name_node, bytes);
        if !name.is_empty() {
            return Some(name);
        }
    }
    for idx in 0..node.named_child_count() {
        let Some(child) = node.named_child(idx as u32) else {
            continue;
        };
        if let Some(found) = extract_receiver_param_name(child, bytes) {
            return Some(found);
        }
    }
    None
}

fn collect_param_names(node: Node<'_>, bytes: &[u8], out: &mut Vec<String>) {
    match node.kind() {
        "identifier" | "property_identifier" | "shorthand_property_identifier_pattern" => {
            let name = text(node, bytes);
            if !name.is_empty() && !out.contains(&name) {
                out.push(name);
            }
        }
        "default_parameter" | "typed_parameter" | "typed_default_parameter" => {
            if let Some(name) = node.child_by_field_name("name") {
                collect_param_names(name, bytes, out);
            }
        }
        _ => {
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                collect_param_names(child, bytes, out);
            }
        }
    }
}

pub fn is_function_like(node: Node<'_>) -> bool {
    matches!(
        node.kind(),
        "function_declaration"
            | "function_expression"
            | "arrow_function"
            | "function_definition"
            | "method_declaration"
            | "function_item"
            | "closure_expression"
            | "func_literal"
            | "decorated_definition"
            | "method"
            | "singleton_method"
            | "block"
            | "do_block"
    )
}

pub fn is_handler_reference(node: Node<'_>) -> bool {
    is_function_like(node)
        || matches!(
            node.kind(),
            "identifier"
                | "member_expression"
                | "attribute"
                | "selector_expression"
                | "field_expression"
                | "scoped_identifier"
                | "field_access"
                | "constant"
                | "scope_resolution"
        )
}

pub fn call_site_from_node(node: Node<'_>, bytes: &[u8]) -> CallSite {
    if matches!(
        node.kind(),
        "call_expression" | "call" | "method_invocation" | "method_call_expression"
    ) {
        let name = call_name(node, bytes);
        let arg_nodes = node
            .child_by_field_name("arguments")
            .map(named_children)
            .unwrap_or_default();
        let args = arg_nodes.iter().map(|arg| text(*arg, bytes)).collect();
        let args_value_refs = arg_nodes
            .iter()
            .map(|arg| extract_value_refs(*arg, bytes))
            .collect();
        CallSite {
            name,
            args,
            span: span(node),
            args_value_refs,
        }
    } else {
        CallSite {
            name: text(node, bytes),
            args: Vec::new(),
            span: span(node),
            args_value_refs: Vec::new(),
        }
    }
}

pub fn call_sites_from_value(node: Node<'_>, bytes: &[u8]) -> Vec<CallSite> {
    if matches!(node.kind(), "array" | "list" | "tuple") {
        named_children(node)
            .into_iter()
            .map(|child| call_site_from_node(child, bytes))
            .filter(|call| !call.name.is_empty())
            .collect()
    } else {
        let call = call_site_from_node(node, bytes);
        if call.name.is_empty() {
            Vec::new()
        } else {
            vec![call]
        }
    }
}

pub fn auth_check_from_call_site(
    call: &CallSite,
    line: usize,
    rules: &AuthAnalysisRules,
) -> Option<AuthCheck> {
    let kind = if rules.is_admin_guard(&call.name, &call.args) {
        AuthCheckKind::AdminGuard
    } else if rules.is_login_guard(&call.name) {
        AuthCheckKind::LoginGuard
    } else if rules.is_authorization_check(&call.name) {
        classify_auth_check(&call.name, rules)
    } else {
        return None;
    };

    Some(AuthCheck {
        kind,
        callee: call.name.clone(),
        subjects: Vec::new(),
        span: call.span,
        line,
        args: call.args.clone(),
        condition_text: None,
    })
}

pub fn extract_value_refs(node: Node<'_>, bytes: &[u8]) -> Vec<ValueRef> {
    match node.kind() {
        "member_expression"
        | "attribute"
        | "selector_expression"
        | "field_expression"
        | "field_access" => member_value_ref(node, bytes).into_iter().collect(),
        "subscript_expression" | "subscript" | "element_reference" | "index_expression" => {
            subscript_value_ref(node, bytes).into_iter().collect()
        }
        "call_expression" | "call" | "method_invocation" | "method_call_expression" => {
            call_value_ref(node, bytes)
                .map(|value| vec![value])
                .unwrap_or_else(|| {
                    let mut refs = Vec::new();
                    for idx in 0..node.named_child_count() {
                        let Some(child) = node.named_child(idx as u32) else {
                            continue;
                        };
                        refs.extend(extract_value_refs(child, bytes));
                    }
                    refs
                })
        }
        "identifier"
        // Ruby `@foo` instance variables and `@@foo` class variables are
        // leaves with no named children, so the catch-all recurse arm
        // would yield an empty subject set.  Surface them as Identifier
        // value-refs so receiver-side ownership checks (`@issue.visible?`)
        // produce a subject that the row-fetch exemption can match.
        | "instance_variable"
        | "class_variable"
        | "global_variable" => vec![ValueRef {
            source_kind: ValueSourceKind::Identifier,
            name: text(node, bytes),
            base: None,
            field: None,
            index: None,
            span: span(node),
        }],
        _ => {
            let mut refs = Vec::new();
            for idx in 0..node.named_child_count() {
                let Some(child) = node.named_child(idx as u32) else {
                    continue;
                };
                refs.extend(extract_value_refs(child, bytes));
            }
            refs
        }
    }
}

fn call_value_ref(node: Node<'_>, bytes: &[u8]) -> Option<ValueRef> {
    let callee = call_name(node, bytes);
    let args = node
        .child_by_field_name("arguments")
        .map(named_children)
        .unwrap_or_default();
    let chain = member_chain(node, bytes);

    if let Some(value) = accessor_call_value_ref(node, &callee, &chain, &args, bytes) {
        return Some(value);
    }

    if !args.is_empty() {
        return None;
    }
    if chain.is_empty() {
        return None;
    }
    let name = chain.join(".");
    let field = chain.last().cloned();
    let base = if chain.len() > 1 {
        Some(chain[..chain.len() - 1].join("."))
    } else {
        None
    };

    Some(ValueRef {
        source_kind: classify_member_chain(&chain),
        name,
        base,
        field,
        index: None,
        span: span(node),
    })
}

fn member_value_ref(node: Node<'_>, bytes: &[u8]) -> Option<ValueRef> {
    let chain = member_chain(node, bytes);
    if chain.is_empty() {
        return None;
    }
    let name = chain.join(".");
    let field = chain.last().cloned();
    let base = if chain.len() > 1 {
        Some(chain[..chain.len() - 1].join("."))
    } else {
        None
    };
    let source_kind = classify_member_chain(&chain);

    Some(ValueRef {
        source_kind,
        name,
        base,
        field,
        index: None,
        span: span(node),
    })
}

fn classify_member_chain(chain: &[String]) -> ValueSourceKind {
    if matches_request_param(chain) {
        ValueSourceKind::RequestParam
    } else if matches_request_body(chain) {
        ValueSourceKind::RequestBody
    } else if matches_request_query(chain) {
        ValueSourceKind::RequestQuery
    } else if matches_session_context(chain) {
        ValueSourceKind::Session
    } else if chain.first().is_some_and(|segment| {
        matches!(
            segment.to_ascii_lowercase().as_str(),
            "invitation" | "token" | "invite"
        )
    }) {
        ValueSourceKind::TokenField
    } else {
        ValueSourceKind::MemberField
    }
}

fn matches_request_param(chain: &[String]) -> bool {
    let lower = lower_segments(chain);
    (lower.first().is_some_and(|segment| segment == "params"))
        || (lower.len() >= 2 && lower[0] == "self" && lower[1] == "params")
        || (lower.len() >= 3
            && matches!(lower[0].as_str(), "req" | "request")
            && lower[1] == "params")
        || (lower.len() >= 3 && lower[0] == "ctx" && lower[1] == "params")
}

fn matches_request_body(chain: &[String]) -> bool {
    let lower = lower_segments(chain);
    (lower.len() >= 3 && matches!(lower[0].as_str(), "req" | "request") && lower[1] == "body")
        || (lower.len() >= 3
            && matches!(lower[0].as_str(), "req" | "request")
            && matches!(
                lower[1].as_str(),
                "form" | "json" | "values" | "post" | "data"
            ))
        || (lower.len() >= 4 && lower[0] == "ctx" && lower[1] == "request" && lower[2] == "body")
        || (lower.len() >= 3 && lower[0] == "ctx" && lower[1] == "body")
}

fn matches_request_query(chain: &[String]) -> bool {
    let lower = lower_segments(chain);
    (lower.len() >= 3 && matches!(lower[0].as_str(), "req" | "request") && lower[1] == "query")
        || (lower.len() >= 3
            && matches!(lower[0].as_str(), "req" | "request")
            && matches!(lower[1].as_str(), "args" | "get"))
        || (lower.len() >= 3 && lower[0] == "ctx" && lower[1] == "query")
        || (lower.len() >= 4 && lower[0] == "ctx" && lower[1] == "request" && lower[2] == "query")
}

fn matches_session_context(chain: &[String]) -> bool {
    let lower = lower_segments(chain);
    (lower.first().is_some_and(|segment| {
        matches!(
            segment.as_str(),
            "session"
                | "current_user"
                | "current_account"
                | "current_member"
                | "securitycontext"
                | "principal"
                | "authentication"
        )
    })) || (lower.len() >= 2
        && matches!(lower[0].as_str(), "req" | "request")
        && matches!(lower[1].as_str(), "session" | "user" | "currentuser"))
        || (lower.len() >= 3
            && lower[0] == "self"
            && matches!(lower[1].as_str(), "request" | "session" | "current_user")
            && matches!(lower[2].as_str(), "session" | "user" | "currentuser"))
        || (lower.len() >= 3
            && lower[0] == "ctx"
            && matches!(lower[1].as_str(), "session" | "state"))
}

fn subscript_value_ref(node: Node<'_>, bytes: &[u8]) -> Option<ValueRef> {
    let object = node
        .child_by_field_name("object")
        .or_else(|| node.child_by_field_name("value"))
        .or_else(|| node.child_by_field_name("operand"));
    let index = node
        .child_by_field_name("index")
        .or_else(|| node.child_by_field_name("subscript"));
    let (object, index) = if let (Some(object), Some(index)) = (object, index) {
        (object, index)
    } else {
        let children = named_children(node);
        match children.as_slice() {
            [object, index, ..] => (*object, *index),
            _ => return None,
        }
    };
    let base_chain = member_chain(object, bytes);
    let base = if base_chain.is_empty() {
        text(object, bytes)
    } else {
        base_chain.join(".")
    };
    let index_text = text(index, bytes);
    let field = Some(strip_quotes(&index_text));
    let source_kind = if base_chain.is_empty() {
        ValueSourceKind::ArrayIndex
    } else {
        match classify_member_chain(&base_chain) {
            ValueSourceKind::MemberField => ValueSourceKind::ArrayIndex,
            other => other,
        }
    };

    Some(ValueRef {
        source_kind,
        name: if source_kind == ValueSourceKind::ArrayIndex {
            format!("{base}[{index_text}]")
        } else {
            format!("{base}.{}", strip_quotes(&index_text))
        },
        base: Some(base),
        field,
        index: Some(index_text),
        span: span(node),
    })
}

pub fn member_chain(node: Node<'_>, bytes: &[u8]) -> Vec<String> {
    if node.kind() == "call" {
        let mut chain = if let Some(receiver) = node.child_by_field_name("receiver") {
            member_chain(receiver, bytes)
        } else {
            Vec::new()
        };
        let method = node
            .child_by_field_name("method")
            .or_else(|| node.child_by_field_name("name"))
            .map(|method| text(method, bytes))
            .unwrap_or_default();
        if !method.is_empty() {
            chain.push(method);
        }
        return chain;
    }

    if node.kind() == "method_invocation" || node.kind() == "method_call_expression" {
        let mut chain = node
            .child_by_field_name("object")
            .or_else(|| node.child_by_field_name("receiver"))
            .map(|object| member_chain(object, bytes))
            .unwrap_or_default();
        let method = node
            .child_by_field_name("name")
            .or_else(|| node.child_by_field_name("method"))
            .map(|method| text(method, bytes))
            .unwrap_or_default();
        if !method.is_empty() {
            chain.push(method);
        }
        return chain;
    }

    if node.kind() == "scope_resolution" {
        let mut chain = Vec::new();
        if let Some(scope) = node.child_by_field_name("scope") {
            chain.extend(member_chain(scope, bytes));
        }
        if let Some(name) = node.child_by_field_name("name") {
            let value = text(name, bytes);
            if !value.is_empty() {
                chain.push(value);
            }
        }
        return chain;
    }

    if node.kind() == "scoped_identifier" {
        let mut chain = Vec::new();
        if let Some(path) = node.child_by_field_name("path") {
            chain.extend(member_chain(path, bytes));
        }
        if let Some(name) = node.child_by_field_name("name") {
            let value = text(name, bytes);
            if !value.is_empty() {
                chain.push(value);
            }
        }
        return chain;
    }

    if !matches!(
        node.kind(),
        "member_expression"
            | "attribute"
            | "selector_expression"
            | "field_expression"
            | "field_access"
    ) {
        let value = text(node, bytes);
        return if value.is_empty() {
            Vec::new()
        } else {
            vec![value]
        };
    }

    let mut chain = Vec::new();
    if let Some(object) = node
        .child_by_field_name("object")
        .or_else(|| node.child_by_field_name("value"))
        .or_else(|| node.child_by_field_name("operand"))
        .or_else(|| node.child_by_field_name("argument"))
    {
        chain.extend(member_chain(object, bytes));
    }
    if let Some(property) = node
        .child_by_field_name("property")
        .or_else(|| node.child_by_field_name("attribute"))
        .or_else(|| node.child_by_field_name("field"))
        .or_else(|| node.child_by_field_name("name"))
    {
        let property_text = text(property, bytes);
        if !property_text.is_empty() {
            chain.push(property_text);
        }
    }
    chain
}

pub fn callee_name(node: Node<'_>, bytes: &[u8]) -> String {
    match node.kind() {
        "identifier" | "property_identifier" | "constant" | "field_identifier" => text(node, bytes),
        "member_expression"
        | "attribute"
        | "selector_expression"
        | "field_expression"
        | "scoped_identifier"
        | "field_access"
        | "scope_resolution"
        | "call"
        | "method_invocation"
        | "method_call_expression" => member_chain(node, bytes).join("."),
        _ => text(node, bytes),
    }
}

pub fn call_name(node: Node<'_>, bytes: &[u8]) -> String {
    if !matches!(
        node.kind(),
        "call_expression" | "call" | "method_invocation" | "method_call_expression"
    ) {
        return callee_name(node, bytes);
    }

    if let Some(function) = node.child_by_field_name("function") {
        return callee_name(function, bytes);
    }

    let method = node
        .child_by_field_name("method")
        .or_else(|| node.child_by_field_name("name"))
        .map(|child| text(child, bytes))
        .unwrap_or_default();
    let receiver = node
        .child_by_field_name("receiver")
        .or_else(|| node.child_by_field_name("object"))
        .or_else(|| node.child_by_field_name("scope"))
        .or_else(|| node.child_by_field_name("argument"))
        .map(|child| member_chain(child, bytes).join("."))
        .filter(|value| !value.is_empty());

    match (receiver, method.is_empty()) {
        (Some(receiver), false) => format!("{receiver}.{method}"),
        (_, false) => method,
        _ => text(node, bytes),
    }
}

pub fn member_target(node: Node<'_>, bytes: &[u8]) -> Option<(String, String)> {
    let object = node
        .child_by_field_name("object")
        .or_else(|| node.child_by_field_name("operand"))
        .or_else(|| node.child_by_field_name("value"))
        .or_else(|| node.child_by_field_name("receiver"))
        .or_else(|| node.child_by_field_name("argument"))?;
    let property = node
        .child_by_field_name("property")
        .or_else(|| node.child_by_field_name("field"))
        .or_else(|| node.child_by_field_name("attribute"))
        .or_else(|| node.child_by_field_name("name"))?;
    Some((text(object, bytes), text(property, bytes)))
}

pub fn http_method_from_name(name: &str) -> Option<HttpMethod> {
    match name.to_ascii_lowercase().as_str() {
        "get" => Some(HttpMethod::Get),
        "post" => Some(HttpMethod::Post),
        "put" => Some(HttpMethod::Put),
        "delete" => Some(HttpMethod::Delete),
        "patch" => Some(HttpMethod::Patch),
        "all" | "any" => Some(HttpMethod::All),
        "use" => Some(HttpMethod::Use),
        _ => None,
    }
}

pub fn join_route_paths(prefix: &str, route: &str) -> String {
    match (prefix.trim_end_matches('/'), route.trim_start_matches('/')) {
        ("", "") => "/".to_string(),
        ("", route) => format!("/{route}"),
        (prefix, "") => prefix.to_string(),
        (prefix, route) => format!("{prefix}/{route}"),
    }
}

fn call_receiver_subjects(node: Node<'_>, bytes: &[u8]) -> Vec<ValueRef> {
    let mut subjects = Vec::new();
    if let Some(receiver) = node
        .child_by_field_name("receiver")
        .or_else(|| node.child_by_field_name("object"))
        .or_else(|| node.child_by_field_name("argument"))
        .or_else(|| {
            node.child_by_field_name("function").and_then(|function| {
                function
                    .child_by_field_name("object")
                    .or_else(|| function.child_by_field_name("operand"))
                    .or_else(|| function.child_by_field_name("argument"))
            })
        })
    {
        subjects.extend(extract_value_refs(receiver, bytes));
    }
    subjects
}

pub fn string_literal_value(node: Node<'_>, bytes: &[u8]) -> Option<String> {
    match node.kind() {
        "string"
        | "template_string"
        | "string_literal"
        | "interpreted_string_literal"
        | "raw_string_literal" => Some(strip_quotes(&text(node, bytes))),
        _ => None,
    }
}

pub fn object_property_value<'tree>(
    node: Node<'tree>,
    bytes: &[u8],
    names: &[&str],
) -> Option<Node<'tree>> {
    if node.kind() != "object" {
        return None;
    }

    for child in named_children(node) {
        match child.kind() {
            "pair" => {
                let Some(key) = child.child_by_field_name("key") else {
                    continue;
                };
                let key_name = strip_quotes(&text(key, bytes));
                if names.iter().any(|name| *name == key_name) {
                    return child.child_by_field_name("value");
                }
            }
            "shorthand_property_identifier" | "identifier" => {
                let key_name = text(child, bytes);
                if names.iter().any(|name| *name == key_name) {
                    return Some(child);
                }
            }
            _ => {}
        }
    }

    None
}

pub fn decorated_definition_child(node: Node<'_>) -> Option<Node<'_>> {
    node.child_by_field_name("definition")
}

pub fn function_definition_node(node: Node<'_>) -> Node<'_> {
    decorated_definition_child(node).unwrap_or(node)
}

pub fn named_children(node: Node<'_>) -> Vec<Node<'_>> {
    let mut children = Vec::new();
    for idx in 0..node.named_child_count() {
        if let Some(child) = node.named_child(idx as u32) {
            children.push(child);
        }
    }
    children
}

pub fn text(node: Node<'_>, bytes: &[u8]) -> String {
    node.utf8_text(bytes).unwrap_or("").to_string()
}

pub fn span(node: Node<'_>) -> (usize, usize) {
    (node.start_byte(), node.end_byte())
}

fn dedup_value_refs(values: &mut Vec<ValueRef>) {
    let mut deduped = Vec::new();
    for value in values.drain(..) {
        if !deduped
            .iter()
            .any(|existing: &ValueRef| existing.name == value.name && existing.span == value.span)
        {
            deduped.push(value);
        }
    }
    *values = deduped;
}

fn lower_segments(chain: &[String]) -> Vec<String> {
    chain
        .iter()
        .map(|segment| segment.to_ascii_lowercase())
        .collect()
}

fn accessor_call_value_ref(
    node: Node<'_>,
    callee: &str,
    chain: &[String],
    args: &[Node<'_>],
    bytes: &[u8],
) -> Option<ValueRef> {
    let method = bare_method_name(callee);
    let field = args
        .first()
        .and_then(|arg| string_literal_value(*arg, bytes));
    let source_kind = match method {
        "Param" | "PathParam" => Some(ValueSourceKind::RequestParam),
        "Query" | "QueryParam" | "DefaultQuery" | "getParameter" | "getQueryString" => {
            Some(ValueSourceKind::RequestQuery)
        }
        "PostForm" | "FormValue" | "DefaultPostForm" => Some(ValueSourceKind::RequestBody),
        "Get" | "GetString" | "MustGet" | "getAttribute" => Some(ValueSourceKind::Session),
        _ if chain.first().is_some_and(|segment| {
            matches!(
                segment.to_ascii_lowercase().as_str(),
                "invitation" | "token" | "invite"
            )
        }) && method.starts_with("get")
            && method.len() > 3 =>
        {
            Some(ValueSourceKind::TokenField)
        }
        _ => None,
    }?;

    let normalized_field = field
        .or_else(|| {
            if source_kind == ValueSourceKind::TokenField && method.starts_with("get") {
                Some(method[3..].to_string())
            } else {
                None
            }
        })
        .map(|field| {
            let mut chars = field.chars();
            let Some(first) = chars.next() else {
                return field;
            };
            format!("{}{}", first.to_ascii_lowercase(), chars.as_str())
        })
        .filter(|field| !field.is_empty());

    let base = match source_kind {
        ValueSourceKind::Session => Some("session".to_string()),
        _ if chain.len() > 1 => Some(chain[..chain.len() - 1].join(".")),
        _ => chain.first().cloned(),
    };

    let name = if let Some(field) = normalized_field.as_deref() {
        match base.as_deref() {
            Some(base) if !base.is_empty() => format!("{base}.{field}"),
            _ => field.to_string(),
        }
    } else {
        callee.to_string()
    };

    Some(ValueRef {
        source_kind,
        name,
        base,
        field: normalized_field,
        index: None,
        span: span(node),
    })
}

#[cfg(test)]
mod tests {
    use super::{is_owner_field_subject, is_self_actor_subject, is_self_actor_type_text};
    use crate::auth_analysis::model::{ValueRef, ValueSourceKind};

    #[test]
    fn is_self_actor_type_text_matches_known_wrappers() {
        // Tight exact set: bare names whose entire identity is "auth subject".
        assert!(is_self_actor_type_text("Authenticated"));
        assert!(is_self_actor_type_text("Identity"));
        assert!(is_self_actor_type_text("Principal"));

        // Structural form: <PREFIX>User<SUFFIX?>.
        assert!(is_self_actor_type_text("CurrentUser"));
        assert!(is_self_actor_type_text("SessionUser"));
        assert!(is_self_actor_type_text("AuthUser"));
        assert!(is_self_actor_type_text("AdminUser"));
        assert!(is_self_actor_type_text("AuthenticatedUser"));
        // Lemmy: LocalUserView (the real-repo motivation for the
        // structural recogniser).
        assert!(is_self_actor_type_text("LocalUserView"));
        assert!(is_self_actor_type_text("LocalUser"));
        assert!(is_self_actor_type_text("LoggedInUser"));
        assert!(is_self_actor_type_text("CurrentUserContext"));
        assert!(is_self_actor_type_text("AuthenticatedUserSession"));
        assert!(is_self_actor_type_text("SessionUserToken"));
        assert!(is_self_actor_type_text("AdminUserInfo"));
        // Qualified paths resolve to last segment.
        assert!(is_self_actor_type_text("crate::auth::CurrentUser"));
        assert!(is_self_actor_type_text("crate::user::LocalUserView"));
        assert!(is_self_actor_type_text("&CurrentUser"));
        assert!(is_self_actor_type_text("&mut AuthUser"));
        // Generic wrappers: match on the base segment.
        assert!(is_self_actor_type_text("CurrentUser<Admin>"));
        assert!(is_self_actor_type_text("LocalUserView<Admin>"));

        // Non-matches.
        // Bare `User` — too loose; commonly a deserialised payload type.
        assert!(!is_self_actor_type_text("User"));
        assert!(!is_self_actor_type_text("UserPreferences"));
        // `UserView` lacks an authority-prefix segment and stays a
        // payload-shaped name.
        assert!(!is_self_actor_type_text("UserView"));
        // No prefix vocabulary match — still rejected.
        assert!(!is_self_actor_type_text("PaymentUser"));
        // Wrong suffix vocabulary.
        assert!(!is_self_actor_type_text("CurrentUserPreferences"));
        // Framework extractors / unrelated types.
        assert!(!is_self_actor_type_text("Db"));
        assert!(!is_self_actor_type_text("Path<(i64,)>"));
        assert!(!is_self_actor_type_text("Json<Body>"));
        // `RequireAuth` / `RequireLogin` were dropped from the exact
        // set: they aren't `User`-bearing types and aren't
        // semantically the auth subject — they're guard markers.  The
        // route-aware `axum::classify_guard_type` still treats them
        // as a login guard via the looser substring match.
        assert!(!is_self_actor_type_text("RequireAuth"));
        assert!(!is_self_actor_type_text("RequireLogin"));
    }

    fn ident(name: &str) -> ValueRef {
        ValueRef {
            source_kind: ValueSourceKind::Identifier,
            name: name.to_string(),
            base: None,
            field: None,
            index: None,
            span: (0, 0),
        }
    }

    fn member(base: &str, field: &str) -> ValueRef {
        ValueRef {
            source_kind: ValueSourceKind::MemberField,
            name: format!("{base}.{field}"),
            base: Some(base.to_string()),
            field: Some(field.to_string()),
            index: None,
            span: (0, 0),
        }
    }

    fn session(base: &str, field: &str) -> ValueRef {
        ValueRef {
            source_kind: ValueSourceKind::Session,
            name: format!("{base}.{field}"),
            base: Some(base.to_string()),
            field: Some(field.to_string()),
            index: None,
            span: (0, 0),
        }
    }

    #[test]
    fn is_owner_field_subject_matches_known_column_names() {
        assert!(is_owner_field_subject(&ident("owner_id")));
        assert!(is_owner_field_subject(&ident("user_id")));
        assert!(is_owner_field_subject(&ident("author_id")));
        assert!(is_owner_field_subject(&ident("created_by")));
        assert!(is_owner_field_subject(&member("row", "owner_id")));
        assert!(!is_owner_field_subject(&ident("group_id")));
        assert!(!is_owner_field_subject(&ident("doc_id")));
        assert!(!is_owner_field_subject(&ident("user")));
    }

    #[test]
    fn is_self_actor_subject_matches_known_self_shapes() {
        assert!(is_self_actor_subject(&member("user", "id")));
        assert!(is_self_actor_subject(&member("current_user", "id")));
        assert!(is_self_actor_subject(&session("req.user", "id")));
        assert!(is_self_actor_subject(&session("ctx.session.user", "id")));
        // Wrong field.
        assert!(!is_self_actor_subject(&member("user", "workspace_id")));
        // Unknown base.
        assert!(!is_self_actor_subject(&member("target", "id")));
        // Plain identifier, no base.
        assert!(!is_self_actor_subject(&ident("user_id")));
    }

    #[test]
    fn type_text_is_trpc_options_matches_alias_and_inline_marker() {
        use super::type_text_is_trpc_options;
        use std::collections::HashSet;
        let mut aliases = HashSet::new();
        aliases.insert("GetOptions".to_string());
        aliases.insert("UpdateOptions".to_string());

        // Inline `TrpcSessionUser` marker — accepted regardless of alias set.
        assert!(type_text_is_trpc_options(
            ": { ctx: { user: NonNullable<TrpcSessionUser> } }",
            &aliases
        ));
        assert!(type_text_is_trpc_options(
            ": { user: TrpcSessionUser }",
            &HashSet::new()
        ));

        // Plain alias name match.
        assert!(type_text_is_trpc_options(": GetOptions", &aliases));
        assert!(type_text_is_trpc_options("GetOptions", &aliases));

        // Generic-wrapped alias.
        assert!(type_text_is_trpc_options(": Promise<GetOptions>", &aliases));
        assert!(type_text_is_trpc_options(
            ": NonNullable<UpdateOptions>",
            &aliases
        ));

        // Negatives: alias not in set, no inline marker.
        assert!(!type_text_is_trpc_options(": OtherOptions", &aliases));
        assert!(!type_text_is_trpc_options(": Promise<Foo>", &aliases));
        assert!(!type_text_is_trpc_options(": SomeRandomType", &aliases));
        // Substring of a longer identifier must NOT match.
        assert!(!type_text_is_trpc_options(": MyGetOptionsX", &aliases));
    }

    #[test]
    fn body_text_references_trpc_marker_recognises_known_markers() {
        use super::body_text_references_trpc_marker as bm;
        assert!(bm("type X = { user: NonNullable<TrpcSessionUser> }"));
        assert!(bm("interface Ctx extends TRPCContext { ... }"));
        assert!(bm("type Ctx = ProtectedTRPCContext"));
        assert!(bm("export type Y = { ctx: TrpcContext }"));
        // Negatives.
        assert!(!bm("type X = { user: User }"));
        assert!(!bm("type X = SessionContext"));
        assert!(!bm("type X = { foo: SomeContext }"));
    }

    /// Pin the string-level analogue used by
    /// `value_is_self_scoped_session_id_chain`: it must accept the
    /// same set of session-scoped bases that `checks.rs::
    /// is_self_scoped_session_base` accepts.  When you add a new base
    /// to one, add it to the other and update both tests.
    #[test]
    fn is_self_scoped_session_base_text_matches_known_session_bases() {
        use super::is_self_scoped_session_base_text as bt;
        // Express / passport idioms.
        assert!(bt("req.user"));
        assert!(bt("request.user"));
        assert!(bt("req.session.user"));
        assert!(bt("req.session.currentUser"));
        // Bare session.user (Next.js / NextAuth idiom).
        assert!(bt("session.user"));
        assert!(bt("session.currentUser"));
        // Koa ctx.state / ctx.session.
        assert!(bt("ctx.session.user"));
        assert!(bt("ctx.state.user"));
        // Negatives — bases that are NOT canonical authed-user roots.
        assert!(!bt("req.body"));
        assert!(!bt("req.params"));
        assert!(!bt("ctx.user"));
        assert!(!bt("data.user"));
        assert!(!bt("user"));
    }
}