dalfox-rs 0.3.0

Type-safe asynchronous wrapper for the Dalfox XSS scanner (Dalfox ≥3) with JSON findings, stored XSS support, and multi-format result formatting
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
//! The execution orchestration engine for Dalfox.
//!
//! Handles process lifecycle, async I/O streaming, stderr capture,
//! and scan deadline enforcement. Supports URL, file, pipe, and
//! stored XSS scanning modes.

use crate::builder::DalfoxBuilder;
use crate::error::DalfoxError;
use crate::types::{DalfoxFinding, DalfoxJsonEnvelope, DalfoxResult};
use std::process::Stdio;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::process::Command;

/// Dalfox `--format` value used for batch vs streaming output parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DalfoxOutputFormat {
    /// Single JSON document with `findings` and `meta`.
    Json,
    /// Newline-delimited finding records (`jsonl`).
    Jsonl,
}

/// Executes Dalfox scans with full process lifecycle management.
///
/// Created via [`super::Dalfox::builder()`] → [`.build()`](DalfoxBuilder::build).
/// Supports multiple scan modes and streaming output.
pub struct DalfoxRunner {
    config: DalfoxBuilder,
}

impl DalfoxRunner {
    pub(crate) fn new(config: DalfoxBuilder) -> Self {
        Self { config }
    }

    /// Returns the path that will be used for the dalfox binary.
    pub fn binary_path(&self) -> &str {
        self.config.binary_path.as_deref().unwrap_or("dalfox")
    }

    /// Check if the dalfox binary is available and executable.
    pub fn is_available(&self) -> bool {
        std::process::Command::new(self.binary_path())
            .arg("-V")
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    }

