dalfox-rs 0.5.5

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
//! Strictly-typed structures for Dalfox scan results.
//!
//! Every field from Dalfox's JSON output is mapped to a concrete Rust type,
//! with enums for known-finite value sets and `Other`/`Unknown` fallbacks
//! for forward compatibility with newer Dalfox versions.

use serde::{Deserialize, Serialize};
use std::fmt;

/// The classification of a finding event.
///
/// Dalfox emits different event types depending on the confidence
/// and nature of the detection.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EventType {
    /// Verified XSS vulnerability with confirmed execution.
    #[serde(rename = "V")]
    Verified,
    /// Grep-based match (information disclosure, sensitive patterns).
    #[serde(rename = "G")]
    Grep,
    /// Informational finding (no direct vulnerability).
    #[serde(rename = "I")]
    Information,
    /// Reflected parameter detected but unverified.
    #[serde(rename = "R")]
    Reflected,
    /// AST-based DOM XSS detection.
    #[serde(rename = "A")]
    Ast,
    /// Unknown event type from a newer Dalfox version.
    #[serde(untagged)]
    Other(String),
}

impl fmt::Display for EventType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Verified => write!(f, "Verified"),
            Self::Grep => write!(f, "Grep"),
            Self::Information => write!(f, "Info"),
            Self::Reflected => write!(f, "Reflected"),
            Self::Ast => write!(f, "AST"),
            Self::Other(s) => write!(f, "{s}"),
        }
    }
}

/// Vulnerability severity as reported by Dalfox.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Severity {
    /// High severity (critical/high impact XSS).
    #[serde(rename = "High")]
    High,
    /// Medium severity.
    #[serde(rename = "Medium")]
    Medium,
    /// Low severity.
    #[serde(rename = "Low")]
    Low,
    /// Informational severity.
    #[serde(rename = "Information", alias = "Info")]
    Information,
    /// Unknown severity from a newer Dalfox version.
    #[serde(untagged)]
    Unknown(String),
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::High => write!(f, "High"),
            Self::Medium => write!(f, "Medium"),
            Self::Low => write!(f, "Low"),
            Self::Information => write!(f, "Info"),
            Self::Unknown(s) => write!(f, "{s}"),
        }
    }
}

/// HTTP method used in the finding.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Method {
    /// HTTP GET.
    #[serde(rename = "GET")]
    Get,
    /// HTTP POST.
    #[serde(rename = "POST")]
    Post,
    /// HTTP PUT.
    #[serde(rename = "PUT")]
    Put,
    /// HTTP DELETE.
    #[serde(rename = "DELETE")]
    Delete,
    /// HTTP HEAD.
    #[serde(rename = "HEAD")]
    Head,
    /// HTTP OPTIONS.
    #[serde(rename = "OPTIONS")]
    Options,
    /// HTTP PATCH.
    #[serde(rename = "PATCH")]
    Patch,
    /// Other or custom HTTP method.
    #[serde(untagged)]
    Other(String),
}

impl fmt::Display for Method {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Get => write!(f, "GET"),
            Self::Post => write!(f, "POST"),
            Self::Put => write!(f, "PUT"),
            Self::Delete => write!(f, "DELETE"),
            Self::Head => write!(f, "HEAD"),
            Self::Options => write!(f, "OPTIONS"),
            Self::Patch => write!(f, "PATCH"),
            Self::Other(s) => write!(f, "{s}"),
        }
    }
}

/// A structured finding reported by Dalfox via its JSON output.
///
/// Each finding represents a single detected XSS vector with full
/// contextual information about the injection point, payload, and evidence.
///
/// Dalfox v3 JSON omits `poc` and places the PoC URL in [`data`](Self::data).
/// Prefer [`poc_url`](Self::poc_url) when displaying or exporting findings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DalfoxFinding {
    /// The classification of this finding (verified, grep, info, reflected).
    #[serde(rename = "type")]
    pub event_type: EventType,

    /// Legacy proof-of-concept URL (absent in Dalfox v3 JSON; defaults to empty).
    ///
    /// For v3 output, use [`data`](Self::data) or [`poc_url`](Self::poc_url).
    #[serde(default)]
    pub poc: String,

    /// HTTP method used for the scan request.
    pub method: Method,

    /// Request URL or body data. In Dalfox v3 this holds the PoC URL for GET findings.
    #[serde(default)]
    pub data: String,

    /// The specific parameter that was injected.
    pub param: String,

    /// The actual XSS payload used.
    pub payload: String,

    /// The response snippet verifying payload reflection or execution.
    #[serde(default)]
    pub evidence: String,

    /// CWE classification identifier (e.g. "CWE-79").
    pub cwe: String,

    /// The vulnerability severity rating.
    pub severity: Severity,

    /// Injection context label from Dalfox v3 (e.g. `inHTML`, `inJS`).
    #[serde(default)]
    pub inject_type: Option<String>,

    /// Parameter location from Dalfox v3 (e.g. `Query`, `Body`).
    #[serde(default)]
    pub location: Option<String>,

    /// Human-readable finding summary from Dalfox v3.
    #[serde(default)]
    pub message_str: Option<String>,

    /// Long-form type label from Dalfox v3 (e.g. `Verified XSS - ...`).
    #[serde(default)]
    pub type_description: Option<String>,
}

