lonkero 3.6.2

Web scanner built for actual pentests. Fast, modular, Rust.
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
// Copyright (c) 2026 Bountyy Oy. All rights reserved.
// This software is proprietary and confidential.

use crate::http_client::HttpClient;
use crate::types::{Confidence, ScanConfig, Severity, Vulnerability};
use anyhow::Result;
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tracing::{debug, info};

pub struct JsSensitiveInfoScanner {
    http_client: Arc<HttpClient>,
    patterns: SensitivePatterns,
}

/// Categories of sensitive information
#[derive(Debug, Clone)]
struct SensitivePatterns {
    /// Jira/issue tracker patterns
    jira_patterns: Vec<CompiledPattern>,
    /// Internal tool URLs
    internal_tools: Vec<CompiledPattern>,
    /// Document/file paths
    document_patterns: Vec<CompiledPattern>,
    /// Admin/debug logic
    admin_debug_patterns: Vec<CompiledPattern>,
    /// Sensitive comments
    comment_patterns: Vec<CompiledPattern>,
    /// Credential patterns
    credential_patterns: Vec<CompiledPattern>,
    /// Employee/internal info
    employee_patterns: Vec<CompiledPattern>,
    /// Environment/config leaks
    environment_patterns: Vec<CompiledPattern>,
    /// Analytics/BI tools
    analytics_patterns: Vec<CompiledPattern>,
}

#[derive(Clone)]
struct CompiledPattern {
    name: String,
    regex: Regex,
    severity: Severity,
    description: String,
    cwe: String,
}

impl std::fmt::Debug for CompiledPattern {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CompiledPattern")
            .field("name", &self.name)
            .field("severity", &self.severity)
            .finish()
    }
}

/// Found sensitive information
#[derive(Debug, Clone)]
struct SensitiveMatch {
    pattern_name: String,
    matched_value: String,
    context: String,
    line_number: usize,
    severity: Severity,
    category: String,
    cwe: String,
    description: String,
}

impl JsSensitiveInfoScanner {
    pub fn new(http_client: Arc<HttpClient>) -> Self {
        Self {
            http_client,
            patterns: Self::build_patterns(),
        }
    }

