foxguard 0.6.2

Security scanner as fast as a linter. 170+ built-in rules, 10 languages, sub-second scans.
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
//! Intraprocedural, flow-insensitive taint analysis for JavaScript/TypeScript.
//!
//! Ported from `python_taint.rs` as part of issue #18. The surface mirrors
//! the Python engine intentionally — `TaintSpec`, `NodeMatcher`,
//! `TaintFinding`, and `analyze_tree` have identical shapes so a future
//! refactor that extracts the language-agnostic core is cheap. For now we
//! keep two engines so each grammar's quirks stay local.
//!
//! # Scope (same as Python)
//!
//! - **Per function.** Each `function_declaration`, `function_expression`,
//!   `arrow_function`, and `method_definition` body is analyzed independently.
//! - **Per file.** No cross-file analysis.
//! - **Flow-insensitive.** Statements are processed in source order; a
//!   reassignment with a clean RHS clears the target's taint.
//! - **No container sensitivity.** `x["k"]` is tainted when `x` is tainted.
//! - **One level of attribute propagation.** `req.body` is tainted when `req`
//!   is tainted. `req.body.name` is tainted when `req` is tainted.
//! - **One level of wrapping-call propagation.** `String(tainted)` stays
//!   tainted unless the callee is in `sanitizers`.
//! - **Template-literal propagation.** Any `template_string` with an
//!   interpolation whose expression is tainted is itself tainted.
//! - **Sanitizers collapse to "clean".**
//!
//! Everything specific to a library is expressed declaratively via `TaintSpec`.

use super::common::AliasTable;
use crate::rules::cross_file::{CrossFileSummaryMap, FunctionTaintSummary, ParamSinkFlow};
use std::borrow::Cow;
use std::collections::HashMap;
use std::path::PathBuf;
use tree_sitter::{Node, Tree};

// ─── Public API ───────────────────────────────────────────────────────────

/// A pattern that matches an AST node for taint analysis.
///
/// Surface matches `python_taint::NodeMatcher` exactly so both engines can
/// share a YAML bridge later.
#[derive(Debug, Clone)]
pub enum NodeMatcher {
    /// Match a member-expression access like `req.body` or `request.query`.
    ///
    /// Triggers whenever the *leftmost* identifier in a chain equals `root`
    /// and the *final* property segment equals `field`.
    Attribute {
        root: String,
        field: String,
        description: String,
    },

    /// Match a call whose callee resolves (raw or via the alias table) to
    /// `canonical`.
    Call {
        canonical: String,
        description: String,
    },

    /// Match any use of a function parameter whose name is in this list.
    /// Used to mark Express-style handlers `(req, res) => {...}` as having
    /// `req` pre-tainted without an explicit source assignment.
    ParamName {
        names: Vec<String>,
        description: String,
    },

    /// Match any method call whose final property name equals `method`,
    /// regardless of receiver. Only meaningful as a sink matcher.
    MethodName { method: String, description: String },

    /// Match an assignment where the LHS is a member expression whose
    /// property name equals `field`. JS-specific: covers the
    /// `element.innerHTML = tainted` pattern, which is not a call and so
    /// cannot be expressed as `Call`.
    MemberAssign { field: String, description: String },
}

impl NodeMatcher {
    pub fn description(&self) -> &str {
        match self {
            NodeMatcher::Attribute { description, .. } => description,
            NodeMatcher::Call { description, .. } => description,
            NodeMatcher::ParamName { description, .. } => description,
            NodeMatcher::MethodName { description, .. } => description,
            NodeMatcher::MemberAssign { description, .. } => description,
        }
    }
}

/// Declarative taint specification consumed by the engine.
#[derive(Debug, Clone, Default)]
pub struct TaintSpec {
    pub sources: Vec<NodeMatcher>,
    pub sinks: Vec<NodeMatcher>,
    pub sanitizers: Vec<NodeMatcher>,
}

/// A single source→sink flow reported by the engine.
#[derive(Debug, Clone)]
pub struct TaintFinding {
    pub sink_start_byte: usize,
    pub sink_end_byte: usize,
    pub sink_line: usize,
    pub sink_column: usize,
    pub sink_end_line: usize,
    pub sink_end_column: usize,
    pub source_description: String,
    pub sink_description: String,
    /// 1-indexed line where the taint source was introduced.
    pub source_line: usize,
}

/// Cross-file context passed to `analyze_tree_with_cross_file` to enable
/// cross-file taint propagation. When `Some`, the engine resolves calls to
/// imported functions via the summary map and emits findings when tainted
/// arguments reach cross-file sinks.
#[derive(Clone)]
pub struct CrossFileInfo<'a> {
    /// Map from local import name (e.g. `"./services"` module specifier or
    /// local binding) to the resolved file path.
    pub import_to_path: &'a HashMap<String, PathBuf>,
    /// Cross-file summaries keyed by canonical file path.
    pub summaries: &'a CrossFileSummaryMap,
    /// The rule ID currently being analyzed. Cross-file findings are only
    /// emitted when the summary's `sink_rule_id` matches this value.
    pub current_rule_id: &'a str,
}

/// Return-taint summary map keyed by a function's simple name. Mirrors
/// `python_taint::ReturnSummary`. Only top-level `function_declaration`s
/// and arrow/function-expression helpers assigned to a `const`/`let`/
/// `var` identifier are collected — instance methods and object-literal
/// methods are out of scope for v1 because they live on objects with
/// different call semantics. Function-name collisions are resolved
/// last-write-wins (known v1 limitation).
pub type ReturnSummary = HashMap<String, Option<String>>;

/// Bundles the read-only context that every internal walker needs,
/// replacing the repeated `(source, spec, aliases, summaries)` tuple.
struct AnalysisContext<'a> {
    source: &'a str,
    spec: &'a TaintSpec,
    aliases: Option<&'a AliasTable>,
    summaries: &'a ReturnSummary,
    /// Cross-file info for resolving imported function calls.
    cross_file: Option<&'a CrossFileInfo<'a>>,
}

/// Run the taint engine over every function/method body inside `root` and
/// return one `TaintFinding` per source→sink flow.
///
/// Runs two passes per file. Pass 1 builds the return-taint summary for
/// every eligible function in the file. Pass 2 re-analyzes each scope
/// with that summary available so bare helper calls propagate their
/// return taint into the caller. See `python_taint::analyze_tree` for
/// the full design; the JS engine mirrors it.
pub fn analyze_tree(
    root: Node<'_>,
    source: &str,
    spec: &TaintSpec,
    aliases: Option<&AliasTable>,
) -> Vec<TaintFinding> {
    analyze_tree_with_cross_file(root, source, spec, aliases, None)
}

/// Like [`analyze_tree`] but with optional cross-file taint summaries.
///
/// When `cross_file` is `Some`, calls to imported functions are resolved
/// against the summary map. If a tainted argument reaches a sink in the
/// imported function (per its summary), a finding is emitted in the
/// caller's file.
pub fn analyze_tree_with_cross_file<'a>(
    root: Node<'_>,
    source: &'a str,
    spec: &'a TaintSpec,
    aliases: Option<&'a AliasTable>,
    cross_file: Option<&'a CrossFileInfo<'a>>,
) -> Vec<TaintFinding> {
    let empty_summary = ReturnSummary::new();
    let mut summaries = ReturnSummary::new();
    let pass1_ctx = AnalysisContext {
        source,
        spec,
        aliases,
        summaries: &empty_summary,
        cross_file: None,
    };
    collect_summary_targets(root, source, &mut |name, func_node| {
        let ret = summarize_function(func_node, &pass1_ctx);
        summaries.insert(name, ret);
    });

    let ctx = AnalysisContext {
        source,
        spec,
        aliases,
        summaries: &summaries,
        cross_file,
    };
    let mut findings = Vec::new();
    collect_function_scopes(root, &mut |func_node| {
        analyze_function(func_node, &ctx, &mut findings);
    });
    findings
}

