From 7fd79e4ebcf1aa92ab9a22c0802ae5ee223f1697 Mon Sep 17 00:00:00 2001 From: CyberSecurityUP Date: Sat, 14 Nov 2026 12:17:46 -0300 Subject: [PATCH] feat(harness,web): Artex-inspired adaptive autonomy engine MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five new modules for adaptive, self-directed exploitation: - adaptive.rs: payload mutation engine — tech-stack-aware generation, WAF bypass evolution, response-driven mutation, per-engagement journal - request_analyzer.rs: HTTP response intelligence — reflection detection with context-aware XSS suggestions, error fingerprinting, differential analysis (baseline vs attack), parameter discovery, auth context - exploration_graph.rs: dual-graph architecture — global asset graph + per-engagement exploration graph with causality edges and bidirectional anchors driving a live coverage map - planner.rs: reactive event-driven planner — coverage-driven, fact-driven, chain-driven, hint-driven intent generation with persistent todolist and dependency sequencing - noise_governor.rs: adaptive rate control — per-host throttling, 429/503 exponential backoff, request caching/dedup, stealth mode Integration: - pipeline.rs injects adaptive context into agent prompts - RECON_SYS enhanced with dnsgen, favicon hash, waymore techniques - Web UI: new Adaptive tab with live dashboard for all subsystems - Server: parses adaptive_json/graph_json/planner_json/noise_json events --- neurosploit-rs/crates/harness/src/adaptive.rs | 842 ++++++++++++++ .../crates/harness/src/exploration_graph.rs | 548 +++++++++ neurosploit-rs/crates/harness/src/lib.rs | 12 +- .../crates/harness/src/noise_governor.rs | 485 ++++++++ neurosploit-rs/crates/harness/src/pipeline.rs | 26 + neurosploit-rs/crates/harness/src/planner.rs | 580 ++++++++++ .../crates/harness/src/request_analyzer.rs | 1001 +++++++++++++++++ web/public/app.js | 531 ++++++++- web/public/index.html | 274 +++-- web/public/style.css | 492 ++++++-- web/server.js | 49 +- 11 files changed, 4650 insertions(+), 190 deletions(-) create mode 100644 neurosploit-rs/crates/harness/src/adaptive.rs create mode 100644 neurosploit-rs/crates/harness/src/exploration_graph.rs create mode 100644 neurosploit-rs/crates/harness/src/noise_governor.rs create mode 100644 neurosploit-rs/crates/harness/src/planner.rs create mode 100644 neurosploit-rs/crates/harness/src/request_analyzer.rs diff --git a/neurosploit-rs/crates/harness/src/adaptive.rs b/neurosploit-rs/crates/harness/src/adaptive.rs new file mode 100644 index 0000000..f714ffa --- /dev/null +++ b/neurosploit-rs/crates/harness/src/adaptive.rs @@ -0,0 +1,842 @@ +//! Adaptive Payload Engine — context-aware payload generation and mutation. +//! +//! Static payloads fail against modern targets: WAFs learn signatures, frameworks +//! sanitize known patterns, and every target has a unique parser stack. This +//! engine generates payloads that adapt to: +//! +//! 1. **Target stack** — technology, framework, version detected during recon +//! 2. **WAF behavior** — what got blocked, what encoding bypassed it +//! 3. **Response patterns** — how the target reacts to different inputs +//! 4. **Failed attempts** — payloads that didn't work inform the next mutation +//! +//! The engine maintains a per-engagement payload journal that records what was +//! tried, what worked, and what was blocked — so every subsequent agent benefits +//! from earlier agents' discoveries. + +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; + +/// A payload with its generation context and outcome. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PayloadRecord { + pub payload: String, + pub class: String, + pub target_param: String, + pub encoding: Encoding, + pub outcome: Outcome, + pub waf_response: Option, + pub response_code: u16, + pub response_len: usize, + pub timestamp: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Outcome { + /// Payload reached the application and triggered the vulnerability. + Triggered, + /// Payload reached the application but did not trigger. + Reached, + /// WAF blocked before the application saw it. + WafBlocked, + /// Target returned an error unrelated to the payload. + Error, + /// Not yet tested. + Pending, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Encoding { + None, + UrlEncode, + DoubleUrlEncode, + HtmlEntity, + UnicodeNormalize, + Base64, + HexEncode, + Utf7, + ChunkedTransfer, + NullByte, + CommentInjection, + CaseToggle, + Concatenation, +} + +impl Encoding { + pub fn all() -> &'static [Encoding] { + &[ + Encoding::None, Encoding::UrlEncode, Encoding::DoubleUrlEncode, + Encoding::HtmlEntity, Encoding::UnicodeNormalize, Encoding::Base64, + Encoding::HexEncode, Encoding::NullByte, Encoding::CommentInjection, + Encoding::CaseToggle, Encoding::Concatenation, + ] + } + + pub fn apply(&self, input: &str) -> String { + match self { + Encoding::None => input.to_string(), + Encoding::UrlEncode => url_encode(input), + Encoding::DoubleUrlEncode => url_encode(&url_encode(input)), + Encoding::HtmlEntity => html_entity_encode(input), + Encoding::UnicodeNormalize => unicode_normalize(input), + Encoding::Base64 => { + use base64::Engine; + base64::engine::general_purpose::STANDARD.encode(input) + } + Encoding::HexEncode => hex_encode(input), + Encoding::NullByte => format!("{input}\x00"), + Encoding::CommentInjection => inject_comments(input), + Encoding::CaseToggle => toggle_case(input), + Encoding::Concatenation => concatenate_split(input), + _ => input.to_string(), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct WafResponse { + pub vendor: String, + pub status: u16, + pub blocked_pattern: String, +} + +/// Technology-aware payload templates per vulnerability class. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PayloadTemplate { + pub class: String, + pub base_payloads: Vec, + pub stack_variants: HashMap>, +} + +/// The adaptive engine: accumulates knowledge per engagement and generates +/// context-aware payloads. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct AdaptiveEngine { + pub journal: Vec, + pub stack: TargetStack, + pub waf_profile: WafProfile, + pub param_profiles: HashMap, +} + +/// What we know about the target's technology. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct TargetStack { + pub server: String, + pub framework: String, + pub language: String, + pub database: String, + pub waf: String, + pub cdn: String, + pub versions: HashMap, + pub custom_headers: Vec, +} + +/// Behavioral profile of a WAF built from observed responses. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct WafProfile { + pub vendor: String, + pub blocked_keywords: Vec, + pub allowed_encodings: Vec, + pub block_status: u16, + pub block_body_pattern: String, + pub rate_limit_threshold: Option, + pub challenge_type: Option, +} + +/// What we know about a specific parameter from probing it. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct ParamProfile { + pub name: String, + pub location: ParamLocation, + pub reflected: bool, + pub filtered_chars: Vec, + pub max_length: Option, + pub content_type: String, + pub escape_context: EscapeContext, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ParamLocation { + #[default] + Query, + Body, + Header, + Cookie, + Path, + Json, + Xml, + Multipart, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum EscapeContext { + #[default] + Unknown, + HtmlBody, + HtmlAttribute, + HtmlAttributeUnquoted, + JavaScript, + JsonValue, + SqlString, + SqlNumeric, + UrlPath, + CssValue, + XmlCdata, +} + +impl AdaptiveEngine { + pub fn new() -> Self { + Self::default() + } + + /// Record a payload attempt and its outcome. + pub fn record(&mut self, record: PayloadRecord) { + if record.outcome == Outcome::WafBlocked { + if let Some(ref waf) = record.waf_response { + if !self.waf_profile.blocked_keywords.iter().any(|k| record.payload.contains(k)) { + self.waf_profile.blocked_keywords.push(extract_trigger(&record.payload)); + } + self.waf_profile.vendor = waf.vendor.clone(); + self.waf_profile.block_status = waf.status; + } + } + if record.outcome == Outcome::Triggered { + let enc = record.encoding; + if !self.waf_profile.allowed_encodings.contains(&enc) { + self.waf_profile.allowed_encodings.push(enc); + } + } + self.journal.push(record); + } + + /// Update the target stack from recon data. + pub fn ingest_recon(&mut self, recon: &serde_json::Value) { + if let Some(s) = recon.get("tech").and_then(|v| v.as_str()) { + self.stack.server = s.to_string(); + } + if let Some(v) = recon.get("versions").and_then(|v| v.as_object()) { + for (k, val) in v { + if let Some(s) = val.as_str() { + self.stack.versions.insert(k.clone(), s.to_string()); + } + } + } + if let Some(fw) = recon.get("framework").and_then(|v| v.as_str()) { + self.stack.framework = fw.to_string(); + } + if let Some(lang) = recon.get("language").and_then(|v| v.as_str()) { + self.stack.language = lang.to_string(); + } + if let Some(db) = recon.get("database").and_then(|v| v.as_str()) { + self.stack.database = db.to_string(); + } + } + + /// Update a parameter's profile from probing results. + pub fn profile_param(&mut self, name: &str, profile: ParamProfile) { + self.param_profiles.insert(name.to_string(), profile); + } + + /// Generate adapted payloads for a vulnerability class and parameter. + pub fn generate(&self, class: &str, param: Option<&str>) -> Vec { + let base = base_payloads(class); + let stack_variants = stack_specific_payloads(class, &self.stack); + let mut results = Vec::new(); + + let profile = param.and_then(|p| self.param_profiles.get(p)); + let tried: std::collections::HashSet = self.journal.iter() + .filter(|r| r.class == class) + .map(|r| r.payload.clone()) + .collect(); + + let successful_encodings = &self.waf_profile.allowed_encodings; + let blocked_keywords = &self.waf_profile.blocked_keywords; + + for payload in base.iter().chain(stack_variants.iter()) { + if tried.contains(payload.as_str()) { + continue; + } + + let needs_bypass = blocked_keywords.iter().any(|kw| payload.contains(kw)); + + if needs_bypass { + for enc in bypass_encodings(blocked_keywords, successful_encodings) { + let mutated = enc.apply(payload); + if !tried.contains(&mutated) { + results.push(AdaptivePayload { + payload: mutated, + encoding: enc, + rationale: format!("WAF bypass: {enc:?} avoids blocked pattern"), + priority: priority_score(class, &enc, profile, true), + }); + } + } + } else { + let adapted = adapt_to_context(payload, profile); + results.push(AdaptivePayload { + payload: adapted, + encoding: Encoding::None, + rationale: context_rationale(class, profile), + priority: priority_score(class, &Encoding::None, profile, false), + }); + } + } + + // Mutation-based payloads from successful attempts in the journal + for rec in self.journal.iter().filter(|r| r.outcome == Outcome::Triggered && r.class == class) { + for mutation in mutate_payload(&rec.payload, class) { + if !tried.contains(&mutation) { + results.push(AdaptivePayload { + payload: mutation, + encoding: rec.encoding, + rationale: "Mutation of previously successful payload".into(), + priority: 90, + }); + } + } + } + + results.sort_by(|a, b| b.priority.cmp(&a.priority)); + results.truncate(50); + results + } + + /// Generate the prompt block that injects adaptive context into agent prompts. + pub fn prompt_block(&self) -> String { + if self.journal.is_empty() && self.stack.server.is_empty() { + return String::new(); + } + + let mut s = String::from("\nADAPTIVE PAYLOAD INTELLIGENCE:\n"); + + if !self.stack.server.is_empty() || !self.stack.framework.is_empty() { + s.push_str(&format!("Target stack: server={} framework={} lang={} db={}\n", + self.stack.server, self.stack.framework, self.stack.language, self.stack.database)); + } + + if !self.waf_profile.vendor.is_empty() { + s.push_str(&format!("WAF detected: {} (blocks on status {})\n", + self.waf_profile.vendor, self.waf_profile.block_status)); + if !self.waf_profile.blocked_keywords.is_empty() { + let kws: Vec<&str> = self.waf_profile.blocked_keywords.iter() + .take(20).map(|s| s.as_str()).collect(); + s.push_str(&format!("Blocked patterns: {}\n", kws.join(", "))); + } + if !self.waf_profile.allowed_encodings.is_empty() { + let encs: Vec = self.waf_profile.allowed_encodings.iter() + .map(|e| format!("{e:?}")).collect(); + s.push_str(&format!("Successful bypass encodings: {}\n", encs.join(", "))); + } + } + + let triggered: Vec<&PayloadRecord> = self.journal.iter() + .filter(|r| r.outcome == Outcome::Triggered).collect(); + if !triggered.is_empty() { + s.push_str(&format!("Successful payloads so far: {} (use these as basis for mutations)\n", triggered.len())); + for rec in triggered.iter().take(10) { + s.push_str(&format!(" [{class}] {payload} ({enc:?})\n", + class = rec.class, + payload = &rec.payload[..rec.payload.len().min(120)], + enc = rec.encoding)); + } + } + + let blocked_count = self.journal.iter().filter(|r| r.outcome == Outcome::WafBlocked).count(); + if blocked_count > 0 { + s.push_str(&format!("WAF blocks observed: {} — adapt payloads using bypass encodings above\n", blocked_count)); + } + + for (name, prof) in &self.param_profiles { + if prof.reflected || !prof.filtered_chars.is_empty() { + s.push_str(&format!("Param '{name}': reflected={} filtered={:?} context={:?}\n", + prof.reflected, prof.filtered_chars, prof.escape_context)); + } + } + + s.push('\n'); + s + } + + /// Serialize to JSON for persistence between phases. + pub fn save(&self, path: &std::path::Path) -> std::io::Result<()> { + let json = serde_json::to_string_pretty(self) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?; + std::fs::write(path, json) + } + + /// Load from a previous phase's persisted state. + pub fn load(path: &std::path::Path) -> std::io::Result { + let json = std::fs::read_to_string(path)?; + serde_json::from_str(&json) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)) + } +} + +/// A generated payload with context about why it was chosen. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AdaptivePayload { + pub payload: String, + pub encoding: Encoding, + pub rationale: String, + pub priority: u32, +} + +// ── Internal helpers ── + +fn base_payloads(class: &str) -> Vec { + match class.to_uppercase().as_str() { + s if s.contains("XSS") || s.contains("CWE-79") => vec![ + "", + "", + "", + "javascript:alert(1)", + "
", + "\">
", + "'-alert(1)-'", + "
`) + .join(''); + const legend = ['critical', 'high', 'medium', 'low', 'info'] + .filter(s => counts[s] > 0) + .map(s => `${counts[s]} ${s}`) + .join(''); + targetEl.innerHTML = `
${segs}
${legend}
`; + targetEl.hidden = false; +} function show(el, on) { if (el) el.hidden = !on; } // Failures used to surface through `alert()`, which blocks the page and hides @@ -102,7 +125,7 @@ function clearFieldErrors() { $$('.field-error').forEach((el) => { el.textConten // view navigation // --------------------------------------------------------------------------- -const ALL_VIEWS = ['dashView','wizardView','liveView','detailView','pentestsView','prreviewsView','issuesView','reposView','domainsView','networksView','vaultView','guardrailsView','integrationsView','settingsView']; +const ALL_VIEWS = ['homeView','dashView','wizardView','liveView','detailView','pentestsView','prreviewsView','issuesView','reposView','domainsView','networksView','vaultView','guardrailsView','integrationsView','settingsView']; function switchView(viewName) { state.activeView = viewName; @@ -125,6 +148,7 @@ function switchView(viewName) { if (viewName === 'vault') loadVault(); if (viewName === 'guardrails') loadGuardrails(); if (viewName === 'dash') renderDashboard(); + if (viewName === 'home') renderHome(); } function timeAgo(ts) { @@ -146,8 +170,10 @@ function timeAgo(ts) { function applyTheme() { document.documentElement.setAttribute('data-theme', state.theme); - $('#btnThemeToggle').textContent = state.theme === 'dark' ? '☀' : '☾'; - $('#btnThemeToggle').title = state.theme === 'dark' ? 'Switch to light theme' : 'Switch to dark theme'; + $('#btnThemeToggle').innerHTML = state.theme === 'dark' ? '' : ''; + const themeLabel = state.theme === 'dark' ? 'Switch to light theme' : 'Switch to dark theme'; + $('#btnThemeToggle').title = themeLabel; + $('#btnThemeToggle').setAttribute('aria-label', themeLabel); // xterm paints into a canvas and doesn't inherit CSS variables — it has to // be told the palette changed. if (term.xterm) term.xterm.options.theme = termColors(); @@ -732,6 +758,8 @@ function bindRunTabs(scopeEl) { bindRunTabs($('#liveView')); bindRunTabs($('#detailView')); +$('#coverageSearch')?.addEventListener('input', () => renderCoverageTab()); + const ACTIVE_JOB_KEY = 'ns-active-job'; function attachLiveJob(id, target, name, pinnedAgents) { @@ -773,6 +801,10 @@ function attachLiveJob(id, target, name, pinnedAgents) { es.addEventListener('log', (e) => appendLog(JSON.parse(e.data).line)); es.addEventListener('finding', (e) => addFinding(JSON.parse(e.data).finding)); es.addEventListener('agent', (e) => { const a = JSON.parse(e.data); if (state.currentJob) { (state.currentJob.agentStatus ||= {})[a.name] = { status: a.status, found: a.found || 0 }; renderAgentPanel(state.currentJob.agentStatus); } }); + es.addEventListener('adaptive', (e) => updateAdaptiveTab(JSON.parse(e.data))); + es.addEventListener('graph', (e) => updateGraphTab(JSON.parse(e.data))); + es.addEventListener('planner', (e) => updatePlannerTab(JSON.parse(e.data))); + es.addEventListener('noise', (e) => updateNoiseTab(JSON.parse(e.data))); es.addEventListener('snapshot', (e) => applySnapshot(JSON.parse(e.data))); es.addEventListener('done', (e) => { applySnapshot(JSON.parse(e.data)); @@ -852,9 +884,9 @@ function appendLog(line) { const list = $('#logList'); list.appendChild(div); list.scrollTop = list.scrollHeight; - // When the terminal is attached to this engagement it is the same stream — - // mirror it there so the operator types and reads in one place. if (term.mode === 'job' && term.xterm) termWrite(line + '\r\n'); + const dot = $('#activityTabDot'); + if (dot) { dot.classList.add('live'); clearTimeout(dot._t); dot._t = setTimeout(() => dot.classList.remove('live'), 3000); } } // Only run/whitebox/greybox jobs are REPL-backed (interactive: true) — the @@ -1014,6 +1046,89 @@ bindFindingTableClicks('#detailFindingsTable tbody', () => state.detailFindings function addFinding(f) { state.currentJob.findings.push(f); renderFindings('live'); + renderCoverageTab(); + renderSevProgressBar($('#liveSevBar'), state.currentJob?.findings); +} + +function renderCoverageTab() { + const list = $('#coverageList'); + const stats = $('#coverageStats'); + const empty = $('#coverageEmpty'); + const search = $('#coverageSearch'); + if (!list) return; + const findings = state.currentJob?.findings || []; + const endpoints = new Map(); + for (const f of findings) { + const ep = (f.endpoint || '').trim(); + if (!ep) continue; + const atk = f.evidence_data?.attack; + const method = (atk?.method || f.method || 'GET').toUpperCase(); + const status = atk?.status || 0; + const key = `${method} ${ep}`; + if (!endpoints.has(key)) { + endpoints.set(key, { method, path: ep, status, findings: [], severities: new Set() }); + } + const entry = endpoints.get(key); + entry.findings.push(f); + entry.severities.add(f.severity); + } + const agentStatus = state.currentJob?.agentStatus || {}; + const agentNames = Object.keys(agentStatus); + const tested = endpoints.size; + const withFindings = [...endpoints.values()].filter(e => e.findings.length > 0).length; + + if (!tested && !agentNames.length) { list.innerHTML = ''; if (empty) empty.hidden = false; return; } + if (empty) empty.hidden = true; + + if (stats) { + stats.innerHTML = ` +
Endpoints${tested}
+
With findings${withFindings}
+
Clean${tested - withFindings}
+ `; + } + + const pillsEl = $('#coveragePills'); + if (pillsEl) { + const all = [...endpoints.values()]; + const reported = all.filter(e => e.findings.length > 0).length; + const clean = all.filter(e => e.findings.length === 0).length; + pillsEl.innerHTML = ` + + + + ${reported + clean} of ${tested} checked + `; + $$('.cv-pill', pillsEl).forEach(pill => { + pill.addEventListener('click', () => { + $$('.cv-pill', pillsEl).forEach(p => p.classList.remove('active')); + pill.classList.add('active'); + state.coverageFilter = pill.dataset.cvFilter || ''; + renderCoverageTab(); + }); + }); + } + + const q = (search?.value || '').toLowerCase(); + let rows = [...endpoints.values()]; + const cvFilter = state.coverageFilter || ''; + if (cvFilter === 'reported') rows = rows.filter(e => e.findings.length > 0); + else if (cvFilter === 'clean') rows = rows.filter(e => e.findings.length === 0); + if (q) rows = rows.filter(e => `${e.method} ${e.path}`.toLowerCase().includes(q)); + rows.sort((a, b) => b.findings.length - a.findings.length || a.path.localeCompare(b.path)); + + list.innerHTML = rows.map(e => { + const badge = e.findings.length ? 'found' : 'tested'; + const statusCls = e.status >= 500 ? 's-5' : e.status >= 400 ? 's-4' : e.status >= 300 ? 's-3' : e.status >= 200 ? 's-2' : ''; + return `
+ ${esc(e.method)} + ${esc(e.path)} + ${e.status ? `${e.status}` : ''} + ${e.findings.length ? `${e.findings.length} finding(s)` : 'tested'} +
`; + }).join(''); + const dot = $('#coverageTabDot'); + if (dot) dot.classList.toggle('live', rows.some(e => e.findings.length > 0)); } // Live "what's being tested" grid: one chip per agent, coloured by status. @@ -1024,7 +1139,6 @@ function renderAgentPanel(statusMap) { const entries = Object.entries(statusMap || {}); if (!entries.length) { panel.hidden = true; return; } panel.hidden = false; - // Order: running first, then found, then pending, then done, then failed. const rank = (s, found) => s === 'running' ? 0 : (s === 'done' && found > 0) ? 1 : s === 'pending' ? 2 : s === 'done' ? 3 : 4; entries.sort((a, b) => rank(a[1].status, a[1].found) - rank(b[1].status, b[1].found) || a[0].localeCompare(b[0])); const cls = (s, found) => s === 'running' ? 'running' : s === 'failed' ? 'failed' : (s === 'done' && found > 0) ? 'found' : s === 'done' ? 'done' : 'pending'; @@ -1033,6 +1147,46 @@ function renderAgentPanel(statusMap) { const done = entries.filter(([, s]) => s.status === 'done' || s.status === 'failed').length; const run = entries.filter(([, s]) => s.status === 'running').length; $('#agentPanel .agent-panel-head > span').textContent = `What's being tested — ${run} running · ${done}/${entries.length} done`; + renderAgentsTab(statusMap); + const countEl = $('#liveAgentsCount'); + if (countEl) countEl.textContent = entries.length; + const dot = $('#agentsTabDot'); + if (dot) dot.classList.toggle('live', run > 0); +} + +function renderAgentsTab(statusMap) { + const grid = $('#agentsTabGrid'); + const stats = $('#agentsTabStats'); + const empty = $('#agentsTabEmpty'); + if (!grid) return; + const entries = Object.entries(statusMap || {}); + if (!entries.length) { grid.innerHTML = ''; if (empty) empty.hidden = false; return; } + if (empty) empty.hidden = true; + const rank = (s, found) => s === 'running' ? 0 : (s === 'done' && found > 0) ? 1 : s === 'pending' ? 2 : s === 'done' ? 3 : 4; + entries.sort((a, b) => rank(a[1].status, a[1].found) - rank(b[1].status, b[1].found) || a[0].localeCompare(b[0])); + const cls = (s, found) => s === 'running' ? 'running' : s === 'failed' ? 'failed' : (s === 'done' && found > 0) ? 'found' : s === 'done' ? 'done' : 'pending'; + const running = entries.filter(([, s]) => s.status === 'running').length; + const done = entries.filter(([, s]) => s.status === 'done' || s.status === 'failed').length; + const found = entries.reduce((a, [, s]) => a + (s.found || 0), 0); + const failed = entries.filter(([, s]) => s.status === 'failed').length; + if (stats) { + stats.innerHTML = ` +
Total${entries.length}
+
Running${running}
+
Done${done}
+
Findings${found}
+ ${failed ? `
Errors${failed}
` : ''} + `; + } + grid.innerHTML = entries.map(([name, st]) => { + const c = cls(st.status, st.found); + return `
+ + ${esc(name)} + ${esc(st.status)} + ${st.found ? `${st.found}` : ''} +
`; + }).join(''); } function applySnapshot(snap) { @@ -1196,15 +1350,43 @@ function openFindingModal(f, pocs, runId) { $('#fmSev').textContent = f.severity || 'info'; $('#fmTitle').textContent = f.title || '(untitled finding)'; - const meta = [ - ['CWE', f.cwe], ['CVSS', f.cvss], ['OWASP', f.owasp], ['MITRE', f.mitre], - ['Stage', f.stage], ['Exploitability', f.exploitability], - ['Confidence', f.confidence ? f.confidence.toFixed(2) : ''], ['Votes', f.votes], - ['Review status', f.review_status], ['Auth context', f.auth_context], - ['Account', f.account], ['Agent', f.agent], + const cvssRaw = String(f.cvss || ''); + const cvssScore = cvssRaw.match(/[\d.]+/)?.[0] || ''; + const cvssVector = cvssRaw.match(/\(CVSS[^)]*\)/)?.[0] || ''; + const cvssVal = parseFloat(cvssScore) || 0; + const cvssClass = cvssVal >= 7 ? 'fm-cvss-high' : cvssVal >= 4 ? 'fm-cvss-med' : 'fm-cvss-low'; + const method = (f.evidence_data?.attack?.method || f.method || '').toUpperCase(); + const endpoint = f.endpoint || ''; + const endpointHtml = endpoint + ? `
${method ? `${esc(method)}` : ''}${esc(endpoint)}
` + : '—'; + const cvssHtml = cvssScore + ? `${esc(cvssScore)}${cvssVector ? `${esc(cvssVector)}` : ''}` + : '—'; + const metaCells = [ + { label: 'CVSS', value: cvssHtml, raw: true }, + { label: 'CWE', value: f.cwe }, + { label: 'Endpoint', value: endpointHtml, raw: true }, + { label: 'Confidence', value: f.confidence ? f.confidence.toFixed(2) : '' }, + { label: 'Stage', value: f.stage }, + { label: 'Review status', value: f.review_status }, + { label: 'Agent', value: f.agent }, + { label: 'Votes', value: f.votes }, ]; - $('#fmMeta').innerHTML = meta.map(([k, v]) => - `
${esc(k)}
${esc(v || '—')}
`).join(''); + $('#fmMeta').innerHTML = metaCells.map(c => + `
${esc(c.label)}
${c.raw ? c.value : `${esc(c.value || '—')}`}
`).join(''); + + const actionsEl = $('#fmActions'); + if (actionsEl) { + actionsEl.innerHTML = ` + + + `; + actionsEl.querySelector('[data-action="copy-md"]')?.addEventListener('click', () => { + const md = `## ${f.severity} — ${f.title}\n\n**CVSS:** ${cvssScore || '—'} ${cvssVector} | **CWE:** ${f.cwe || '—'}\n**Endpoint:** ${method} ${endpoint}\n\n${f.impact || f.evidence || ''}\n\n### Remediation\n${f.remediation || '—'}`; + navigator.clipboard.writeText(md).then(() => toast('Finding copied as Markdown')); + }); + } // The report footer ("Identified and validated by NeuroSploit...") gets // baked into impact/business_impact by the reporter — strip it from every @@ -1815,6 +1997,18 @@ async function loadDetail(id) { reportLink.href = `/api/runs/${encodeURIComponent(id)}/asset/report.html`; show(reportLink, true); } else show(reportLink, false); + const reportNav = $('#detailReportNav'); + if (reportNav) { + if (detail.assets.includes('report.html')) { + const reportUrl = `/api/runs/${encodeURIComponent(id)}/asset/report.html`; + reportNav.innerHTML = `
Report sections
+ Executive summary + Technical analysis + Methodology + Recommendations`; + reportNav.hidden = false; + } else { reportNav.hidden = true; } + } // The PDF is produced by the harness (Typst) when that binary is present, so // it is offered only when it actually exists — a dead download button is // worse than none. @@ -1832,10 +2026,97 @@ async function loadDetail(id) { show(pdfLink, true); } else show(pdfLink, false); afterDetailLoaded(id, detail); + renderDetailAgents(detail); + renderDetailCoverage(detail); + renderSevProgressBar($('#detailSevBar'), detail.findings); if (token !== state.detailToken) return; if (detail.status?.state === 'running') state.detailPoll = setInterval(() => loadDetail(id), 4000); } +function renderDetailAgents(detail) { + const grid = $('#detailAgentsGrid'); + const stats = $('#detailAgentsStats'); + const empty = $('#detailAgentsEmpty'); + const countEl = $('#detailAgentsCount'); + if (!grid) return; + const agentMap = {}; + for (const f of (detail.findings || [])) { + const name = f.agent || 'unknown'; + if (!agentMap[name]) agentMap[name] = { status: 'done', found: 0 }; + agentMap[name].found++; + } + const totalRan = detail.status?.agents_ran || Object.keys(agentMap).length; + if (countEl) countEl.textContent = totalRan; + const entries = Object.entries(agentMap); + if (!entries.length) { grid.innerHTML = ''; if (empty) empty.hidden = false; return; } + if (empty) empty.hidden = true; + entries.sort((a, b) => b[1].found - a[1].found || a[0].localeCompare(b[0])); + if (stats) { + stats.innerHTML = ` +
Total ran${totalRan}
+
With findings${entries.filter(([,s]) => s.found > 0).length}
+
Total findings${entries.reduce((a,[,s]) => a + s.found, 0)}
+ `; + } + grid.innerHTML = entries.map(([name, st]) => + `
+ + ${esc(name)} + done + ${st.found ? `${st.found}` : ''} +
` + ).join(''); +} + +function renderDetailCoverage(detail) { + const list = $('#detailCoverageList'); + const stats = $('#detailCoverageStats'); + const empty = $('#detailCoverageEmpty'); + const search = $('#detailCoverageSearch'); + if (!list) return; + const findings = detail.findings || []; + const endpoints = new Map(); + for (const f of findings) { + const ep = (f.endpoint || '').trim(); + if (!ep) continue; + const atk = f.evidence_data?.attack; + const method = (atk?.method || f.method || 'GET').toUpperCase(); + const status = atk?.status || 0; + const key = `${method} ${ep}`; + if (!endpoints.has(key)) endpoints.set(key, { method, path: ep, status, findings: [] }); + endpoints.get(key).findings.push(f); + } + const tested = endpoints.size; + const withFindings = [...endpoints.values()].filter(e => e.findings.length > 0).length; + if (!tested) { list.innerHTML = ''; if (empty) empty.hidden = false; return; } + if (empty) empty.hidden = true; + if (stats) { + stats.innerHTML = ` +
Endpoints${tested}
+
With findings${withFindings}
+
Clean${tested - withFindings}
+ `; + } + const render = () => { + const q = (search?.value || '').toLowerCase(); + let rows = [...endpoints.values()]; + if (q) rows = rows.filter(e => `${e.method} ${e.path}`.toLowerCase().includes(q)); + rows.sort((a, b) => b.findings.length - a.findings.length || a.path.localeCompare(b.path)); + list.innerHTML = rows.map(e => { + const badge = e.findings.length ? 'found' : 'tested'; + const statusCls = e.status >= 500 ? 's-5' : e.status >= 400 ? 's-4' : e.status >= 300 ? 's-3' : e.status >= 200 ? 's-2' : ''; + return `
+ ${esc(e.method)} + ${esc(e.path)} + ${e.status ? `${e.status}` : ''} + ${e.findings.length ? `${e.findings.length} finding(s)` : 'tested'} +
`; + }).join(''); + }; + render(); + if (search) search.oninput = render; +} + // --------------------------------------------------------------------------- // Auth & Keys modal // --------------------------------------------------------------------------- @@ -2056,7 +2337,8 @@ function termEnsure() { } term.xterm = new Terminal({ fontFamily: getComputedStyle(document.documentElement).getPropertyValue('--mono').trim() || 'monospace', - fontSize: 12, + fontSize: 13, + lineHeight: 1.3, cursorBlink: true, convertEol: true, // the harness writes bare \n; without this every line stair-steps scrollback: 8000, @@ -2075,6 +2357,10 @@ function termEnsure() { term.ro.observe($('#termHost')); } window.addEventListener('resize', termFit); + // Cell width is measured from the font; re-fit once it has actually loaded so + // the last column is not clipped by a stale measurement. + if (document.fonts?.ready) document.fonts.ready.then(() => termFit()); + setTimeout(termFit, 150); return true; } @@ -2544,28 +2830,42 @@ async function renderDashboard() { const maxSev = Math.max(1, ...Object.values(sevCounts)); const maxCwe = Math.max(1, ...topCwe.map(([, n]) => n)); + const hour = new Date().getHours(); + const greeting = hour < 12 ? 'Good morning' : hour < 18 ? 'Good afternoon' : 'Good evening'; + body.innerHTML = ` +
${greeting} +
Here's your security posture overview
+
+
+
Security score
+
+ + + + +
${score}
+
+
${esc(band.label)}
+
+
+
Open issues
+
${findings.length}
+
${needsReview} awaiting review
+
Engagements
${runs.length}
${targets.size} distinct target(s)
-
-
Findings
-
${findings.length}
-
${needsReview} awaiting human review
-
Agents run
${runs.reduce((a, r) => a + (r.agentsRan || 0), 0).toLocaleString('en-US')}
across ${runs.length} run(s)
-
-
Exposure score
-
${score}/100
-
${esc(band.label)}
-
@@ -2724,6 +3024,48 @@ function openFairParams(params) { body.scrollTop = body.scrollTop; // keep the page anchored while the modal opens } +// --------------------------------------------------------------------------- +// Home landing — quick-start cards + recent runs +// --------------------------------------------------------------------------- + +async function renderHome() { + const recent = $('#homeRecent'); + if (!recent) return; + try { + const runs = await api('/api/runs'); + const last5 = (runs || []).slice(0, 5); + if (!last5.length) { recent.innerHTML = ''; return; } + recent.innerHTML = ` +
Recent engagements
+
+ ${last5.map(r => ``).join('')} +
`; + $$('.home-recent-item', recent).forEach(btn => { + btn.addEventListener('click', () => { + const run = (runs || []).find(r => r.id === btn.dataset.id); + if (run) openRun(run); + }); + }); + } catch { recent.innerHTML = ''; } +} + +// Home card click handlers — select mode and go to wizard +$$('.home-card').forEach(card => { + card.addEventListener('click', () => { + const mode = card.dataset.mode; + leaveLiveJob(); + clearInterval(state.detailPoll); + switchView('wizard'); + if (mode) selectMode(mode); + goToStep(0); + }); +}); + function showDashboard() { leaveLiveJob(); clearInterval(state.detailPoll); @@ -2743,6 +3085,19 @@ $('#btnDashRefresh')?.addEventListener('click', renderDashboard); $('#dashRange')?.addEventListener('change', renderDashboard); $('#runFilter')?.addEventListener('input', (e) => { state.runFilter = e.target.value; renderSidebar(); }); +// ⌘K / Ctrl+K — focus the sidebar search +document.addEventListener('keydown', (e) => { + if ((e.metaKey || e.ctrlKey) && e.key === 'k') { + e.preventDefault(); + const input = $('#runFilter'); + if (input) { input.focus(); input.select(); } + const sidebar = $('#sidebar'); + if (sidebar && !sidebar.classList.contains('open') && window.matchMedia('(max-width: 900px)').matches) { + setSidebar(true); + } + } +}); + // --------------------------------------------------------------------------- // boot // --------------------------------------------------------------------------- @@ -2769,7 +3124,7 @@ window.matchMedia(NARROW).addEventListener('change', (m) => { if (!m.matches) se async function boot() { applyTheme(); - switchView('dash'); + switchView('home'); selectMode('run'); goToStep(0); renderCustomLeads(); @@ -2919,14 +3274,14 @@ function extrasPanelsHtml(uid) {
TimeHostMethodURLStatusTypeSize
- - + +
Loading…
@@ -128,21 +149,31 @@
All findings across every engagement
- - - -
Loading…
+
+
+ +
+
+ + +
+ +
+
Loading…
+
@@ -200,7 +231,7 @@
Credentials used so agents test as a logged-in user. Kept only for this session.
- +
Sent to the CLI as an ephemeral creds file.
@@ -220,7 +251,7 @@
- +
Imports endpoints as known surface — file or directory of .json files.
@@ -262,7 +293,7 @@
The hard scope is the boundary: a request whose host is not listed is refused before it is sent. Exclusions always win. A capability token still caps all of this.
- +
Exact host · *.wildcard · CIDR · https://host/path prefix. Empty = nothing extra enforced.
@@ -401,12 +432,12 @@
-
New Pentest
+
New pentest
Asset → Scope & Auth → Leads → Model & Run → Review
- - + +
- +
- +
- +
Same as the CLI --class / REPL /class. Leave empty for recon-driven selection.
- +
Authentication
@@ -499,7 +530,7 @@
- +
@@ -672,7 +703,7 @@
- + Download log @@ -685,6 +716,7 @@
0 / 0 agents
+ + + +
@@ -805,7 +938,7 @@