lonkero 3.7.0

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
// 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;
use std::sync::Arc;
use tracing::{debug, info};

pub struct NextJsSecurityScanner {
    http_client: Arc<HttpClient>,
    known_cves: Vec<NextJsCVE>,
}

#[derive(Clone)]
struct NextJsCVE {
    cve_id: String,
    affected_versions: String,
    severity: Severity,
    description: String,
    check_type: CVECheckType,
}

#[derive(Clone)]
enum CVECheckType {
    MiddlewareBypass,
    ServerAction,
    ImageOptimization,
    DataExposure,
    PathTraversal,
    SSRF,
    DoS,
}

impl NextJsSecurityScanner {
    pub fn new(http_client: Arc<HttpClient>) -> Self {
        Self {
            http_client,
            known_cves: Self::build_cve_database(),
        }
    }

    /// Build database of known Next.js CVEs
    fn build_cve_database() -> Vec<NextJsCVE> {
        vec![
            // Middleware bypass vulnerabilities
            NextJsCVE {
                cve_id: "CVE-2024-34351".to_string(),
                affected_versions: "13.4.0 - 14.1.0".to_string(),
                severity: Severity::Critical,
                description: "Server-Side Request Forgery (SSRF) in Server Actions via Host header manipulation".to_string(),
                check_type: CVECheckType::MiddlewareBypass,
            },
            NextJsCVE {
                cve_id: "CVE-2024-34350".to_string(),
                affected_versions: "<14.1.1".to_string(),
                severity: Severity::High,
                description: "Inconsistent interpretation of crafted HTTP requests leading to authentication bypass".to_string(),
                check_type: CVECheckType::MiddlewareBypass,
            },
            NextJsCVE {
                cve_id: "CVE-2024-39693".to_string(),
                affected_versions: "<14.2.4".to_string(),
                severity: Severity::High,
                description: "Authorization bypass through x-middleware-subrequest header".to_string(),
                check_type: CVECheckType::MiddlewareBypass,
            },
            NextJsCVE {
                cve_id: "CVE-2025-29927".to_string(),
                affected_versions: "<14.2.25, <15.2.3".to_string(),
                severity: Severity::Critical,
                description: "Middleware bypass via x-middleware-subrequest header allowing auth bypass".to_string(),
                check_type: CVECheckType::MiddlewareBypass,
            },
            // Server Action vulnerabilities
            NextJsCVE {
                cve_id: "CVE-2024-46982".to_string(),
                affected_versions: "<14.2.10".to_string(),
                severity: Severity::High,
                description: "Cache poisoning in Server Actions leading to denial of service".to_string(),
                check_type: CVECheckType::DoS,
            },
            // Image optimization vulnerabilities
            NextJsCVE {
                cve_id: "CVE-2024-47831".to_string(),
                affected_versions: "<14.2.7".to_string(),
                severity: Severity::High,
                description: "SSRF vulnerability in image optimization allowing internal network access".to_string(),
                check_type: CVECheckType::ImageOptimization,
            },
            NextJsCVE {
                cve_id: "CVE-2023-46298".to_string(),
                affected_versions: "<13.4.20".to_string(),
                severity: Severity::High,
                description: "SSRF via image optimization with custom domains".to_string(),
                check_type: CVECheckType::ImageOptimization,
            },
            // Path traversal
            NextJsCVE {
                cve_id: "CVE-2024-51479".to_string(),
                affected_versions: "<14.2.18, <15.0.4".to_string(),
                severity: Severity::High,
                description: "Unauthorized access to root-level files via path traversal".to_string(),
                check_type: CVECheckType::PathTraversal,
            },
            // Data exposure
            NextJsCVE {
                cve_id: "CVE-2024-56332".to_string(),
                affected_versions: "<14.2.21, <15.1.2".to_string(),
                severity: Severity::Medium,
                description: "Information disclosure through error messages exposing internal paths".to_string(),
                check_type: CVECheckType::DataExposure,
            },
        ]
    }

    /// Main scan entry point
    pub async fn scan(
        &self,
        url: &str,
        config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        // Check license
        if !crate::license::has_feature("cms_security") {
            debug!("[Next.js] Skipping - requires Personal license or higher");
            return Ok((vec![], 0));
        }

        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        // Detect if target is running Next.js
        tests_run += 1;
        let (is_nextjs, version) = self.detect_nextjs(url).await;

        if !is_nextjs {
            debug!("[Next.js] Target does not appear to be running Next.js");
            return Ok((vec![], tests_run));
        }

        info!(
            "[Next.js] Detected Next.js application{}",
            version
                .as_ref()
                .map(|v| format!(" (version: {})", v))
                .unwrap_or_default()
        );

        // Discover routes from JavaScript bundles for enhanced testing
        let discovered_routes = self.discover_routes(url).await.unwrap_or_default();
        if !discovered_routes.is_empty() {
            info!(
                "[Next.js] Discovered {} routes for security testing",
                discovered_routes.len()
            );
        }

        // Test middleware bypass vulnerabilities
        let (bypass_vulns, bypass_tests) = self.check_middleware_bypass(url, config).await?;
        vulnerabilities.extend(bypass_vulns);
        tests_run += bypass_tests;

        // Test _next/data exposure
        let (data_vulns, data_tests) = self.check_next_data_exposure(url, config).await?;
        vulnerabilities.extend(data_vulns);
        tests_run += data_tests;

        // Test API route misconfigurations
        let (api_vulns, api_tests) = self.check_api_routes(url, config).await?;
        vulnerabilities.extend(api_vulns);
        tests_run += api_tests;

        // Test environment variable exposure
        let (env_vulns, env_tests) = self.check_env_exposure(url, config).await?;
        vulnerabilities.extend(env_vulns);
        tests_run += env_tests;

        // Test image optimization SSRF
        let (img_vulns, img_tests) = self.check_image_ssrf(url, config).await?;
        vulnerabilities.extend(img_vulns);
        tests_run += img_tests;

        // Test draft/preview mode
        let (draft_vulns, draft_tests) = self.check_draft_mode(url, config).await?;
        vulnerabilities.extend(draft_vulns);
        tests_run += draft_tests;

        // Test ISR revalidation exposure
        let (isr_vulns, isr_tests) = self.check_isr_revalidation(url, config).await?;
        vulnerabilities.extend(isr_vulns);
        tests_run += isr_tests;

        // Test source map exposure
        let (sourcemap_vulns, sourcemap_tests) = self.check_source_maps(url, config).await?;
        vulnerabilities.extend(sourcemap_vulns);
        tests_run += sourcemap_tests;

        // Test Next.js config exposure
        let (config_vulns, config_tests) = self.check_config_exposure(url, config).await?;
        vulnerabilities.extend(config_vulns);
        tests_run += config_tests;

        // Test server actions
        let (action_vulns, action_tests) = self.check_server_actions(url, config).await?;
        vulnerabilities.extend(action_vulns);
        tests_run += action_tests;

        // Check known CVEs based on detected version
        if let Some(ref ver) = version {
            let (cve_vulns, cve_tests) = self.check_version_cves(url, ver, config).await?;
            vulnerabilities.extend(cve_vulns);
            tests_run += cve_tests;
        }

        // Test discovered routes for middleware bypass
        if !discovered_routes.is_empty() {
            let (route_vulns, route_tests) = self
                .check_discovered_routes_bypass(url, &discovered_routes, config)
                .await?;
            vulnerabilities.extend(route_vulns);
            tests_run += route_tests;
        }

        info!(
            "[Next.js] Completed: {} vulnerabilities, {} tests",
            vulnerabilities.len(),
            tests_run
        );

        Ok((vulnerabilities, tests_run))
    }