    fn build_patterns() -> SensitivePatterns {
        SensitivePatterns {
            jira_patterns: vec![
                CompiledPattern {
                    name: "Jira Ticket Reference".to_string(),
                    // Must be uppercase letters followed by dash and number, and NOT match common CSS/JS patterns
                    // Require at least 3 letters to avoid matching CSS like "fi-2", and number >= 10 to avoid "north-1"
                    regex: Regex::new(r#"\b([A-Z]{3,10}-\d{2,6})\b"#).unwrap(),
                    severity: Severity::Low,
                    description: "Jira ticket reference found - may reveal project names and internal tracking".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Jira URL".to_string(),
                    regex: Regex::new(r#"https?://[a-zA-Z0-9\-]+\.atlassian\.net/[^\s\"'<>]+"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Direct Jira URL found - exposes internal issue tracker".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Jira On-Premise URL".to_string(),
                    regex: Regex::new(r#"https?://jira\.[a-zA-Z0-9\-]+\.[a-zA-Z]+[^\s\"'<>]*"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Self-hosted Jira URL found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
            ],
            internal_tools: vec![
                CompiledPattern {
                    name: "Confluence URL".to_string(),
                    regex: Regex::new(r#"https?://[a-zA-Z0-9\-]+\.atlassian\.net/wiki/[^\s\"'<>]+"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Confluence documentation URL found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Slack Webhook".to_string(),
                    regex: Regex::new(r#"https://hooks\.slack\.com/services/[A-Z0-9]+/[A-Z0-9]+/[a-zA-Z0-9]+"#).unwrap(),
                    severity: Severity::High,
                    description: "Slack webhook URL exposed - can be used to send messages to internal channels".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Discord Webhook".to_string(),
                    regex: Regex::new(r#"https://discord(?:app)?\.com/api/webhooks/\d+/[a-zA-Z0-9_-]+"#).unwrap(),
                    severity: Severity::High,
                    description: "Discord webhook URL exposed".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Internal GitLab URL".to_string(),
                    regex: Regex::new(r#"https?://gitlab\.[a-zA-Z0-9\-]+\.[a-zA-Z]+[^\s\"'<>]*"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Internal GitLab URL found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Jenkins URL".to_string(),
                    regex: Regex::new(r#"https?://jenkins\.[a-zA-Z0-9\-]+\.[a-zA-Z]+[^\s\"'<>]*"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Jenkins CI/CD URL found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "SonarQube URL".to_string(),
                    regex: Regex::new(r#"https?://sonar[a-zA-Z0-9\-]*\.[a-zA-Z0-9\-]+\.[a-zA-Z]+[^\s\"'<>]*"#).unwrap(),
                    severity: Severity::Medium,
                    description: "SonarQube code quality URL found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Grafana URL".to_string(),
                    regex: Regex::new(r#"https?://grafana\.[a-zA-Z0-9\-]+\.[a-zA-Z]+[^\s\"'<>]*"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Grafana monitoring URL found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Kibana URL".to_string(),
                    regex: Regex::new(r#"https?://kibana\.[a-zA-Z0-9\-]+\.[a-zA-Z]+[^\s\"'<>]*"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Kibana logging URL found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
            ],
            document_patterns: vec![
                CompiledPattern {
                    name: "PDF Document Path".to_string(),
                    regex: Regex::new(r#"[\"'/][a-zA-Z0-9_\-/]+\.pdf"#).unwrap(),
                    severity: Severity::Low,
                    description: "PDF document path found - may contain sensitive documents".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Excel/CSV Path".to_string(),
                    regex: Regex::new(r#"[\"'/][a-zA-Z0-9_\-/]+\.(xlsx?|csv)"#).unwrap(),
                    severity: Severity::Low,
                    description: "Spreadsheet file path found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Internal Document Server".to_string(),
                    regex: Regex::new(r#"https?://docs?\.[a-zA-Z0-9\-]+\.[a-zA-Z]+[^\s\"'<>]*"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Internal document server URL found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "SharePoint URL".to_string(),
                    regex: Regex::new(r#"https?://[a-zA-Z0-9\-]+\.sharepoint\.com[^\s\"'<>]*"#).unwrap(),
                    severity: Severity::Medium,
                    description: "SharePoint URL found - may expose internal documents".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Google Drive Document".to_string(),
                    regex: Regex::new(r#"https://docs\.google\.com/(document|spreadsheets|presentation)/d/[a-zA-Z0-9_-]+"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Google Drive document URL found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
            ],
            admin_debug_patterns: vec![
                CompiledPattern {
                    name: "isDev/isDebug Flag".to_string(),
                    regex: Regex::new(r#"(?i)(isDev|isDebug|isTest|debugMode|devMode|testMode)\s*[=:]\s*(true|1|!0)"#).unwrap(),
                    severity: Severity::High,
                    description: "Debug/development mode flag enabled in production".to_string(),
                    cwe: "CWE-489".to_string(),
                },
                CompiledPattern {
                    name: "Admin Check Logic".to_string(),
                    regex: Regex::new(r#"(?i)(isAdmin|isSuperUser|isRoot|hasAdminRole)\s*[=:&|]"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Admin privilege check logic exposed - may reveal access control bypass".to_string(),
                    cwe: "CWE-284".to_string(),
                },
                CompiledPattern {
                    name: "Debug Endpoint".to_string(),
                    regex: Regex::new(r#"[\"'](/debug|/admin/debug|/api/debug|/__debug__|/phpinfo|/server-status)[\"']"#).unwrap(),
                    severity: Severity::High,
                    description: "Debug endpoint reference found".to_string(),
                    cwe: "CWE-489".to_string(),
                },
                CompiledPattern {
                    name: "Console.log with Sensitive Data".to_string(),
                    regex: Regex::new(r#"console\.(log|debug|info)\s*\([^)]*(?i)(password|secret|token|key|auth|credit|ssn)[^)]*\)"#).unwrap(),
                    severity: Severity::High,
                    description: "Console logging of sensitive data detected".to_string(),
                    cwe: "CWE-532".to_string(),
                },
                CompiledPattern {
                    name: "Bypass Authentication Flag".to_string(),
                    regex: Regex::new(r#"(?i)(bypassAuth|skipAuth|noAuth|disableAuth|mockAuth)\s*[=:]\s*(true|1)"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Authentication bypass flag found".to_string(),
                    cwe: "CWE-287".to_string(),
                },
                CompiledPattern {
                    name: "Feature Flag - Admin".to_string(),
                    regex: Regex::new(r#"(?i)(?:feature|flag)[_.]?(?:admin|superuser|elevated)"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Admin feature flag reference found".to_string(),
                    cwe: "CWE-284".to_string(),
                },
            ],
            comment_patterns: vec![
                CompiledPattern {
                    name: "TODO with Security Implication".to_string(),
                    regex: Regex::new(r#"(?i)(//|/\*|\*)\s*(TODO|FIXME|HACK|XXX|BUG)[:\s].*(?:security|auth|password|token|key|vuln|exploit|bypass|inject)"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Security-related TODO/FIXME comment found".to_string(),
                    cwe: "CWE-615".to_string(),
                },
                CompiledPattern {
                    name: "Hardcoded Credential Comment".to_string(),
                    regex: Regex::new(r#"(?i)(//|/\*|\*)\s*(?:password|secret|key|token)\s*[=:]\s*[^\s]+"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Hardcoded credential in comment".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Temporary/Test Comment".to_string(),
                    regex: Regex::new(r#"(?i)(//|/\*|\*)\s*(TEMP|TEST|REMOVE|DELETE|DEBUG)\s*[:-]"#).unwrap(),
                    severity: Severity::Low,
                    description: "Temporary/test code marker found".to_string(),
                    cwe: "CWE-489".to_string(),
                },
                CompiledPattern {
                    name: "Internal Note".to_string(),
                    regex: Regex::new(r#"(?i)(//|/\*|\*)\s*(internal|private|confidential|do not share)"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Internal/confidential note in code".to_string(),
                    cwe: "CWE-615".to_string(),
                },
            ],
            credential_patterns: vec![
                CompiledPattern {
                    name: "AWS Access Key".to_string(),
                    regex: Regex::new(r#"AKIA[0-9A-Z]{16}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "AWS Access Key ID found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "AWS Secret Key Pattern".to_string(),
                    regex: Regex::new(r#"(?i)aws.{0,20}secret.{0,20}['\"][0-9a-zA-Z/+=]{40}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "AWS Secret Access Key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Generic API Key".to_string(),
                    regex: Regex::new(r#"(?i)(api[_-]?key|apikey)\s*[=:]\s*['\"][a-zA-Z0-9_\-]{20,}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "API key found in JavaScript".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Generic Secret".to_string(),
                    regex: Regex::new(r#"(?i)(secret|private[_-]?key)\s*[=:]\s*['\"][a-zA-Z0-9_\-]{16,}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Secret/private key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Password Assignment".to_string(),
                    regex: Regex::new(r#"(?i)password\s*[=:]\s*['\"][^'\"]{4,}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Hardcoded password found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Bearer Token".to_string(),
                    regex: Regex::new(r#"(?i)bearer\s+[a-zA-Z0-9_\-\.]{20,}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Bearer token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "JWT Token".to_string(),
                    regex: Regex::new(r#"eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*"#).unwrap(),
                    severity: Severity::High,
                    description: "JWT token found in JavaScript".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Private Key Block".to_string(),
                    regex: Regex::new(r#"-----BEGIN\s+(RSA\s+)?PRIVATE\s+KEY-----"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Private key found in JavaScript".to_string(),
                    cwe: "CWE-321".to_string(),
                },
                CompiledPattern {
                    name: "Google API Key".to_string(),
                    regex: Regex::new(r#"AIza[0-9A-Za-z\-_]{35}"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Google API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Stripe Key".to_string(),
                    regex: Regex::new(r#"(?:sk|pk)_(test|live)_[a-zA-Z0-9]{24,}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Stripe API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "GitHub Token".to_string(),
                    regex: Regex::new(r#"gh[pousr]_[A-Za-z0-9_]{36,}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "GitHub token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "NPM Token".to_string(),
                    regex: Regex::new(r#"npm_[a-zA-Z0-9]{36}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "NPM token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Mapbox Access Token".to_string(),
                    // Mapbox tokens start with pk.eyJ (public) or sk.eyJ (secret)
                    regex: Regex::new(r#"(?:pk|sk)\.eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Mapbox access token found - can be exploited for massive billing abuse. \
                        Attackers can automate millions of API calls to Mapbox Static API causing \
                        significant financial damage (~$2 per 1000 requests = $200K for 100M requests).".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Mapbox Secret Token".to_string(),
                    regex: Regex::new(r#"sk\.eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Mapbox SECRET token found - provides elevated API access. \
                        More dangerous than public tokens, should never be exposed client-side.".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "HERE API Key".to_string(),
                    regex: Regex::new(r#"(?i)here[_-]?api[_-]?key\s*[=:]\s*['\"][a-zA-Z0-9_-]{20,}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "HERE Maps API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "OpenAI API Key".to_string(),
                    regex: Regex::new(r#"sk-[a-zA-Z0-9]{20,}T3BlbkFJ[a-zA-Z0-9]{20,}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "OpenAI API key found - can be exploited for significant billing abuse".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Twilio API Key".to_string(),
                    regex: Regex::new(r#"SK[a-f0-9]{32}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Twilio API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "SendGrid API Key".to_string(),
                    regex: Regex::new(r#"SG\.[a-zA-Z0-9_-]{22}\.[a-zA-Z0-9_-]{43}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "SendGrid API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Mailgun API Key".to_string(),
                    regex: Regex::new(r#"key-[a-f0-9]{32}"#).unwrap(),
                    severity: Severity::High,
                    description: "Mailgun API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Firebase
                CompiledPattern {
                    name: "Firebase URL".to_string(),
                    regex: Regex::new(r#"https://[a-zA-Z0-9_-]+\.firebaseio\.com"#).unwrap(),
                    severity: Severity::High,
                    description: "Firebase database URL found - check for unauthenticated read/write access".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Firebase API Key".to_string(),
                    regex: Regex::new(r#"(?i)firebase[_-]?api[_-]?key\s*[=:]\s*['\"][a-zA-Z0-9_-]{20,}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Firebase API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Heroku
                CompiledPattern {
                    name: "Heroku API Key".to_string(),
                    regex: Regex::new(r#"(?i)heroku[_-]?api[_-]?key\s*[=:]\s*['\"][a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Heroku API key found - allows full account access".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Azure
                CompiledPattern {
                    name: "Azure Storage Key".to_string(),
                    regex: Regex::new(r#"(?i)DefaultEndpointsProtocol=https;AccountName=[^;]+;AccountKey=[a-zA-Z0-9+/=]{88}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Azure Storage connection string with account key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Azure SAS Token".to_string(),
                    regex: Regex::new(r#"[?&]sig=[a-zA-Z0-9%]{43,}(&|$)"#).unwrap(),
                    severity: Severity::High,
                    description: "Azure SAS token found - check expiration and permissions".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // DigitalOcean
                CompiledPattern {
                    name: "DigitalOcean Token".to_string(),
                    regex: Regex::new(r#"dop_v1_[a-f0-9]{64}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "DigitalOcean personal access token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "DigitalOcean OAuth Token".to_string(),
                    regex: Regex::new(r#"doo_v1_[a-f0-9]{64}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "DigitalOcean OAuth token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "DigitalOcean Refresh Token".to_string(),
                    regex: Regex::new(r#"dor_v1_[a-f0-9]{64}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "DigitalOcean refresh token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // GitLab
                CompiledPattern {
                    name: "GitLab Personal Access Token".to_string(),
                    regex: Regex::new(r#"glpat-[a-zA-Z0-9_-]{20}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "GitLab personal access token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "GitLab Pipeline Token".to_string(),
                    regex: Regex::new(r#"glptt-[a-f0-9]{40}"#).unwrap(),
                    severity: Severity::High,
                    description: "GitLab pipeline trigger token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "GitLab Runner Token".to_string(),
                    regex: Regex::new(r#"glrt-[a-zA-Z0-9_-]{20}"#).unwrap(),
                    severity: Severity::High,
                    description: "GitLab runner registration token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Bitbucket
                CompiledPattern {
                    name: "Bitbucket App Password".to_string(),
                    regex: Regex::new(r#"(?i)bitbucket[_-]?(?:app[_-]?)?password\s*[=:]\s*['\"][a-zA-Z0-9]{20,}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Bitbucket app password found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Telegram
                CompiledPattern {
                    name: "Telegram Bot Token".to_string(),
                    regex: Regex::new(r#"\d{8,10}:[a-zA-Z0-9_-]{35}"#).unwrap(),
                    severity: Severity::High,
                    description: "Telegram bot token found - allows bot control and message access".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Facebook
                CompiledPattern {
                    name: "Facebook Access Token".to_string(),
                    regex: Regex::new(r#"EAA[a-zA-Z0-9]{100,}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Facebook access token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Facebook App Secret".to_string(),
                    regex: Regex::new(r#"(?i)fb[_-]?(?:app[_-]?)?secret\s*[=:]\s*['\"][a-f0-9]{32}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Facebook app secret found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Twitter
                CompiledPattern {
                    name: "Twitter Bearer Token".to_string(),
                    regex: Regex::new(r#"AAAAAAAAAAAAAAAAAAA[a-zA-Z0-9%]{30,}"#).unwrap(),
                    severity: Severity::High,
                    description: "Twitter bearer token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Twitter API Key".to_string(),
                    regex: Regex::new(r#"(?i)twitter[_-]?(?:api[_-]?)?(?:key|consumer)\s*[=:]\s*['\"][a-zA-Z0-9]{25}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Twitter API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Shopify
                CompiledPattern {
                    name: "Shopify Access Token".to_string(),
                    regex: Regex::new(r#"shpat_[a-f0-9]{32}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Shopify access token found - allows store API access".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Shopify Private App Token".to_string(),
                    regex: Regex::new(r#"shppa_[a-f0-9]{32}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Shopify private app access token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Shopify Shared Secret".to_string(),
                    regex: Regex::new(r#"shpss_[a-f0-9]{32}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Shopify shared secret found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // PayPal/Braintree
                CompiledPattern {
                    name: "PayPal/Braintree Access Token".to_string(),
                    regex: Regex::new(r#"access_token\$production\$[a-z0-9]{16}\$[a-f0-9]{32}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "PayPal/Braintree production access token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Square
                CompiledPattern {
                    name: "Square Access Token".to_string(),
                    regex: Regex::new(r#"sq0atp-[a-zA-Z0-9_-]{22}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Square access token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Square OAuth Secret".to_string(),
                    regex: Regex::new(r#"sq0csp-[a-zA-Z0-9_-]{43}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Square OAuth secret found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Algolia
                CompiledPattern {
                    name: "Algolia Admin API Key".to_string(),
                    regex: Regex::new(r#"(?i)algolia[_-]?(?:admin[_-]?)?(?:api[_-]?)?key\s*[=:]\s*['\"][a-f0-9]{32}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Algolia admin API key found - allows index modification".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Cloudinary
                CompiledPattern {
                    name: "Cloudinary URL".to_string(),
                    regex: Regex::new(r#"cloudinary://[0-9]+:[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Cloudinary URL with API secret found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Sentry
                CompiledPattern {
                    name: "Sentry DSN".to_string(),
                    regex: Regex::new(r#"https://[a-f0-9]{32}@[a-z0-9]+\.ingest\.sentry\.io/[0-9]+"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Sentry DSN found - may allow error injection".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Sentry Auth Token".to_string(),
                    regex: Regex::new(r#"sntrys_[a-zA-Z0-9]{64}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Sentry auth token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Datadog
                CompiledPattern {
                    name: "Datadog API Key".to_string(),
                    regex: Regex::new(r#"(?i)datadog[_-]?api[_-]?key\s*[=:]\s*['\"][a-f0-9]{32}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Datadog API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Datadog App Key".to_string(),
                    regex: Regex::new(r#"(?i)datadog[_-]?app[_-]?key\s*[=:]\s*['\"][a-f0-9]{40}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Datadog app key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // New Relic
                CompiledPattern {
                    name: "New Relic License Key".to_string(),
                    regex: Regex::new(r#"(?i)new[_-]?relic[_-]?license\s*[=:]\s*['\"][a-f0-9]{40}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "New Relic license key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "New Relic API Key".to_string(),
                    regex: Regex::new(r#"NRAK-[A-Z0-9]{27}"#).unwrap(),
                    severity: Severity::High,
                    description: "New Relic API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Anthropic
                CompiledPattern {
                    name: "Anthropic API Key".to_string(),
                    regex: Regex::new(r#"sk-ant-api[a-zA-Z0-9_-]{32,}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Anthropic API key found - can be exploited for billing abuse".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Cohere
                CompiledPattern {
                    name: "Cohere API Key".to_string(),
                    regex: Regex::new(r#"(?i)cohere[_-]?api[_-]?key\s*[=:]\s*['\"][a-zA-Z0-9]{40}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Cohere API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Notion
                CompiledPattern {
                    name: "Notion Integration Token".to_string(),
                    regex: Regex::new(r#"secret_[a-zA-Z0-9]{43}"#).unwrap(),
                    severity: Severity::High,
                    description: "Notion integration token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Asana
                CompiledPattern {
                    name: "Asana Personal Access Token".to_string(),
                    regex: Regex::new(r#"[01]/[0-9]{16}:[a-f0-9]{32}"#).unwrap(),
                    severity: Severity::High,
                    description: "Asana personal access token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Linear
                CompiledPattern {
                    name: "Linear API Key".to_string(),
                    regex: Regex::new(r#"lin_api_[a-zA-Z0-9]{40}"#).unwrap(),
                    severity: Severity::High,
                    description: "Linear API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Doppler
                CompiledPattern {
                    name: "Doppler API Key".to_string(),
                    regex: Regex::new(r#"dp\.pt\.[a-zA-Z0-9]{43}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Doppler API key found - secrets manager access".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Postman
                CompiledPattern {
                    name: "Postman API Key".to_string(),
                    regex: Regex::new(r#"PMAK-[a-f0-9]{24}-[a-f0-9]{34}"#).unwrap(),
                    severity: Severity::High,
                    description: "Postman API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Supabase
                CompiledPattern {
                    name: "Supabase Service Key".to_string(),
                    regex: Regex::new(r#"sbp_[a-f0-9]{40}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Supabase service key found - bypasses RLS".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // PlanetScale
                CompiledPattern {
                    name: "PlanetScale Token".to_string(),
                    regex: Regex::new(r#"pscale_tkn_[a-zA-Z0-9_-]{43}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "PlanetScale database token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "PlanetScale Password".to_string(),
                    regex: Regex::new(r#"pscale_pw_[a-zA-Z0-9_-]{43}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "PlanetScale database password found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Vercel
                CompiledPattern {
                    name: "Vercel Token".to_string(),
                    regex: Regex::new(r#"(?i)vercel[_-]?token\s*[=:]\s*['\"][a-zA-Z0-9]{24}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Vercel authentication token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Netlify
                CompiledPattern {
                    name: "Netlify Personal Access Token".to_string(),
                    regex: Regex::new(r#"nfp_[a-zA-Z0-9]{40}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Netlify personal access token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Contentful
                CompiledPattern {
                    name: "Contentful Delivery Token".to_string(),
                    regex: Regex::new(r#"(?i)contentful[_-]?(?:delivery[_-]?)?token\s*[=:]\s*['\"][a-zA-Z0-9_-]{43}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Contentful delivery/preview token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Airtable - API keys must be in assignment context to avoid false positives
                // like "keyboard", "keydown", "keypress", etc.
                CompiledPattern {
                    name: "Airtable API Key".to_string(),
                    // Real Airtable keys look like: keyXXXXXXXXXXXXXX (key + 14 alphanumeric chars)
                    // Require assignment context (=, :, or quote) to filter out variable names
                    regex: Regex::new(r#"[=:'"]\s*key[a-zA-Z0-9]{14}\s*['"}\],;]"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Potential Airtable API key".to_string(),
                    cwe: "CWE-312".to_string(),
                },
                CompiledPattern {
                    name: "Airtable Personal Access Token".to_string(),
                    regex: Regex::new(r#"pat[a-zA-Z0-9]{14}\.[a-f0-9]{64}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Airtable personal access token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Okta
                CompiledPattern {
                    name: "Okta API Token".to_string(),
                    regex: Regex::new(r#"00[a-zA-Z0-9_-]{40}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Okta API token found - identity provider access".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Auth0
                CompiledPattern {
                    name: "Auth0 Client Secret".to_string(),
                    regex: Regex::new(r#"(?i)auth0[_-]?client[_-]?secret\s*[=:]\s*['\"][a-zA-Z0-9_-]{32,}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Auth0 client secret found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Pusher
                CompiledPattern {
                    name: "Pusher App Key".to_string(),
                    regex: Regex::new(r#"(?i)pusher[_-]?(?:app[_-]?)?key\s*[=:]\s*['\"][a-f0-9]{20}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Pusher app key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // PGP Private Key
                CompiledPattern {
                    name: "PGP Private Key".to_string(),
                    regex: Regex::new(r#"-----BEGIN PGP PRIVATE KEY BLOCK-----"#).unwrap(),
                    severity: Severity::Critical,
                    description: "PGP private key found".to_string(),
                    cwe: "CWE-321".to_string(),
                },
                // SSH Private Key
                CompiledPattern {
                    name: "SSH Private Key (OpenSSH)".to_string(),
                    regex: Regex::new(r#"-----BEGIN OPENSSH PRIVATE KEY-----"#).unwrap(),
                    severity: Severity::Critical,
                    description: "OpenSSH private key found".to_string(),
                    cwe: "CWE-321".to_string(),
                },
                CompiledPattern {
                    name: "SSH Private Key (DSA)".to_string(),
                    regex: Regex::new(r#"-----BEGIN DSA PRIVATE KEY-----"#).unwrap(),
                    severity: Severity::Critical,
                    description: "DSA private key found".to_string(),
                    cwe: "CWE-321".to_string(),
                },
                CompiledPattern {
                    name: "SSH Private Key (EC)".to_string(),
                    regex: Regex::new(r#"-----BEGIN EC PRIVATE KEY-----"#).unwrap(),
                    severity: Severity::Critical,
                    description: "EC private key found".to_string(),
                    cwe: "CWE-321".to_string(),
                },
                // Generic high-entropy secrets
                CompiledPattern {
                    name: "Hardcoded Basic Auth".to_string(),
                    regex: Regex::new(r#"(?i)authorization\s*[=:]\s*['\"]basic\s+[a-zA-Z0-9+/=]{20,}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Hardcoded Basic authentication header found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // MongoDB Atlas
                CompiledPattern {
                    name: "MongoDB Atlas Connection String".to_string(),
                    regex: Regex::new(r#"mongodb\+srv://[^:]+:[^@]+@[a-zA-Z0-9.-]+\.mongodb\.net"#).unwrap(),
                    severity: Severity::Critical,
                    description: "MongoDB Atlas connection string with credentials found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Redis
                CompiledPattern {
                    name: "Redis URL with Password".to_string(),
                    regex: Regex::new(r#"redis://[^:]+:[^@]+@[^\s\"'<>]+"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Redis connection URL with password found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // MySQL/PostgreSQL
                CompiledPattern {
                    name: "MySQL Connection String".to_string(),
                    regex: Regex::new(r#"mysql://[^:]+:[^@]+@[^\s\"'<>]+"#).unwrap(),
                    severity: Severity::Critical,
                    description: "MySQL connection string with credentials found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "PostgreSQL Connection String".to_string(),
                    regex: Regex::new(r#"postgres(?:ql)?://[^:]+:[^@]+@[^\s\"'<>]+"#).unwrap(),
                    severity: Severity::Critical,
                    description: "PostgreSQL connection string with credentials found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // RabbitMQ/AMQP
                CompiledPattern {
                    name: "AMQP Connection String".to_string(),
                    regex: Regex::new(r#"amqps?://[^:]+:[^@]+@[^\s\"'<>]+"#).unwrap(),
                    severity: Severity::Critical,
                    description: "AMQP/RabbitMQ connection string with credentials found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Instagram
                CompiledPattern {
                    name: "Instagram Access Token".to_string(),
                    regex: Regex::new(r#"(?i)instagram[_-]?(?:access[_-]?)?token\s*[=:]\s*['\"][0-9]{5,}[.][a-zA-Z0-9_-]+['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Instagram access token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Dropbox
                CompiledPattern {
                    name: "Dropbox Access Token".to_string(),
                    regex: Regex::new(r#"sl\.[a-zA-Z0-9_-]{130,}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Dropbox access token found - allows file access".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Dropbox App Secret".to_string(),
                    regex: Regex::new(r#"(?i)dropbox[_-]?(?:app[_-]?)?secret\s*[=:]\s*['\"][a-z0-9]{15}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Dropbox app secret found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Zoom
                CompiledPattern {
                    name: "Zoom JWT Token".to_string(),
                    regex: Regex::new(r#"(?i)zoom[_-]?(?:jwt[_-]?)?token\s*[=:]\s*['\"]eyJ[a-zA-Z0-9_-]+\.eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Zoom JWT token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // CircleCI
                CompiledPattern {
                    name: "CircleCI API Token".to_string(),
                    regex: Regex::new(r#"(?i)circle[_-]?(?:ci[_-]?)?token\s*[=:]\s*['\"][a-f0-9]{40}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "CircleCI API token found - allows build access".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Travis CI
                CompiledPattern {
                    name: "Travis CI Token".to_string(),
                    regex: Regex::new(r#"(?i)travis[_-]?(?:ci[_-]?)?token\s*[=:]\s*['\"][a-zA-Z0-9_-]{22}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Travis CI token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Docker Hub
                CompiledPattern {
                    name: "Docker Hub Access Token".to_string(),
                    regex: Regex::new(r#"dckr_pat_[a-zA-Z0-9_-]{27}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Docker Hub personal access token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Mailchimp
                CompiledPattern {
                    name: "Mailchimp API Key".to_string(),
                    regex: Regex::new(r#"[a-f0-9]{32}-us[0-9]{1,2}"#).unwrap(),
                    severity: Severity::High,
                    description: "Mailchimp API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // HubSpot
                CompiledPattern {
                    name: "HubSpot API Key".to_string(),
                    regex: Regex::new(r#"(?i)hubspot[_-]?(?:api[_-]?)?key\s*[=:]\s*['\"][a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "HubSpot API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "HubSpot Private App Token".to_string(),
                    regex: Regex::new(r#"pat-[a-z]{2,3}-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "HubSpot private app token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Zendesk
                CompiledPattern {
                    name: "Zendesk API Token".to_string(),
                    regex: Regex::new(r#"(?i)zendesk[_-]?(?:api[_-]?)?token\s*[=:]\s*['\"][a-zA-Z0-9]{40}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Zendesk API token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Intercom
                CompiledPattern {
                    name: "Intercom Access Token".to_string(),
                    regex: Regex::new(r#"(?i)intercom[_-]?(?:access[_-]?)?token\s*[=:]\s*['\"][a-zA-Z0-9=_-]{60,}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Intercom access token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Jira/Atlassian
                CompiledPattern {
                    name: "Atlassian API Token".to_string(),
                    regex: Regex::new(r#"(?i)atlassian[_-]?(?:api[_-]?)?token\s*[=:]\s*['\"][a-zA-Z0-9]{24}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Atlassian API token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Trello
                CompiledPattern {
                    name: "Trello API Key".to_string(),
                    regex: Regex::new(r#"(?i)trello[_-]?(?:api[_-]?)?key\s*[=:]\s*['\"][a-f0-9]{32}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Trello API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Snyk
                CompiledPattern {
                    name: "Snyk API Token".to_string(),
                    regex: Regex::new(r#"(?i)snyk[_-]?(?:api[_-]?)?token\s*[=:]\s*['\"][a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Snyk API token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // LaunchDarkly
                CompiledPattern {
                    name: "LaunchDarkly SDK Key".to_string(),
                    regex: Regex::new(r#"sdk-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"#).unwrap(),
                    severity: Severity::High,
                    description: "LaunchDarkly SDK key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "LaunchDarkly API Key".to_string(),
                    regex: Regex::new(r#"api-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "LaunchDarkly API key found - full access".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Bugsnag
                CompiledPattern {
                    name: "Bugsnag API Key".to_string(),
                    regex: Regex::new(r#"(?i)bugsnag[_-]?(?:api[_-]?)?key\s*[=:]\s*['\"][a-f0-9]{32}['\"]"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Bugsnag API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Rollbar
                CompiledPattern {
                    name: "Rollbar Access Token".to_string(),
                    regex: Regex::new(r#"(?i)rollbar[_-]?(?:access[_-]?)?token\s*[=:]\s*['\"][a-f0-9]{32}['\"]"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Rollbar access token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Vonage/Nexmo
                CompiledPattern {
                    name: "Vonage/Nexmo API Secret".to_string(),
                    regex: Regex::new(r#"(?i)(?:nexmo|vonage)[_-]?(?:api[_-]?)?secret\s*[=:]\s*['\"][a-zA-Z0-9]{16}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Vonage/Nexmo API secret found - allows SMS/voice access".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // MessageBird
                CompiledPattern {
                    name: "MessageBird API Key".to_string(),
                    regex: Regex::new(r#"(?i)messagebird[_-]?(?:api[_-]?)?key\s*[=:]\s*['\"][a-zA-Z0-9]{25}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "MessageBird API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Plivo
                CompiledPattern {
                    name: "Plivo Auth Token".to_string(),
                    regex: Regex::new(r#"(?i)plivo[_-]?(?:auth[_-]?)?token\s*[=:]\s*['\"][a-zA-Z0-9]{40}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Plivo auth token found - allows SMS/voice access".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // URL with embedded credentials (e.g., Elasticsearch, MongoDB, Redis)
                // Must match: https://user:pass@host or http://user:pass@host:port
                // Key: The @ symbol MUST be present and password comes BEFORE @
                // Example: https://admin:secret123@elastic.example.com:9200
                CompiledPattern {
                    name: "URL with Embedded Credentials".to_string(),
                    // Pattern breakdown:
                    // - https?:// - protocol
                    // - [a-zA-Z0-9_][a-zA-Z0-9_-]* - username (starts with alphanumeric)
                    // - : - separator between user and pass
                    // - [^@\s'"<>]+ - password (anything except @ and whitespace, at least 1 char)
                    // - @ - REQUIRED separator (this is key - regular URLs don't have this)
                    // - [a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,} - hostname with TLD
                    regex: Regex::new(r#"https?://[a-zA-Z0-9_][a-zA-Z0-9_-]*:[^@\s'"<>]+@[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?(?:/[^\s'"<>]*)?"#).unwrap(),
                    severity: Severity::Critical,
                    description: "URL with embedded credentials found (e.g., https://user:pass@host)".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Dynatrace
                CompiledPattern {
                    name: "Dynatrace API Token".to_string(),
                    regex: Regex::new(r#"dt0c01\.[a-zA-Z0-9]{24}\.[a-f0-9]{64}"#).unwrap(),
                    severity: Severity::High,
                    description: "Dynatrace API token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Grafana
                CompiledPattern {
                    name: "Grafana API Key".to_string(),
                    regex: Regex::new(r#"eyJrIjoi[a-zA-Z0-9_-]+['\"]?"#).unwrap(),
                    severity: Severity::High,
                    description: "Grafana API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Grafana Cloud API Token".to_string(),
                    regex: Regex::new(r#"glc_[a-zA-Z0-9_-]{32,}"#).unwrap(),
                    severity: Severity::High,
                    description: "Grafana Cloud API token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Pulumi
                CompiledPattern {
                    name: "Pulumi Access Token".to_string(),
                    regex: Regex::new(r#"pul-[a-f0-9]{40}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Pulumi access token found - infrastructure access".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // HashiCorp
                CompiledPattern {
                    name: "HashiCorp Vault Token".to_string(),
                    regex: Regex::new(r#"hvs\.[a-zA-Z0-9_-]{24,}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "HashiCorp Vault service token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "HashiCorp Terraform Cloud Token".to_string(),
                    regex: Regex::new(r#"[a-zA-Z0-9]{14}\.atlasv1\.[a-zA-Z0-9_-]{60,}"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Terraform Cloud API token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Buildkite
                CompiledPattern {
                    name: "Buildkite Agent Token".to_string(),
                    regex: Regex::new(r#"bkua_[a-f0-9]{40}"#).unwrap(),
                    severity: Severity::High,
                    description: "Buildkite agent token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Codecov
                CompiledPattern {
                    name: "Codecov Token".to_string(),
                    regex: Regex::new(r#"(?i)codecov[_-]?token\s*[=:]\s*['\"][a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Codecov upload token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Twitch
                CompiledPattern {
                    name: "Twitch OAuth Token".to_string(),
                    regex: Regex::new(r#"(?i)twitch[_-]?(?:oauth[_-]?)?token\s*[=:]\s*['\"][a-z0-9]{30}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Twitch OAuth token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // LinkedIn
                CompiledPattern {
                    name: "LinkedIn Client Secret".to_string(),
                    regex: Regex::new(r#"(?i)linkedin[_-]?(?:client[_-]?)?secret\s*[=:]\s*['\"][a-zA-Z0-9]{16}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "LinkedIn client secret found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Spotify
                CompiledPattern {
                    name: "Spotify Client Secret".to_string(),
                    regex: Regex::new(r#"(?i)spotify[_-]?(?:client[_-]?)?secret\s*[=:]\s*['\"][a-f0-9]{32}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Spotify client secret found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Rapid API
                CompiledPattern {
                    name: "RapidAPI Key".to_string(),
                    regex: Regex::new(r#"(?i)(?:rapid|x-rapidapi)[_-]?(?:api[_-]?)?key\s*[=:]\s*['\"][a-f0-9]{50}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "RapidAPI key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Clarifai
                CompiledPattern {
                    name: "Clarifai API Key".to_string(),
                    regex: Regex::new(r#"(?i)clarifai[_-]?(?:api[_-]?)?key\s*[=:]\s*['\"][a-f0-9]{32}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Clarifai API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // IBM Watson
                CompiledPattern {
                    name: "IBM Cloud API Key".to_string(),
                    regex: Regex::new(r#"(?i)ibm[_-]?(?:cloud[_-]?)?(?:api[_-]?)?key\s*[=:]\s*['\"][a-zA-Z0-9_-]{44}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "IBM Cloud API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Yandex
                CompiledPattern {
                    name: "Yandex API Key".to_string(),
                    regex: Regex::new(r#"(?i)yandex[_-]?(?:api[_-]?)?key\s*[=:]\s*['\"]AQVN[a-zA-Z0-9_-]{35,}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Yandex API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // GCP Service Account
                CompiledPattern {
                    name: "GCP Service Account Key".to_string(),
                    regex: Regex::new(r#"\"private_key\":\s*\"-----BEGIN PRIVATE KEY-----"#).unwrap(),
                    severity: Severity::Critical,
                    description: "GCP service account private key found".to_string(),
                    cwe: "CWE-321".to_string(),
                },
                // Fastly
                CompiledPattern {
                    name: "Fastly API Key".to_string(),
                    regex: Regex::new(r#"(?i)fastly[_-]?(?:api[_-]?)?key\s*[=:]\s*['\"][a-zA-Z0-9_-]{32}['\"]"#).unwrap(),
                    severity: Severity::High,
                    description: "Fastly API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                // Cloudflare
                CompiledPattern {
                    name: "Cloudflare API Key".to_string(),
                    regex: Regex::new(r#"(?i)cloudflare[_-]?(?:api[_-]?)?key\s*[=:]\s*['\"][a-f0-9]{37}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Cloudflare API key found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
                CompiledPattern {
                    name: "Cloudflare API Token".to_string(),
                    regex: Regex::new(r#"(?i)cloudflare[_-]?(?:api[_-]?)?token\s*[=:]\s*['\"][a-zA-Z0-9_-]{40}['\"]"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Cloudflare API token found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
            ],
            employee_patterns: vec![
                CompiledPattern {
                    name: "Corporate Email Pattern".to_string(),
                    regex: Regex::new(r#"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(com|org|net|fi|de|uk|io|co)"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Corporate email address found - enables discovery of employee email list/patterns".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Email List/Array".to_string(),
                    // Matches arrays of emails like ["john@company.com", "jane@company.com"]
                    regex: Regex::new(r#"\[\s*["'][a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}["']\s*(?:,\s*["'][a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}["']\s*)+"#).unwrap(),
                    severity: Severity::High,
                    description: "Employee email list found in JavaScript - exposes organizational structure and enables targeted attacks".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Admin/Support Email".to_string(),
                    regex: Regex::new(r#"(?i)(admin|support|help|info|contact|sales|hr|finance|it|dev|ops|security)@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Administrative/departmental email found - reveals internal organization".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Email Domain Pattern".to_string(),
                    // Matches email domain configuration like emailDomain: "company.com"
                    regex: Regex::new(r#"(?i)(email[_-]?domain|allowed[_-]?domain|corporate[_-]?domain)\s*[=:]\s*["']@?([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})["']"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Email domain configuration found - reveals corporate email pattern".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Employee Object".to_string(),
                    // Matches employee objects like {email: "...", name: "..."}
                    regex: Regex::new(r#"\{\s*(?:["']?(?:email|mail)["']?\s*:\s*["'][a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}["'])"#).unwrap(),
                    severity: Severity::High,
                    description: "Employee data object found in JavaScript".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Team/Department List".to_string(),
                    regex: Regex::new(r#"(?i)(team|department|staff|employees?|members?)\s*[=:]\s*\[[\s\S]*?@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"#).unwrap(),
                    severity: Severity::High,
                    description: "Team/department member list found - enables organizational reconnaissance".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Slack User/Channel".to_string(),
                    regex: Regex::new(r#"<@[A-Z0-9]+>|<#[A-Z0-9]+\|[a-zA-Z0-9_-]+>"#).unwrap(),
                    severity: Severity::Low,
                    description: "Slack user/channel reference found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Internal Phone Extension".to_string(),
                    regex: Regex::new(r#"(?i)ext(?:ension)?\.?\s*\d{3,5}"#).unwrap(),
                    severity: Severity::Low,
                    description: "Internal phone extension found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Employee ID Pattern".to_string(),
                    regex: Regex::new(r#"(?i)(employee[_-]?id|emp[_-]?id|staff[_-]?id|worker[_-]?id)\s*[=:]\s*["']?[A-Z0-9]{4,12}["']?"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Employee ID pattern found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Organization Chart Data".to_string(),
                    regex: Regex::new(r#"(?i)(org[_-]?chart|hierarchy|reports[_-]?to|manager|supervisor)\s*[=:]"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Organizational hierarchy data found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Active Directory/LDAP Reference".to_string(),
                    // Must be in LDAP context - look for actual LDAP URLs or complete DN patterns
                    // IMPORTANT: Do NOT match standalone OU=, CN=, DC= as these appear in minified JS (e.g., oU=!0)
                    // Only match:
                    // 1. Complete LDAP URLs: ldap://...
                    // 2. Complete DN with multiple components: CN=value,DC=value or OU=value,DC=value
                    // 3. Explicit "active_directory" or "active-directory" strings
                    regex: Regex::new(r#"(?i)(?:ldap://[a-zA-Z0-9\.\-]+(?::\d+)?(?:/[^\s\"'<>]*)?|active[_-]directory\b|(?:CN|OU)=[a-zA-Z][a-zA-Z0-9_\- ]{2,},\s*(?:DC|OU|CN)=[a-zA-Z][a-zA-Z0-9_\- ]+)"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Active Directory/LDAP reference found - reveals internal identity infrastructure".to_string(),
                    cwe: "CWE-200".to_string(),
                },
            ],
            environment_patterns: vec![
                CompiledPattern {
                    name: "Staging/Dev URL".to_string(),
                    regex: Regex::new(r#"https?://(?:staging|dev|test|qa|uat|preprod|sandbox)\.[a-zA-Z0-9\-]+\.[a-zA-Z]+[^\s\"'<>]*"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Staging/development environment URL found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Internal IP Address".to_string(),
                    regex: Regex::new(r#"(?:10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3})"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Internal IP address found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Localhost Reference".to_string(),
                    regex: Regex::new(r#"https?://(?:localhost|127\.0\.0\.1):\d+"#).unwrap(),
                    severity: Severity::Low,
                    description: "Localhost URL found - may indicate debug code".to_string(),
                    cwe: "CWE-489".to_string(),
                },
                CompiledPattern {
                    name: "Environment Variable Reference".to_string(),
                    regex: Regex::new(r#"process\.env\.(?:SECRET|PASSWORD|API_KEY|TOKEN|PRIVATE)"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Reference to sensitive environment variable".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Database Connection String".to_string(),
                    regex: Regex::new(r#"(?:mongodb|mysql|postgres|postgresql|redis|amqp)://[^\s\"'<>]+"#).unwrap(),
                    severity: Severity::Critical,
                    description: "Database connection string found".to_string(),
                    cwe: "CWE-798".to_string(),
                },
            ],
            analytics_patterns: vec![
                CompiledPattern {
                    name: "PowerBI Embed URL".to_string(),
                    regex: Regex::new(r#"https://app\.powerbi\.com/[^\s\"'<>]+"#).unwrap(),
                    severity: Severity::Medium,
                    description: "PowerBI dashboard URL found - may expose business analytics".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "PowerBI Report ID".to_string(),
                    regex: Regex::new(r#"(?i)reportId\s*[=:]\s*['\"][a-f0-9\-]{36}['\"]"#).unwrap(),
                    severity: Severity::Medium,
                    description: "PowerBI report ID found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Tableau URL".to_string(),
                    regex: Regex::new(r#"https://[a-zA-Z0-9\-]+\.tableau(?:software)?\.com[^\s\"'<>]*"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Tableau analytics URL found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Looker URL".to_string(),
                    regex: Regex::new(r#"https://[a-zA-Z0-9\-]+\.looker\.com[^\s\"'<>]*"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Looker analytics URL found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Datadog Dashboard".to_string(),
                    regex: Regex::new(r#"https://app\.datadoghq\.com/[^\s\"'<>]+"#).unwrap(),
                    severity: Severity::Medium,
                    description: "Datadog dashboard URL found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Mixpanel Project".to_string(),
                    regex: Regex::new(r#"(?i)mixpanel\.init\s*\(\s*['\"][a-f0-9]{32}['\"]"#).unwrap(),
                    severity: Severity::Low,
                    description: "Mixpanel project token found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Amplitude API Key".to_string(),
                    regex: Regex::new(r#"(?i)amplitude\.init\s*\(\s*['\"][a-f0-9]{32}['\"]"#).unwrap(),
                    severity: Severity::Low,
                    description: "Amplitude API key found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
                CompiledPattern {
                    name: "Segment Write Key".to_string(),
                    regex: Regex::new(r#"(?i)analytics\.load\s*\(\s*['\"][a-zA-Z0-9]{22,}['\"]"#).unwrap(),
                    severity: Severity::Low,
                    description: "Segment write key found".to_string(),
                    cwe: "CWE-200".to_string(),
                },
            ],
        }
    }

    /// Scan for sensitive information leakage in JavaScript
    pub async fn scan(
        &self,
        url: &str,
        config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        info!("Scanning for JavaScript sensitive information leakage");

        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;
        let mut all_matches: Vec<SensitiveMatch> = Vec::new();

        // Get the main page
        tests_run += 1;
        let response = match self.http_client.get(url).await {
            Ok(r) => r,
            Err(_) => return Ok((vulnerabilities, tests_run)),
        };

        // Scan the main page content
        let page_matches = self.scan_content(&response.body, "Main page");
        all_matches.extend(page_matches);

        // Extract and scan JavaScript files
        let js_urls = self.extract_js_urls(&response.body, url);
        info!("Found {} JavaScript files to scan", js_urls.len());

        // Limit JS files in fast mode
        let js_limit = if config.scan_mode.as_str() == "fast" {
            5
        } else {
            20
        };

        for js_url in js_urls.iter().take(js_limit) {
            tests_run += 1;
            if let Ok(js_response) = self.http_client.get(js_url).await {
                let js_matches = self.scan_content(&js_response.body, js_url);
                all_matches.extend(js_matches);
            }
        }

        // Group matches by category and severity
        let grouped = self.group_matches(&all_matches);

        // Create vulnerabilities from grouped matches
        for (category, matches) in grouped {
            if matches.is_empty() {
                continue;
            }

            // Determine overall severity (highest among matches)
            let max_severity = matches
                .iter()
                .map(|m| &m.severity)
                .max_by_key(|s| match s {
                    Severity::Critical => 4,
                    Severity::High => 3,
                    Severity::Medium => 2,
                    Severity::Low => 1,
                    Severity::Info => 0,
                })
                .cloned()
                .unwrap_or(Severity::Low);

            // Build evidence
            let evidence = matches
                .iter()
                .take(10) // Limit evidence items
                .map(|m| {
                    format!(
                        "- {} (line {}): {}\n  Context: {}",
                        m.pattern_name,
                        m.line_number,
                        Self::truncate(&m.matched_value, 100),
                        Self::truncate(&m.context, 150)
                    )
                })
                .collect::<Vec<_>>()
                .join("\n\n");

            let additional = if matches.len() > 10 {
                format!("\n\n... and {} more instances", matches.len() - 10)
            } else {
                String::new()
            };

            // Get CWE from first match
            let cwe = matches
                .first()
                .map(|m| m.cwe.clone())
                .unwrap_or_else(|| "CWE-200".to_string());

            let cvss = match max_severity {
                Severity::Critical => 9.0,
                Severity::High => 7.5,
                Severity::Medium => 5.3,
                Severity::Low => 3.1,
                Severity::Info => 0.0,
            };

            vulnerabilities.push(Vulnerability {
                id: format!("js_sensitive_{}_{}", category.to_lowercase().replace(" ", "_"), Self::generate_id()),
                vuln_type: format!("JavaScript Sensitive Information - {}", category),
                severity: max_severity,
                confidence: Confidence::High,
                category: "Information Disclosure".to_string(),
                url: url.to_string(),
                parameter: None,
                payload: format!("{} instances found", matches.len()),
                description: format!(
                    "Found {} instances of potentially sensitive {} information in JavaScript code. \
                    This information may be useful to attackers for reconnaissance or direct exploitation.",
                    matches.len(),
                    category
                ),
                evidence: Some(format!("{}{}", evidence, additional)),
                cwe,
                cvss,
                verified: true,
                false_positive: false,
                remediation: self.get_remediation_for_category(&category),
                discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_data: None,
            });
        }

        // Fast mode: stop after finding vulnerabilities
        if config.scan_mode.as_str() == "fast" && !vulnerabilities.is_empty() {
            return Ok((vulnerabilities, tests_run));
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Scan content for sensitive patterns
    fn scan_content(&self, content: &str, source: &str) -> Vec<SensitiveMatch> {
        let mut matches = Vec::new();
        let lines: Vec<&str> = content.lines().collect();

        // Skip very large files (likely minified/bundled)
        if content.len() > 5_000_000 {
            debug!("Skipping very large file: {}", source);
            return matches;
        }

        // Scan each category of patterns
        self.scan_patterns(
            &self.patterns.credential_patterns,
            content,
            &lines,
            source,
            "Credentials",
            &mut matches,
        );
        self.scan_patterns(
            &self.patterns.admin_debug_patterns,
            content,
            &lines,
            source,
            "Admin/Debug",
            &mut matches,
        );
        self.scan_patterns(
            &self.patterns.jira_patterns,
            content,
            &lines,
            source,
            "Issue Tracking",
            &mut matches,
        );
        self.scan_patterns(
            &self.patterns.internal_tools,
            content,
            &lines,
            source,
            "Internal Tools",
            &mut matches,
        );
        self.scan_patterns(
            &self.patterns.document_patterns,
            content,
            &lines,
            source,
            "Documents",
            &mut matches,
        );
        self.scan_patterns(
            &self.patterns.comment_patterns,
            content,
            &lines,
            source,
            "Comments",
            &mut matches,
        );
        self.scan_patterns(
            &self.patterns.environment_patterns,
            content,
            &lines,
            source,
            "Environment",
            &mut matches,
        );
        self.scan_patterns(
            &self.patterns.analytics_patterns,
            content,
            &lines,
            source,
            "Analytics",
            &mut matches,
        );
        self.scan_patterns(
            &self.patterns.employee_patterns,
            content,
            &lines,
            source,
            "Employee Info",
            &mut matches,
        );

        matches
    }

    /// Scan content with a set of patterns
    fn scan_patterns(
        &self,
        patterns: &[CompiledPattern],
        content: &str,
        lines: &[&str],
        source: &str,
        category: &str,
        matches: &mut Vec<SensitiveMatch>,
    ) {
        for pattern in patterns {
            for cap in pattern.regex.captures_iter(content) {
                let matched = cap.get(0).unwrap().as_str();

                // Skip false positives
                if self.is_false_positive(matched, &pattern.name, content) {
                    continue;
                }

                // Find line number
                let match_start = cap.get(0).unwrap().start();
                let line_number = content[..match_start].matches('\n').count() + 1;

                // Get context
                let context = if line_number <= lines.len() {
                    lines[line_number - 1].to_string()
                } else {
                    String::new()
                };

                matches.push(SensitiveMatch {
                    pattern_name: pattern.name.clone(),
                    matched_value: matched.to_string(),
                    context: format!("{}: {}", source, context),
                    line_number,
                    severity: pattern.severity.clone(),
                    category: category.to_string(),
                    cwe: pattern.cwe.clone(),
                    description: pattern.description.clone(),
                });
            }
        }
    }

    /// Check if a match is likely a false positive
    fn is_false_positive(&self, matched: &str, pattern_name: &str, content: &str) -> bool {
        let matched_lower = matched.to_lowercase();

        // Generic API key - skip if it's a placeholder/example
        if pattern_name.contains("API Key")
            || pattern_name.contains("Secret")
            || pattern_name.contains("Password")
        {
            let placeholder_patterns = [
                "your_",
                "example",
                "xxx",
                "placeholder",
                "change_me",
                "insert_",
                "todo",
                "fixme",
                "replace",
                "dummy",
                "test_",
                "sample",
                "<your",
                "{your",
                "[your",
                "api_key_here",
                "secret_here",
            ];
            for p in placeholder_patterns {
                if matched_lower.contains(p) {
                    return true;
                }
            }
        }

        // Skip Jira patterns that are common CSS/JS/web false positives
        if pattern_name == "Jira Ticket Reference" {
            let matched_lower = matched.to_lowercase();
            let parts: Vec<&str> = matched.split('-').collect();

            if parts.len() == 2 {
                let prefix = parts[0].to_uppercase();
                let suffix = parts[1];

                // Skip if suffix is too short (< 2 digits) - likely CSS/JS patterns
                if suffix.len() < 2 {
                    return true;
                }

                // Skip common false positives like ISO codes, CSS classes, etc.
                let common_fp_prefixes = [
                    "UTF",
                    "ISO",
                    "ASCII",
                    "EUC", // Character encodings
                    "CSS",
                    "HTML",
                    "SVG",
                    "XML", // Web standards
                    "RGB",
                    "HSL",
                    "HEX", // Color formats
                    "GET",
                    "POST",
                    "PUT",
                    "DELETE", // HTTP methods
                    "PNG",
                    "JPG",
                    "GIF",
                    "WEBP", // Image formats
                    "MP3",
                    "MP4",
                    "WAV",
                    "AVI", // Media formats
                    "NORTH",
                    "SOUTH",
                    "EAST",
                    "WEST", // Directions
                    "TOP",
                    "BOTTOM",
                    "LEFT",
                    "RIGHT", // Positions
                    "SCRIPT",
                    "STYLE",
                    "LINK", // HTML tags
                    "INSET",
                    "OUTSET", // CSS values
                    "INDEX",
                    "LENGTH",
                    "LAST",
                    "LASTINDEX", // JS properties
                    "PANOSE",    // Font metadata
                    "SEC",
                    "MIN",
                    "MAX", // Time/math abbreviations
                    "FI",
                    "FL",
                    "FF", // Font ligatures
                    "ID",
                    "REF",
                    "KEY", // Generic identifiers
                ];
                if common_fp_prefixes.iter().any(|fp| prefix == *fp) {
                    return true;
                }

                // Also check for common CSS/Tailwind patterns (case insensitive)
                let css_patterns = [
                    "col-",
                    "row-",
                    "flex-",
                    "grid-",
                    "gap-",
                    "space-",
                    "text-",
                    "font-",
                    "bg-",
                    "border-",
                    "rounded-",
                    "px-",
                    "py-",
                    "pt-",
                    "pb-",
                    "pl-",
                    "pr-",
                    "mx-",
                    "my-",
                    "w-",
                    "h-",
                    "min-",
                    "max-",
                    "z-",
                    "top-",
                    "left-",
                    "right-",
                    "bottom-",
                    "inset-",
                    "opacity-",
                    "scale-",
                    "rotate-",
                    "translate-",
                    "duration-",
                    "delay-",
                    "ease-",
                    "transition-",
                    "sr-",
                    "not-",
                    "group-",
                    "peer-",
                    "focus-",
                    "hover-",
                    "active-",
                    "disabled-",
                    "checked-",
                    "first-",
                    "last-",
                    "odd-",
                    "even-",
                    "xs-",
                    "sm-",
                    "md-",
                    "lg-",
                    "xl-",
                ];
                if css_patterns.iter().any(|p| matched_lower.starts_with(p)) {
                    return true;
                }

                // Skip common JS property patterns
                let js_patterns = [
                    "length-",
                    "index-",
                    "count-",
                    "size-",
                    "width-",
                    "height-",
                    "offset-",
                    "margin-",
                    "padding-",
                    "border-",
                    "radius-",
                    "timeout-",
                    "interval-",
                    "delay-",
                    "version-",
                    "revision-",
                    "lastindex-",
                    "script-",
                    "style-",
                    "class-",
                    "data-",
                ];
                if js_patterns.iter().any(|p| matched_lower.starts_with(p)) {
                    return true;
                }
            }
        }

        // Skip email patterns that are examples or public contact emails
        if pattern_name.contains("Email") || pattern_name.contains("Corporate Email") {
            let example_domains = [
                "example.com",
                "example.org",
                "test.com",
                "localhost",
                "domain.com",
            ];
            for domain in example_domains {
                if matched_lower.contains(domain) {
                    return true;
                }
            }
            // Skip public contact emails - these are intentionally public
            let public_prefixes = [
                "info@",
                "contact@",
                "support@",
                "help@",
                "sales@",
                "hello@",
                "press@",
                "media@",
                "feedback@",
                "enquiries@",
                "team@",
                "mail@",
                "office@",
                "admin@",
                "noreply@",
                "no-reply@",
            ];
            for prefix in public_prefixes {
                if matched_lower.starts_with(prefix) {
                    return true;
                }
            }
        }

        // Skip localhost references in development-only contexts
        if pattern_name.contains("Localhost") {
            // Check if there's a conditional around it
            let pos = content.find(matched).unwrap_or(0);
            let context_start = pos.saturating_sub(100);
            let context = &content[context_start..pos.min(content.len())];
            if context.contains("isDev")
                || context.contains("isDebug")
                || context.contains("NODE_ENV")
            {
                return true;
            }
        }

        // Skip PDF patterns that are clearly public/intended
        if pattern_name.contains("PDF") {
            let public_paths = [
                "/public/",
                "/assets/",
                "/static/",
                "/docs/",
                "documentation",
            ];
            for path in public_paths {
                if matched_lower.contains(path) {
                    return true;
                }
            }
        }

        false
    }

    /// Extract JavaScript URLs from HTML
    fn extract_js_urls(&self, html: &str, base_url: &str) -> Vec<String> {
        let mut urls = HashSet::new();

        // Pattern for script src
        let script_pattern = Regex::new(r#"<script[^>]*src=["']([^"']+)["']"#).unwrap();

        for cap in script_pattern.captures_iter(html) {
            if let Some(src) = cap.get(1) {
                let src_str = src.as_str();

                // Skip external CDNs we don't need to scan
                if src_str.contains("cdn")
                    || src_str.contains("googleapis.com")
                    || src_str.contains("cloudflare")
                    || src_str.contains("unpkg.com")
                    || src_str.contains("jsdelivr")
                {
                    continue;
                }

                let full_url = self.resolve_url(src_str, base_url);
                urls.insert(full_url);
            }
        }

        // Also look for dynamically loaded scripts
        let import_pattern =
            Regex::new(r#"import\s*\(\s*["']([^"']+\.js[^"']*)["']\s*\)"#).unwrap();
        for cap in import_pattern.captures_iter(html) {
            if let Some(path) = cap.get(1) {
                let full_url = self.resolve_url(path.as_str(), base_url);
                urls.insert(full_url);
            }
        }

        urls.into_iter().collect()
    }

    /// Resolve relative URL to absolute
    fn resolve_url(&self, src: &str, base_url: &str) -> String {
        if src.starts_with("http://") || src.starts_with("https://") {
            return src.to_string();
        }

        if let Ok(base) = url::Url::parse(base_url) {
            if src.starts_with("//") {
                return format!("{}:{}", base.scheme(), src);
            }

            if let Ok(resolved) = base.join(src) {
                return resolved.to_string();
            }
        }

        // Fallback
        if src.starts_with('/') {
            if let Ok(parsed) = url::Url::parse(base_url) {
                let host = parsed.host_str().unwrap_or("localhost");
                let scheme = parsed.scheme();
                return format!("{}://{}{}", scheme, host, src);
            }
        }

        src.to_string()
    }

    /// Group matches by category
    fn group_matches<'a>(
        &self,
        matches: &'a [SensitiveMatch],
    ) -> HashMap<String, Vec<&'a SensitiveMatch>> {
        let mut grouped: HashMap<String, Vec<&SensitiveMatch>> = HashMap::new();

        for m in matches {
            grouped.entry(m.category.clone()).or_default().push(m);
        }

        // Deduplicate by matched value within each category
        for (_, matches) in grouped.iter_mut() {
            let mut seen = HashSet::new();
            matches.retain(|m| seen.insert(m.matched_value.clone()));
        }

        grouped
    }

    /// Get remediation advice for a category
    fn get_remediation_for_category(&self, category: &str) -> String {
        match category {
            "Credentials" => "1. CRITICAL: Rotate all exposed credentials immediately\n\
                              2. Remove hardcoded secrets from source code\n\
                              3. Use environment variables or secret managers\n\
                              4. Implement proper secret scanning in CI/CD\n\
                              5. Review git history for exposed secrets"
                .to_string(),
            "Admin/Debug" => "1. Remove debug flags and code before production deployment\n\
                              2. Use build-time environment checks to strip debug code\n\
                              3. Implement proper feature flags with server-side control\n\
                              4. Remove console.log statements with sensitive data\n\
                              5. Use production builds that strip development code"
                .to_string(),
            "Issue Tracking" => "1. Remove internal issue tracker references from client code\n\
                                 2. Use generic error messages instead of ticket numbers\n\
                                 3. Implement server-side error logging with correlation IDs\n\
                                 4. Review what internal information is exposed"
                .to_string(),
            "Internal Tools" => "1. Remove internal tool URLs from client-side code\n\
                                 2. Ensure internal tools require authentication\n\
                                 3. Use network segmentation to protect internal resources\n\
                                 4. Audit for webhook/integration URL exposure"
                .to_string(),
            "Documents" => "1. Move sensitive documents behind authentication\n\
                            2. Remove internal document paths from client code\n\
                            3. Implement access controls on document servers\n\
                            4. Use pre-signed URLs with expiration for document access"
                .to_string(),
            "Comments" => "1. Strip comments from production JavaScript builds\n\
                           2. Use minification/uglification in build process\n\
                           3. Review TODO/FIXME comments for sensitive information\n\
                           4. Implement code review process for comment content"
                .to_string(),
            "Environment" => "1. Remove staging/dev URLs from production code\n\
                              2. Use environment-specific configuration\n\
                              3. Implement proper network isolation between environments\n\
                              4. Remove database connection strings from client code"
                .to_string(),
            "Analytics" => "1. Review which analytics dashboards are referenced\n\
                            2. Ensure PowerBI/Tableau dashboards require authentication\n\
                            3. Use row-level security in BI tools\n\
                            4. Audit analytics data for sensitive information"
                .to_string(),
            "Employee Info" => "1. Remove internal email addresses from client code\n\
                                2. Use role-based contact forms instead of direct emails\n\
                                3. Audit code for PII exposure\n\
                                4. Implement proper contact management"
                .to_string(),
            _ => "1. Review and remove sensitive information from client-side code\n\
                  2. Implement proper access controls\n\
                  3. Use server-side processing for sensitive operations\n\
                  4. Conduct regular security audits"
                .to_string(),
        }
    }

    /// Truncate string with ellipsis
    fn truncate(s: &str, max_len: usize) -> String {
        if s.len() <= max_len {
            s.to_string()
        } else {
            format!("{}...", &s[..max_len])
        }
    }

    /// Generate unique ID
    fn generate_id() -> String {
        use rand::Rng;
        let mut rng = rand::rng();
        format!("{:08x}", rng.random::<u32>())
    }
}

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

    #[test]
    fn test_jira_ticket_pattern() {
        // Pattern requires 3+ letter prefix and 2+ digit number to avoid CSS/JS false positives
        let pattern = Regex::new(r#"\b([A-Z]{3,10}-\d{2,6})\b"#).unwrap();

        assert!(pattern.is_match("PROJ-123"));
        assert!(pattern.is_match("SEC-12"));
        assert!(pattern.is_match("MYPROJECT-99999"));
        assert!(!pattern.is_match("A-1")); // Too short prefix
        assert!(!pattern.is_match("FI-2")); // Too short prefix (CSS false positive)
        assert!(!pattern.is_match("NORTH-1")); // Single digit (CSS false positive)
        assert!(!pattern.is_match("inset-0")); // CSS value
    }

    #[test]
    fn test_aws_key_pattern() {
        let pattern = Regex::new(r#"AKIA[0-9A-Z]{16}"#).unwrap();

        assert!(pattern.is_match("AKIAIOSFODNN7EXAMPLE"));
        assert!(!pattern.is_match("AKIA123")); // Too short
    }

    #[test]
    fn test_jwt_pattern() {
        let pattern =
            Regex::new(r#"eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*"#).unwrap();

        // Example JWT (not real)
        let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U";
        assert!(pattern.is_match(jwt));
    }

    #[test]
    fn test_powerbi_pattern() {
        let pattern = Regex::new(r#"https://app\.powerbi\.com/[^\s\"'<>]+"#).unwrap();

        assert!(pattern.is_match("https://app.powerbi.com/groups/abc123/reports/xyz789"));
    }

    #[test]
    fn test_is_dev_pattern() {
        let pattern = Regex::new(
            r#"(?i)(isDev|isDebug|isTest|debugMode|devMode|testMode)\s*[=:]\s*(true|1|!0)"#,
        )
        .unwrap();

        assert!(pattern.is_match("isDev = true"));
        assert!(pattern.is_match("isDebug: true"));
        assert!(pattern.is_match("testMode = 1"));
        assert!(pattern.is_match("debugMode: !0"));
    }
}