    /// Get the dalfox version string, if the binary is available.
    pub async fn version(&self) -> Result<String, DalfoxError> {
        let output = Command::new(self.binary_path())
            .arg("-V")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .await
            .map_err(|e| map_spawn_error(e, self.binary_path()))?;

        if !output.status.success() {
            return Err(DalfoxError::BinaryNotFound {
                path: self.binary_path().to_string(),
            });
        }

        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    fn map_spawn_result(
        &self,
        result: Result<tokio::process::Child, std::io::Error>,
    ) -> Result<tokio::process::Child, DalfoxError> {
        result.map_err(|e| map_spawn_error(e, self.binary_path()))
    }

    fn append_common_args(&self, args: &mut Vec<String>, format: DalfoxOutputFormat) {
        args.push("--format".into());
        args.push(match format {
            DalfoxOutputFormat::Json => "json",
            DalfoxOutputFormat::Jsonl => "jsonl",
        }
        .into());

        // ── Auth & Identity ──
        if let Some(cookie) = &self.config.cookie {
            args.push("--cookies".into());
            args.push(cookie.clone());
        }
        if let Some(raw_file) = &self.config.cookie_from_raw {
            args.push("--cookie-from-raw".into());
            args.push(raw_file.clone());
        }
        if let Some(ua) = &self.config.user_agent {
            args.push("--user-agent".into());
            args.push(ua.clone());
        }
        if let Some(proxy) = &self.config.proxy {
            args.push("--proxy".into());
            args.push(proxy.clone());
        }

        // ── Performance ──
        if let Some(timeout) = self.config.request_timeout_secs {
            args.push("--timeout".into());
            args.push(timeout.to_string());
        }
        if let Some(delay) = self.config.delay_ms {
            args.push("--delay".into());
            args.push(delay.to_string());
        }
        if let Some(workers) = self.config.workers {
            args.push("--workers".into());
            args.push(workers.to_string());
        }

        // ── Engine Features ──
        if self.config.skip_mining_all {
            args.push("--skip-mining".into());
        }
        if self.config.skip_mining_dom {
            args.push("--skip-mining-dom".into());
        }
        if self.config.skip_mining_dict {
            args.push("--skip-mining-dict".into());
        }
        if self.config.only_discovery {
            args.push("--only-discovery".into());
        }
        if self.config.only_custom_payload {
            args.push("--only-custom-payload".into());
        }
        if self.config.follow_redirects {
            args.push("--follow-redirects".into());
        }
        if self.config.waf_evasion {
            args.push("--waf-evasion".into());
        }
        if self.config.debug_mode {
            args.push("--debug".into());
        }
        if self.config.silence {
            args.push("--silence".into());
        }

        // ── Parameters & Scopes ──
        if let Some(p) = &self.config.param {
            args.push("--param".into());
            args.push(p.clone());
        }
        if let Some(dict) = &self.config.mining_dict {
            args.push("--mining-dict-word".into());
            args.push(dict.clone());
        }
        if let Some(m) = &self.config.method {
            args.push("--method".into());
            args.push(m.clone());
        }
        if let Some(d) = &self.config.data {
            args.push("--data".into());
            args.push(d.clone());
        }
        if let Some(codes) = &self.config.ignore_return_codes {
            args.push("--ignore-return".into());
            args.push(codes.clone());
        }

        // ── Payloads & PoC ──
        if let Some(url) = &self.config.blind_callback {
            args.push("--blind".into());
            args.push(url.clone());
        }
        if let Some(rp) = &self.config.remote_payloads {
            args.push("--remote-payloads".into());
            args.push(rp.clone());
        }
        if let Some(rw) = &self.config.remote_wordlists {
            args.push("--remote-wordlists".into());
            args.push(rw.clone());
        }
        if let Some(val) = &self.config.custom_alert_value {
            args.push("--custom-alert-value".into());
            args.push(val.clone());
        }
        if let Some(poc_filter) = &self.config.only_poc {
            args.push("--only-poc".into());
            args.push(poc_filter.clone());
        }
        if let Some(pt) = &self.config.poc_type {
            args.push("--poc-type".into());
            args.push(pt.clone());
        }

        // ── Output ──
        if let Some(out) = &self.config.output_file {
            args.push("--output".into());
            args.push(out.clone());
        }

        // ── Custom headers and payloads ──
        for header in &self.config.custom_headers {
            args.push("--headers".into());
            args.push(header.clone());
        }
        for payload in &self.config.payloads {
            args.push("--custom-payload".into());
            args.push(payload.clone());
        }
    }

    fn build_scan_args(&self, format: DalfoxOutputFormat) -> Vec<String> {
        let mut args = vec!["scan".to_string()];
        self.append_common_args(&mut args, format);
        args
    }

    fn build_file_args(&self, format: DalfoxOutputFormat) -> Vec<String> {
        let mut args = vec!["file".to_string()];
        self.append_common_args(&mut args, format);
        args
    }

    fn build_pipe_args(&self, format: DalfoxOutputFormat) -> Vec<String> {
        let mut args = vec!["pipe".to_string()];
        self.append_common_args(&mut args, format);
        args
    }

    fn command_from_args(&self, args: &[String]) -> Command {
        let mut cmd = Command::new(self.binary_path());
        cmd.args(args);
        cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
        cmd.kill_on_drop(true);
        cmd
    }

    /// Build a `dalfox scan` command with flags after the subcommand.
    fn build_scan_command(&self, format: DalfoxOutputFormat) -> Command {
        self.command_from_args(&self.build_scan_args(format))
    }

    /// Build a `dalfox file` command with flags after the subcommand.
    fn build_file_command(&self, format: DalfoxOutputFormat) -> Command {
        self.command_from_args(&self.build_file_args(format))
    }

    /// Build a `dalfox pipe` command with flags after the subcommand.
    fn build_pipe_command(&self, format: DalfoxOutputFormat) -> Command {
        self.command_from_args(&self.build_pipe_args(format))
    }

    /// Read full stdout as a single Dalfox v3 JSON envelope.
    async fn parse_json_document(
        &self,
        mut child: tokio::process::Child,
    ) -> Result<DalfoxResult, DalfoxError> {
        let start = std::time::Instant::now();

        let stdout = child.stdout.take().ok_or_else(|| {
            DalfoxError::ExecutionFailed(std::io::Error::new(
                std::io::ErrorKind::BrokenPipe,
                "failed to capture stdout from dalfox process",
            ))
        })?;

        let stderr_handle = child.stderr.take();
        let stderr_task = tokio::spawn(async move {
            let mut buf = String::new();
            if let Some(stderr) = stderr_handle {
                let mut reader = BufReader::new(stderr);
                let _ = tokio::io::AsyncReadExt::read_to_string(&mut reader, &mut buf).await;
            }
            buf
        });

        let mut stdout_buf = String::new();
        let mut reader = BufReader::new(stdout);
        reader
            .read_to_string(&mut stdout_buf)
            .await
            .map_err(DalfoxError::ExecutionFailed)?;

        let mut findings = Vec::new();
        let mut parse_errors = Vec::new();
        let mut meta = None;

        let trimmed = stdout_buf.trim();
        if !trimmed.is_empty() {
            match serde_json::from_str::<DalfoxJsonEnvelope>(trimmed) {
                Ok(envelope) => {
                    findings = envelope.findings;
                    meta = envelope.meta;
                }
                Err(err) => {
                    tracing::warn!(
                        output = %trimmed,
                        error = %err,
                        "failed to parse dalfox JSON envelope"
                    );
                    parse_errors.push(format!("{err}: {trimmed}"));
                }
            }
        }

        let status = child.wait().await?;
        let stderr_output = stderr_task.await.unwrap_or_default();
        let exit_code = status.code();

        if !status.success() && findings.is_empty() {
            return Err(DalfoxError::ProcessFailed {
                status: exit_code.unwrap_or(-1),
                stderr: stderr_output,
            });
        }

        Ok(DalfoxResult {
            findings,
            parse_errors,
            stderr_output,
            exit_code,
            scan_duration: Some(start.elapsed()),
            meta,
        })
    }

    /// Parse `--format jsonl` stdout, invoking a callback per finding line.
    async fn parse_jsonl_stream<F>(
        &self,
        mut child: tokio::process::Child,
        mut on_finding: Option<F>,
    ) -> Result<DalfoxResult, DalfoxError>
    where
        F: FnMut(&DalfoxFinding),
    {
        let start = std::time::Instant::now();

        let stdout = child.stdout.take().ok_or_else(|| {
            DalfoxError::ExecutionFailed(std::io::Error::new(
                std::io::ErrorKind::BrokenPipe,
                "failed to capture stdout from dalfox process",
            ))
        })?;

        let stderr_handle = child.stderr.take();
        let stderr_task = tokio::spawn(async move {
            let mut buf = String::new();
            if let Some(stderr) = stderr_handle {
                let mut reader = BufReader::new(stderr);
                let _ = tokio::io::AsyncReadExt::read_to_string(&mut reader, &mut buf).await;
            }
            buf
        });

        let mut reader = BufReader::new(stdout).lines();
        let mut findings = Vec::new();
        let mut parse_errors = Vec::new();

        loop {
            match reader.next_line().await {
                Ok(Some(line)) => {
                    let trimmed = line.trim();
                    if trimmed.is_empty() {
                        continue;
                    }
                    if !trimmed.starts_with('{') {
                        continue;
                    }
                    match serde_json::from_str::<DalfoxFinding>(trimmed) {
                        Ok(finding) => {
                            if let Some(ref mut cb) = on_finding {
                                cb(&finding);
                            }
                            findings.push(finding);
                        }
                        Err(_) => {
                            // Ignore meta-only or non-finding JSONL lines.
                            if serde_json::from_str::<DalfoxJsonEnvelope>(trimmed).is_ok() {
                                continue;
                            }
                            tracing::warn!(
                                line = %trimmed,
                                "failed to parse dalfox JSONL finding line"
                            );
                            parse_errors.push(format!("unrecognized jsonl line: {trimmed}"));
                        }
                    }
                }
                Ok(None) => break,
                Err(err) => return Err(DalfoxError::ExecutionFailed(err)),
            }
        }

        let status = child.wait().await?;
        let stderr_output = stderr_task.await.unwrap_or_default();
        let exit_code = status.code();

        if !status.success() && findings.is_empty() {
            return Err(DalfoxError::ProcessFailed {
                status: exit_code.unwrap_or(-1),
                stderr: stderr_output,
            });
        }

        Ok(DalfoxResult {
            findings,
            parse_errors,
            stderr_output,
            exit_code,
            scan_duration: Some(start.elapsed()),
            meta: None,
        })
    }

    /// Execute a scan with the configured deadline (if any).
    async fn execute_scan(
        &self,
        child: tokio::process::Child,
    ) -> Result<DalfoxResult, DalfoxError> {
        if let Some(deadline_secs) = self.config.scan_deadline_secs {
            let deadline = std::time::Duration::from_secs(deadline_secs);
            match tokio::time::timeout(deadline, self.parse_json_document(child)).await {
                Ok(result) => result,
                Err(_) => Err(DalfoxError::ScanDeadlineExceeded { deadline_secs }),
            }
        } else {
            self.parse_json_document(child).await
        }
    }

    /// Execute a scan with streaming callback and deadline enforcement.
    async fn execute_scan_streaming<F>(
        &self,
        child: tokio::process::Child,
        on_finding: F,
    ) -> Result<DalfoxResult, DalfoxError>
    where
        F: FnMut(&DalfoxFinding),
    {
        if let Some(deadline_secs) = self.config.scan_deadline_secs {
            let deadline = std::time::Duration::from_secs(deadline_secs);
            match tokio::time::timeout(
                deadline,
                self.parse_jsonl_stream(child, Some(on_finding)),
            )
            .await
            {
                Ok(result) => result,
                Err(_) => Err(DalfoxError::ScanDeadlineExceeded { deadline_secs }),
            }
        } else {
            self.parse_jsonl_stream(child, Some(on_finding)).await
        }
    }

    // ── Scan Modes ───────────────────────────────────────────────

    /// Scan a single target URL for XSS vulnerabilities.
    ///
    /// # Errors
    ///
    /// Returns [`DalfoxError::ExecutionFailed`] if the binary cannot be spawned,
    /// [`DalfoxError::ProcessFailed`] if Dalfox exits non-zero with no findings,
    /// or [`DalfoxError::ScanDeadlineExceeded`] if the deadline is hit.
    pub async fn scan_url(&self, target_url: &str) -> Result<DalfoxResult, DalfoxError> {
        let mut cmd = self.build_scan_command(DalfoxOutputFormat::Json);
        cmd.arg(target_url);
        self.execute_scan(self.map_spawn_result(cmd.spawn())?).await
    }

    /// Scan a single target URL with a real-time callback for each finding.
    ///
    /// The callback is invoked as soon as each finding is parsed from the
    /// output stream, enabling real-time alerting or progress tracking.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dalfox_rs::Dalfox;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let runner = Dalfox::builder().build();
    /// let result = runner.scan_url_streaming("http://example.com?q=test", |finding| {
    ///     eprintln!("LIVE: {}", finding);
    /// }).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn scan_url_streaming<F>(
        &self,
        target_url: &str,
        on_finding: F,
    ) -> Result<DalfoxResult, DalfoxError>
    where
        F: FnMut(&DalfoxFinding),
    {
        let mut cmd = self.build_scan_command(DalfoxOutputFormat::Jsonl);
        cmd.arg(target_url);
        self.execute_scan_streaming(self.map_spawn_result(cmd.spawn())?, on_finding)
            .await
    }

