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
// 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};

/// Client-side route extracted from JavaScript
#[derive(Debug, Clone)]
struct ClientRoute {
    path: String,
    requires_auth: bool,
    required_roles: Vec<String>,
    component: Option<String>,
    meta: HashMap<String, String>,
    framework: RouteFramework,
}

#[derive(Debug, Clone, PartialEq)]
enum RouteFramework {
    Vue,
    React,
    Angular,
    NextJS,
    Unknown,
}

pub struct ClientRouteAuthBypassScanner {
    http_client: Arc<HttpClient>,
}

impl ClientRouteAuthBypassScanner {
    pub fn new(http_client: Arc<HttpClient>) -> Self {
        Self { http_client }
    }

    /// Scan for client-side route authorization bypass vulnerabilities
    pub async fn scan(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        // PREMIUM FEATURE: Client Route Auth Bypass requires Professional license
        if !crate::license::is_feature_available("client_route_auth_bypass") {
            debug!("[ClientRouteAuth] Feature requires Professional license or higher");
            return Ok((vulnerabilities, tests_run));
        }

        info!(
            "[ClientRouteAuth] Scanning for client-side route auth bypass: {}",
            url
        );

        // Step 1: Fetch main page to discover JavaScript bundles
        tests_run += 1;
        let response = match self.http_client.get(url).await {
            Ok(r) => r,
            Err(e) => {
                debug!("[ClientRouteAuth] Failed to fetch main page: {}", e);
                return Ok((vulnerabilities, tests_run));
            }
        };

        // Step 2: Extract JavaScript bundle URLs
        let js_urls = self.extract_js_bundle_urls(url, &response.body);

        if js_urls.is_empty() {
            info!("[ClientRouteAuth] No JavaScript bundles found - skipping");
            return Ok((vulnerabilities, tests_run));
        }

        info!(
            "[ClientRouteAuth] Found {} JavaScript bundles to analyze",
            js_urls.len()
        );

        // Step 3: Fetch and analyze each JavaScript bundle
        let mut all_routes = Vec::new();

        for js_url in js_urls.iter().take(10) {
            // Limit to first 10 bundles for performance
            tests_run += 1;

            if let Ok(js_response) = self.http_client.get(js_url).await {
                let routes = self.extract_routes_from_js(&js_response.body);

                if !routes.is_empty() {
                    info!(
                        "[ClientRouteAuth] Extracted {} routes from {}",
                        routes.len(),
                        js_url
                    );
                    all_routes.extend(routes);
                }
            }
        }

        // Deduplicate routes by path
        let unique_routes = self.deduplicate_routes(all_routes);

        if unique_routes.is_empty() {
            info!("[ClientRouteAuth] No client-side routes discovered - skipping tests");
            return Ok((vulnerabilities, tests_run));
        }

        info!(
            "[ClientRouteAuth] Discovered {} unique client routes",
            unique_routes.len()
        );

        // Log discovered routes for debugging
        for route in &unique_routes {
            debug!(
                "[ClientRouteAuth] Route: {} (auth: {}, roles: {:?})",
                route.path, route.requires_auth, route.required_roles
            );
        }

        // Step 4: Test routes for authorization bypass
        for route in &unique_routes {
            // Test 1: Authentication bypass (if route requires auth)
            if route.requires_auth {
                tests_run += 1;
                if let Some(vuln) = self.test_auth_bypass(url, route).await {
                    vulnerabilities.push(vuln);
                }
            }

            // Test 2: Role-based access control (RBAC) bypass
            if !route.required_roles.is_empty() {
                tests_run += 1;
                if let Some(vuln) = self.test_rbac_bypass(url, route).await {
                    vulnerabilities.push(vuln);
                }
            }

            // Test 3: IDOR testing for parameterized routes
            if route.path.contains(":id") || route.path.contains("/:") {
                tests_run += 1;
                if let Some(vuln) = self.test_idor(url, route).await {
                    vulnerabilities.push(vuln);
                }
            }
        }

        info!(
            "[SUCCESS] [ClientRouteAuth] Completed {} tests, found {} vulnerabilities",
            tests_run,
            vulnerabilities.len()
        );

        Ok((vulnerabilities, tests_run))
    }

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