/// Walk `root` and invoke `visit(name, body_node)` for every function
/// whose simple name we can recover: top-level `function_declaration`s
/// and `const foo = (...) => {...}` / `const foo = function(...) {...}`
/// variable declarators with an arrow-function or function-expression
/// initializer. Nested definitions inside other function scopes are NOT
/// descended into for v1 — their summaries would rarely be useful and
/// instance-method / class-method handling is explicitly out of scope.
fn collect_summary_targets<'tree, F>(node: Node<'tree>, source: &str, visit: &mut F)
where
    F: FnMut(String, Node<'tree>),
{
    // Function declarations: record by name, don't descend into their
    // body (nested helpers are out of scope for v1 summaries).
    if matches!(
        node.kind(),
        "function_declaration" | "generator_function_declaration"
    ) {
        if let Some(name) = node.child_by_field_name("name") {
            visit(node_text(name, source).to_string(), node);
        }
        return;
    }
    // `const foo = (...) => ...` / `const foo = function(...) {...}`
    if node.kind() == "variable_declarator" {
        if let (Some(name), Some(value)) = (
            node.child_by_field_name("name"),
            node.child_by_field_name("value"),
        ) {
            if name.kind() == "identifier"
                && matches!(value.kind(), "arrow_function" | "function_expression")
            {
                visit(node_text(name, source).to_string(), value);
                return;
            }
        }
    }
    // Otherwise recurse, but don't descend into *other* function scopes:
    // nested-scope helpers are out of scope for v1.
    if is_function_scope(node.kind()) {
        return;
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_summary_targets(child, source, visit);
    }
}

/// Pass-1 walker: compute the return-taint summary for a single function
/// scope. Walks the body with the normal state machinery but throws away
/// sink findings and records the first tainted return expression it sees.
fn summarize_function(func_node: Node<'_>, ctx: &AnalysisContext<'_>) -> Option<String> {
    let mut state = TaintState::default();
    if let Some(params) = func_node.child_by_field_name("parameters") {
        seed_param_sources(params, ctx.source, ctx.spec, &mut state);
    }
    if let Some(single) = func_node.child_by_field_name("parameter") {
        if single.kind() == "identifier" {
            let name = node_text(single, ctx.source);
            for matcher in &ctx.spec.sources {
                if let NodeMatcher::ParamName { names, description } = matcher {
                    if names.iter().any(|n| n == name) {
                        let line = single.start_position().row + 1;
                        state.taint(name.to_string(), description.clone(), line);
                        break;
                    }
                }
            }
        }
    }
    let body = func_node.child_by_field_name("body")?;

    // Arrow-function concise body (`() => expr`): the body field holds
    // the expression directly rather than a `statement_block`, and there
    // is no `return_statement` node to visit. Evaluate taint on it up
    // front so the summary still reflects the implicit return.
    if func_node.kind() == "arrow_function" && body.kind() != "statement_block" {
        return expression_taint(body, ctx, &state).map(|(desc, _line)| desc);
    }

    let mut scratch: Vec<TaintFinding> = Vec::new();
    let mut return_taint: Option<String> = None;
    walk_body_for_summary(body, ctx, &mut state, &mut scratch, &mut return_taint);
    return_taint
}

fn walk_body_for_summary(
    node: Node<'_>,
    ctx: &AnalysisContext<'_>,
    state: &mut TaintState,
    findings: &mut Vec<TaintFinding>,
    return_taint: &mut Option<String>,
) {
    if is_function_scope(node.kind()) {
        return;
    }

    match node.kind() {
        "variable_declarator" => {
            handle_variable_declarator(node, ctx, state);
        }
        "assignment_expression" => {
            handle_assignment(node, ctx, state, findings);
        }
        "call_expression" => {
            handle_call(node, ctx, state, findings);
        }
        "return_statement" => {
            if return_taint.is_none() {
                let mut cursor = node.walk();
                for child in node.named_children(&mut cursor) {
                    if let Some((desc, _line)) = expression_taint(child, ctx, state) {
                        *return_taint = Some(desc);
                        break;
                    }
                }
            }
        }
        _ => {}
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        walk_body_for_summary(child, ctx, state, findings, return_taint);
    }
}

// ─── Cross-file summary extraction ───────────────────────────────────────

/// Extract cross-file taint summaries for every exported function in a JS/TS
/// file. Each parameter is treated as a synthetic taint source and the engine
/// checks which sinks it can reach. The resulting summaries are consumed in
/// pass 2 by callers in other files.
///
/// The `rule_specs` argument should be the output of
/// [`crate::rules::javascript::js_taint_rule_specs()`].
pub fn extract_cross_file_summaries(
    root: Node<'_>,
    source: &str,
    aliases: Option<&AliasTable>,
    rule_specs: &[(&str, TaintSpec)],
) -> Vec<FunctionTaintSummary> {
    let mut summaries = Vec::new();

    collect_exported_functions(root, source, &mut |func_name, func_node| {
        let param_names = collect_param_names(func_node, source);
        if param_names.is_empty() {
            return;
        }

        let mut params_to_sink: Vec<ParamSinkFlow> = Vec::new();
        let mut params_to_return: Vec<usize> = Vec::new();

        for (param_idx, param_name) in param_names.iter().enumerate() {
            let synthetic_source = NodeMatcher::ParamName {
                names: vec![param_name.clone()],
                description: format!("parameter '{}'", param_name),
            };

            // Check return-taint: does this parameter flow to a return value?
            let return_spec = TaintSpec {
                sources: vec![synthetic_source.clone()],
                sinks: vec![],
                sanitizers: vec![],
            };
            let empty_summary = ReturnSummary::new();
            let return_ctx = AnalysisContext {
                source,
                spec: &return_spec,
                aliases,
                summaries: &empty_summary,
                cross_file: None,
            };
            let ret_taint = summarize_function(func_node, &return_ctx);
            if ret_taint.is_some() && !params_to_return.contains(&param_idx) {
                params_to_return.push(param_idx);
            }

            // Check sink-taint: does this parameter reach any sink?
            for (rule_id, rule_spec) in rule_specs {
                let synthetic_spec = TaintSpec {
                    sources: vec![synthetic_source.clone()],
                    sinks: rule_spec.sinks.clone(),
                    sanitizers: rule_spec.sanitizers.clone(),
                };
                let sink_ctx = AnalysisContext {
                    source,
                    spec: &synthetic_spec,
                    aliases,
                    summaries: &empty_summary,
                    cross_file: None,
                };
                let mut findings = Vec::new();
                analyze_function(func_node, &sink_ctx, &mut findings);
                if !findings.is_empty() {
                    let already = params_to_sink
                        .iter()
                        .any(|f| f.param_index == param_idx && f.sink_rule_id == *rule_id);
                    if !already {
                        params_to_sink.push(ParamSinkFlow {
                            param_index: param_idx,
                            sink_rule_id: rule_id.to_string(),
                            sink_description: findings[0].sink_description.clone(),
                        });
                    }
                }
            }
        }

        if !params_to_sink.is_empty() || !params_to_return.is_empty() {
            summaries.push(FunctionTaintSummary {
                name: func_name,
                params_to_return,
                params_to_sink,
            });
        }
    });

    summaries
}

/// Collect parameter names from a function node in declaration order.
fn collect_param_names(func_node: Node<'_>, source: &str) -> Vec<String> {
    let Some(params) = func_node.child_by_field_name("parameters") else {
        // Arrow with single bare parameter: `x => ...`
        if let Some(single) = func_node.child_by_field_name("parameter") {
            if single.kind() == "identifier" {
                return vec![node_text(single, source).to_string()];
            }
        }
        return Vec::new();
    };
    let mut names = Vec::new();
    let mut cursor = params.walk();
    for child in params.children(&mut cursor) {
        let param_name = match child.kind() {
            "identifier" => Some(node_text(child, source)),
            "assignment_pattern" => child
                .child_by_field_name("left")
                .filter(|n| n.kind() == "identifier")
                .map(|n| node_text(n, source)),
            "rest_pattern" => {
                let mut inner = child.walk();
                let mut found: Option<&str> = None;
                for c in child.named_children(&mut inner) {
                    if c.kind() == "identifier" {
                        found = Some(node_text(c, source));
                        break;
                    }
                }
                found
            }
            _ => None,
        };
        if let Some(name) = param_name {
            names.push(name.to_string());
        }
    }
    names
}

/// Walk the AST to find exported function declarations and their names.
/// Handles:
/// - `module.exports = { runQuery, evalExpression }` (CommonJS shorthand)
/// - `module.exports = { runQuery: runQuery }` (explicit value)
/// - `module.exports.foo = function(...)` (direct assignment)
/// - `export function foo(...)` / `export const foo = (...)` (ES modules)
/// - `export { foo }` (ES named re-exports)
///
/// The callback receives (function_name, function_node).
fn collect_exported_functions<'tree, F>(root: Node<'tree>, source: &str, visit: &mut F)
where
    F: FnMut(String, Node<'tree>),
{
    // First, find all top-level function declarations and const arrow/fn
    // assignments so we can resolve names to nodes.
    let mut func_defs: HashMap<String, Node<'tree>> = HashMap::new();
    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        match child.kind() {
            "function_declaration" | "generator_function_declaration" => {
                if let Some(name) = child.child_by_field_name("name") {
                    func_defs.insert(node_text(name, source).to_string(), child);
                }
            }
            "lexical_declaration" | "variable_declaration" => {
                let mut inner = child.walk();
                for decl in child.children(&mut inner) {
                    if decl.kind() == "variable_declarator" {
                        if let (Some(name), Some(value)) = (
                            decl.child_by_field_name("name"),
                            decl.child_by_field_name("value"),
                        ) {
                            if name.kind() == "identifier"
                                && matches!(value.kind(), "arrow_function" | "function_expression")
                            {
                                func_defs.insert(node_text(name, source).to_string(), value);
                            }
                        }
                    }
                }
            }
            "export_statement" => {
                // `export function foo(...)` or `export const foo = (...) => ...`
                let mut inner = child.walk();
                for c in child.children(&mut inner) {
                    match c.kind() {
                        "function_declaration" | "generator_function_declaration" => {
                            if let Some(name) = c.child_by_field_name("name") {
                                let n = node_text(name, source).to_string();
                                func_defs.insert(n.clone(), c);
                                visit(n.clone(), c);
                                // If this is a default export, also register
                                // under the name "default" so that
                                // `import X from "..."` can resolve it.
                                let is_default = child.children(&mut child.walk()).any(|sib| {
                                    !sib.is_named() && node_text(sib, source) == "default"
                                });
                                if is_default {
                                    func_defs.insert("default".to_string(), c);
                                    visit("default".to_string(), c);
                                }
                            }
                        }
                        "lexical_declaration" | "variable_declaration" => {
                            let mut d = c.walk();
                            for decl in c.children(&mut d) {
                                if decl.kind() == "variable_declarator" {
                                    if let (Some(name), Some(value)) = (
                                        decl.child_by_field_name("name"),
                                        decl.child_by_field_name("value"),
                                    ) {
                                        if name.kind() == "identifier"
                                            && matches!(
                                                value.kind(),
                                                "arrow_function" | "function_expression"
                                            )
                                        {
                                            let n = node_text(name, source).to_string();
                                            func_defs.insert(n.clone(), value);
                                            visit(n, value);
                                        }
                                    }
                                }
                            }
                        }
                        // `export default function handler(req) {}` — named
                        // default export. Also handles anonymous:
                        // `export default function(req) {}` (function_expression
                        // without a name field).
                        "function_expression" | "arrow_function" => {
                            // Check if this export_statement has a `default` keyword.
                            let is_default = child
                                .children(&mut child.walk())
                                .any(|sib| !sib.is_named() && node_text(sib, source) == "default");
                            if is_default {
                                // Anonymous default export — use "default" as the name.
                                let n = "default".to_string();
                                func_defs.insert(n.clone(), c);
                                visit(n, c);
                            }
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }

    // Now scan for module.exports patterns.
    scan_module_exports(root, source, &func_defs, visit);
}

/// Scan for `module.exports = { ... }` and `module.exports.x = ...` patterns.
fn scan_module_exports<'tree, F>(
    root: Node<'tree>,
    source: &str,
    func_defs: &HashMap<String, Node<'tree>>,
    visit: &mut F,
) where
    F: FnMut(String, Node<'tree>),
{
    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        if child.kind() != "expression_statement" {
            continue;
        }
        let Some(expr) = child.named_child(0) else {
            continue;
        };
        if expr.kind() != "assignment_expression" {
            continue;
        }
        let Some(left) = expr.child_by_field_name("left") else {
            continue;
        };
        let Some(right) = expr.child_by_field_name("right") else {
            continue;
        };
        let left_text = node_text(left, source);

        // `module.exports = { runQuery, evalExpression }`
        if left_text == "module.exports" && right.kind() == "object" {
            let mut obj_cursor = right.walk();
            for prop in right.named_children(&mut obj_cursor) {
                match prop.kind() {
                    // `{ runQuery }` — shorthand
                    "shorthand_property_identifier" | "shorthand_property" => {
                        let name = node_text(prop, source).to_string();
                        if let Some(func_node) = func_defs.get(&name) {
                            visit(name, *func_node);
                        }
                    }
                    // `{ runQuery: runQuery }` or `{ runQuery: function(...) {} }`
                    "pair" => {
                        if let Some(key) = prop.child_by_field_name("key") {
                            let export_name = node_text(key, source).to_string();
                            if let Some(value) = prop.child_by_field_name("value") {
                                if matches!(value.kind(), "arrow_function" | "function_expression")
                                {
                                    visit(export_name, value);
                                } else if value.kind() == "identifier" {
                                    let ref_name = node_text(value, source);
                                    if let Some(func_node) = func_defs.get(ref_name) {
                                        visit(export_name, *func_node);
                                    }
                                }
                            }
                        }
                    }
                    _ => {}
                }
            }
        }

        // `module.exports.foo = function(...)` or `module.exports.foo = someFunc`
        if left_text.starts_with("module.exports.") {
            let export_name = left_text.strip_prefix("module.exports.").unwrap();
            if matches!(right.kind(), "arrow_function" | "function_expression") {
                visit(export_name.to_string(), right);
            } else if right.kind() == "identifier" {
                let ref_name = node_text(right, source);
                if let Some(func_node) = func_defs.get(ref_name) {
                    visit(export_name.to_string(), *func_node);
                }
            }
        }
    }
}

// ─── JS import resolution for cross-file analysis ────────────────────────

/// Resolve JS import/require specifiers to file paths on disk.
///
/// Handles:
/// - `const services = require("./services")` → resolve `./services` to
///   `services.js` (or `.ts`, `.mjs`, etc.) in the same directory
/// - `import { foo } from "./services"` → same resolution
/// - `const { foo } = require("./services")` → maps both the module name
///   and `__from__:./services:foo` for direct-name resolution
///
/// Returns a map from module specifier / synthetic keys to resolved file paths.
pub fn resolve_js_imports_to_paths(
    source: &str,
    tree: &Tree,
    current_file: &std::path::Path,
) -> HashMap<String, PathBuf> {
    let mut result = HashMap::new();
    let Some(parent_dir) = current_file.parent() else {
        return result;
    };

    resolve_js_imports_walk(&mut result, tree.root_node(), source, parent_dir);
    result
}

/// File extensions to try when resolving a bare JS/TS module specifier.
const JS_EXTENSIONS: &[&str] = &[".js", ".ts", ".mjs", ".cjs", ".jsx", ".tsx"];

/// Try to resolve a relative module specifier to a file on disk.
/// Tries the specifier as-is first, then with each extension, then as
/// a directory with `index.*`.
fn resolve_js_module_path(parent_dir: &std::path::Path, specifier: &str) -> Option<PathBuf> {
    // Only resolve relative specifiers (starting with . or ..)
    if !specifier.starts_with('.') {
        return None;
    }

    let base = parent_dir.join(specifier);

    // 1. Try the specifier as-is (e.g. `./services.js`)
    if base.is_file() {
        return Some(base);
    }

    // 2. Try appending each extension
    for ext in JS_EXTENSIONS {
        let candidate = parent_dir.join(format!("{}{}", specifier, ext));
        if candidate.is_file() {
            return Some(candidate);
        }
    }

    // 3. Try as directory with index.*
    if base.is_dir() {
        for ext in JS_EXTENSIONS {
            let candidate = base.join(format!("index{}", ext));
            if candidate.is_file() {
                return Some(candidate);
            }
        }
    }

    None
}

fn resolve_js_imports_walk(
    result: &mut HashMap<String, PathBuf>,
    node: Node<'_>,
    source: &str,
    parent_dir: &std::path::Path,
) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "import_statement" => {
                resolve_js_import_statement(result, child, source, parent_dir);
            }
            "lexical_declaration" | "variable_declaration" => {
                resolve_js_require_decl(result, child, source, parent_dir);
            }
            "export_statement" => {
                // `export { foo } from "./mod"` — treat like an import
                resolve_js_import_statement(result, child, source, parent_dir);
            }
            "program" | "statement_block" => {
                resolve_js_imports_walk(result, child, source, parent_dir);
            }
            _ => {}
        }
    }
}

fn resolve_js_import_statement(
    result: &mut HashMap<String, PathBuf>,
    node: Node<'_>,
    source: &str,
    parent_dir: &std::path::Path,
) {
    let Some(src_node) = node.child_by_field_name("source") else {
        return;
    };
    let module = string_literal_text(src_node, source);
    if module.is_empty() {
        return;
    }
    let Some(resolved) = resolve_js_module_path(parent_dir, &module) else {
        return;
    };

    // Map the module specifier to the resolved path.
    result.insert(module.clone(), resolved.clone());

    // For named imports `import { foo } from "./mod"`, also create
    // `__from__:./mod:foo` entries so `handle_cross_file_call` can resolve
    // direct calls to `foo(...)`.
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() != "import_clause" {
            continue;
        }
        let mut inner = child.walk();
        for spec in child.children(&mut inner) {
            match spec.kind() {
                "named_imports" => {
                    let mut n_cursor = spec.walk();
                    for isp in spec.children(&mut n_cursor) {
                        if isp.kind() != "import_specifier" {
                            continue;
                        }
                        let name = isp
                            .child_by_field_name("name")
                            .map(|n| node_text(n, source).to_string());
                        let alias = isp
                            .child_by_field_name("alias")
                            .map(|n| node_text(n, source).to_string());
                        if let Some(real) = name {
                            let local = alias.unwrap_or_else(|| real.clone());
                            let key = format!("__from__:{}:{}", module, real);
                            result.insert(key, resolved.clone());
                            // Also map the local name → module for
                            // attribute-style calls
                            let local_key = format!("__from__:{}:{}", module, local);
                            if local != real {
                                result.insert(local_key, resolved.clone());
                            }
                        }
                    }
                }
                // `import handler from "./mod"` — default import.
                // The identifier inside import_clause is the local
                // binding for the default export.
                "identifier" => {
                    let local = node_text(spec, source).to_string();
                    let key = format!("__default__:{}:{}", module, local);
                    result.insert(key, resolved.clone());
                }
                _ => {}
            }
        }
    }
}