    /// Scan a raw HTTP request file (`dalfox file` mode).
    pub async fn scan_file_raw(&self, file_path: &str) -> Result<DalfoxResult, DalfoxError> {
        let mut cmd = self.build_file_command(DalfoxOutputFormat::Json);
        cmd.arg(file_path);
        self.execute_scan(self.map_spawn_result(cmd.spawn())?).await
    }

    /// Scan a raw HTTP request file with streaming callback.
    pub async fn scan_file_raw_streaming<F>(
        &self,
        file_path: &str,
        on_finding: F,
    ) -> Result<DalfoxResult, DalfoxError>
    where
        F: FnMut(&DalfoxFinding),
    {
        let mut cmd = self.build_file_command(DalfoxOutputFormat::Jsonl);
        cmd.arg(file_path);
        self.execute_scan_streaming(self.map_spawn_result(cmd.spawn())?, on_finding)
            .await
    }

    /// Pipe multiple URLs into Dalfox via stdin (`dalfox pipe` mode).
    ///
    /// Each URL is sent as a separate line. Dalfox processes them sequentially.
    pub async fn scan_pipe(&self, urls: Vec<String>) -> Result<DalfoxResult, DalfoxError> {
        let mut cmd = self.build_pipe_command(DalfoxOutputFormat::Json);
        cmd.stdin(Stdio::piped());

        let mut child = self.map_spawn_result(cmd.spawn())?;
        if let Some(mut stdin) = child.stdin.take() {
            let stream_data = urls.join("\n") + "\n";
            stdin.write_all(stream_data.as_bytes()).await?;
            stdin.flush().await?;
        }

        self.execute_scan(child).await
    }

