use std::path::PathBuf;
use std::process::ExitCode;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use anyhow::Context;
use clap::Parser;
use website_vulnerability_scanner::advisories;
use website_vulnerability_scanner::application;
use website_vulnerability_scanner::checks::parse_header_pair;
use website_vulnerability_scanner::diff;
use website_vulnerability_scanner::fix_config::ServerKind;
#[cfg(feature = "gui")]
use website_vulnerability_scanner::gui;
use website_vulnerability_scanner::models::{
FailThreshold, ReportAudience, ScanConfig, ScanProfile,
};
use website_vulnerability_scanner::report::{html, json, markdown, sarif, terminal};
use website_vulnerability_scanner::rules;
use website_vulnerability_scanner::storage::{self, ProjectConfig};
#[derive(Debug, Parser)]
#[command(
name = "web-vuln-scanner",
version,
about = "Defensive website security & configuration scanner with GUI and CLI reports"
)]
struct Cli {
#[arg(value_name = "URL")]
targets: Vec<String>,
#[arg(long)]
gui: bool,
#[arg(long, value_enum, default_value_t = ScanProfile::Web)]
profile: ScanProfile,
#[arg(long, value_enum, default_value_t = ReportAudience::Developer)]
view: ReportAudience,
#[arg(long, value_name = "NAME_OR_PATH")]
project: Option<String>,
#[arg(long)]
save_run: bool,
#[arg(short = 'r', long = "rules", value_name = "PATH")]
rules_files: Vec<PathBuf>,
#[arg(long, value_name = "PATH_OR_URL")]
openapi: Option<String>,
#[arg(long, value_name = "PATH")]
advisories: Option<PathBuf>,
#[arg(short = 'H', long = "header", value_name = "NAME:VALUE")]
auth_headers: Vec<String>,
#[arg(long, value_name = "LABEL")]
auth_context: Option<String>,
#[arg(long, value_name = "PATH")]
baseline: Option<PathBuf>,
#[arg(long)]
fail_on_regression: bool,
#[arg(long, value_enum)]
fix_config: Option<ServerKind>,
#[arg(short, long, value_name = "PATH")]
file: Option<PathBuf>,
#[arg(long, value_name = "PATH")]
html: Option<PathBuf>,
#[arg(long, value_name = "PATH")]
json: Option<PathBuf>,
#[arg(long, value_name = "PATH")]
md: Option<PathBuf>,
#[arg(long, value_name = "PATH")]
sarif: Option<PathBuf>,
#[arg(long, default_value_t = 10)]
timeout: u64,
#[arg(long, default_value_t = 6)]
concurrency: usize,
#[arg(long, default_value_t = 10)]
max_pages: usize,
#[arg(long, default_value_t = 120)]
max_requests: usize,
#[arg(long)]
skip_paths: bool,
#[arg(long)]
skip_dns: bool,
#[arg(long)]
no_legacy_tls: bool,
#[arg(long)]
no_unauth_check: bool,
#[arg(long)]
hide_passes: bool,
#[arg(long)]
no_color: bool,
#[arg(long, value_enum)]
fail_on: Option<FailThreshold>,
}
async fn run_cli(cli: Cli) -> anyhow::Result<ExitCode> {
if cli.no_color {
colored::control::set_override(false);
}
let mut project_cfg: Option<ProjectConfig> = None;
let mut project_name = "default".to_string();
if let Some(proj_arg) = &cli.project {
let p = PathBuf::from(proj_arg);
if proj_arg.ends_with(".json") || p.exists() {
let loaded = ProjectConfig::load_from(&p)
.with_context(|| format!("failed to load project file: {}", p.display()))?;
project_name = loaded.name.clone();
project_cfg = Some(loaded);
} else {
project_name = proj_arg.clone();
}
}
let mut targets = cli.targets;
if let Some(file_path) = &cli.file {
let content = std::fs::read_to_string(file_path)
.with_context(|| format!("failed to read targets file: {}", file_path.display()))?;
for line in content.lines() {
let trimmed = line.trim();
if !trimmed.is_empty() && !trimmed.starts_with('#') {
targets.push(trimmed.to_string());
}
}
}
if targets.is_empty() {
if let Some(cfg) = &project_cfg {
targets.extend(cfg.targets.clone());
}
}
if targets.is_empty() {
anyhow::bail!(
"No targets specified. Pass a URL (e.g. `web-vuln-scanner https://example.com`), `--file targets.txt`, `--project scanner-project.json`, or `--gui`."
);
}
let mut rule_paths = cli.rules_files.clone();
if let Some(cfg) = &project_cfg {
if let Some(rf) = &cfg.rules_file {
let rp = PathBuf::from(rf);
if !rule_paths.contains(&rp) {
rule_paths.push(rp);
}
}
}
let custom_rules = if rule_paths.is_empty() {
Vec::new()
} else {
rules::load_rules_from_paths(&rule_paths)
.context("failed to load custom JSON rules database")?
};
let adv_path_opt = cli.advisories.clone().or_else(|| {
project_cfg
.as_ref()
.and_then(|c| c.advisories_path.as_ref().map(PathBuf::from))
});
let custom_advisories = if let Some(ap) = adv_path_opt {
advisories::load_advisories_pack(&ap)
.context("failed to load custom JSON advisories pack")?
} else {
Vec::new()
};
let mut parsed_headers = Vec::with_capacity(cli.auth_headers.len());
for raw_hdr in &cli.auth_headers {
parsed_headers.push(parse_header_pair(raw_hdr)?);
}
let baseline_report =
if let Some(base_path) = &cli.baseline {
Some(diff::load_baseline(base_path).with_context(|| {
format!("failed to load baseline JSON: {}", base_path.display())
})?)
} else {
None
};
let auth_context = cli.auth_context.unwrap_or_else(|| {
if let Some(cfg) = &project_cfg {
cfg.auth_context.clone()
} else if parsed_headers.is_empty() {
"anonymous".to_string()
} else {
"custom-headers".to_string()
}
});
let config = if let Some(cfg) = &project_cfg {
let mut sc = cfg.to_scan_config(custom_rules, parsed_headers);
sc.auth_context = auth_context;
sc.custom_advisories = custom_advisories;
if let Some(oa) = &cli.openapi {
sc.openapi_path = Some(oa.clone());
}
if cli.max_requests != 120 {
sc.max_requests = cli.max_requests.max(1);
}
if cli.skip_paths {
sc.skip_paths = true;
}
if cli.skip_dns {
sc.skip_dns = true;
}
if cli.no_legacy_tls {
sc.check_legacy_tls = false;
}
if cli.no_unauth_check {
sc.check_unauth_access = false;
}
sc
} else {
ScanConfig {
timeout_secs: cli.timeout.max(1),
concurrency: cli.concurrency.max(1),
max_pages: cli.max_pages.max(1),
max_requests: cli.max_requests.max(1),
profile: cli.profile,
skip_paths: cli.skip_paths,
skip_dns: cli.skip_dns,
auth_context,
openapi_path: cli.openapi.clone(),
custom_rules,
custom_advisories,
auth_headers: parsed_headers,
check_legacy_tls: !cli.no_legacy_tls,
check_unauth_access: !cli.no_unauth_check,
..ScanConfig::default()
}
};
let cancel_flag = Arc::new(AtomicBool::new(false));
let multi = application::run_multi_scan(&targets, &config, cancel_flag, None).await;
let report_diff = baseline_report
.as_ref()
.map(|base| diff::compare_reports(base, &multi));
terminal::print_terminal_report(
&multi,
!cli.hide_passes,
report_diff.as_ref(),
cli.fix_config,
cli.view,
);
if cli.save_run {
let data_dir = storage::default_data_dir();
let rec = storage::save_run(&data_dir, &project_name, &multi)
.context("failed to persist scan run")?;
println!(
"Saved run '{}' for project '{}' in {}",
rec.run_id,
rec.project,
data_dir.display()
);
}
if let Some(path) = &cli.html {
let rendered = html::render_html_for_view(&multi, cli.view, report_diff.as_ref());
std::fs::write(path, rendered)
.with_context(|| format!("failed to write HTML report to {}", path.display()))?;
println!("HTML report saved: {}", path.display());
}
if let Some(path) = &cli.json {
let rendered = json::render_json(&multi)?;
std::fs::write(path, rendered)
.with_context(|| format!("failed to write JSON report to {}", path.display()))?;
println!("JSON report saved: {}", path.display());
}
if let Some(path) = &cli.md {
let rendered = markdown::render_markdown_for_view(&multi, cli.view, report_diff.as_ref());
std::fs::write(path, rendered)
.with_context(|| format!("failed to write Markdown report to {}", path.display()))?;
println!("Markdown report saved: {}", path.display());
}
if let Some(path) = &cli.sarif {
let rendered = sarif::render_sarif(&multi)?;
std::fs::write(path, rendered)
.with_context(|| format!("failed to write SARIF report to {}", path.display()))?;
println!("SARIF report saved: {}", path.display());
}
if cli.fail_on_regression {
if let Some(d) = &report_diff {
if d.has_new_regressions() {
return Ok(ExitCode::from(2));
}
}
}
if let Some(threshold) = cli.fail_on {
let breached = multi
.reports
.iter()
.flat_map(|r| r.findings.iter())
.any(|f| threshold.matches(f.severity));
if breached {
return Ok(ExitCode::from(2));
}
}
Ok(ExitCode::SUCCESS)
}
#[cfg(feature = "gui")]
fn launch_native_gui(initial: Option<String>) -> ExitCode {
if let Err(err) = gui::launch_gui(initial) {
eprintln!("{err}");
return ExitCode::FAILURE;
}
ExitCode::SUCCESS
}
#[cfg(not(feature = "gui"))]
fn launch_native_gui(_initial: Option<String>) -> ExitCode {
eprintln!(
"Error: This binary was compiled without GUI support (headless `--no-default-features` build). Pass a target URL or `--help`."
);
ExitCode::FAILURE
}
fn main() -> ExitCode {
#[cfg(windows)]
{
let _ = colored::control::set_virtual_terminal(true);
}
let args: Vec<std::ffi::OsString> = std::env::args_os().collect();
if args.len() <= 1 {
return launch_native_gui(None);
}
let cli = Cli::parse();
if cli.gui {
let initial = if cli.targets.is_empty() {
None
} else {
Some(cli.targets.join(", "))
};
return launch_native_gui(initial);
}
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("Failed to initialize Tokio runtime");
match rt.block_on(run_cli(cli)) {
Ok(code) => code,
Err(err) => {
eprintln!("Error: {err:#}");
ExitCode::FAILURE
}
}
}