fn resolve_js_require_decl(
    result: &mut HashMap<String, PathBuf>,
    node: Node<'_>,
    source: &str,
    parent_dir: &std::path::Path,
) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() != "variable_declarator" {
            continue;
        }
        let Some(value) = child.child_by_field_name("value") else {
            continue;
        };
        let Some(module) = require_call_module(value, source) else {
            continue;
        };
        let Some(resolved) = resolve_js_module_path(parent_dir, &module) else {
            continue;
        };
        let Some(name_node) = child.child_by_field_name("name") else {
            continue;
        };

        // Map the module specifier to the resolved path.
        result.insert(module.clone(), resolved.clone());

        match name_node.kind() {
            "identifier" => {
                // `const services = require("./services")`
                // The local name (e.g. "services") maps to the module for
                // attribute-style calls: `services.runQuery(...)`.
                let local = node_text(name_node, source).to_string();
                result.insert(local, resolved.clone());
            }
            "object_pattern" => {
                // `const { runQuery } = require("./services")`
                let mut p_cursor = name_node.walk();
                for p in name_node.children(&mut p_cursor) {
                    match p.kind() {
                        "shorthand_property_identifier_pattern" => {
                            let local = node_text(p, source).to_string();
                            let key = format!("__from__:{}:{}", module, local);
                            result.insert(key, resolved.clone());
                        }
                        "pair_pattern" => {
                            let key_name = p
                                .child_by_field_name("key")
                                .map(|n| node_text(n, source).to_string());
                            let value_name = p
                                .child_by_field_name("value")
                                .map(|n| node_text(n, source).to_string());
                            if let (Some(real), Some(local)) = (key_name, value_name) {
                                let key = format!("__from__:{}:{}", module, real);
                                result.insert(key, resolved.clone());
                                if local != real {
                                    let lkey = format!("__from__:{}:{}", module, local);
                                    result.insert(lkey, resolved.clone());
                                }
                            }
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }
}

// ─── Per-file import alias table ──────────────────────────────────────────

/// Per-file JavaScript/TypeScript import alias table.
///
/// Build a JavaScript/TypeScript import alias table from a parsed tree.
///
/// Maps a local identifier (as it appears in the source) to its canonical
/// dotted path. Handles the common forms:
///
/// - `import { loads } from "pickle"`      -> `loads` -> `pickle.loads`
/// - `import { loads as d } from "pickle"` -> `d`     -> `pickle.loads`
/// - `import foo from "bar"`               -> `foo`   -> `bar` (default)
/// - `import * as ns from "mod"`           -> `ns`    -> `mod`
/// - `const pk = require("pickle")`        -> `pk`    -> `pickle`
/// - `const { loads } = require("pickle")` -> `loads` -> `pickle.loads`
/// - `const { loads: l2 } = require("pickle")` -> `l2` -> `pickle.loads`
///
/// File-scope only; function-local rebindings are not tracked. Dynamic
/// forms (`import("mod")`) are out of scope.
pub fn js_aliases_from_tree(source: &str, tree: &Tree) -> AliasTable {
    let mut aliases = AliasTable::new();
    js_walk_for_imports(&mut aliases, tree.root_node(), source);
    aliases
}

fn js_walk_for_imports(aliases: &mut AliasTable, node: Node<'_>, source: &str) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "import_statement" => js_collect_import(aliases, child, source),
            "lexical_declaration" | "variable_declaration" => {
                js_collect_require_decl(aliases, child, source);
            }
            // Recurse into top-level blocks/conditionals but stop at
            // function bodies — alias resolution there is out of scope.
            "program" | "statement_block" | "if_statement" | "try_statement"
            | "labeled_statement" | "export_statement" => {
                js_walk_for_imports(aliases, child, source);
            }
            _ => {}
        }
    }
}

fn js_collect_import(aliases: &mut AliasTable, node: Node<'_>, source: &str) {
    // import_statement has a `source` field holding a `string` with an
    // inner `string_fragment` that carries the module specifier.
    let Some(src_node) = node.child_by_field_name("source") else {
        return;
    };
    let module = string_literal_text(src_node, source);
    if module.is_empty() {
        return;
    }

    // The import clause is the unnamed child between `import` and `from`.
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() != "import_clause" {
            continue;
        }
        let mut inner = child.walk();
        for spec in child.children(&mut inner) {
            match spec.kind() {
                // `import foo from "bar"` — default import.
                "identifier" => {
                    let local = node_text(spec, source).to_string();
                    aliases.insert(local, module.clone());
                }
                // `import * as ns from "mod"` — namespace import.
                "namespace_import" => {
                    let mut ns_cursor = spec.walk();
                    for c in spec.children(&mut ns_cursor) {
                        if c.kind() == "identifier" {
                            let local = node_text(c, source).to_string();
                            aliases.insert(local, module.clone());
                        }
                    }
                }
                // `import { a, b as c } from "mod"` — named imports.
                "named_imports" => {
                    let mut n_cursor = spec.walk();
                    for isp in spec.children(&mut n_cursor) {
                        if isp.kind() != "import_specifier" {
                            continue;
                        }
                        let name = isp
                            .child_by_field_name("name")
                            .map(|n| node_text(n, source).to_string());
                        let alias = isp
                            .child_by_field_name("alias")
                            .map(|n| node_text(n, source).to_string());
                        if let Some(real) = name {
                            let canonical = format!("{}.{}", module, real);
                            let local = alias.unwrap_or(real);
                            aliases.insert(local, canonical);
                        }
                    }
                }
                _ => {}
            }
        }
    }
}