    /// Pipe multiple URLs with streaming callback.
    pub async fn scan_pipe_streaming<F>(
        &self,
        urls: Vec<String>,
        on_finding: F,
    ) -> Result<DalfoxResult, DalfoxError>
    where
        F: FnMut(&DalfoxFinding),
    {
        let mut cmd = self.build_pipe_command(DalfoxOutputFormat::Jsonl);
        cmd.stdin(Stdio::piped());

        let mut child = self.map_spawn_result(cmd.spawn())?;
        if let Some(mut stdin) = child.stdin.take() {
            let stream_data = urls.join("\n") + "\n";
            stdin.write_all(stream_data.as_bytes()).await?;
            stdin.flush().await?;
        }

        self.execute_scan_streaming(child, on_finding).await
    }

    /// Scan for Stored XSS using separate injection and verification URLs.
    ///
    /// Dalfox's `--sxss` mode injects payloads into `inject_url` and then
    /// checks `trigger_url` for payload execution, detecting persistent
    /// cross-site scripting.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dalfox_rs::Dalfox;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let runner = Dalfox::builder().build();
    /// let result = runner.scan_sxss(
    ///     "http://example.com/comment?body=test",
    ///     "http://example.com/view-comments",
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn scan_sxss(
        &self,
        inject_url: &str,
        trigger_url: &str,
    ) -> Result<DalfoxResult, DalfoxError> {
        let mut cmd = self.build_scan_command(DalfoxOutputFormat::Json);
        cmd.arg("--sxss")
            .arg("--sxss-url")
            .arg(trigger_url)
            .arg(inject_url);
        self.execute_scan(self.map_spawn_result(cmd.spawn())?).await
    }