impl DalfoxFinding {
    /// PoC URL for this finding: `data` when `poc` is empty (Dalfox v3), else `poc`.
    pub fn poc_url(&self) -> &str {
        if self.poc.is_empty() {
            &self.data
        } else {
            &self.poc
        }
    }
}

impl fmt::Display for DalfoxFinding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "[{sev}][{evt}] {cwe} on param '{param}' via {method}{poc}",
            sev = self.severity,
            evt = self.event_type,
            cwe = self.cwe,
            param = self.param,
            method = self.method,
            poc = self.poc_url(),
        )
    }
}

/// Top-level JSON document emitted by Dalfox v3 with `--format json`.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct DalfoxJsonEnvelope {
    /// Parsed XSS findings from the scan.
    #[serde(default)]
    pub findings: Vec<DalfoxFinding>,
    /// Scan metadata (version, timing, counts). Ignored if absent or unparseable.
    #[serde(default)]
    pub meta: Option<serde_json::Value>,
    /// Discovered parameters (`--only-discovery` output). Preserved as raw JSON.
    #[serde(default)]
    pub params: Option<serde_json::Value>,
}

/// Aggregate results from a Dalfox scan execution.
///
/// Contains the parsed findings, diagnostic metadata, and any parse errors
/// encountered while processing Dalfox's output stream.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct DalfoxResult {
    /// The detected XSS findings from the scan.
    pub findings: Vec<DalfoxFinding>,

    /// Lines from Dalfox output that failed to parse as valid findings.
    ///
    /// Non-empty values indicate a potential Dalfox schema change or
    /// corrupted output. Each entry contains `"parse_error: raw_line"`.
    pub parse_errors: Vec<String>,

    /// Captured stderr output from the Dalfox process.
    ///
    /// Contains warnings, progress information, and diagnostic messages
    /// emitted by the Dalfox binary during execution.
    pub stderr_output: String,

    /// The exit code of the Dalfox process, if available.
    pub exit_code: Option<i32>,

    /// Wall-clock duration of the scan.
    pub scan_duration: Option<std::time::Duration>,

    /// Optional metadata from Dalfox's JSON envelope (`meta` field).
    pub meta: Option<serde_json::Value>,

    /// Optional discovered parameters from Dalfox's JSON envelope (`params` field).
    ///
    /// Populated when `--only-discovery` is used; findings may be empty.
    pub params: Option<serde_json::Value>,
}

/// Supported output formats for scan results.
///
/// Use with [`DalfoxResult::format_as`] to convert findings into
/// the desired output representation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OutputFormat {
    /// Compact single-line JSON array.
    Json,
    /// Pretty-printed JSON array.
    JsonPretty,
    /// Comma-separated values with header row.
    Csv,
    /// GitHub-flavored Markdown table.
    Markdown,
    /// Human-readable plain text report.
    Plain,
}

impl DalfoxResult {
    /// Format the scan results in the specified output format.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use dalfox_rs::types::{DalfoxResult, OutputFormat};
    /// let result = DalfoxResult::default();
    /// let csv = result.format_as(OutputFormat::Csv);
    /// assert!(csv.starts_with("severity,"));
    /// ```
    pub fn format_as(&self, format: OutputFormat) -> String {
        match format {
            OutputFormat::Json => self.format_json(false),
            OutputFormat::JsonPretty => self.format_json(true),
            OutputFormat::Csv => self.format_csv(),
            OutputFormat::Markdown => self.format_markdown(),
            OutputFormat::Plain => self.format_plain(),
        }
    }

    fn format_json(&self, pretty: bool) -> String {
        let result = if pretty {
            serde_json::to_string_pretty(&self.findings)
        } else {
            serde_json::to_string(&self.findings)
        };
        // Vec<DalfoxFinding> serialization is infallible for well-formed types,
        // but we handle the impossible case gracefully.
        match result {
            Ok(json) => json,
            Err(err) => format!("{{\"error\": \"serialization failed: {err}\"}}"),
        }
    }