fn js_collect_require_decl(aliases: &mut AliasTable, node: Node<'_>, source: &str) {
    // Walk each variable_declarator under the decl.
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() != "variable_declarator" {
            continue;
        }
        let Some(value) = child.child_by_field_name("value") else {
            continue;
        };
        // Match `require("mod")` on the RHS.
        let Some(module) = require_call_module(value, source) else {
            continue;
        };
        let Some(name_node) = child.child_by_field_name("name") else {
            continue;
        };
        match name_node.kind() {
            "identifier" => {
                // `const pk = require("pickle")` -> pk -> pickle
                let local = node_text(name_node, source).to_string();
                aliases.insert(local, module);
            }
            "object_pattern" => {
                // `const { loads, dumps: d } = require("pickle")`
                let mut p_cursor = name_node.walk();
                for p in name_node.children(&mut p_cursor) {
                    match p.kind() {
                        "shorthand_property_identifier_pattern" => {
                            let local = node_text(p, source).to_string();
                            let canonical = format!("{}.{}", module, local);
                            aliases.insert(local, canonical);
                        }
                        "pair_pattern" => {
                            let key = p
                                .child_by_field_name("key")
                                .map(|n| node_text(n, source).to_string());
                            let value = p
                                .child_by_field_name("value")
                                .map(|n| node_text(n, source).to_string());
                            if let (Some(key), Some(value)) = (key, value) {
                                let canonical = format!("{}.{}", module, key);
                                aliases.insert(value, canonical);
                            }
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }
}

/// If `expr` is a `require("...")` call expression, return the module name.
fn require_call_module(expr: Node<'_>, source: &str) -> Option<String> {
    if expr.kind() != "call_expression" {
        return None;
    }
    let func = expr.child_by_field_name("function")?;
    if func.kind() != "identifier" || node_text(func, source) != "require" {
        return None;
    }
    let args = expr.child_by_field_name("arguments")?;
    let mut cursor = args.walk();
    for arg in args.named_children(&mut cursor) {
        if arg.kind() == "string" {
            return Some(string_literal_text(arg, source));
        }
    }
    None
}

/// Extract the textual content of a `string` literal node (without the
/// surrounding quotes), using its `string_fragment` child.
fn string_literal_text(node: Node<'_>, source: &str) -> String {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "string_fragment" {
            return node_text(child, source).to_string();
        }
    }
    // Empty-string literal has no fragment child — fall back to trimming.
    let raw = node_text(node, source);
    raw.trim_matches(|c: char| c == '"' || c == '\'' || c == '`')
        .to_string()
}

// ─── Internals ────────────────────────────────────────────────────────────

/// Node kinds that introduce a fresh taint scope (a function body).
fn is_function_scope(kind: &str) -> bool {
    matches!(
        kind,
        "function_declaration"
            | "function_expression"
            | "arrow_function"
            | "method_definition"
            | "generator_function"
            | "generator_function_declaration"
    )
}

fn collect_function_scopes<'tree, F>(node: Node<'tree>, visit: &mut F)
where
    F: FnMut(Node<'tree>),
{
    if is_function_scope(node.kind()) {
        visit(node);
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_function_scopes(child, visit);
    }
}

#[derive(Clone, Debug)]
struct TaintInfo {
    description: String,
    line: usize,
}

#[derive(Default)]
struct TaintState {
    tainted: HashMap<String, TaintInfo>,
}

impl TaintState {
    fn taint(&mut self, name: String, description: String, line: usize) {
        self.tainted.insert(name, TaintInfo { description, line });
    }

    fn clear(&mut self, name: &str) {
        self.tainted.remove(name);
    }

    fn info(&self, name: &str) -> Option<&TaintInfo> {
        self.tainted.get(name)
    }
}

fn analyze_function(
    func_node: Node<'_>,
    ctx: &AnalysisContext<'_>,
    findings: &mut Vec<TaintFinding>,
) {
    let mut state = TaintState::default();

    if let Some(params) = func_node.child_by_field_name("parameters") {
        seed_param_sources(params, ctx.source, ctx.spec, &mut state);
    }
    // Arrow functions with a single bare parameter have `parameter` instead
    // of `parameters` (e.g. `x => x + 1`). tree-sitter-javascript actually
    // wraps it in `formal_parameters` when there is a paren, but a bare
    // identifier parameter is an `identifier` child field-named `parameter`.
    if let Some(single) = func_node.child_by_field_name("parameter") {
        if single.kind() == "identifier" {
            let name = node_text(single, ctx.source);
            let line = single.start_position().row + 1;
            for matcher in &ctx.spec.sources {
                if let NodeMatcher::ParamName { names, description } = matcher {
                    if names.iter().any(|n| n == name) {
                        state.taint(name.to_string(), description.clone(), line);
                        break;
                    }
                }
            }
        }
    }

    let Some(body) = func_node.child_by_field_name("body") else {
        return;
    };
    walk_body(body, ctx, &mut state, findings);
}

fn seed_param_sources(params: Node<'_>, source: &str, spec: &TaintSpec, state: &mut TaintState) {
    let mut cursor = params.walk();
    for child in params.children(&mut cursor) {
        let param_name = match child.kind() {
            "identifier" => node_text(child, source),
            // `function f(x = 1)` — tree-sitter-javascript wraps the name in
            // an `assignment_pattern` with `left`/`right` fields.
            "assignment_pattern" => {
                let Some(left) = child.child_by_field_name("left") else {
                    continue;
                };
                if left.kind() != "identifier" {
                    continue;
                }
                node_text(left, source)
            }
            // Rest params `...rest`
            "rest_pattern" => {
                let mut inner = child.walk();
                let mut found: Option<&str> = None;
                for c in child.named_children(&mut inner) {
                    if c.kind() == "identifier" {
                        found = Some(node_text(c, source));
                        break;
                    }
                }
                match found {
                    Some(n) => n,
                    None => continue,
                }
            }
            _ => continue,
        };

        for matcher in &spec.sources {
            if let NodeMatcher::ParamName { names, description } = matcher {
                if names.iter().any(|n| n == param_name) {
                    let line = child.start_position().row + 1;
                    state.taint(param_name.to_string(), description.clone(), line);
                    break;
                }
            }
        }
    }
}

fn walk_body(
    node: Node<'_>,
    ctx: &AnalysisContext<'_>,
    state: &mut TaintState,
    findings: &mut Vec<TaintFinding>,
) {
    // Nested function scopes have their own taint state — skip them; they'll
    // be picked up independently by analyze_tree.
    if is_function_scope(node.kind()) {
        return;
    }

    match node.kind() {
        "variable_declarator" => handle_variable_declarator(node, ctx, state),
        "assignment_expression" => handle_assignment(node, ctx, state, findings),
        "call_expression" => handle_call(node, ctx, state, findings),
        _ => {}
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        walk_body(child, ctx, state, findings);
    }
}

fn handle_variable_declarator(node: Node<'_>, ctx: &AnalysisContext<'_>, state: &mut TaintState) {
    let Some(name) = node.child_by_field_name("name") else {
        return;
    };
    let Some(value) = node.child_by_field_name("value") else {
        // Bare `let x;` with no initializer — nothing to do.
        return;
    };

    if name.kind() == "identifier" {
        let lhs = node_text(name, ctx.source).to_string();
        if let Some((desc, src_line)) = expression_taint(value, ctx, state) {
            state.taint(lhs, desc, src_line);
        } else {
            state.clear(&lhs);
        }
        return;
    }

    // Destructuring: `const { a } = req.body` or `const [a, b] = arr`.
    // Conservative semantics: if the RHS is tainted at all, taint every
    // bound name. We do not attempt per-slot pairing for JS because
    // destructuring shapes are more varied than Python's tuple unpack.
    if matches!(name.kind(), "object_pattern" | "array_pattern") {
        let targets = collect_destructuring_targets(name, ctx.source);
        if let Some((desc, src_line)) = expression_taint(value, ctx, state) {
            for t in &targets {
                state.taint(t.clone(), desc.clone(), src_line);
            }
        } else {
            for t in &targets {
                state.clear(t);
            }
        }
    }
}

fn collect_destructuring_targets(node: Node<'_>, source: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        match child.kind() {
            "identifier" | "shorthand_property_identifier_pattern" => {
                out.push(node_text(child, source).to_string());
            }
            "pair_pattern" => {
                if let Some(v) = child.child_by_field_name("value") {
                    if v.kind() == "identifier" {
                        out.push(node_text(v, source).to_string());
                    } else if matches!(v.kind(), "object_pattern" | "array_pattern") {
                        out.extend(collect_destructuring_targets(v, source));
                    }
                }
            }
            "object_pattern" | "array_pattern" => {
                out.extend(collect_destructuring_targets(child, source));
            }
            "rest_pattern" => {
                let mut inner = child.walk();
                for c in child.named_children(&mut inner) {
                    if c.kind() == "identifier" {
                        out.push(node_text(c, source).to_string());
                    }
                }
            }
            _ => {}
        }
    }
    out
}

fn handle_assignment(
    node: Node<'_>,
    ctx: &AnalysisContext<'_>,
    state: &mut TaintState,
    findings: &mut Vec<TaintFinding>,
) {
    let (Some(left), Some(right)) = (
        node.child_by_field_name("left"),
        node.child_by_field_name("right"),
    ) else {
        return;
    };

    // Check MemberAssign sinks first: `el.innerHTML = tainted`.
    if left.kind() == "member_expression" {
        if let Some(prop) = left.child_by_field_name("property") {
            let prop_name = node_text(prop, ctx.source);
            if let Some(sink_desc) = ctx.spec.sinks.iter().find_map(|m| match m {
                NodeMatcher::MemberAssign { field, description } if field == prop_name => {
                    Some(description.clone())
                }
                _ => None,
            }) {
                if let Some((src_desc, src_line)) = expression_taint(right, ctx, state) {
                    let start = node.start_position();
                    let end = node.end_position();
                    findings.push(TaintFinding {
                        sink_start_byte: node.start_byte(),
                        sink_end_byte: node.end_byte(),
                        sink_line: start.row + 1,
                        sink_column: start.column + 1,
                        sink_end_line: end.row + 1,
                        sink_end_column: end.column + 1,
                        source_description: src_desc,
                        sink_description: sink_desc,
                        source_line: src_line,
                    });
                }
            }
        }
        // Member-expression LHS: no local name to taint.
        return;
    }

    if left.kind() == "identifier" {
        let lhs = node_text(left, ctx.source).to_string();
        if let Some((desc, src_line)) = expression_taint(right, ctx, state) {
            state.taint(lhs, desc, src_line);
        } else {
            state.clear(&lhs);
        }
        return;
    }

    // Destructuring LHS: `({ a } = req.body)` or `[a, b] = arr`.
    if matches!(left.kind(), "object_pattern" | "array_pattern") {
        let targets = collect_destructuring_targets(left, ctx.source);
        if let Some((desc, src_line)) = expression_taint(right, ctx, state) {
            for t in &targets {
                state.taint(t.clone(), desc.clone(), src_line);
            }
        } else {
            for t in &targets {
                state.clear(t);
            }
        }
    }
}