    /// Scan for Stored XSS with streaming callback.
    pub async fn scan_sxss_streaming<F>(
        &self,
        inject_url: &str,
        trigger_url: &str,
        on_finding: F,
    ) -> Result<DalfoxResult, DalfoxError>
    where
        F: FnMut(&DalfoxFinding),
    {
        let mut cmd = self.build_scan_command(DalfoxOutputFormat::Jsonl);
        cmd.arg("--sxss")
            .arg("--sxss-url")
            .arg(trigger_url)
            .arg(inject_url);
        self.execute_scan_streaming(self.map_spawn_result(cmd.spawn())?, on_finding)
            .await
    }

    /// Returns the argv that would be passed to `dalfox` for [`scan_url`].
    #[cfg(test)]
    pub(crate) fn scan_url_argv_for_test(&self, target_url: &str) -> Vec<String> {
        let mut args = self.build_scan_args(DalfoxOutputFormat::Json);
        args.push(target_url.to_string());
        args
    }
}

fn map_spawn_error(err: std::io::Error, path: &str) -> DalfoxError {
    if err.kind() == std::io::ErrorKind::NotFound {
        DalfoxError::BinaryNotFound {
            path: path.to_string(),
        }
    } else {
        DalfoxError::ExecutionFailed(err)
    }
}

// ── Result filtering helpers ─────────────────────────────────────

impl DalfoxResult {
    /// Filter findings by severity level.
    ///
    /// Returns only findings matching the given severity.
    pub fn findings_by_severity(&self, severity: &crate::types::Severity) -> Vec<&DalfoxFinding> {
        self.findings
            .iter()
            .filter(|f| &f.severity == severity)
            .collect()
    }