        // Pattern 1: <script src="/app.js">
        let script_regex = Regex::new(r#"<script[^>]+src=["']([^"']+\.js[^"']*)["']"#).unwrap();

        for cap in script_regex.captures_iter(html) {
            if let Some(js_path) = cap.get(1) {
                let js_url = self.resolve_url(base_url, js_path.as_str());
                js_urls.push(js_url);
            }
        }

        // Pattern 2: Look for common bundle names in HTML
        let common_bundles = vec![
            "/app.js",
            "/main.js",
            "/bundle.js",
            "/vendor.js",
            "/js/app.js",
            "/js/main.js",
            "/static/js/main.js",
            "/dist/app.js",
            "/dist/main.js",
        ];

        for bundle in common_bundles {
            if html.contains(bundle) {
                js_urls.push(self.resolve_url(base_url, bundle));
            }
        }

        js_urls
    }

    /// Extract client-side routes from JavaScript code
    fn extract_routes_from_js(&self, js_code: &str) -> Vec<ClientRoute> {
        let mut routes = Vec::new();

        // Try each framework's route extraction
        routes.extend(self.extract_vue_routes(js_code));
        routes.extend(self.extract_react_routes(js_code));
        routes.extend(self.extract_angular_routes(js_code));
        routes.extend(self.extract_nextjs_routes(js_code));

        routes
    }