    fn format_csv(&self) -> String {
        let mut buf = String::from(
            "severity,type,method,param,cwe,poc,payload,evidence,inject_type,location,message_str,type_description\n",
        );
        for finding in &self.findings {
            buf.push_str(&format!(
                "{},{},{},{},{},{},{},{},{},{},{},{}\n",
                csv_escape(&finding.severity.to_string()),
                csv_escape(&finding.event_type.to_string()),
                csv_escape(&finding.method.to_string()),
                csv_escape(&finding.param),
                csv_escape(&finding.cwe),
                csv_escape(finding.poc_url()),
                csv_escape(&finding.payload),
                csv_escape(&finding.evidence),
                csv_escape(opt_str(&finding.inject_type)),
                csv_escape(opt_str(&finding.location)),
                csv_escape(opt_str(&finding.message_str)),
                csv_escape(opt_str(&finding.type_description)),
            ));
        }
        buf
    }

    fn format_markdown(&self) -> String {
        if self.findings.is_empty() {
            return "No findings.\n".to_string();
        }
        let mut buf = String::from(
            "| Severity | Type | Method | Param | CWE | PoC | Payload | Inject | Location | Message | Description |\n",
        );
        buf.push_str("|----------|------|--------|-------|-----|-----|---------|--------|----------|---------|-------------|\n");
        for finding in &self.findings {
            buf.push_str(&format!(
                "| {} | {} | {} | `{}` | {} | [link]({}) | `{}` | {} | {} | {} | {} |\n",
                finding.severity,
                finding.event_type,
                finding.method,
                finding.param,
                finding.cwe,
                md_link_target(finding.poc_url()),
                md_escape(&finding.payload),
                md_escape(opt_str(&finding.inject_type)),
                md_escape(opt_str(&finding.location)),
                md_escape(opt_str(&finding.message_str)),
                md_escape(opt_str(&finding.type_description)),
            ));
        }
        buf
    }

    fn format_plain(&self) -> String {
        if self.findings.is_empty() {
            return "No XSS findings detected.\n".to_string();
        }
        let mut buf = format!("=== {} Finding(s) ===\n\n", self.findings.len());
        for (i, finding) in self.findings.iter().enumerate() {
            let evidence_display = if finding.evidence.is_empty() {
                "(none)"
            } else {
                &finding.evidence
            };
            buf.push_str(&format!(
                "#{} [{}] {} ({})\n  Parameter:   {}\n  Method:      {}\n  PoC:         {}\n  Payload:     {}\n  Evidence:    {}\n",
                i + 1,
                finding.severity,
                finding.cwe,
                finding.event_type,
                finding.param,
                finding.method,
                finding.poc_url(),
                finding.payload,
                evidence_display,
            ));
            if let Some(inject_type) = &finding.inject_type {
                buf.push_str(&format!("  Inject type: {inject_type}\n"));
            }
            if let Some(location) = &finding.location {
                buf.push_str(&format!("  Location:    {location}\n"));
            }
            if let Some(message) = &finding.message_str {
                buf.push_str(&format!("  Message:     {message}\n"));
            }
            if let Some(desc) = &finding.type_description {
                buf.push_str(&format!("  Description: {desc}\n"));
            }
            buf.push('\n');
        }
        if !self.parse_errors.is_empty() {
            buf.push_str(&format!(
                "--- {} Parse Error(s) ---\n",
                self.parse_errors.len()
            ));
            for err in &self.parse_errors {
                buf.push_str(&format!("{err}\n"));
            }
        }
        buf
    }
}

/// Escape a value for CSV output.
fn csv_escape(value: &str) -> String {
    let neutralized = neutralize_csv_formula(value);
    if neutralized.contains(',') || neutralized.contains('"') || neutralized.contains('\n') {
        format!("\"{}\"", neutralized.replace('"', "\"\""))
    } else {
        neutralized
    }
}

/// Prefix spreadsheet formula triggers so Excel/LibreOffice do not execute cell contents.
fn neutralize_csv_formula(value: &str) -> String {
    let first = value.chars().next();
    if first.is_some_and(|c| matches!(c, '=' | '+' | '-' | '@' | '\t' | '\r')) {
        format!("'{value}")
    } else {
        value.to_string()
    }
}

fn opt_str(opt: &Option<String>) -> &str {
    opt.as_deref().unwrap_or("")
}

/// Escape pipe and backtick characters for Markdown table cells.
fn md_escape(value: &str) -> String {
    value.replace('|', "\\|").replace('`', "\\`")
}