    /// Filter findings by event type.
    pub fn findings_by_type(&self, event_type: &crate::types::EventType) -> Vec<&DalfoxFinding> {
        self.findings
            .iter()
            .filter(|f| &f.event_type == event_type)
            .collect()
    }

    /// Returns only verified (confirmed) XSS findings.
    pub fn verified_findings(&self) -> Vec<&DalfoxFinding> {
        self.findings_by_type(&crate::types::EventType::Verified)
    }

    /// Returns only high-severity findings.
    pub fn high_severity_findings(&self) -> Vec<&DalfoxFinding> {
        self.findings_by_severity(&crate::types::Severity::High)
    }

    /// Returns true if the scan found at least one verified vulnerability.
    pub fn has_verified_findings(&self) -> bool {
        self.findings
            .iter()
            .any(|f| f.event_type == crate::types::EventType::Verified)
    }

    /// Returns true if any parse errors occurred during output processing.
    pub fn has_parse_errors(&self) -> bool {
        !self.parse_errors.is_empty()
    }
}

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

    #[test]
    fn builder_creates_runner() {
        let runner = Dalfox::builder()
            .request_timeout(30)
            .scan_deadline(300)
            .workers(10)
            .cookie("session=abc")
            .waf_evasion(true)
            .build();
        let _ = runner;
    }

    #[test]
    fn builder_with_custom_binary() {
        let runner = Dalfox::builder()
            .binary_path("/usr/local/bin/dalfox")
            .build();
        assert_eq!(runner.binary_path(), "/usr/local/bin/dalfox");
    }

    #[test]
    fn builder_with_all_new_flags() {
        let runner = Dalfox::builder()
            .cookie_from_raw("/path/to/burp.txt")
            .only_discovery(true)
            .only_custom_payload(true)
            .follow_redirects(true)
            .debug(true)
            .silence(false)
            .ignore_return("302,403,404")
            .custom_alert_value("document.domain")
            .only_poc("g,v")
            .poc_type("curl")
            .output_file("/tmp/dalfox-out.json")
            .build();
        let _ = runner;
    }

    #[test]
    fn builder_with_headers_and_payloads() {
        let runner = Dalfox::builder()
            .header("X-Custom: value")
            .header("Authorization: Bearer token")
            .payload("<script>alert(1)</script>")
            .payload("'\"><img src=x onerror=alert(1)>")
            .build();
        let _ = runner;
    }

    #[test]
    fn backward_compat_timeout_sets_both() {
        let builder = DalfoxBuilder::new().timeout(30);
        assert_eq!(builder.request_timeout_secs, Some(30));
        assert_eq!(builder.scan_deadline_secs, Some(30));
    }

    #[test]
    fn binary_path_defaults_to_dalfox() {
        let runner = Dalfox::builder().build();
        assert_eq!(runner.binary_path(), "dalfox");
    }

    #[test]
    fn result_filtering_helpers() {
        let result = DalfoxResult::default();
        assert!(result.verified_findings().is_empty());
        assert!(result.high_severity_findings().is_empty());
        assert!(!result.has_verified_findings());
        assert!(!result.has_parse_errors());
    }

    #[test]
    fn scan_url_puts_subcommand_before_flags_and_target_last() {
        let runner = Dalfox::builder().workers(5).cookie("a=b").build();
        let args = runner.scan_url_argv_for_test("http://example.com/?q=1");
        let scan_pos = args.iter().position(|a| a == "scan").expect("scan subcommand");
        let format_pos = args
            .iter()
            .position(|a| a == "--format")
            .expect("--format flag");
        assert!(scan_pos < format_pos);
        assert!(args.contains(&"--workers".to_string()));
        assert!(args.contains(&"--cookies".to_string()));
        assert_eq!(args.last().map(String::as_str), Some("http://example.com/?q=1"));
        assert!(!args.iter().any(|a| a == "url"));
    }

    #[tokio::test]
    async fn version_against_live_dalfox_when_available() {
        let runner = Dalfox::builder().build();
        if !runner.is_available() {
            return;
        }
        let version = runner.version().await.expect("version from live dalfox");
        assert!(version.contains("dalfox"));
    }
}