fn handle_call(
    node: Node<'_>,
    ctx: &AnalysisContext<'_>,
    state: &mut TaintState,
    findings: &mut Vec<TaintFinding>,
) {
    let Some(func) = node.child_by_field_name("function") else {
        return;
    };
    let callee_text = node_text(func, ctx.source);
    let resolved: Cow<'_, str> = match ctx.aliases {
        Some(a) => a.resolve(callee_text),
        None => Cow::Borrowed(callee_text),
    };
    let final_segment = resolved.rsplit('.').next().unwrap_or(resolved.as_ref());

    let sink_desc = ctx.spec.sinks.iter().find_map(|m| match m {
        NodeMatcher::Call {
            canonical,
            description,
        } if canonical.as_str() == resolved.as_ref() => Some(description.clone()),
        NodeMatcher::MethodName {
            method,
            description,
        } if method == final_segment => Some(description.clone()),
        _ => None,
    });

    if let Some(sink_desc) = sink_desc {
        let Some(args) = node.child_by_field_name("arguments") else {
            return;
        };
        let mut cursor = args.walk();
        for arg in args.named_children(&mut cursor) {
            if let Some((source_desc, src_line)) = expression_taint(arg, ctx, state) {
                let start = node.start_position();
                let end = node.end_position();
                findings.push(TaintFinding {
                    sink_start_byte: node.start_byte(),
                    sink_end_byte: node.end_byte(),
                    sink_line: start.row + 1,
                    sink_column: start.column + 1,
                    sink_end_line: end.row + 1,
                    sink_end_column: end.column + 1,
                    source_description: source_desc,
                    sink_description: sink_desc.clone(),
                    source_line: src_line,
                });
                break;
            }
        }
        return;
    }

    // ── Cross-file summary check ─────────────────────────────────────
    // If the callee is an imported function with cross-file summaries,
    // check whether any tainted argument reaches a sink in the imported
    // function (per its summary).
    if let Some(cross_file) = ctx.cross_file {
        handle_cross_file_call(node, func, callee_text, ctx, state, findings, cross_file);
    }
}

/// Check if a call targets an imported function with cross-file summaries.
///
/// Handles two import patterns:
/// - `const services = require("./services"); services.runQuery(x)` — attribute call
/// - `const { runQuery } = require("./services"); runQuery(x)` — direct call
/// - `import { runQuery } from "./services"; runQuery(x)` — ES import direct call
fn handle_cross_file_call(
    node: Node<'_>,
    func: Node<'_>,
    callee_text: &str,
    ctx: &AnalysisContext<'_>,
    state: &TaintState,
    findings: &mut Vec<TaintFinding>,
    cross_file: &CrossFileInfo<'_>,
) {
    let resolved = resolve_cross_file_callee(func, callee_text, ctx.source, cross_file);
    let Some((file_path, func_name)) = resolved else {
        return;
    };

    let Some(file_summaries) = cross_file.summaries.get(&file_path) else {
        return;
    };

    let Some(summary) = file_summaries.iter().find(|s| s.name == func_name) else {
        return;
    };

    // Collect argument nodes.
    let Some(args) = node.child_by_field_name("arguments") else {
        return;
    };
    let mut cursor = args.walk();
    let arg_nodes: Vec<Node<'_>> = args.named_children(&mut cursor).collect();

    for flow in &summary.params_to_sink {
        if flow.sink_rule_id != cross_file.current_rule_id {
            continue;
        }
        if flow.param_index >= arg_nodes.len() {
            continue;
        }
        let arg = arg_nodes[flow.param_index];
        if let Some((source_desc, src_line)) = expression_taint(arg, ctx, state) {
            let start = node.start_position();
            let end = node.end_position();
            findings.push(TaintFinding {
                sink_start_byte: node.start_byte(),
                sink_end_byte: node.end_byte(),
                sink_line: start.row + 1,
                sink_column: start.column + 1,
                sink_end_line: end.row + 1,
                sink_end_column: end.column + 1,
                source_description: source_desc,
                sink_description: format!(
                    "{} (via cross-file call to {})",
                    flow.sink_description, func_name
                ),
                source_line: src_line,
            });
            return;
        }
    }
}

/// Resolve a call-site callee to (file_path, function_name) using the
/// cross-file import map.
fn resolve_cross_file_callee(
    func: Node<'_>,
    callee_text: &str,
    source: &str,
    cross_file: &CrossFileInfo<'_>,
) -> Option<(PathBuf, String)> {
    // Pattern 1: attribute call `module.func(...)` where `module` is a
    // require'd/imported module (e.g. `services.runQuery`).
    if func.kind() == "member_expression" {
        if let Some(object) = func.child_by_field_name("object") {
            if object.kind() == "identifier" {
                let module_name = node_text(object, source);
                if let Some(file_path) = cross_file.import_to_path.get(module_name) {
                    if let Some(prop) = func.child_by_field_name("property") {
                        let func_name = node_text(prop, source).to_string();
                        return Some((file_path.clone(), func_name));
                    }
                }
            }
        }
    }

    // Pattern 2: direct call `func(...)` where `func` was destructured
    // from a require or imported with ES `import { func } from "..."`.
    if func.kind() == "identifier" {
        for (key, file_path) in cross_file.import_to_path.iter() {
            if let Some(rest) = key.strip_prefix("__from__:") {
                if let Some((_module, name)) = rest.split_once(':') {
                    if name == callee_text {
                        return Some((file_path.clone(), name.to_string()));
                    }
                }
            }
        }
    }

    // Pattern 3: `callee_text` might be a dotted path like `services.runQuery`
    // that wasn't parsed as a member_expression (e.g. from alias resolution).
    if callee_text.contains('.') {
        let parts: Vec<&str> = callee_text.splitn(2, '.').collect();
        if parts.len() == 2 {
            if let Some(file_path) = cross_file.import_to_path.get(parts[0]) {
                return Some((file_path.clone(), parts[1].to_string()));
            }
        }
    }

    // Pattern 4: default import — `import handler from "./mod"; handler(...)`.
    // The import resolution stores `__default__:./mod:handler` entries.
    if func.kind() == "identifier" {
        for (key, file_path) in cross_file.import_to_path.iter() {
            if let Some(rest) = key.strip_prefix("__default__:") {
                if let Some((_module, local_name)) = rest.split_once(':') {
                    if local_name == callee_text {
                        return Some((file_path.clone(), "default".to_string()));
                    }
                }
            }
        }
    }

    None
}

fn expression_taint(
    expr: Node<'_>,
    ctx: &AnalysisContext<'_>,
    state: &TaintState,
) -> Option<(String, usize)> {
    let expr_line = expr.start_position().row + 1;

    // Direct source match on this expression.
    if let Some(desc) = match_source(expr, ctx.source, ctx.spec, ctx.aliases) {
        return Some((desc, expr_line));
    }

    // Tainted identifier reference.
    if expr.kind() == "identifier" {
        let name = node_text(expr, ctx.source);
        if let Some(info) = state.info(name) {
            return Some((info.description.clone(), info.line));
        }
    }

    // Tainted member-expression root: `x.y` where `x` is tainted.
    if expr.kind() == "member_expression" {
        if let Some(object) = expr.child_by_field_name("object") {
            if let Some(result) = expression_taint(object, ctx, state) {
                return Some(result);
            }
        }
    }

    // Tainted subscript: `x[k]` where `x` is tainted (no key sensitivity).
    if expr.kind() == "subscript_expression" {
        if let Some(object) = expr.child_by_field_name("object") {
            if let Some(result) = expression_taint(object, ctx, state) {
                return Some(result);
            }
        }
    }

    // Template literals propagate taint through any interpolation whose
    // inner expression is tainted: `` `foo ${x}` `` is tainted when `x` is.
    if expr.kind() == "template_string" {
        let mut cursor = expr.walk();
        for child in expr.children(&mut cursor) {
            if child.kind() == "template_substitution" {
                let mut inner = child.walk();
                for inner_child in child.named_children(&mut inner) {
                    if let Some(result) = expression_taint(inner_child, ctx, state) {
                        return Some(result);
                    }
                }
            }
        }
    }

    // Ternary expression: `cond ? tainted : safe`.
    // Conservative: if EITHER branch is tainted, the result is tainted.
    if expr.kind() == "ternary_expression" {
        if let Some(consequence) = expr.child_by_field_name("consequence") {
            if let Some(result) = expression_taint(consequence, ctx, state) {
                return Some(result);
            }
        }
        if let Some(alternative) = expr.child_by_field_name("alternative") {
            if let Some(result) = expression_taint(alternative, ctx, state) {
                return Some(result);
            }
        }
    }

    // Binary plus (string concat): `"x" + tainted` is tainted.
    if expr.kind() == "binary_expression" {
        let mut cursor = expr.walk();
        for child in expr.named_children(&mut cursor) {
            if let Some(result) = expression_taint(child, ctx, state) {
                return Some(result);
            }
        }
    }

    // Await expression: `await <inner>` — unwrap and recurse so that
    // `await req.json()` propagates the taint of the inner call.
    if expr.kind() == "await_expression" {
        let mut cursor = expr.walk();
        for child in expr.named_children(&mut cursor) {
            if let Some(result) = expression_taint(child, ctx, state) {
                return Some(result);
            }
        }
    }

    // Array / object literals: propagate taint from any element.
    // This lets `[...req.body]` and `[tainted, clean]` carry taint.
    if matches!(expr.kind(), "array" | "object") {
        let mut cursor = expr.walk();
        for child in expr.named_children(&mut cursor) {
            if let Some(result) = expression_taint(child, ctx, state) {
                return Some(result);
            }
        }
    }

    // Spread element: `...inner` — unwrap and recurse into the inner expression
    // so that `[...req.body]` and `func(...tainted)` propagate taint.
    if expr.kind() == "spread_element" {
        let mut cursor = expr.walk();
        for child in expr.named_children(&mut cursor) {
            if let Some(result) = expression_taint(child, ctx, state) {
                return Some(result);
            }
        }
    }

    // Parenthesized / unary / sequence wrappers: recurse into children.
    if matches!(
        expr.kind(),
        "parenthesized_expression" | "unary_expression" | "sequence_expression"
    ) {
        let mut cursor = expr.walk();
        for child in expr.named_children(&mut cursor) {
            if let Some(result) = expression_taint(child, ctx, state) {
                return Some(result);
            }
        }
    }

    // Wrapping call: `String(tainted)` / `bytes(tainted)`. Sanitizers short
    // circuit this and collapse to clean.
    if expr.kind() == "call_expression" {
        if is_sanitizer_call(expr, ctx.source, ctx.spec, ctx.aliases) {
            return None;
        }
        if let Some(args) = expr.child_by_field_name("arguments") {
            let mut cursor = args.walk();
            for arg in args.named_children(&mut cursor) {
                if let Some(result) = expression_taint(arg, ctx, state) {
                    return Some(result);
                }
            }
        }

        // Method-call propagation on a tainted root: `x.foo(...)` is
        // tainted when the receiver `x` (or any member/subscript chain
        // rooted at a tainted value) is tainted. Conservative: tainted-in
        // → tainted-out, mirroring the wrapping-call rule. Method calls
        // on literal receivers (e.g. `"foo".toUpperCase()`) are NOT
        // tainted because the recursive `expression_taint` on the object
        // returns None for a bare string literal.
        if let Some(func) = expr.child_by_field_name("function") {
            if func.kind() == "member_expression" {
                if let Some(object) = func.child_by_field_name("object") {
                    if let Some(result) = expression_taint(object, ctx, state) {
                        return Some(result);
                    }
                }
            }
        }

        // Same-file interprocedural v1: a bare identifier callee whose
        // name is in the return-summary map propagates the summary's
        // taint description through the call result. Method calls
        // (`obj.helper()`) are out of scope for v1.
        if let Some(func) = expr.child_by_field_name("function") {
            if func.kind() == "identifier" {
                let callee = node_text(func, ctx.source);
                if let Some(Some(desc)) = ctx.summaries.get(callee) {
                    return Some((format!("{desc} (via {callee})"), expr_line));
                }
            }
        }
    }

    None
}