    /// Detect if target is running Next.js
    async fn detect_nextjs(&self, url: &str) -> (bool, Option<String>) {
        // Check multiple indicators
        let mut is_nextjs = false;
        let mut version = None;

        // 1. Check _next directory
        let next_static = format!("{}/_next/static/", url.trim_end_matches('/'));
        if let Ok(resp) = self.http_client.get(&next_static).await {
            if resp.status_code != 404 {
                is_nextjs = true;
            }
        }

        // 2. Check for __NEXT_DATA__ script tag
        if let Ok(resp) = self.http_client.get(url).await {
            if resp.body.contains("__NEXT_DATA__") || resp.body.contains("_next/static") {
                is_nextjs = true;
            }

            // Extract version from build manifest or __NEXT_DATA__
            let version_re = Regex::new(r#"(?i)next(?:\.js)?[/\s]*v?(\d+\.\d+(?:\.\d+)?)"#).ok();
            if let Some(re) = version_re {
                if let Some(caps) = re.captures(&resp.body) {
                    version = caps.get(1).map(|m| m.as_str().to_string());
                }
            }

            // Check X-Powered-By header
            if let Some(powered_by) = resp.headers.get("x-powered-by") {
                let powered_by_lower = powered_by.to_lowercase();
                if powered_by_lower.contains("next.js") || powered_by_lower.contains("next") {
                    is_nextjs = true;
                    // Extract version from header
                    let header_version_re =
                        Regex::new(r#"(?i)next\.js?\s*v?(\d+\.\d+(?:\.\d+)?)"#).ok();
                    if let Some(re) = header_version_re {
                        if let Some(caps) = re.captures(&powered_by) {
                            version = caps.get(1).map(|m| m.as_str().to_string());
                        }
                    }
                }
            }
        }

        // 3. Check for Next.js specific headers
        let api_test = format!("{}/api/health", url.trim_end_matches('/'));
        if let Ok(resp) = self.http_client.get(&api_test).await {
            // Check for Next.js cache headers
            if resp.headers.contains_key("x-nextjs-cache")
                || resp.headers.contains_key("x-nextjs-matched-path")
            {
                is_nextjs = true;
            }
        }

        (is_nextjs, version)
    }

    /// Check for middleware bypass vulnerabilities
    async fn check_middleware_bypass(
        &self,
        url: &str,
        config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let base = url.trim_end_matches('/');

        // Test protected paths that might have middleware
        let protected_paths = [
            "/admin",
            "/dashboard",
            "/api/admin",
            "/api/private",
            "/protected",
            "/internal",
            "/settings",
            "/account",
        ];

        // CVE-2024-34351 / CVE-2025-29927: x-middleware-subrequest bypass
        for path in &protected_paths {
            tests_run += 1;
            let test_url = format!("{}{}", base, path);

            // First check if path is protected (returns 401/403 normally)
            let normal_resp = match self.http_client.get(&test_url).await {
                Ok(r) => r,
                Err(_) => continue,
            };

            if normal_resp.status_code != 401 && normal_resp.status_code != 403 {
                continue; // Not a protected path
            }

            // Try bypass with x-middleware-subrequest header
            tests_run += 1;
            let mut headers = HashMap::new();
            headers.insert("x-middleware-subrequest".to_string(), "1".to_string());

            let headers_vec: Vec<(String, String)> = headers
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect();
            if let Ok(bypass_resp) = self
                .http_client
                .get_with_headers(&test_url, headers_vec)
                .await
            {
                // Check if we bypassed authentication
                if bypass_resp.status_code == 200
                    || (bypass_resp.status_code != 401 && bypass_resp.status_code != 403)
                {
                    vulnerabilities.push(Vulnerability {
                        id: format!("nextjs_middleware_bypass_{}", Self::generate_id()),
                        vuln_type: "Next.js Middleware Bypass - Authentication Bypass".to_string(),
                        severity: Severity::Critical,
                        confidence: Confidence::High,
                        category: "Authentication".to_string(),
                        url: test_url.clone(),
                        parameter: Some("x-middleware-subrequest".to_string()),
                        payload: "x-middleware-subrequest: 1".to_string(),
                        description: format!(
                            "Next.js middleware authentication bypass via x-middleware-subrequest header. \
                            The protected path '{}' returns {} normally but {} with bypass header. \
                            This vulnerability (CVE-2025-29927/CVE-2024-39693) allows attackers to bypass \
                            authentication middleware by adding a special header that tricks Next.js into \
                            thinking the request is a subrequest from middleware itself.",
                            path, normal_resp.status_code, bypass_resp.status_code
                        ),
                        evidence: Some(format!(
                            "Normal request: {} {} (blocked)\n\
                            With x-middleware-subrequest: {} {} (bypassed)\n\
                            Response length: {} bytes",
                            "GET", test_url,
                            bypass_resp.status_code,
                            if bypass_resp.status_code == 200 { "OK" } else { "accessible" },
                            bypass_resp.body.len()
                        )),
                        cwe: "CWE-287".to_string(),
                        cvss: 9.8,
                        verified: true,
                        false_positive: false,
                        remediation: "1. Upgrade Next.js to latest version (14.2.25+ or 15.2.3+)\n\
                                      2. Add server-side authentication checks that don't rely solely on middleware\n\
                                      3. Implement defense in depth - validate auth at API route level\n\
                                      4. Use next.config.js to block x-middleware-subrequest header from external requests".to_string(),
                        discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                    });
                }
            }

            // Try variations of the bypass
            let bypass_variations = [
                ("x-middleware-subrequest", "true"),
                (
                    "x-middleware-subrequest",
                    "middleware:middleware:middleware:middleware:middleware",
                ),
                ("X-Middleware-Subrequest", "1"),
                ("x-middleware-prefetch", "1"),
                ("x-middleware-invoke", "1"),
            ];

            for (header, value) in bypass_variations {
                tests_run += 1;
                let mut headers = HashMap::new();
                headers.insert(header.to_string(), value.to_string());

                let headers_vec: Vec<(String, String)> = headers
                    .iter()
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect();
                if let Ok(bypass_resp) = self
                    .http_client
                    .get_with_headers(&test_url, headers_vec)
                    .await
                {
                    if bypass_resp.status_code == 200 && normal_resp.status_code != 200 {
                        vulnerabilities.push(Vulnerability {
                            id: format!("nextjs_middleware_bypass_{}", Self::generate_id()),
                            vuln_type: "Next.js Middleware Bypass Variant".to_string(),
                            severity: Severity::Critical,
                            confidence: Confidence::High,
                            category: "Authentication".to_string(),
                            url: test_url.clone(),
                            parameter: Some(header.to_string()),
                            payload: format!("{}: {}", header, value),
                            description: format!(
                                "Authentication bypass using {} header variant at path '{}'.",
                                header, path
                            ),
                            evidence: Some(format!(
                                "Bypass header: {}: {}\nStatus changed: {} -> {}",
                                header, value, normal_resp.status_code, bypass_resp.status_code
                            )),
                            cwe: "CWE-287".to_string(),
                            cvss: 9.8,
                            verified: true,
                            false_positive: false,
                            remediation:
                                "Upgrade Next.js and implement server-side auth validation."
                                    .to_string(),
                            discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                        });
                        break;
                    }
                }
            }

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

        Ok((vulnerabilities, tests_run))
    }

    /// Check for _next/data exposure
    async fn check_next_data_exposure(
        &self,
        url: &str,
        config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let base = url.trim_end_matches('/');

        // Fetch main page to get build ID
        let main_resp = match self.http_client.get(url).await {
            Ok(r) => r,
            Err(_) => return Ok((vec![], tests_run)),
        };

        // Extract buildId from __NEXT_DATA__
        let build_id_re = Regex::new(r#"buildId["']?\s*:\s*["']([^"']+)["']"#)?;
        let build_id = build_id_re
            .captures(&main_resp.body)
            .and_then(|c| c.get(1))
            .map(|m| m.as_str().to_string());

        let build_id = match build_id {
            Some(id) => id,
            None => {
                debug!("[Next.js] Could not extract buildId");
                return Ok((vec![], tests_run));
            }
        };

        // Test _next/data endpoints for various pages
        let pages_to_test = [
            "/index",
            "/admin",
            "/dashboard",
            "/user",
            "/profile",
            "/settings",
            "/api-docs",
            "/internal",
        ];

        for page in &pages_to_test {
            tests_run += 1;
            let data_url = format!("{}/_next/data/{}{}.json", base, build_id, page);

            if let Ok(resp) = self.http_client.get(&data_url).await {
                if resp.status_code == 200 && resp.body.starts_with("{") {
                    // Check for sensitive data in the response
                    let sensitive_patterns = [
                        ("email", r#"(?i)["']email["']\s*:\s*["'][^"']+@[^"']+"#),
                        ("password", r#"(?i)["']password["']\s*:"#),
                        ("token", r#"(?i)["'](?:auth|access|api)?[_-]?token["']\s*:"#),
                        (
                            "secret",
                            r#"(?i)["'](?:secret|private)[_-]?(?:key)?["']\s*:"#,
                        ),
                        ("user_id", r#"(?i)["']user[_-]?id["']\s*:"#),
                        ("session", r#"(?i)["']session["']\s*:"#),
                        ("credit_card", r#"\d{13,16}"#),
                        ("ssn", r#"\d{3}-\d{2}-\d{4}"#),
                    ];

                    let mut found_sensitive = Vec::new();
                    for (name, pattern) in &sensitive_patterns {
                        if let Ok(re) = Regex::new(pattern) {
                            if re.is_match(&resp.body) {
                                found_sensitive.push(*name);
                            }
                        }
                    }

                    if !found_sensitive.is_empty() {
                        vulnerabilities.push(Vulnerability {
                            id: format!("nextjs_data_exposure_{}", Self::generate_id()),
                            vuln_type: "Next.js Data Exposure - Sensitive Information Leak".to_string(),
                            severity: Severity::High,
                            confidence: Confidence::High,
                            category: "Information Disclosure".to_string(),
                            url: data_url.clone(),
                            parameter: Some(format!("_next/data/{}", page)),
                            payload: format!("GET /_next/data/{}{}.json", build_id, page),
                            description: format!(
                                "The Next.js _next/data endpoint for '{}' exposes sensitive information. \
                                Data from getServerSideProps/getStaticProps is accessible via direct \
                                URL access, potentially leaking: {}",
                                page, found_sensitive.join(", ")
                            ),
                            evidence: Some(format!(
                                "Endpoint: {}\n\
                                Status: 200 OK\n\
                                Content-Type: application/json\n\
                                Sensitive fields found: {}\n\
                                Response preview: {}...",
                                data_url,
                                found_sensitive.join(", "),
                                &resp.body[..resp.body.len().min(200)]
                            )),
                            cwe: "CWE-200".to_string(),
                            cvss: 7.5,
                            verified: true,
                            false_positive: false,
                            remediation: "1. Review getServerSideProps/getStaticProps for sensitive data exposure\n\
                                          2. Implement proper authorization in data fetching functions\n\
                                          3. Filter sensitive fields before returning props\n\
                                          4. Use authentication checks in getServerSideProps\n\
                                          5. Consider using API routes for sensitive data access".to_string(),
                            discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                        });
                    }
                }
            }

            if config.scan_mode.as_str() == "fast" && !vulnerabilities.is_empty() {
                break;
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Check API route misconfigurations
    async fn check_api_routes(
        &self,
        url: &str,
        config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let base = url.trim_end_matches('/');

        // Common API routes to check
        let api_routes = [
            "/api/users",
            "/api/admin",
            "/api/config",
            "/api/settings",
            "/api/internal",
            "/api/debug",
            "/api/graphql",
            "/api/auth/[...nextauth]",
            "/api/auth/session",
            "/api/auth/providers",
            "/api/trpc",
            "/api/health",
            "/api/status",
            "/api/env",
            "/api/test",
        ];

        for route in &api_routes {
            tests_run += 1;
            let api_url = format!("{}{}", base, route);

            if let Ok(resp) = self.http_client.get(&api_url).await {
                // Check for exposed internal APIs
                if resp.status_code == 200 {
                    let body_lower = resp.body.to_lowercase();

                    // Check for actual sensitive data exposure, not generic keywords
                    // Removed "internal", "debug", "config", "database", "secret" which
                    // appear on almost any informational page
                    let is_sensitive = body_lower.contains("connection_string")
                        || body_lower.contains("api_key")
                        || body_lower.contains("password=")
                        || body_lower.contains("password\":")
                        || body_lower.contains("secret_key")
                        || body_lower.contains("aws_access_key")
                        || body_lower.contains("private_key");

                    if is_sensitive
                        && (route.contains("internal")
                            || route.contains("debug")
                            || route.contains("config"))
                    {
                        vulnerabilities.push(Vulnerability {
                            id: format!("nextjs_api_exposure_{}", Self::generate_id()),
                            vuln_type: "Next.js API Route - Internal Endpoint Exposed".to_string(),
                            severity: Severity::High,
                            confidence: Confidence::Medium,
                            category: "Information Disclosure".to_string(),
                            url: api_url.clone(),
                            parameter: Some(route.to_string()),
                            payload: format!("GET {}", route),
                            description: format!(
                                "Internal API route '{}' is publicly accessible and returns sensitive data. \
                                This endpoint should be protected with authentication.",
                                route
                            ),
                            evidence: Some(format!(
                                "Status: 200 OK\n\
                                Contains sensitive keywords\n\
                                Response preview: {}...",
                                &resp.body[..resp.body.len().min(300)]
                            )),
                            cwe: "CWE-200".to_string(),
                            cvss: 6.5,
                            verified: true,
                            false_positive: false,
                            remediation: "1. Add authentication middleware to sensitive API routes\n\
                                          2. Use getServerSession for auth validation\n\
                                          3. Implement role-based access control\n\
                                          4. Remove debug/internal endpoints in production".to_string(),
                            discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                        });
                    }
                }

                // Check for CORS misconfiguration on API routes
                tests_run += 1;
                let mut headers = HashMap::new();
                headers.insert("Origin".to_string(), "https://evil.com".to_string());

                let headers_vec: Vec<(String, String)> = headers
                    .iter()
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect();
                if let Ok(cors_resp) = self
                    .http_client
                    .get_with_headers(&api_url, headers_vec)
                    .await
                {
                    if let Some(acao) = cors_resp.headers.get("access-control-allow-origin") {
                        if acao == "https://evil.com" || acao == "*" {
                            let has_credentials = cors_resp
                                .headers
                                .get("access-control-allow-credentials")
                                .map(|v| v == "true")
                                .unwrap_or(false);

                            if has_credentials || acao == "https://evil.com" {
                                vulnerabilities.push(Vulnerability {
                                    id: format!("nextjs_cors_misconfig_{}", Self::generate_id()),
                                    vuln_type: "Next.js API - CORS Misconfiguration".to_string(),
                                    severity: if has_credentials { Severity::High } else { Severity::Medium },
                                    confidence: Confidence::High,
                                    category: "Misconfiguration".to_string(),
                                    url: api_url.clone(),
                                    parameter: Some("CORS".to_string()),
                                    payload: "Origin: https://evil.com".to_string(),
                                    description: format!(
                                        "API route '{}' has permissive CORS configuration allowing requests from any origin{}.",
                                        route,
                                        if has_credentials { " WITH credentials" } else { "" }
                                    ),
                                    evidence: Some(format!(
                                        "Access-Control-Allow-Origin: {}\n\
                                        Access-Control-Allow-Credentials: {}",
                                        acao, has_credentials
                                    )),
                                    cwe: "CWE-942".to_string(),
                                    cvss: if has_credentials { 8.1 } else { 5.3 },
                                    verified: true,
                                    false_positive: false,
                                    remediation: "Configure CORS properly in next.config.js or API route:\n\
                                                  - Use specific allowed origins\n\
                                                  - Don't use wildcard with credentials\n\
                                                  - Validate Origin header server-side".to_string(),
                                    discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                                });
                            }
                        }
                    }
                }
            }

            if config.scan_mode.as_str() == "fast" && !vulnerabilities.is_empty() {
                break;
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Check for environment variable exposure
    async fn check_env_exposure(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        // Fetch page and check for exposed env variables
        tests_run += 1;
        if let Ok(resp) = self.http_client.get(url).await {
            // Look for server-side env variables exposed to client
            // These should only be NEXT_PUBLIC_* but sometimes devs leak others
            let server_env_patterns = [
                (
                    r#"(?i)DATABASE_URL\s*[=:]\s*["'][^"']+["']"#,
                    "DATABASE_URL",
                ),
                (
                    r#"(?i)(?:SECRET|PRIVATE)[_-]?KEY\s*[=:]\s*["'][^"']+["']"#,
                    "SECRET_KEY",
                ),
                (
                    r#"(?i)JWT[_-]?SECRET\s*[=:]\s*["'][^"']+["']"#,
                    "JWT_SECRET",
                ),
                (
                    r#"(?i)API[_-]?(?:KEY|SECRET)\s*[=:]\s*["'][^"']+["']"#,
                    "API_KEY",
                ),
                (
                    r#"(?i)AWS[_-]?(?:ACCESS|SECRET)[^=]*[=:]\s*["'][^"']+["']"#,
                    "AWS_CREDENTIALS",
                ),
                (
                    r#"(?i)STRIPE[_-]?(?:SECRET|SK_)[^=]*[=:]\s*["'][^"']+["']"#,
                    "STRIPE_SECRET",
                ),
                (
                    r#"(?i)SENDGRID[_-]?(?:API|KEY)[^=]*[=:]\s*["'][^"']+["']"#,
                    "SENDGRID_KEY",
                ),
                (r#"(?i)MONGODB_URI\s*[=:]\s*["'][^"']+["']"#, "MONGODB_URI"),
                (r#"(?i)REDIS_URL\s*[=:]\s*["'][^"']+["']"#, "REDIS_URL"),
                (
                    r#"(?i)NEXTAUTH_SECRET\s*[=:]\s*["'][^"']+["']"#,
                    "NEXTAUTH_SECRET",
                ),
            ];

            let mut exposed_vars = Vec::new();
            for (pattern, name) in &server_env_patterns {
                tests_run += 1;
                if let Ok(re) = Regex::new(pattern) {
                    if re.is_match(&resp.body) {
                        exposed_vars.push(*name);
                    }
                }
            }

            if !exposed_vars.is_empty() {
                vulnerabilities.push(Vulnerability {
                    id: format!("nextjs_env_exposure_{}", Self::generate_id()),
                    vuln_type: "Next.js Server Environment Variables Exposed".to_string(),
                    severity: Severity::Critical,
                    confidence: Confidence::High,
                    category: "Information Disclosure".to_string(),
                    url: url.to_string(),
                    parameter: Some("Environment Variables".to_string()),
                    payload: "Client-side JavaScript".to_string(),
                    description: format!(
                        "Server-side environment variables are exposed in client-side JavaScript. \
                        The following sensitive variables were found: {}. \
                        Only NEXT_PUBLIC_* variables should be accessible in the browser.",
                        exposed_vars.join(", ")
                    ),
                    evidence: Some(format!(
                        "Exposed variables: {}\n\
                        Found in: Client-side JavaScript bundle\n\
                        Impact: Attackers can extract credentials and secrets",
                        exposed_vars.join(", ")
                    )),
                    cwe: "CWE-200".to_string(),
                    cvss: 9.1,
                    verified: true,
                    false_positive: false,
                    remediation: "1. Never expose server-side env vars to client\n\
                                  2. Use NEXT_PUBLIC_ prefix ONLY for truly public values\n\
                                  3. Audit .env files and next.config.js for exposure\n\
                                  4. Rotate any exposed credentials immediately\n\
                                  5. Use server-side API routes to access sensitive data"
                        .to_string(),
                    discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                });
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Check for image optimization SSRF
    async fn check_image_ssrf(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let base = url.trim_end_matches('/');

        // Test SSRF payloads via _next/image
        let ssrf_payloads = [
            "http://169.254.169.254/latest/meta-data/", // AWS metadata
            "http://metadata.google.internal/",         // GCP metadata
            "http://169.254.169.254/metadata/v1/",      // Azure/DO
            "http://127.0.0.1:22",                      // Local SSH
            "http://localhost:3000/api/internal",       // Local API
            "http://[::1]",                             // IPv6 localhost
            "http://0.0.0.0/",                          // Null route
        ];

        for payload in &ssrf_payloads {
            tests_run += 1;
            let encoded_url = urlencoding::encode(payload);
            let image_url = format!("{}/_next/image?url={}&w=64&q=75", base, encoded_url);

            if let Ok(resp) = self.http_client.get(&image_url).await {
                // Check for successful SSRF indicators
                let is_ssrf = resp.status_code == 200
                    && (
                        resp.body.contains("ami-") ||          // AWS metadata
                    resp.body.contains("instance-id") ||
                    resp.body.contains("meta-data") ||
                    resp.body.contains("computeMetadata") ||  // GCP
                    resp.body.contains("SSH-")
                        // SSH banner
                    );

                if is_ssrf {
                    vulnerabilities.push(Vulnerability {
                        id: format!("nextjs_image_ssrf_{}", Self::generate_id()),
                        vuln_type: "Next.js Image Optimization SSRF".to_string(),
                        severity: Severity::Critical,
                        confidence: Confidence::High,
                        category: "SSRF".to_string(),
                        url: image_url.clone(),
                        parameter: Some("url".to_string()),
                        payload: payload.to_string(),
                        description: format!(
                            "The Next.js image optimization endpoint is vulnerable to SSRF. \
                            Internal resources can be accessed via /_next/image?url=. \
                            Tested payload: {}",
                            payload
                        ),
                        evidence: Some(format!(
                            "Request: GET {}\n\
                            Status: {}\n\
                            Response contains internal data indicators",
                            image_url, resp.status_code
                        )),
                        cwe: "CWE-918".to_string(),
                        cvss: 9.1,
                        verified: true,
                        false_positive: false,
                        remediation: "1. Upgrade Next.js to latest version\n\
                                      2. Configure images.remotePatterns in next.config.js\n\
                                      3. Use allowlist for image domains\n\
                                      4. Disable image optimization if not needed\n\
                                      5. Block internal IP ranges at network level"
                            .to_string(),
                        discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                    });
                    break;
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Check for draft/preview mode exposure
    async fn check_draft_mode(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let base = url.trim_end_matches('/');

        // Check draft mode API endpoints
        let draft_endpoints = [
            "/api/draft",
            "/api/preview",
            "/api/draft/enable",
            "/api/preview/enable",
            "/api/draft?secret=",
            "/api/preview?secret=",
        ];

        for endpoint in &draft_endpoints {
            tests_run += 1;
            let draft_url = format!("{}{}", base, endpoint);

            if let Ok(resp) = self.http_client.get(&draft_url).await {
                // Check if draft mode is accessible without proper secret
                if resp.status_code == 200 || resp.status_code == 307 {
                    // Check for draft mode cookies being set
                    let has_draft_cookie = resp
                        .headers
                        .get("set-cookie")
                        .map(|c| {
                            c.contains("__prerender_bypass") || c.contains("__next_preview_data")
                        })
                        .unwrap_or(false);

                    if has_draft_cookie {
                        vulnerabilities.push(Vulnerability {
                            id: format!("nextjs_draft_mode_{}", Self::generate_id()),
                            vuln_type: "Next.js Draft Mode Accessible Without Secret".to_string(),
                            severity: Severity::Medium,
                            confidence: Confidence::High,
                            category: "Misconfiguration".to_string(),
                            url: draft_url.clone(),
                            parameter: Some("draft mode".to_string()),
                            payload: endpoint.to_string(),
                            description: "Next.js draft/preview mode can be enabled without proper authentication. \
                                          This allows attackers to bypass caching and potentially access unpublished content.".to_string(),
                            evidence: Some(format!(
                                "Endpoint: {}\n\
                                Draft cookies set: Yes\n\
                                Status: {}",
                                draft_url, resp.status_code
                            )),
                            cwe: "CWE-287".to_string(),
                            cvss: 5.3,
                            verified: true,
                            false_positive: false,
                            remediation: "1. Require secret token for draft mode activation\n\
                                          2. Validate secret in API route before enabling\n\
                                          3. Use environment variable for draft secret\n\
                                          4. Add rate limiting to draft endpoints".to_string(),
                            discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                        });
                        break;
                    }
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Check for ISR revalidation token exposure
    async fn check_isr_revalidation(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let base = url.trim_end_matches('/');

        // Test revalidation endpoints
        let revalidate_endpoints = [
            "/api/revalidate",
            "/api/revalidate-path",
            "/api/cache/revalidate",
            "/api/isr/revalidate",
        ];

        for endpoint in &revalidate_endpoints {
            tests_run += 1;
            let reval_url = format!("{}{}", base, endpoint);

            // Try without token
            if let Ok(resp) = self.http_client.get(&reval_url).await {
                if resp.status_code == 200 && resp.body.contains("revalidated") {
                    vulnerabilities.push(Vulnerability {
                        id: format!("nextjs_isr_exposure_{}", Self::generate_id()),
                        vuln_type: "Next.js ISR Revalidation Without Authentication".to_string(),
                        severity: Severity::Medium,
                        confidence: Confidence::High,
                        category: "Misconfiguration".to_string(),
                        url: reval_url.clone(),
                        parameter: Some("revalidation".to_string()),
                        payload: endpoint.to_string(),
                        description: "ISR revalidation endpoint is accessible without authentication. \
                                      Attackers can force cache invalidation, causing DoS or displaying stale content.".to_string(),
                        evidence: Some(format!(
                            "Endpoint: {}\n\
                            Status: 200 OK\n\
                            Response indicates revalidation succeeded",
                            reval_url
                        )),
                        cwe: "CWE-287".to_string(),
                        cvss: 5.3,
                        verified: true,
                        false_positive: false,
                        remediation: "1. Add secret token validation to revalidation endpoint\n\
                                      2. Use webhook signature verification if triggered by CMS\n\
                                      3. Implement rate limiting\n\
                                      4. Use on-demand revalidation with proper auth".to_string(),
                        discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                    });
                    break;
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Check for source map exposure
    async fn check_source_maps(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        // Get main page to find JS files
        let resp = match self.http_client.get(url).await {
            Ok(r) => r,
            Err(_) => return Ok((vec![], tests_run)),
        };

        // Extract JS file URLs
        let js_pattern = Regex::new(r#"/_next/static/[^"']+\.js"#)?;
        let js_files: Vec<String> = js_pattern
            .find_iter(&resp.body)
            .map(|m| format!("{}{}.map", url.trim_end_matches('/'), m.as_str()))
            .collect();

        for js_map in js_files.iter().take(5) {
            tests_run += 1;
            if let Ok(map_resp) = self.http_client.get(js_map).await {
                if map_resp.status_code == 200 && map_resp.body.contains("mappings") {
                    vulnerabilities.push(Vulnerability {
                        id: format!("nextjs_sourcemap_{}", Self::generate_id()),
                        vuln_type: "Next.js Source Map Exposure".to_string(),
                        severity: Severity::Medium,
                        confidence: Confidence::High,
                        category: "Information Disclosure".to_string(),
                        url: js_map.clone(),
                        parameter: Some("source map".to_string()),
                        payload: "GET *.js.map".to_string(),
                        description: "JavaScript source maps are publicly accessible, exposing original source code. \
                                      This allows attackers to understand application logic and find vulnerabilities.".to_string(),
                        evidence: Some(format!(
                            "Source map URL: {}\n\
                            Status: 200 OK\n\
                            Contains mappings: Yes",
                            js_map
                        )),
                        cwe: "CWE-200".to_string(),
                        cvss: 5.3,
                        verified: true,
                        false_positive: false,
                        remediation: "1. Set productionBrowserSourceMaps: false in next.config.js\n\
                                      2. Remove .map files from production build\n\
                                      3. Use hideSourceMaps: true if using next-compose-plugins".to_string(),
                        discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                    });
                    break;
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Check for Next.js config exposure
    async fn check_config_exposure(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let base = url.trim_end_matches('/');

        // Files that shouldn't be accessible
        let sensitive_files = [
            ("next.config.js", "Next.js configuration"),
            ("next.config.mjs", "Next.js configuration"),
            (".env", "Environment variables"),
            (".env.local", "Local environment variables"),
            (".env.production", "Production environment"),
            ("tsconfig.json", "TypeScript configuration"),
            ("package.json", "Package dependencies"),
            ("package-lock.json", "Dependency lock file"),
            (".next/BUILD_ID", "Build identifier"),
            (".next/build-manifest.json", "Build manifest"),
            (".next/routes-manifest.json", "Routes manifest"),
            (".next/prerender-manifest.json", "Prerender manifest"),
        ];

        for (file, desc) in &sensitive_files {
            tests_run += 1;
            let file_url = format!("{}/{}", base, file);

            if let Ok(resp) = self.http_client.get(&file_url).await {
                if resp.status_code == 200 {
                    let is_config = resp.body.contains("module.exports")
                        || resp.body.contains("export default")
                        || resp.body.starts_with("{")
                        || resp.body.contains("DATABASE_URL")
                        || resp.body.contains("API_KEY");

                    if is_config {
                        vulnerabilities.push(Vulnerability {
                            id: format!("nextjs_config_exposure_{}", Self::generate_id()),
                            vuln_type: format!("Next.js {} Exposed", desc),
                            severity: if file.contains(".env") { Severity::Critical } else { Severity::Medium },
                            confidence: Confidence::High,
                            category: "Information Disclosure".to_string(),
                            url: file_url.clone(),
                            parameter: Some(file.to_string()),
                            payload: format!("GET /{}", file),
                            description: format!(
                                "The {} file is publicly accessible. This may expose sensitive configuration, \
                                API keys, or internal paths.", desc
                            ),
                            evidence: Some(format!(
                                "File: {}\n\
                                Status: 200 OK\n\
                                Preview: {}...",
                                file, &resp.body[..resp.body.len().min(200)]
                            )),
                            cwe: "CWE-200".to_string(),
                            cvss: if file.contains(".env") { 9.1 } else { 5.3 },
                            verified: true,
                            false_positive: false,
                            remediation: "1. Configure web server to block access to config files\n\
                                          2. Move sensitive files outside web root\n\
                                          3. Add to .gitignore and deploy excludes\n\
                                          4. Use next.config.js headers to block access".to_string(),
                            discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                        });
                    }
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Check for Server Actions vulnerabilities
    async fn check_server_actions(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let base = url.trim_end_matches('/');

        // Test Server Actions endpoint with various manipulation techniques
        tests_run += 1;

        // CVE-2024-34351: Host header SSRF in Server Actions
        let mut headers = HashMap::new();
        headers.insert("Content-Type".to_string(), "text/x-component".to_string());
        headers.insert("Next-Action".to_string(), "test".to_string());
        headers.insert("Host".to_string(), "evil.com".to_string());

        let headers_vec: Vec<(String, String)> = headers
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        if let Ok(resp) = self
            .http_client
            .post_with_headers(base, "[]", headers_vec)
            .await
        {
            // Check if the response indicates SSRF potential
            if resp.body.contains("evil.com")
                || resp
                    .headers
                    .get("location")
                    .map(|l| l.contains("evil.com"))
                    .unwrap_or(false)
            {
                vulnerabilities.push(Vulnerability {
                    id: format!("nextjs_server_action_ssrf_{}", Self::generate_id()),
                    vuln_type: "Next.js Server Actions SSRF (CVE-2024-34351)".to_string(),
                    severity: Severity::High,
                    confidence: Confidence::Medium,
                    category: "SSRF".to_string(),
                    url: base.to_string(),
                    parameter: Some("Host header".to_string()),
                    payload: "Host: evil.com".to_string(),
                    description: "Server Actions endpoint is vulnerable to SSRF via Host header manipulation. \
                                  Attackers can make the server send requests to arbitrary hosts.".to_string(),
                    evidence: Some(format!(
                        "Request with Host: evil.com\n\
                        Response references evil.com"
                    )),
                    cwe: "CWE-918".to_string(),
                    cvss: 7.5,
                    verified: true,
                    false_positive: false,
                    remediation: "1. Upgrade to Next.js 14.1.1 or later\n\
                                  2. Validate Host header in middleware\n\
                                  3. Use allowlist for redirect targets".to_string(),
                    discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                });
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Check for version-specific CVEs
    async fn check_version_cves(
        &self,
        url: &str,
        version: &str,
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        // Parse version
        let version_parts: Vec<u32> = version.split('.').filter_map(|p| p.parse().ok()).collect();

        if version_parts.len() < 2 {
            return Ok((vec![], tests_run));
        }

        let major = version_parts[0];
        let minor = version_parts[1];
        let patch = version_parts.get(2).copied().unwrap_or(0);

        for cve in &self.known_cves {
            tests_run += 1;

            // Simple version check - could be more sophisticated
            let is_affected = match cve.cve_id.as_str() {
                "CVE-2025-29927" => {
                    (major == 14 && minor < 2)
                        || (major == 14 && minor == 2 && patch < 25)
                        || (major == 15 && minor < 2)
                        || (major == 15 && minor == 2 && patch < 3)
                }
                "CVE-2024-39693" => {
                    major < 14
                        || (major == 14 && minor < 2)
                        || (major == 14 && minor == 2 && patch < 4)
                }
                "CVE-2024-34351" => (major == 13 && minor >= 4) || (major == 14 && minor < 1),
                "CVE-2024-34350" => {
                    major < 14
                        || (major == 14 && minor < 1)
                        || (major == 14 && minor == 1 && patch < 1)
                }
                "CVE-2024-46982" => {
                    major < 14
                        || (major == 14 && minor < 2)
                        || (major == 14 && minor == 2 && patch < 10)
                }
                "CVE-2024-47831" => {
                    major < 14
                        || (major == 14 && minor < 2)
                        || (major == 14 && minor == 2 && patch < 7)
                }
                "CVE-2023-46298" => {
                    major < 13
                        || (major == 13 && minor < 4)
                        || (major == 13 && minor == 4 && patch < 20)
                }
                "CVE-2024-51479" => {
                    (major == 14 && minor < 2)
                        || (major == 14 && minor == 2 && patch < 18)
                        || (major == 15 && minor < 0)
                        || (major == 15 && minor == 0 && patch < 4)
                }
                "CVE-2024-56332" => {
                    (major == 14 && minor < 2)
                        || (major == 14 && minor == 2 && patch < 21)
                        || (major == 15 && minor < 1)
                        || (major == 15 && minor == 1 && patch < 2)
                }
                _ => false,
            };

            if is_affected {
                vulnerabilities.push(Vulnerability {
                    id: format!("nextjs_cve_{}_{}", cve.cve_id, Self::generate_id()),
                    vuln_type: format!("Next.js {} - {}", cve.cve_id,
                        match cve.check_type {
                            CVECheckType::MiddlewareBypass => "Middleware Bypass",
                            CVECheckType::ServerAction => "Server Action Vulnerability",
                            CVECheckType::ImageOptimization => "Image Optimization SSRF",
                            CVECheckType::DataExposure => "Data Exposure",
                            CVECheckType::PathTraversal => "Path Traversal",
                            CVECheckType::SSRF => "SSRF",
                            CVECheckType::DoS => "Denial of Service",
                        }
                    ),
                    severity: cve.severity.clone(),
                    confidence: Confidence::High,
                    category: "Known Vulnerability".to_string(),
                    url: url.to_string(),
                    parameter: Some(format!("Next.js {}", version)),
                    payload: format!("{}: {}", cve.cve_id, cve.affected_versions),
                    description: format!(
                        "{}\n\nDetected version: {}\nAffected versions: {}",
                        cve.description, version, cve.affected_versions
                    ),
                    evidence: Some(format!(
                        "CVE: {}\n\
                        Detected Version: {}\n\
                        Affected: {}\n\
                        Severity: {:?}",
                        cve.cve_id, version, cve.affected_versions, cve.severity
                    )),
                    cwe: match cve.check_type {
                        CVECheckType::MiddlewareBypass => "CWE-287",
                        CVECheckType::SSRF | CVECheckType::ImageOptimization => "CWE-918",
                        CVECheckType::PathTraversal => "CWE-22",
                        CVECheckType::DataExposure => "CWE-200",
                        _ => "CWE-1035",
                    }.to_string(),
                    cvss: match cve.severity {
                        Severity::Critical => 9.8,
                        Severity::High => 7.5,
                        Severity::Medium => 5.3,
                        _ => 3.0,
                    },
                    verified: false, // Version-based detection
                    false_positive: false,
                    remediation: format!(
                        "Upgrade Next.js to a patched version. Check: https://nvd.nist.gov/vuln/detail/{}",
                        cve.cve_id
                    ),
                    discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                });
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Check discovered routes for middleware bypass vulnerabilities
    async fn check_discovered_routes_bypass(
        &self,
        url: &str,
        routes: &[String],
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let base = url.trim_end_matches('/');

        // Only test routes that look like they might be protected
        let protected_keywords = [
            "admin",
            "dashboard",
            "settings",
            "account",
            "profile",
            "user",
            "private",
            "internal",
            "protected",
            "manage",
            "billing",
        ];

        for route in routes.iter().take(20) {
            // Check if route contains protected keywords
            let route_lower = route.to_lowercase();
            let might_be_protected = protected_keywords.iter().any(|k| route_lower.contains(k));

            if !might_be_protected {
                continue;
            }

            // Expand dynamic route segments with test values
            let test_routes = self.expand_dynamic_route(route);

            for test_route in &test_routes {
                tests_run += 1;
                let test_url = format!("{}{}", base, test_route);

                // Check normal response
                let normal_resp = match self.http_client.get(&test_url).await {
                    Ok(r) => r,
                    Err(_) => continue,
                };

                // Skip if not protected (we want 401/403 responses)
                if normal_resp.status_code != 401 && normal_resp.status_code != 403 {
                    continue;
                }

                debug!(
                    "[Next.js] Found protected route: {} ({})",
                    test_route, normal_resp.status_code
                );

                // Try bypass with x-middleware-subrequest header
                tests_run += 1;
                let headers = vec![(
                    "x-middleware-subrequest".to_string(),
                    "middleware:middleware:middleware:middleware:middleware".to_string(),
                )];

                if let Ok(bypass_resp) = self.http_client.get_with_headers(&test_url, headers).await
                {
                    if bypass_resp.status_code == 200
                        || (bypass_resp.status_code != 401
                            && bypass_resp.status_code != 403
                            && bypass_resp.status_code != 404)
                    {
                        info!(
                            "[Next.js] CRITICAL: Middleware bypass on discovered route: {}",
                            test_route
                        );
                        vulnerabilities.push(Vulnerability {
                            id: format!("nextjs_discovered_route_bypass_{}", Self::generate_id()),
                            vuln_type: "Next.js Middleware Bypass - Discovered Route".to_string(),
                            severity: Severity::Critical,
                            confidence: Confidence::High,
                            category: "Authentication".to_string(),
                            url: test_url.clone(),
                            parameter: Some("x-middleware-subrequest".to_string()),
                            payload: "x-middleware-subrequest: middleware:middleware:middleware:middleware:middleware".to_string(),
                            description: format!(
                                "Next.js middleware bypass discovered on route '{}' extracted from JavaScript bundles. \
                                The route returns {} normally but {} with bypass header. \
                                This is a critical authentication bypass vulnerability (CVE-2025-29927).",
                                test_route, normal_resp.status_code, bypass_resp.status_code
                            ),
                            evidence: Some(format!(
                                "Discovered route: {}\n\
                                Normal response: {}\n\
                                Bypass response: {}\n\
                                Response length: {} bytes",
                                test_route, normal_resp.status_code, bypass_resp.status_code, bypass_resp.body.len()
                            )),
                            cwe: "CWE-287".to_string(),
                            cvss: 9.8,
                            verified: true,
                            false_positive: false,
                            remediation: "1. Upgrade Next.js to latest version (14.2.25+ or 15.2.3+)\n\
                                          2. Implement server-side authentication that doesn't rely on middleware alone\n\
                                          3. Add x-middleware-subrequest to blocked headers in production".to_string(),
                            discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                        });
                    }
                }
            }
        }

        if !vulnerabilities.is_empty() {
            info!(
                "[Next.js] Found {} middleware bypass vulnerabilities on discovered routes",
                vulnerabilities.len()
            );
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Expand dynamic route segments [param] with test values
    fn expand_dynamic_route(&self, route: &str) -> Vec<String> {
        let mut routes = Vec::new();

        // Check if route has dynamic segments
        if !route.contains('[') {
            routes.push(route.to_string());
            return routes;
        }

        // Replace common dynamic segments with test values
        let test_values = [
            ("[lng]", vec!["en", "de", "fr"]),
            ("[id]", vec!["1", "test"]),
            ("[slug]", vec!["test-page"]),
            ("[...slug]", vec!["test/page"]),
            ("[userId]", vec!["1"]),
            ("[orgId]", vec!["1"]),
        ];

        let mut current_routes = vec![route.to_string()];

        for (pattern, replacements) in test_values {
            let mut new_routes = Vec::new();
            for r in &current_routes {
                if r.contains(pattern) {
                    for replacement in &replacements {
                        new_routes.push(r.replace(pattern, replacement));
                    }
                } else {
                    new_routes.push(r.clone());
                }
            }
            if !new_routes.is_empty() {
                current_routes = new_routes;
            }
        }

        // Also handle generic [param] patterns
        let generic_param_re = Regex::new(r"\[[\w]+\]").ok();
        if let Some(re) = generic_param_re {
            for r in &current_routes {
                if re.is_match(r) {
                    // Replace any remaining [param] with "1"
                    routes.push(re.replace_all(r, "1").to_string());
                } else {
                    routes.push(r.clone());
                }
            }
        } else {
            routes = current_routes;
        }

        routes.sort();
        routes.dedup();
        routes
    }

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

    /// Discover Next.js App Router routes from JavaScript bundles
    /// Returns a list of discovered route paths
    pub async fn discover_routes(&self, url: &str) -> Result<Vec<String>> {
        let mut routes = std::collections::HashSet::new();
        let base_url = url.trim_end_matches('/');

        info!("[Next.js] Discovering App Router routes from JavaScript bundles");

        // Fetch the main page to find _next script URLs
        let main_response = match self.http_client.get(url).await {
            Ok(r) => r,
            Err(e) => {
                debug!("[Next.js] Failed to fetch main page: {}", e);
                return Ok(vec![]);
            }
        };

        // Extract all _next script URLs
        let script_urls = self.extract_next_scripts(&main_response.body, base_url);
        info!(
            "[Next.js] Found {} _next scripts to analyze",
            script_urls.len()
        );

        // Analyze each script for route patterns
        for script_url in script_urls.iter().take(30) {
            if let Ok(script_response) = self.http_client.get(script_url).await {
                // Ensure we got JavaScript, not HTML (SPA fallback)
                if script_response.body.contains("<!DOCTYPE")
                    || script_response.body.contains("<html")
                {
                    debug!("[Next.js] Skipping {} - got HTML instead of JS", script_url);
                    continue;
                }

                let script_routes = self.extract_routes_from_script(&script_response.body);
                for route in script_routes {
                    routes.insert(route);
                }
            }
        }

        // Also check for routes in __NEXT_DATA__
        if let Some(next_data_routes) = self.extract_routes_from_next_data(&main_response.body) {
            for route in next_data_routes {
                routes.insert(route);
            }
        }

        // Filter and clean routes
        let mut final_routes: Vec<String> = routes
            .into_iter()
            .filter(|r| self.is_valid_route(r))
            .collect();

        final_routes.sort();
        final_routes.dedup();

        info!("[Next.js] Discovered {} unique routes", final_routes.len());
        for route in &final_routes {
            debug!("[Next.js] Route: {}", route);
        }

        Ok(final_routes)
    }

    /// Extract _next script URLs from HTML
    fn extract_next_scripts(&self, html: &str, base_url: &str) -> Vec<String> {
        let mut scripts = Vec::new();

        // Pattern for script src containing _next
        let script_re = Regex::new(r#"<script[^>]*src=["']([^"']*_next[^"']*)["']"#).ok();
        if let Some(re) = script_re {
            for caps in re.captures_iter(html) {
                if let Some(src) = caps.get(1) {
                    let script_url = self.resolve_url(base_url, src.as_str());
                    scripts.push(script_url);
                }
            }
        }

        // Also check for modulepreload links which often have chunk URLs
        let link_re =
            Regex::new(r#"<link[^>]*href=["']([^"']*_next/static/chunks[^"']*)["']"#).ok();
        if let Some(re) = link_re {
            for caps in re.captures_iter(html) {
                if let Some(href) = caps.get(1) {
                    let script_url = self.resolve_url(base_url, href.as_str());
                    if !scripts.contains(&script_url) {
                        scripts.push(script_url);
                    }
                }
            }
        }

        scripts
    }

    /// Extract routes from JavaScript bundle content
    fn extract_routes_from_script(&self, js_content: &str) -> Vec<String> {
        let mut routes = Vec::new();

        // Pattern 1: App Router file patterns (/app/[path]/(page|layout|loading|error))
        let app_router_re =
            Regex::new(r#"/app/([\w\-\[\]%/]+?)/(layout|page|loading|error|template|not-found)"#)
                .ok();
        if let Some(re) = app_router_re {
            for caps in re.captures_iter(js_content) {
                if let Some(path) = caps.get(1) {
                    let route = self.decode_and_format_route(path.as_str());
                    routes.push(route);
                }
            }
        }

        // Pattern 2: pathname strings (common in Next.js routing)
        let pathname_patterns = [
            r#"pathname[:\s=]+["'`](/[\w\-/\[\]]+)["'`]"#,
            r#"href[:\s=]+["'`](/[\w\-/\[\]]+)["'`]"#,
            r#"route[:\s=]+["'`](/[\w\-/\[\]]+)["'`]"#,
            r#"path[:\s=]+["'`](/[\w\-/\[\]]+)["'`]"#,
            r#"redirect[:\s=]+["'`](/[\w\-/\[\]]+)["'`]"#,
            r#"navigate[:\s=]+["'`](/[\w\-/\[\]]+)["'`]"#,
            r#"push\(["'`](/[\w\-/\[\]]+)["'`]"#,
            r#"replace\(["'`](/[\w\-/\[\]]+)["'`]"#,
        ];

        for pattern in &pathname_patterns {
            if let Ok(re) = Regex::new(pattern) {
                for caps in re.captures_iter(js_content) {
                    if let Some(path) = caps.get(1) {
                        let route = path.as_str().to_string();
                        if !route.contains("_next") && !route.contains("http") && route.len() > 1 {
                            routes.push(route);
                        }
                    }
                }
            }
        }

        // Pattern 3: Common path strings that look like routes
        let path_string_re = Regex::new(r#"["'`](/(?:dashboard|admin|api|auth|settings|profile|users|account|billing|projects|workspace|analytics|reports|help|docs)[\w\-/\[\]]*)["'`]"#).ok();
        if let Some(re) = path_string_re {
            for caps in re.captures_iter(js_content) {
                if let Some(path) = caps.get(1) {
                    routes.push(path.as_str().to_string());
                }
            }
        }

        routes
    }

    /// Extract routes from __NEXT_DATA__ script tag
    fn extract_routes_from_next_data(&self, html: &str) -> Option<Vec<String>> {
        let mut routes = Vec::new();

        // Find __NEXT_DATA__ content
        let next_data_re =
            Regex::new(r#"<script id="__NEXT_DATA__"[^>]*>([^<]+)</script>"#).ok()?;
        let caps = next_data_re.captures(html)?;
        let json_content = caps.get(1)?.as_str();

        // Extract paths from the JSON
        let path_patterns = [
            r#""page"\s*:\s*"(/[^"]+)""#,
            r#""asPath"\s*:\s*"(/[^"]+)""#,
            r#""pathname"\s*:\s*"(/[^"]+)""#,
            r#""route"\s*:\s*"(/[^"]+)""#,
        ];

        for pattern in &path_patterns {
            if let Ok(re) = Regex::new(pattern) {
                for caps in re.captures_iter(json_content) {
                    if let Some(path) = caps.get(1) {
                        let route = path.as_str().to_string();
                        if !route.contains("_next")
                            && !route.contains("_error")
                            && !route.contains("_app")
                        {
                            routes.push(route);
                        }
                    }
                }
            }
        }

        // Also extract any dynamicIds or sortedPages arrays
        let sorted_pages_re = Regex::new(r#""sortedPages"\s*:\s*\[([^\]]+)\]"#).ok();
        if let Some(re) = sorted_pages_re {
            if let Some(caps) = re.captures(json_content) {
                if let Some(pages_array) = caps.get(1) {
                    let page_re = Regex::new(r#""(/[^"]+)""#).ok();
                    if let Some(page_pattern) = page_re {
                        for page_caps in page_pattern.captures_iter(pages_array.as_str()) {
                            if let Some(page) = page_caps.get(1) {
                                let route = page.as_str().to_string();
                                if !route.contains("_next")
                                    && !route.contains("_error")
                                    && !route.contains("_app")
                                {
                                    routes.push(route);
                                }
                            }
                        }
                    }
                }
            }
        }

        if routes.is_empty() {
            None
        } else {
            Some(routes)
        }
    }

    /// Decode URL-encoded route segments and format as a clean route
    fn decode_and_format_route(&self, path: &str) -> String {
        let decoded = path
            .replace("%5B", "[")
            .replace("%5D", "]")
            .replace("%5Blng%5D", "[lng]")
            .replace("(", "") // Remove route groups
            .replace(")", "");

        // Clean up the path
        let cleaned: String = decoded
            .split('/')
            .filter(|segment| !segment.is_empty() && !segment.starts_with('_'))
            .collect::<Vec<_>>()
            .join("/");

        format!("/{}", cleaned)
    }

    /// Check if a route string is valid (not a file, asset, or invalid pattern)
    fn is_valid_route(&self, route: &str) -> bool {
        // Must start with /
        if !route.starts_with('/') {
            return false;
        }

        // Skip common file extensions and assets
        let invalid_suffixes = [
            ".js", ".css", ".png", ".jpg", ".gif", ".svg", ".woff", ".ttf", ".ico", ".map", ".json",
        ];
        for suffix in &invalid_suffixes {
            if route.ends_with(suffix) {
                return false;
            }
        }

        // Skip internal Next.js paths
        let invalid_prefixes = ["/_next", "/_error", "/_app", "/_document"];
        for prefix in &invalid_prefixes {
            if route.starts_with(prefix) {
                return false;
            }
        }

        // Skip very short or likely invalid routes
        if route == "/" || route.len() < 2 {
            return true; // Root is valid
        }

        // Skip routes that look like hashes or random strings
        if route.len() > 50 || route.contains("chunk-") {
            return false;
        }

        true
    }

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

        if path.starts_with("//") {
            return format!("https:{}", path);
        }

        if path.starts_with('/') {
            // Extract origin from base_url
            if let Ok(parsed) = url::Url::parse(base_url) {
                return format!("{}{}", parsed.origin().ascii_serialization(), path);
            }
        }

        format!(
            "{}/{}",
            base_url.trim_end_matches('/'),
            path.trim_start_matches('/')
        )
    }
}