/// Format a URL for a Markdown link destination without truncating at `)` or `(`.
///
/// Dalfox v3 `data`/`poc` URLs are already percent-encoded; this wraps destinations that
/// contain parentheses or spaces in angle brackets. Literal `<`/`>` in such URLs are
/// percent-encoded inside the brackets so the link parser does not terminate early.
fn md_link_target(url: &str) -> String {
    if url.contains(')') || url.contains('(') || url.contains(' ') {
        let escaped = url.replace('<', "%3C").replace('>', "%3E");
        format!("<{escaped}>")
    } else {
        url.to_string()
    }
}

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

    #[test]
    fn finding_deserialize_v3_without_poc() {
        let json = include_str!("../tests/fixtures/v3_verified_finding.json");
        let finding: DalfoxFinding = serde_json::from_str(json).expect("v3 finding JSON");
        assert_eq!(finding.event_type, EventType::Verified);
        assert_eq!(finding.poc, "");
        assert!(!finding.data.is_empty());
        assert_eq!(finding.poc_url(), finding.data.as_str());
    }

    #[test]
    fn finding_deserialize() {
        let json = r#"{"type":"V","poc":"http://example.com?q=%3Cscript%3Ealert(1)%3C/script%3E","method":"GET","data":"","param":"q","payload":"<script>alert(1)</script>","evidence":"<script>alert(1)</script>","cwe":"CWE-79","severity":"High"}"#;
        let finding: DalfoxFinding = serde_json::from_str(json).expect("valid finding JSON");
        assert_eq!(finding.event_type, EventType::Verified);
        assert_eq!(finding.param, "q");
        assert_eq!(finding.severity, Severity::High);
        assert_eq!(finding.cwe, "CWE-79");
        assert_eq!(finding.method, Method::Get);
    }

    #[test]
    fn event_type_variants() {
        assert_eq!(
            serde_json::from_str::<EventType>("\"V\"").expect("verified"),
            EventType::Verified
        );
        assert_eq!(
            serde_json::from_str::<EventType>("\"G\"").expect("grep"),
            EventType::Grep
        );
        assert_eq!(
            serde_json::from_str::<EventType>("\"I\"").expect("info"),
            EventType::Information
        );
        assert_eq!(
            serde_json::from_str::<EventType>("\"R\"").expect("reflected"),
            EventType::Reflected
        );
        assert_eq!(
            serde_json::from_str::<EventType>("\"XNEW\"").expect("unknown"),
            EventType::Other("XNEW".to_string())
        );
    }

    #[test]
    fn severity_aliases() {
        assert_eq!(
            serde_json::from_str::<Severity>("\"Info\"").expect("info alias"),
            Severity::Information
        );
        assert_eq!(
            serde_json::from_str::<Severity>("\"Information\"").expect("info full"),
            Severity::Information
        );
        assert_eq!(
            serde_json::from_str::<Severity>("\"POTENTIAL\"").expect("unknown"),
            Severity::Unknown("POTENTIAL".to_string())
        );
    }

    #[test]
    fn method_patch_variant() {
        assert_eq!(
            serde_json::from_str::<Method>("\"PATCH\"").expect("patch"),
            Method::Patch
        );
        assert_eq!(
            serde_json::from_str::<Method>("\"CUSTOM\"").expect("custom"),
            Method::Other("CUSTOM".to_string())
        );
    }

    #[test]
    fn result_default_is_empty() {
        let result = DalfoxResult::default();
        assert!(result.findings.is_empty());
        assert!(result.parse_errors.is_empty());
        assert!(result.stderr_output.is_empty());
        assert!(result.exit_code.is_none());
        assert!(result.scan_duration.is_none());
        assert!(result.meta.is_none());
        assert!(result.params.is_none());
    }

    #[test]
    fn json_envelope_deserialize_with_meta() {
        let json = r#"{"findings":[],"meta":{"dalfox_version":"3.1.2","targets_input":1}}"#;
        let envelope: DalfoxJsonEnvelope =
            serde_json::from_str(json).expect("valid v3 JSON envelope");
        assert!(envelope.findings.is_empty());
        let meta = envelope.meta.expect("meta present");
        assert_eq!(meta["dalfox_version"], "3.1.2");
    }

    #[test]
    fn json_envelope_deserialize_discovery_params() {
        let json = r#"{"meta":{"dalfox_version":"3.1.2"},"params":[{"name":"q"}]}"#;
        let envelope: DalfoxJsonEnvelope =
            serde_json::from_str(json).expect("valid discovery envelope");
        assert!(envelope.findings.is_empty());
        let params = envelope.params.expect("params present");
        let arr = params.as_array().expect("params array");
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["name"], "q");
    }

    #[test]
    fn json_envelope_deserialize_findings_and_meta() {
        let json = r#"{
            "findings":[{"type":"V","poc":"http://example.com","method":"GET","param":"q","payload":"x","cwe":"CWE-79","severity":"High"}],
            "meta":{"dalfox_version":"3.1.2"}
        }"#;
        let envelope: DalfoxJsonEnvelope =
            serde_json::from_str(json).expect("valid envelope with findings");
        assert_eq!(envelope.findings.len(), 1);
        assert_eq!(envelope.findings[0].event_type, EventType::Verified);
    }

    #[test]
    fn event_type_ast_variant() {
        assert_eq!(
            serde_json::from_str::<EventType>("\"A\"").expect("ast"),
            EventType::Ast
        );
        assert_eq!(EventType::Ast.to_string(), "AST");
    }

    #[test]
    fn format_csv_header() {
        let result = DalfoxResult::default();
        let csv = result.format_as(OutputFormat::Csv);
        assert!(csv.starts_with(
            "severity,type,method,param,cwe,poc,payload,evidence,inject_type,location,message_str,type_description\n"
        ));
    }

    #[test]
    fn format_csv_includes_v3_fields() {
        let json = include_str!("../tests/fixtures/v3_verified_finding.json");
        let finding: DalfoxFinding = serde_json::from_str(json).expect("v3 finding");
        let result = DalfoxResult {
            findings: vec![finding],
            ..Default::default()
        };
        let csv = result.format_as(OutputFormat::Csv);
        assert!(csv.contains("inHTML"));
        assert!(csv.contains("Query"));
        assert!(csv.contains("Triggered XSS Payload"));
        assert!(csv.contains("Verified XSS - payload confirmed"));
    }

    #[test]
    fn format_markdown_poc_url_with_paren_not_truncated() {
        let finding = DalfoxFinding {
            event_type: EventType::Verified,
            poc: String::new(),
            method: Method::Get,
            data: "http://example.com/?q=alert(1)".to_string(),
            param: "q".to_string(),
            payload: "x".to_string(),
            evidence: String::new(),
            cwe: "CWE-79".to_string(),
            severity: Severity::High,
            inject_type: None,
            location: None,
            message_str: None,
            type_description: None,
        };
        let result = DalfoxResult {
            findings: vec![finding],
            ..Default::default()
        };
        let md = result.format_as(OutputFormat::Markdown);
        assert!(
            md.contains("[link](<http://example.com/?q=alert(1)>)"),
            "PoC URL with ) must use angle-bracket link target, got: {md}"
        );
        assert!(
            !md.contains("[link](http://example.com/?q=alert(1)"),
            "unescaped ) must not terminate the Markdown link early: {md}"
        );
    }

    #[test]
    fn md_link_target_escapes_angle_brackets_in_parens_url() {
        assert_eq!(md_link_target("http://x/?a=<b>"), "http://x/?a=<b>");
        assert_eq!(md_link_target("http://x/?a=(1)"), "<http://x/?a=(1)>");
    }

    #[test]
    fn format_plain_empty() {
        let result = DalfoxResult::default();
        let plain = result.format_as(OutputFormat::Plain);
        assert_eq!(plain, "No XSS findings detected.\n");
    }

    #[test]
    fn format_markdown_empty() {
        let result = DalfoxResult::default();
        let md = result.format_as(OutputFormat::Markdown);
        assert_eq!(md, "No findings.\n");
    }

    #[test]
    fn csv_escape_handles_commas_and_quotes() {
        assert_eq!(csv_escape("hello,world"), "\"hello,world\"");
        assert_eq!(csv_escape("say \"hi\""), "\"say \"\"hi\"\"\"");
        assert_eq!(csv_escape("simple"), "simple");
    }

    #[test]
    fn csv_escape_neutralizes_formula_injection() {
        assert_eq!(csv_escape("=cmd|' /C calc'!A0"), "'=cmd|' /C calc'!A0");
        assert_eq!(csv_escape("+1234"), "'+1234");
        assert_eq!(csv_escape("-1+2"), "'-1+2");
        assert_eq!(csv_escape("@SUM(A1)"), "'@SUM(A1)");
    }

    #[test]
    fn display_impls_are_readable() {
        assert_eq!(EventType::Verified.to_string(), "Verified");
        assert_eq!(Severity::High.to_string(), "High");
        assert_eq!(Method::Get.to_string(), "GET");
    }
}