fn is_sanitizer_call(
    call_node: Node<'_>,
    source: &str,
    spec: &TaintSpec,
    aliases: Option<&AliasTable>,
) -> bool {
    if call_node.kind() != "call_expression" {
        return false;
    }
    let Some(func) = call_node.child_by_field_name("function") else {
        return false;
    };
    let callee_text = node_text(func, source);
    let resolved: Cow<'_, str> = match aliases {
        Some(a) => a.resolve(callee_text),
        None => Cow::Borrowed(callee_text),
    };
    let final_segment = resolved.rsplit('.').next().unwrap_or(&resolved);
    for matcher in &spec.sanitizers {
        match matcher {
            NodeMatcher::Call { canonical, .. } => {
                if callee_text == canonical.as_str() || resolved.as_ref() == canonical.as_str() {
                    return true;
                }
            }
            NodeMatcher::MethodName { method, .. } => {
                if method == final_segment {
                    return true;
                }
            }
            _ => {}
        }
    }
    false
}

fn match_source(
    node: Node<'_>,
    source: &str,
    spec: &TaintSpec,
    aliases: Option<&AliasTable>,
) -> Option<String> {
    for matcher in &spec.sources {
        match matcher {
            NodeMatcher::Attribute {
                root,
                field,
                description,
            } => {
                if node.kind() != "member_expression" {
                    continue;
                }
                let Some(prop) = node.child_by_field_name("property") else {
                    continue;
                };
                if node_text(prop, source) != field.as_str() {
                    continue;
                }
                let Some(raw_root) = leftmost_identifier(node, source) else {
                    continue;
                };
                if raw_root == root.as_str() {
                    return Some(description.clone());
                }
                if let Some(a) = aliases {
                    if a.resolve(raw_root).as_ref() == root.as_str() {
                        return Some(description.clone());
                    }
                }
            }
            NodeMatcher::Call {
                canonical,
                description,
            } => {
                if node.kind() != "call_expression" {
                    continue;
                }
                let Some(func) = node.child_by_field_name("function") else {
                    continue;
                };
                let callee_text = node_text(func, source);
                if callee_text == canonical.as_str() {
                    return Some(description.clone());
                }
                if let Some(a) = aliases {
                    if a.resolve(callee_text).as_ref() == canonical.as_str() {
                        return Some(description.clone());
                    }
                }
            }
            NodeMatcher::ParamName { .. } => {
                // Seeded at function entry, not matched on expressions.
            }
            NodeMatcher::MethodName { .. } | NodeMatcher::MemberAssign { .. } => {
                // Sink-only matchers.
            }
        }
    }
    None
}

/// Canonical set of untrusted-input sources for JavaScript/TypeScript web
/// handlers. Organized by framework; add new sources to the matching
/// section and keep the layout stable so future contributors know where
/// their entries belong.
///
/// Frameworks covered today:
/// 1. Generic handler parameters (`req`, `request`) — Express / Fastify /
///    Next.js App Router share this convention.
/// 2. Express-style `req.*` / `request.*` attribute access.
/// 3. Next.js App Router (`request.nextUrl.*`, `request.cookies.*`).
/// 4. Hono (`c.req.*` call / attribute patterns — `c` is intentionally
///    NOT added as a `ParamName` matcher because single-letter locals
///    named `c` are extremely common in generic JS and would explode
///    false positives).
/// 5. Fastify — largely overlaps with Express sources above; no new
///    matchers needed today, but future Fastify-only fields go here.
/// 6. SvelteKit (`event.request`, `event.params`, `event.url`). `event`
///    is intentionally NOT a `ParamName` matcher — browser DOM event
///    handlers use the same name and would flood false positives.
/// 7. Deno (`Deno.args`, `Deno.env.get`).
///
/// Several method-call sources (`request.headers.get(...)`,
/// `request.cookies.get(...)`, `request.formData()`, `request.json()`)
/// require the engine to propagate taint from a method-call *receiver*
/// into the call expression's result. That is tracked as issue #27 and
/// is not expressible with the `NodeMatcher` variants today. Once #27
/// lands, those patterns will fire automatically for any handler whose
/// parameter is already seeded as `request` / `req` — no new matchers
/// required here.
pub fn javascript_taint_sources() -> Vec<NodeMatcher> {
    vec![
        // ─── 1. Generic handler parameters ────────────────────────────
        NodeMatcher::ParamName {
            names: vec!["req".into(), "request".into()],
            description: "untrusted request parameter".into(),
        },
        // ─── 2. Express / general `req.*` and `request.*` ────────────
        NodeMatcher::Attribute {
            root: "req".into(),
            field: "body".into(),
            description: "req.body".into(),
        },
        NodeMatcher::Attribute {
            root: "req".into(),
            field: "query".into(),
            description: "req.query".into(),
        },
        NodeMatcher::Attribute {
            root: "req".into(),
            field: "params".into(),
            description: "req.params".into(),
        },
        NodeMatcher::Attribute {
            root: "req".into(),
            field: "headers".into(),
            description: "req.headers".into(),
        },
        NodeMatcher::Attribute {
            root: "req".into(),
            field: "cookies".into(),
            description: "req.cookies".into(),
        },
        NodeMatcher::Attribute {
            root: "request".into(),
            field: "body".into(),
            description: "request.body".into(),
        },
        NodeMatcher::Attribute {
            root: "request".into(),
            field: "query".into(),
            description: "request.query".into(),
        },
        NodeMatcher::Attribute {
            root: "request".into(),
            field: "params".into(),
            description: "request.params".into(),
        },
        NodeMatcher::Attribute {
            root: "request".into(),
            field: "headers".into(),
            description: "request.headers".into(),
        },
        NodeMatcher::Attribute {
            root: "request".into(),
            field: "cookies".into(),
            description: "request.cookies".into(),
        },
        // ─── 3. Next.js App Router ───────────────────────────────────
        // `request.nextUrl` exposes a parsed URL — `.searchParams`,
        // `.pathname`, `.href` are all untrusted when `request` is the
        // handler input. `request.cookies` overlaps with Express above.
        // Method-call variants (`request.headers.get`, `request.json`,
        // `request.formData`, `request.cookies.get`) depend on issue
        // #27 — see the header comment above.
        NodeMatcher::Attribute {
            root: "request".into(),
            field: "nextUrl".into(),
            description: "Next.js request.nextUrl".into(),
        },
        // ─── 4. Hono ─────────────────────────────────────────────────
        // Hono handlers receive a context `c` whose `c.req` is the
        // untrusted request. Direct `c.req` attribute access is covered
        // by the `Attribute` matcher below; the most common call forms
        // are enumerated explicitly so the engine picks them up even
        // though `c` is never seeded via `ParamName` (see header
        // comment for the rationale).
        NodeMatcher::Attribute {
            root: "c".into(),
            field: "req".into(),
            description: "Hono c.req".into(),
        },
        NodeMatcher::Call {
            canonical: "c.req.query".into(),
            description: "Hono c.req.query()".into(),
        },
        NodeMatcher::Call {
            canonical: "c.req.param".into(),
            description: "Hono c.req.param()".into(),
        },
        NodeMatcher::Call {
            canonical: "c.req.header".into(),
            description: "Hono c.req.header()".into(),
        },
        NodeMatcher::Call {
            canonical: "c.req.json".into(),
            description: "Hono c.req.json()".into(),
        },
        NodeMatcher::Call {
            canonical: "c.req.formData".into(),
            description: "Hono c.req.formData()".into(),
        },
        NodeMatcher::Call {
            canonical: "c.req.parseBody".into(),
            description: "Hono c.req.parseBody()".into(),
        },
        // ─── 5. Fastify ──────────────────────────────────────────────
        // Fastify uses the same `request.body` / `.query` / `.params` /
        // `.headers` / `.cookies` surface as Express, so the section 2
        // matchers already cover it. Add Fastify-specific fields here
        // if any ever diverge.
        // ─── 6. SvelteKit ────────────────────────────────────────────
        // `event` is intentionally NOT a `ParamName` matcher — DOM
        // event handlers use the same name. Rely on explicit
        // attribute paths from the request event object.
        NodeMatcher::Attribute {
            root: "event".into(),
            field: "request".into(),
            description: "SvelteKit event.request".into(),
        },
        NodeMatcher::Attribute {
            root: "event".into(),
            field: "params".into(),
            description: "SvelteKit event.params".into(),
        },
        NodeMatcher::Attribute {
            root: "event".into(),
            field: "url".into(),
            description: "SvelteKit event.url".into(),
        },
        // ─── 7. Deno ─────────────────────────────────────────────────
        NodeMatcher::Attribute {
            root: "Deno".into(),
            field: "args".into(),
            description: "Deno.args".into(),
        },
        NodeMatcher::Call {
            canonical: "Deno.env.get".into(),
            description: "Deno.env.get()".into(),
        },
        // ─── 8. Koa ──────────────────────────────────────────────────
        // Koa handlers receive a context object `ctx`. `ctx.request.body`
        // is the parsed body; `ctx.query`, `ctx.params`, and `ctx.headers`
        // are delegated getters. `ctx.request.query` is covered by taint
        // propagation from the `ctx` root.
        NodeMatcher::ParamName {
            names: vec!["ctx".into()],
            description: "Koa context parameter".into(),
        },
        NodeMatcher::Attribute {
            root: "ctx".into(),
            field: "body".into(),
            description: "Koa ctx.request.body".into(),
        },
        NodeMatcher::Attribute {
            root: "ctx".into(),
            field: "query".into(),
            description: "Koa ctx.query".into(),
        },
        NodeMatcher::Attribute {
            root: "ctx".into(),
            field: "params".into(),
            description: "Koa ctx.params".into(),
        },
        NodeMatcher::Attribute {
            root: "ctx".into(),
            field: "headers".into(),
            description: "Koa ctx.headers".into(),
        },
        // ─── 9. NestJS ───────────────────────────────────────────────
        // NestJS uses decorators (@Body(), @Query(), @Param(), @Headers())
        // to inject request data into handler parameters. In compiled JS
        // the decorated parameters retain their names, so we match common
        // NestJS parameter names as a conservative approximation.
        NodeMatcher::ParamName {
            names: vec![
                "body".into(),
                "query".into(),
                "params".into(),
                "headers".into(),
            ],
            description: "NestJS decorated parameter".into(),
        },
    ]
}

/// Walk a member-expression chain leftward and return the leftmost
/// identifier text. For `req.body.name`, returns `"req"`. For `x.y`,
/// returns `"x"`.
fn leftmost_identifier<'a>(mut node: Node<'_>, source: &'a str) -> Option<&'a str> {
    loop {
        match node.kind() {
            "identifier" => return Some(node_text(node, source)),
            "member_expression" => {
                node = node.child_by_field_name("object")?;
            }
            "subscript_expression" => {
                node = node.child_by_field_name("object")?;
            }
            _ => return None,
        }
    }
}

fn node_text<'a>(node: Node<'_>, source: &'a str) -> &'a str {
    &source[node.byte_range()]
}