    /// Extract Vue Router routes
    fn extract_vue_routes(&self, js_code: &str) -> Vec<ClientRoute> {
        let mut routes = Vec::new();

        // Pattern 1: {path: "/admin", meta: {requireAuth: true}}
        let auth_regex = Regex::new(
            r#"(?:path|name):\s*["']([^"']+)["'][^}]*meta:\s*\{[^}]*requireAuth:\s*(!0|true)"#,
        )
        .unwrap();

        for cap in auth_regex.captures_iter(js_code) {
            if let Some(path) = cap.get(1) {
                routes.push(ClientRoute {
                    path: path.as_str().to_string(),
                    requires_auth: true,
                    required_roles: Vec::new(),
                    component: None,
                    meta: HashMap::new(),
                    framework: RouteFramework::Vue,
                });
            }
        }

        // Pattern 2: {path: "/admin", meta: {requireAnyRole: ["ADMIN", "MANAGEMENT"]}}
        let role_regex =
            Regex::new(r#"path:\s*["']([^"']+)["'][^}]*requireAnyRole:\s*\[([^\]]+)\]"#).unwrap();

        for cap in role_regex.captures_iter(js_code) {
            if let (Some(path), Some(roles_str)) = (cap.get(1), cap.get(2)) {
                let roles: Vec<String> = roles_str
                    .as_str()
                    .split(',')
                    .map(|r| r.trim().trim_matches(|c| c == '"' || c == '\'').to_string())
                    .filter(|r| !r.is_empty())
                    .collect();

                routes.push(ClientRoute {
                    path: path.as_str().to_string(),
                    requires_auth: true,
                    required_roles: roles,
                    component: None,
                    meta: HashMap::new(),
                    framework: RouteFramework::Vue,
                });
            }
        }

        // Pattern 3: Simple path extraction (fallback)
        let path_regex = Regex::new(r#"path:\s*["']([/][^"']+)["']"#).unwrap();

        for cap in path_regex.captures_iter(js_code) {
            if let Some(path) = cap.get(1) {
                let path_str = path.as_str();

                // Skip if already found with metadata
                if routes.iter().any(|r| r.path == path_str) {
                    continue;
                }

                // Infer auth requirement from path patterns
                let requires_auth = path_str.contains("/admin")
                    || path_str.contains("/user")
                    || path_str.contains("/dashboard")
                    || path_str.contains("/profile")
                    || path_str.contains("/settings");

                if requires_auth {
                    routes.push(ClientRoute {
                        path: path_str.to_string(),
                        requires_auth,
                        required_roles: Vec::new(),
                        component: None,
                        meta: HashMap::new(),
                        framework: RouteFramework::Vue,
                    });
                }
            }
        }

        routes
    }

    /// Extract React Router routes
    fn extract_react_routes(&self, js_code: &str) -> Vec<ClientRoute> {
        let mut routes = Vec::new();

        // Pattern 1: <Route path="/admin" requireAuth />
        let route_regex = Regex::new(
            r#"<(?:Route|PrivateRoute)[^>]*path=["']([^"']+)["'][^>]*(?:requireAuth|private)"#,
        )
        .unwrap();

        for cap in route_regex.captures_iter(js_code) {
            if let Some(path) = cap.get(1) {
                routes.push(ClientRoute {
                    path: path.as_str().to_string(),
                    requires_auth: true,
                    required_roles: Vec::new(),
                    component: None,
                    meta: HashMap::new(),
                    framework: RouteFramework::React,
                });
            }
        }

        // Pattern 2: {path: "/admin", element: <Admin />, protected: true}
        let protected_regex =
            Regex::new(r#"path:\s*["']([^"']+)["'][^}]*(?:protected|requireAuth):\s*(!0|true)"#)
                .unwrap();

        for cap in protected_regex.captures_iter(js_code) {
            if let Some(path) = cap.get(1) {
                routes.push(ClientRoute {
                    path: path.as_str().to_string(),
                    requires_auth: true,
                    required_roles: Vec::new(),
                    component: None,
                    meta: HashMap::new(),
                    framework: RouteFramework::React,
                });
            }
        }

        routes
    }

    /// Extract Angular Router routes
    fn extract_angular_routes(&self, js_code: &str) -> Vec<ClientRoute> {
        let mut routes = Vec::new();

        // Pattern: {path: 'admin', canActivate: [AuthGuard]}
        let guard_regex =
            Regex::new(r#"path:\s*["']([^"']+)["'][^}]*canActivate:\s*\[([^\]]+)\]"#).unwrap();

        for cap in guard_regex.captures_iter(js_code) {
            if let (Some(path), Some(guards)) = (cap.get(1), cap.get(2)) {
                let has_auth_guard =
                    guards.as_str().contains("Auth") || guards.as_str().contains("Guard");

                if has_auth_guard {
                    routes.push(ClientRoute {
                        path: format!("/{}", path.as_str().trim_start_matches('/')),
                        requires_auth: true,
                        required_roles: Vec::new(),
                        component: None,
                        meta: HashMap::new(),
                        framework: RouteFramework::Angular,
                    });
                }
            }
        }

        routes
    }

    /// Extract Next.js routes (from getServerSideProps patterns)
    fn extract_nextjs_routes(&self, js_code: &str) -> Vec<ClientRoute> {
        let routes = Vec::new();

        // Pattern: getServerSideProps with session check
        if js_code.contains("getServerSideProps") && js_code.contains("session") {
            // Next.js App Router routes are file-system based and not directly extractable
            // from bundled JavaScript. The route structure is determined by the file system
            // layout (app/ or pages/ directories), not by JavaScript code analysis.
            // Route detection for Next.js is handled by probing common paths instead.
            debug!("Next.js getServerSideProps detected - routes are file-system based");
        }

        routes
    }

    /// Deduplicate routes by path
    fn deduplicate_routes(&self, routes: Vec<ClientRoute>) -> Vec<ClientRoute> {
        let mut seen = HashSet::new();
        let mut unique = Vec::new();

        for route in routes {
            if seen.insert(route.path.clone()) {
                unique.push(route);
            }
        }

        unique
    }

    /// Test if protected route can be accessed without authentication
    async fn test_auth_bypass(&self, base_url: &str, route: &ClientRoute) -> Option<Vulnerability> {
        let test_path = self.replace_route_params(&route.path, "1");
        let test_url = self.resolve_url(base_url, &test_path);

        debug!("[ClientRouteAuth] Testing auth bypass on: {}", test_url);

        let response = match self.http_client.get(&test_url).await {
            Ok(r) => r,
            Err(_) => return None,
        };

        // Check if we got actual protected content without authentication
        let is_bypass = response.status_code == 200
            && response.status_code != 404  // Route must exist
            && !response.body.to_lowercase().contains("login")
            && !response.body.to_lowercase().contains("sign in")
            && !response.body.to_lowercase().contains("unauthorized")
            && !response.body.to_lowercase().contains("not found")
            && !response.body.to_lowercase().contains("redirect")
            && response.body.len() > 500; // Must have substantial content

        if is_bypass {
            info!("[VULN] Auth bypass found on route: {}", route.path);

            Some(Vulnerability {
                id: format!("crauth_{}", uuid::Uuid::new_v4().simple()),
                vuln_type: "Client Route Authentication Bypass".to_string(),
                severity: Severity::Critical,
                confidence: Confidence::High,
                category: "Access Control".to_string(),
                url: test_url.clone(),
                parameter: Some("route".to_string()),
                payload: route.path.clone(),
                description: format!(
                    "Client-side route '{}' requires authentication but can be accessed without credentials. \
                     The route is declared with requireAuth=true in {} Router but server-side \
                     authorization is not enforced.",
                    route.path,
                    match route.framework {
                        RouteFramework::Vue => "Vue",
                        RouteFramework::React => "React",
                        RouteFramework::Angular => "Angular",
                        RouteFramework::NextJS => "Next.js",
                        RouteFramework::Unknown => "unknown",
                    }
                ),
                evidence: Some(format!(
                    "Route metadata indicates authentication required, but HTTP {} returned without credentials. \
                     Response length: {} bytes (substantial content suggests real page, not redirect).",
                    response.status_code, response.body.len()
                )),
                cwe: "CWE-306".to_string(),
                cvss: 9.1,
                verified: true,
                false_positive: false,
                remediation: "1. CRITICAL: Implement server-side authentication checks\n\
                             2. Verify user session/token on EVERY request to protected routes\n\
                             3. Don't rely solely on client-side route guards\n\
                             4. Return 401 Unauthorized for unauthenticated requests\n\
                             5. Implement middleware/interceptors for route protection\n\
                             6. Use frameworks like Next.js getServerSideProps for SSR auth\n\
                             7. Validate JWT/session tokens server-side\n\
                             8. Log unauthorized access attempts".to_string(),
                discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_data: None,
            })
        } else {
            None
        }
    }

    /// Test if route with role requirements can be bypassed
    async fn test_rbac_bypass(&self, base_url: &str, route: &ClientRoute) -> Option<Vulnerability> {
        let test_path = self.replace_route_params(&route.path, "1");
        let test_url = self.resolve_url(base_url, &test_path);

        debug!(
            "[ClientRouteAuth] Testing RBAC bypass on: {} (requires roles: {:?})",
            test_url, route.required_roles
        );

        // Try accessing without any authentication
        let response = match self.http_client.get(&test_url).await {
            Ok(r) => r,
            Err(_) => return None,
        };

        // Check if we can access role-protected route
        let is_bypass = response.status_code == 200
            && response.status_code != 404
            && !response.body.to_lowercase().contains("forbidden")
            && !response.body.to_lowercase().contains("unauthorized")
            && !response.body.to_lowercase().contains("login")
            && !response.body.to_lowercase().contains("not found")
            && response.body.len() > 500;

        if is_bypass {
            info!(
                "[VULN] RBAC bypass found on route: {} (requires: {:?})",
                route.path, route.required_roles
            );

            Some(Vulnerability {
                id: format!("crrbac_{}", uuid::Uuid::new_v4().simple()),
                vuln_type: "Client Route RBAC Bypass".to_string(),
                severity: Severity::Critical,
                confidence: Confidence::High,
                category: "Access Control".to_string(),
                url: test_url.clone(),
                parameter: Some("role".to_string()),
                payload: route.path.clone(),
                description: format!(
                    "Client-side route '{}' requires roles {:?} but can be accessed without proper authorization. \
                     Role-based access control (RBAC) is declared in client-side router but not enforced server-side.",
                    route.path, route.required_roles
                ),
                evidence: Some(format!(
                    "Route declares requireAnyRole={:?} but HTTP {} returned full content without role verification. \
                     This allows privilege escalation to admin/management functionality.",
                    route.required_roles, response.status_code
                )),
                cwe: "CWE-639".to_string(),
                cvss: 9.8,
                verified: true,
                false_positive: false,
                remediation: "1. CRITICAL: Implement server-side role verification\n\
                             2. Check user roles on EVERY request to protected routes\n\
                             3. Return 403 Forbidden for unauthorized roles\n\
                             4. Don't rely on client-side role guards\n\
                             5. Use role-based middleware/decorators (@RequireRole)\n\
                             6. Validate roles from JWT claims or session\n\
                             7. Log role bypass attempts for security monitoring\n\
                             8. Implement principle of least privilege".to_string(),
                discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_data: None,
            })
        } else {
            None
        }
    }

    /// Test for IDOR vulnerabilities in parameterized routes
    async fn test_idor(&self, base_url: &str, route: &ClientRoute) -> Option<Vulnerability> {
        // Test common IDOR patterns
        let test_ids = vec!["1", "2", "999", "admin", "0"];

        for test_id in &test_ids {
            let test_path = self.replace_route_params(&route.path, test_id);
            let test_url = self.resolve_url(base_url, &test_path);

            debug!("[ClientRouteAuth] Testing IDOR on: {}", test_url);

            if let Ok(response) = self.http_client.get(&test_url).await {
                // Check if we can access other users' data
                if response.status_code == 200
                    && response.status_code != 404
                    && response.body.len() > 500
                    && !response.body.to_lowercase().contains("not found")
                    && !response.body.to_lowercase().contains("unauthorized")
                {
                    info!(
                        "[VULN] Potential IDOR found on route: {} with ID: {}",
                        route.path, test_id
                    );

                    return Some(Vulnerability {
                        id: format!("crador_{}", uuid::Uuid::new_v4().simple()),
                        vuln_type: "Client Route IDOR".to_string(),
                        severity: Severity::High,
                        confidence: Confidence::Medium,
                        category: "Access Control".to_string(),
                        url: test_url.clone(),
                        parameter: Some("id".to_string()),
                        payload: test_id.to_string(),
                        description: format!(
                            "Client-side route '{}' with ID parameter allows accessing arbitrary resources. \
                             Insecure Direct Object Reference (IDOR) vulnerability enables unauthorized data access.",
                            route.path
                        ),
                        evidence: Some(format!(
                            "Route pattern '{}' returned HTTP 200 with ID='{}'. No ownership verification detected. \
                             Users may access other users' data by manipulating the ID parameter.",
                            route.path, test_id
                        )),
                        cwe: "CWE-639".to_string(),
                        cvss: 7.5,
                        verified: false,
                        false_positive: false,
                        remediation: "1. Verify user ownership of requested resource\n\
                                     2. Check if current user ID matches resource owner\n\
                                     3. Implement server-side authorization checks\n\
                                     4. Use indirect references (UUIDs instead of sequential IDs)\n\
                                     5. Return 403 Forbidden for unauthorized access\n\
                                     6. Log IDOR attempts for security monitoring\n\
                                     7. Implement row-level security in database\n\
                                     8. Use GraphQL field-level authorization".to_string(),
                        discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_data: None,
                    });
                }
            }
        }

        None
    }

    /// Replace route parameters with test values
    fn replace_route_params(&self, path: &str, value: &str) -> String {
        path.replace(":id", value)
            .replace(":userId", value)
            .replace(":companyId", value)
            .replace(":orderId", value)
            .replace(":workerId", value)
            .replace(":shiftId", value)
    }

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

        let base_trimmed = base.trim_end_matches('/');
        let path_trimmed = path.trim_start_matches('/');

        format!("{}/{}", base_trimmed, path_trimmed)
    }
}

// UUID helper
mod uuid {
    use rand::Rng;

    pub struct Uuid;

    impl Uuid {
        pub fn new_v4() -> Self {
            Uuid
        }

        pub fn simple(&self) -> String {
            let mut rng = rand::rng();
            format!("{:08x}{:08x}", rng.random::<u32>(), rng.random::<u32>())
        }
    }
}

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

    #[test]
    fn test_extract_vue_routes() {
        let scanner = ClientRouteAuthBypassScanner::new(Arc::new(
            crate::http_client::HttpClient::new(30, 3).unwrap(),
        ));

        let js_code = r#"
            {path:"/admin",meta:{requireAnyRole:["ADMIN","MANAGEMENT"]}},
            {path:"/user/:id",meta:{requireAuth:true}},
            {path:"/driver",meta:{requireAnyRole:["DRIVER"]}}
        "#;

        let routes = scanner.extract_vue_routes(js_code);

        assert!(routes.len() >= 2);
        assert!(routes.iter().any(|r| r.path == "/admin"));
        assert!(routes.iter().any(|r| r.requires_auth));
    }

    #[test]
    fn test_replace_route_params() {
        let scanner = ClientRouteAuthBypassScanner::new(Arc::new(
            crate::http_client::HttpClient::new(30, 3).unwrap(),
        ));

        assert_eq!(
            scanner.replace_route_params("/user/:id", "123"),
            "/user/123"
        );
        assert_eq!(
            scanner.replace_route_params("/company/:companyId/user/:userId", "1"),
            "/company/1/user/1"
        );
    }

    #[test]
    fn test_resolve_url() {
        let scanner = ClientRouteAuthBypassScanner::new(Arc::new(
            crate::http_client::HttpClient::new(30, 3).unwrap(),
        ));

        assert_eq!(
            scanner.resolve_url("https://example.com", "/admin"),
            "https://example.com/admin"
        );

        assert_eq!(
            scanner.resolve_url("https://example.com/", "admin"),
            "https://example.com/admin"
        );
    }
}