// ─── Tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::parser::parse_file;
    use crate::Language;

    fn spec_innerhtml_from_req() -> TaintSpec {
        TaintSpec {
            sources: javascript_taint_sources(),
            sinks: vec![
                NodeMatcher::MemberAssign {
                    field: "innerHTML".into(),
                    description: "innerHTML assignment".into(),
                },
                NodeMatcher::MemberAssign {
                    field: "outerHTML".into(),
                    description: "outerHTML assignment".into(),
                },
                NodeMatcher::Call {
                    canonical: "document.write".into(),
                    description: "document.write".into(),
                },
            ],
            sanitizers: vec![],
        }
    }

    fn run(source: &str) -> Vec<TaintFinding> {
        let tree = parse_file(source, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(source, &tree);
        analyze_tree(
            tree.root_node(),
            source,
            &spec_innerhtml_from_req(),
            Some(&aliases),
        )
    }

    #[test]
    fn direct_flow_req_body_to_innerhtml() {
        let src = r#"
function handler(req) {
    document.getElementById("x").innerHTML = req.body;
}
"#;
        let f = run(src);
        assert_eq!(f.len(), 1);
        assert!(f[0].source_description.contains("req.body"));
        assert_eq!(f[0].sink_description, "innerHTML assignment");
    }

    #[test]
    fn express_param_source_is_implicit() {
        // No explicit `req.body` access: the handler uses the bare `req`
        // parameter, which is tainted via ParamName.
        let src = r#"
app.get("/", function(req, res) {
    document.write(req);
});
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn express_param_source_via_field_access() {
        let src = r#"
app.get("/", function(req, res) {
    document.write(req.body.title);
});
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn template_literal_propagates_taint() {
        let src = r#"
function handler(req) {
    const el = document.getElementById("x");
    el.innerHTML = `<p>${req.body.name}</p>`;
}
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn reassignment_to_literal_kills_taint() {
        let src = r#"
function handler(req) {
    let data = req.body.data;
    data = "clean";
    document.write(data);
}
"#;
        assert_eq!(run(src).len(), 0);
    }

    #[test]
    fn subscript_on_tainted_root_is_tainted() {
        let src = r#"
function handler(req) {
    document.write(req.body["payload"]);
}
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn one_hop_assignment_propagates() {
        let src = r#"
function handler(req) {
    const name = req.query.name;
    document.getElementById("x").innerHTML = name;
}
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn alias_chain_propagates() {
        let src = r#"
function handler(req) {
    const data = req.body.data;
    const moreData = data;
    document.write(moreData);
}
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn no_source_no_finding() {
        let src = r#"
function handler() {
    const x = "static";
    document.write(x);
    document.getElementById("a").innerHTML = "<p>hi</p>";
}
"#;
        assert_eq!(run(src).len(), 0);
    }

    #[test]
    fn nested_function_has_independent_taint() {
        let src = r#"
function outer(req) {
    const data = req.body;
    function inner() {
        document.write(data);
    }
    return inner;
}
"#;
        // `outer` has no sink call; `inner` sees no source because `data`
        // is not in its local taint state.
        assert_eq!(run(src).len(), 0);
    }

    #[test]
    fn arrow_function_body_is_analyzed() {
        let src = r#"
const handler = (req, res) => {
    document.write(req.body.x);
};
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn alias_resolution_through_import_table() {
        // `const { loads } = require("pickle"); loads(x)` must resolve to
        // `pickle.loads` — verified via a spec that uses Call sink matching.
        let src = r#"
const { loads } = require("pickle");
function handler(req) {
    loads(req.body);
}
"#;
        let spec = TaintSpec {
            sources: javascript_taint_sources(),
            sinks: vec![NodeMatcher::Call {
                canonical: "pickle.loads".into(),
                description: "pickle.loads".into(),
            }],
            sanitizers: vec![],
        };
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let findings = analyze_tree(tree.root_node(), src, &spec, Some(&aliases));
        assert_eq!(findings.len(), 1);
    }

    #[test]
    fn alias_import_star_as_namespace() {
        let src = r#"
import * as pickle from "pickle";
function handler(req) {
    pickle.loads(req.body);
}
"#;
        let spec = TaintSpec {
            sources: javascript_taint_sources(),
            sinks: vec![NodeMatcher::Call {
                canonical: "pickle.loads".into(),
                description: "pickle.loads".into(),
            }],
            sanitizers: vec![],
        };
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let findings = analyze_tree(tree.root_node(), src, &spec, Some(&aliases));
        assert_eq!(findings.len(), 1);
    }

    #[test]
    fn require_default_binding_resolves() {
        let src = r#"const pk = require("pickle");"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let a = js_aliases_from_tree(src, &tree);
        assert_eq!(a.get("pk"), Some("pickle"));
        assert_eq!(a.resolve("pk.loads"), "pickle.loads");
    }

    #[test]
    fn named_import_with_alias_resolves() {
        let src = r#"import { loads as l2 } from "pickle";"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let a = js_aliases_from_tree(src, &tree);
        assert_eq!(a.get("l2"), Some("pickle.loads"));
    }

    #[test]
    fn string_concat_propagates_taint() {
        let src = r#"
function handler(req) {
    document.write("<h1>" + req.body.title + "</h1>");
}
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn interprocedural_tainted_return_propagates_to_caller() {
        // Use a module-scoped `req` so the caller's argument list is clean
        // and the only path to taint in the caller is via the helper's
        // return summary.
        let src = r#"
function getUserInput() {
    return req.body;
}

function handler() {
    const data = getUserInput();
    document.write(data);
}
"#;
        let f = run(src);
        assert_eq!(f.len(), 1);
        assert!(f[0].source_description.contains("getUserInput"));
    }

    #[test]
    fn interprocedural_clean_return_does_not_fire() {
        let src = r#"
function cleanHelper() {
    return "static";
}

function handler() {
    document.write(cleanHelper());
}
"#;
        assert_eq!(run(src).len(), 0);
    }

    #[test]
    fn interprocedural_late_definition_still_found() {
        let src = r#"
function handler() {
    const data = helper();
    document.write(data);
}

function helper() {
    return req.body;
}
"#;
        let f = run(src);
        assert_eq!(f.len(), 1);
        assert!(f[0].source_description.contains("helper"));
    }

    #[test]
    fn multi_hop_chain_is_out_of_scope_v1() {
        // Two-hop chain: `middle` calls `sourceFn`. Pass 1 uses an empty
        // summary, so `middle`'s return is seen as clean. Documented
        // v1 limitation — the test pins the behavior. The handler has
        // no tainted argument (no `req` param or access), so the only
        // path to taint would be a working multi-hop summary.
        let src = r#"
function sourceFn() {
    return req.body;
}

function middle() {
    return sourceFn();
}

function handler() {
    document.write(middle());
}
"#;
        assert_eq!(run(src).len(), 0);
    }

    #[test]
    fn interprocedural_arrow_function_helper_propagates() {
        // Arrow-function helper with concise body assigned to a const.
        let src = r#"
const getInput = () => req.body;

function handler() {
    document.write(getInput());
}
"#;
        let f = run(src);
        assert_eq!(f.len(), 1);
        assert!(f[0].source_description.contains("getInput"));
    }

    #[test]
    fn interprocedural_arrow_function_block_body_propagates() {
        let src = r#"
const getInput = () => { return req.body; };

function handler() {
    const data = getInput();
    document.write(data);
}
"#;
        let f = run(src);
        assert_eq!(f.len(), 1);
        assert!(f[0].source_description.contains("getInput"));
    }

    #[test]
    fn method_call_on_tainted_source_propagates() {
        // `req.body.get("x")` — receiver `req.body` is a source, method
        // call result must carry the taint into the sink.
        let src = r#"
function handler(req) {
    const data = req.body.get("x");
    document.write(data);
}
"#;
        let f = run(src);
        assert_eq!(f.len(), 1);
        assert!(f[0].source_description.contains("req.body"));
    }

    #[test]
    fn method_call_with_args_still_tainted() {
        let src = r#"
function handler(req) {
    const data = req.body.get("x", "default");
    document.write(data);
}
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn chained_method_calls_preserve_taint() {
        let src = r#"
function handler(req) {
    const data = req.body.get("x").trim().toUpperCase();
    document.write(data);
}
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn to_string_on_tainted_value_is_tainted() {
        let src = r#"
function handler(req) {
    const data = req.body.toString();
    document.write(data);
}
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn sanitizer_call_kills_taint() {
        let mut spec = spec_innerhtml_from_req();
        spec.sanitizers = vec![NodeMatcher::Call {
            canonical: "escapeHtml".into(),
            description: "escapeHtml".into(),
        }];
        let src = r#"
function handler(req) {
    const raw = req.body;
    const clean = escapeHtml(raw);
    document.write(clean);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        assert_eq!(
            analyze_tree(tree.root_node(), src, &spec, Some(&aliases)).len(),
            0
        );
    }

    // ─── SSTI rule tests ────────────────────────────────────────────────

    #[test]
    fn ssti_ejs_render_from_req_body() {
        let spec = super::super::javascript::TaintSsti::spec();
        let src = r#"
const ejs = require("ejs");
function handler(req, res) {
    const template = req.body.template;
    ejs.render(template);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let findings = analyze_tree(tree.root_node(), src, &spec, Some(&aliases));
        assert!(!findings.is_empty(), "expected SSTI finding for ejs.render");
        assert!(findings[0].sink_description.contains("ejs.render"));
    }

    #[test]
    fn ssti_no_finding_when_static_template() {
        let spec = super::super::javascript::TaintSsti::spec();
        let src = r#"
const ejs = require("ejs");
function handler(req, res) {
    ejs.render("<h1>Hello</h1>");
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let findings = analyze_tree(tree.root_node(), src, &spec, Some(&aliases));
        assert!(findings.is_empty(), "static template should not fire SSTI");
    }

    // ─── XPath injection rule tests ─────────────────────────────────────

    #[test]
    fn xpath_select_from_req_query() {
        let spec = super::super::javascript::TaintXpathInjection::spec();
        let src = r#"
const xpath = require("xpath");
function handler(req, res) {
    const expr = req.query.path;
    xpath.select(expr, doc);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let findings = analyze_tree(tree.root_node(), src, &spec, Some(&aliases));
        assert!(!findings.is_empty(), "expected XPath injection finding");
        assert!(findings[0].sink_description.contains("xpath.select"));
    }

    #[test]
    fn xpath_no_finding_when_static_expression() {
        let spec = super::super::javascript::TaintXpathInjection::spec();
        let src = r#"
const xpath = require("xpath");
function handler(req, res) {
    xpath.select("//book/title", doc);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let findings = analyze_tree(tree.root_node(), src, &spec, Some(&aliases));
        assert!(findings.is_empty(), "static XPath should not fire");
    }

    // ─── LDAP injection rule tests ──────────────────────────────────────

    #[test]
    fn ldap_search_from_req_body() {
        let spec = super::super::javascript::TaintLdapInjection::spec();
        let src = r#"
function handler(req, res) {
    const filter = req.body.username;
    client.search(filter);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let findings = analyze_tree(tree.root_node(), src, &spec, Some(&aliases));
        assert!(
            !findings.is_empty(),
            "expected LDAP injection finding for .search()"
        );
        assert!(findings[0]
            .sink_description
            .contains("LDAP client.search()"));
    }

    #[test]
    fn ldap_no_finding_when_static_filter() {
        let spec = super::super::javascript::TaintLdapInjection::spec();
        let src = r#"
function handler(req, res) {
    client.search("dc=example", { filter: "(cn=admin)" });
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let findings = analyze_tree(tree.root_node(), src, &spec, Some(&aliases));
        assert!(findings.is_empty(), "static LDAP filter should not fire");
    }

    // Issue #133: String.prototype.search() must not trigger LDAP rule.
    #[test]
    fn ldap_no_finding_for_string_search() {
        let spec = super::super::javascript::TaintLdapInjection::spec();
        let src = r#"
function handler(req, res) {
    const pattern = req.body.pattern;
    "hello world".search(pattern);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let findings = analyze_tree(tree.root_node(), src, &spec, Some(&aliases));
        assert!(
            findings.is_empty(),
            "String.prototype.search() should not fire LDAP rule"
        );
    }

    // Issue #133: Function.prototype.bind() must not trigger LDAP rule.
    #[test]
    fn ldap_no_finding_for_function_bind() {
        let spec = super::super::javascript::TaintLdapInjection::spec();
        let src = r#"
function handler(req, res) {
    const ctx = req.body.context;
    handler.bind(ctx);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let findings = analyze_tree(tree.root_node(), src, &spec, Some(&aliases));
        assert!(
            findings.is_empty(),
            "Function.prototype.bind() should not fire LDAP rule"
        );
    }

    #[test]
    fn cross_file_summary_extraction_finds_exported_functions() {
        // services.js-like fixture
        let src = r#"
const db = { query(_q) { return []; } };

function runQuery(name) {
    return db.query("SELECT * FROM users WHERE name = '" + name + "'");
}

function evalExpression(expr) {
    return eval(expr);
}

module.exports = { runQuery, evalExpression };
"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let rule_specs = crate::rules::javascript::js_taint_rule_specs();
        let summaries =
            extract_cross_file_summaries(tree.root_node(), src, Some(&aliases), &rule_specs);

        eprintln!("summaries: {:#?}", summaries);
        let names: Vec<&str> = summaries.iter().map(|s| s.name.as_str()).collect();
        assert!(
            names.contains(&"runQuery"),
            "expected runQuery in summaries, got {:?}",
            names
        );
        assert!(
            names.contains(&"evalExpression"),
            "expected evalExpression in summaries, got {:?}",
            names
        );

        let rq = summaries.iter().find(|s| s.name == "runQuery").unwrap();
        assert!(
            rq.params_to_sink
                .iter()
                .any(|f| f.sink_rule_id == "js/taint-sql-injection"),
            "expected runQuery to have sql-injection sink flow, got {:?}",
            rq.params_to_sink
        );

        let ee = summaries
            .iter()
            .find(|s| s.name == "evalExpression")
            .unwrap();
        assert!(
            ee.params_to_sink
                .iter()
                .any(|f| f.sink_rule_id == "js/taint-eval"),
            "expected evalExpression to have eval sink flow, got {:?}",
            ee.params_to_sink
        );
    }

    #[test]
    fn export_default_named_function_produces_summary() {
        let src = r#"
export default function handler(req) {
    db.query("SELECT " + req.body);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let rule_specs = crate::rules::javascript::js_taint_rule_specs();
        let summaries =
            extract_cross_file_summaries(tree.root_node(), src, Some(&aliases), &rule_specs);

        eprintln!("summaries: {:#?}", summaries);
        let names: Vec<&str> = summaries.iter().map(|s| s.name.as_str()).collect();
        // Should produce both the named export and a "default" alias.
        assert!(
            names.contains(&"handler"),
            "expected 'handler' in summaries, got {:?}",
            names
        );
        assert!(
            names.contains(&"default"),
            "expected 'default' in summaries, got {:?}",
            names
        );

        let def = summaries.iter().find(|s| s.name == "default").unwrap();
        assert!(
            def.params_to_sink
                .iter()
                .any(|f| f.sink_rule_id == "js/taint-sql-injection"),
            "expected default export to have sql-injection sink flow, got {:?}",
            def.params_to_sink
        );
    }

    #[test]
    fn export_default_anonymous_function_produces_summary() {
        let src = r#"
export default function(req) {
    db.query("SELECT " + req.body);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let rule_specs = crate::rules::javascript::js_taint_rule_specs();
        let summaries =
            extract_cross_file_summaries(tree.root_node(), src, Some(&aliases), &rule_specs);

        let names: Vec<&str> = summaries.iter().map(|s| s.name.as_str()).collect();
        assert!(
            names.contains(&"default"),
            "expected 'default' in summaries, got {:?}",
            names
        );
    }

    #[test]
    fn export_default_arrow_function_produces_summary() {
        let src = r#"
export default (req) => {
    db.query("SELECT " + req.body);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("parse");
        let aliases = js_aliases_from_tree(src, &tree);
        let rule_specs = crate::rules::javascript::js_taint_rule_specs();
        let summaries =
            extract_cross_file_summaries(tree.root_node(), src, Some(&aliases), &rule_specs);

        let names: Vec<&str> = summaries.iter().map(|s| s.name.as_str()).collect();
        assert!(
            names.contains(&"default"),
            "expected 'default' in summaries for arrow default export, got {:?}",
            names
        );
    }

    #[test]
    fn import_default_cross_file_finding() {
        // Simulate cross-file: module exports a default function with a
        // SQL-injection sink; a caller imports it as default and passes
        // tainted data.
        let module_src = r#"
export default function handler(req) {
    db.query("SELECT " + req.body);
}
"#;
        let module_tree = parse_file(module_src, Language::JavaScript).expect("parse module");
        let module_aliases = js_aliases_from_tree(module_src, &module_tree);
        let rule_specs = crate::rules::javascript::js_taint_rule_specs();
        let summaries = extract_cross_file_summaries(
            module_tree.root_node(),
            module_src,
            Some(&module_aliases),
            &rule_specs,
        );
        assert!(
            !summaries.is_empty(),
            "expected at least one summary from default export"
        );

        // Build the cross-file summary map keyed by file path.
        let module_path = PathBuf::from("/fake/handler.js");
        let mut summary_map: CrossFileSummaryMap = HashMap::new();
        summary_map.insert(module_path.clone(), summaries);

        // Caller source: `import handler from "./handler"; handler(req.body);`
        let caller_src = r#"
import handler from "./handler";
function route(req) {
    handler(req.body);
}
"#;
        let caller_tree = parse_file(caller_src, Language::JavaScript).expect("parse caller");
        let caller_aliases = js_aliases_from_tree(caller_src, &caller_tree);

        // Build import map manually (we can't resolve files on disk in
        // a unit test, so we wire the mapping by hand).
        let mut import_to_path: HashMap<String, PathBuf> = HashMap::new();
        import_to_path.insert("./handler".to_string(), module_path.clone());
        // Default import entry: __default__:./handler:handler
        import_to_path.insert(
            "__default__:./handler:handler".to_string(),
            module_path.clone(),
        );

        let cross_file = CrossFileInfo {
            import_to_path: &import_to_path,
            summaries: &summary_map,
            current_rule_id: "js/taint-sql-injection",
        };

        let spec = rule_specs
            .iter()
            .find(|(id, _)| *id == "js/taint-sql-injection")
            .map(|(_, s)| s)
            .expect("sql-injection spec");

        let findings = analyze_tree_with_cross_file(
            caller_tree.root_node(),
            caller_src,
            spec,
            Some(&caller_aliases),
            Some(&cross_file),
        );

        eprintln!("findings: {:#?}", findings);
        assert!(
            !findings.is_empty(),
            "expected cross-file finding for default import call"
        );
        assert!(
            findings
                .iter()
                .any(|f| f.sink_description.contains("cross-file")),
            "expected finding to mention cross-file, got: {:?}",
            findings
                .iter()
                .map(|f| &f.sink_description)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn ternary_tainted_consequence_propagates() {
        let src = r#"
function handler(req) {
    const data = true ? req.body : "safe";
    document.getElementById("x").innerHTML = data;
}
"#;
        let f = run(src);
        assert_eq!(f.len(), 1);
        assert!(f[0].source_description.contains("req.body"));
    }

    #[test]
    fn ternary_tainted_alternative_propagates() {
        let src = r#"
function handler(req) {
    const data = false ? "safe" : req.body;
    document.getElementById("x").innerHTML = data;
}
"#;
        let f = run(src);
        assert_eq!(f.len(), 1);
        assert!(f[0].source_description.contains("req.body"));
    }

    #[test]
    fn ternary_clean_both_branches_is_clean() {
        let src = r#"
function handler(req) {
    const data = true ? "a" : "b";
    document.getElementById("x").innerHTML = data;
}
"#;
        assert!(run(src).is_empty());
    }

    // ─── Koa ─────────────────────────────────────────────────────────

    #[test]
    fn koa_ctx_request_body_is_tainted() {
        let src = r#"
router.post("/", async (ctx) => {
    document.write(ctx.request.body);
});
"#;
        let f = run(src);
        assert_eq!(f.len(), 1);
        assert!(
            f[0].source_description.contains("ctx"),
            "expected Koa ctx source, got: {}",
            f[0].source_description
        );
    }

    #[test]
    fn koa_ctx_query_is_tainted() {
        let src = r#"
router.get("/search", async (ctx) => {
    document.getElementById("x").innerHTML = ctx.query.q;
});
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn koa_ctx_params_is_tainted() {
        let src = r#"
router.get("/user/:id", async (ctx) => {
    document.write(ctx.params.id);
});
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn koa_ctx_headers_is_tainted() {
        let src = r#"
router.get("/", async (ctx) => {
    document.write(ctx.headers["x-forwarded-for"]);
});
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn koa_ctx_param_name_taints_bare_ctx() {
        let src = r#"
router.get("/", async (ctx) => {
    document.write(ctx);
});
"#;
        assert_eq!(run(src).len(), 1);
    }

    // ─── NestJS ──────────────────────────────────────────────────────

    #[test]
    fn nestjs_body_param_is_tainted() {
        let src = r#"
function createUser(body) {
    document.write(body.username);
}
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn nestjs_query_param_is_tainted() {
        let src = r#"
function searchUsers(query) {
    document.getElementById("x").innerHTML = query.term;
}
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn nestjs_params_param_is_tainted() {
        let src = r#"
function getUser(params) {
    document.write(params.id);
}
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn nestjs_headers_param_is_tainted() {
        let src = r#"
function handler(headers) {
    document.write(headers["authorization"]);
}
"#;
        assert_eq!(run(src).len(), 1);
    }

    #[test]
    fn await_expression_propagates_taint() {
        let src = r#"
async function handler(req) {
    const data = await req.json();
    document.getElementById("x").innerHTML = data;
}
"#;
        let f = run(src);
        assert_eq!(f.len(), 1);
        assert_eq!(f[0].sink_description, "innerHTML assignment");
    }
}