diff --git a/neurosploit-rs/crates/harness/src/json_extract.rs b/neurosploit-rs/crates/harness/src/json_extract.rs index f557d57..fb67d78 100644 --- a/neurosploit-rs/crates/harness/src/json_extract.rs +++ b/neurosploit-rs/crates/harness/src/json_extract.rs @@ -75,10 +75,26 @@ pub fn parse_lenient(slice: &str) -> Option { fn strip_model_markup(text: &str) -> String { let mut out = text.to_string(); - // DeepSeek DSML tags (fullwidth pipes | = U+FF5C) - let dsml = "\u{FF5C}\u{FF5C}DSML\u{FF5C}\u{FF5C}"; - if out.contains(dsml) { - out = out.replace(dsml, "\n"); + // DeepSeek DSML tags — both double-pipe (||DSML||) and single-pipe + // (|DSML|) variants, plus the XML-like tags DeepSeek v4.1-flash emits: + // , , , etc. + let dsml_double = "\u{FF5C}\u{FF5C}DSML\u{FF5C}\u{FF5C}"; + let dsml_single = "\u{FF5C}DSML\u{FF5C}"; + if out.contains(dsml_double) { + out = out.replace(dsml_double, "\n"); + } + if out.contains(dsml_single) { + // Strip XML-like DSML tags: <|DSML| tag>, , <|DSML| tag attr> + // These wrap tool-call invocations in DeepSeek v4.1+ models. + let re_open = regex::Regex::new(&format!( + r"]*>", + regex::escape(dsml_single) + )); + if let Ok(re) = re_open { + out = re.replace_all(&out, "\n").to_string(); + } else { + out = out.replace(dsml_single, "\n"); + } } // DeepSeek V2/V3 tool_call delimiters @@ -96,6 +112,41 @@ fn strip_model_markup(text: &str) -> String { out = out.replace(&format!(""), "\n"); } + // Model function_call / invoke wrappers — models sometimes emit + // {"name":"...","arguments":{...}} around or + // instead of the JSON we asked for. Strip the wrapper so the JSON inside + // is reachable by the balanced-bracket scanner. + for tag in ["function_call", "invoke", "calls", "parameters", "parameter", + "tool_use", "tool_result", "function", "action", "action_input"] { + out = out.replace(&format!("<{tag}>"), "\n"); + out = out.replace(&format!(""), "\n"); + // Also handle tags with attributes: + let pat = format!("<{tag} "); + while let Some(start) = out.find(&pat) { + if let Some(end) = out[start..].find('>') { + out.replace_range(start..start + end + 1, "\n"); + } else { + break; + } + } + } + + // Qwen chat delimiters + for marker in ["<|im_start|>", "<|im_end|>", "<|im_start|>assistant", "<|im_start|>user"] { + out = out.replace(marker, "\n"); + } + + // Llama special tokens + for marker in ["<|python_tag|>", "<|eom_id|>", "<|start_header_id|>", "<|end_header_id|>", + "<|begin_of_text|>", "<|end_of_text|>"] { + out = out.replace(marker, "\n"); + } + + // Gemma / Mistral + for marker in ["", "", "[INST]", "[/INST]"] { + out = out.replace(marker, "\n"); + } + out } @@ -350,6 +401,30 @@ mod tests { assert_eq!(v[0]["title"], "XSS"); } + #[test] + fn deepseek_v41_single_pipe_dsml_stripped() { + // DeepSeek v4.1-flash emits single-pipe DSML XML tags around tool calls + let dsml = "\u{FF5C}DSML\u{FF5C}"; + let t = format!( + "<{d} calls>\n<{d} invoke name=\"run\">\n<{d} parameter name=\"command\" string=\"true\">curl http://t\n\n\n[{{\"title\":\"CSRF\",\"severity\":\"Medium\"}}]", + d = dsml + ); + let v = parse_reply(&t).unwrap(); + assert_eq!(v[0]["title"], "CSRF"); + } + + #[test] + fn deepseek_v41_pure_toolcall_no_json() { + // When the model returns ONLY tool calls with no JSON findings, parse_reply + // correctly returns None (not a panic or garbage). + let dsml = "\u{FF5C}DSML\u{FF5C}"; + let t = format!( + "<{d} calls>\n<{d} invoke name=\"run\">\n<{d} parameter name=\"command\" string=\"true\">cd /tmp && curl -s http://target | head -40\n\n", + d = dsml + ); + assert!(parse_reply(&t).is_none()); + } + #[test] fn xml_tool_call_wrapper_stripped() { let t = "\n{\"name\":\"run\"}\n\n[{\"title\":\"SQLi\",\"severity\":\"Critical\"}]"; diff --git a/neurosploit-rs/crates/harness/src/pipeline.rs b/neurosploit-rs/crates/harness/src/pipeline.rs index ba66358..d91a7ca 100644 --- a/neurosploit-rs/crates/harness/src/pipeline.rs +++ b/neurosploit-rs/crates/harness/src/pipeline.rs @@ -2589,8 +2589,23 @@ pub async fn run_whitebox(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: S async move { let user = format!( "{}\n\nSOURCE CODE TO REVIEW:\n```\n{}\n```\n\nReply ONLY with a JSON array of findings (may be empty []). \ - Each item: {{id,title,severity,cwe,endpoint,payload,evidence,impact,remediation,confidence}} \ - where `endpoint` is the file:line and `evidence` quotes the vulnerable code. \ + Each item MUST have: {{id, title, severity, cwe, cvss, source_file, affected_endpoint, payload, evidence, \ + evidence_type, impact, remediation, confidence, finding_type, detection_method, preconditions_checked}}.\n\ + FIELD RULES:\n\ + - `title`: a proper vulnerability name (e.g. \"Cross-Site Request Forgery in User Settings Endpoint\"), \ + NEVER include agent names, reviewer names, or file paths in the title.\n\ + - `source_file`: the file:line where vulnerable code lives (e.g. \"ajenti/plugins/core/api/endpoint.py:142\").\n\ + - `affected_endpoint`: the HTTP endpoint this vulnerability affects at runtime (e.g. \"POST /api/settings/apply\"). \ + If unknown from static analysis, write \"requires runtime verification\".\n\ + - `evidence`: quote the EXACT vulnerable code verbatim. This is SOURCE CODE evidence, not attack evidence.\n\ + - `evidence_type`: \"source-code\" for SAST.\n\ + - `finding_type`: \"sast\".\n\ + - `detection_method`: \"static-analysis\" | \"dataflow-trace\" | \"pattern-match\" | \"dependency-scan\".\n\ + - `confidence`: 0.0-1.0, how confident YOU are. 0.9+ only if the vulnerable path is fully traced source-to-sink.\n\ + - `preconditions_checked`: for CSRF findings you MUST check and report: (1) SameSite cookie attribute, \ + (2) CORS configuration, (3) Content-Type enforcement, (4) Origin/Referer validation in middleware, \ + (5) framework CSRF middleware/decorators. For auth findings: session management, token validation. \ + Format as \"checked: X=value, Y=value | not checked: Z\".\n\ When a finding warrants a runnable proof, write a repro script to $NEUROSPLOIT_POCS and put its path in `payload`.", ag.user.replace("{target}", "the provided repository").replace("{recon_json}", "{}"), ctx @@ -2624,7 +2639,18 @@ pub async fn run_whitebox(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: S crate::traces::record_all(cfg.workdir.as_deref(), &raw); let transcript = transcript_of(&raw); - let candidates = dedup_findings(raw.iter().flat_map(|(_, _, f)| f.clone()).collect()); + let mut candidates: Vec = dedup_findings(raw.iter().flat_map(|(_, _, f)| f.clone()).collect()); + // Default SAST metadata for whitebox findings that agents did not set + for f in candidates.iter_mut() { + if f.finding_type.is_empty() { f.finding_type = "sast".into(); } + if f.validation_level.is_empty() { f.validation_level = "source-detection".into(); } + if f.detection_method.is_empty() { f.detection_method = "static-analysis".into(); } + if f.evidence_type.is_empty() { f.evidence_type = "source-code".into(); } + // Separate source_file from endpoint when agent put file:line in endpoint + if f.source_file.is_empty() && f.endpoint.contains(':') && !f.endpoint.contains("://") { + f.source_file = f.endpoint.clone(); + } + } let _ = tx.send(format!("{} candidate finding(s) (deduped) — validating", candidates.len())).await; let findings = validate(candidates, pool, CODE_VOTE_SYS, effective_vote_n(&cfg), &tx).await; let findings = refute_pass(findings, pool, effective_vote_n(&cfg), &tx).await; @@ -3884,6 +3910,9 @@ async fn validate_with_persist(candidates: Vec, pool: &ModelPool, sys: // candidates are dropped as noise. if f.validated { f.review_status = "confirmed".into(); + if f.validation_level.is_empty() || f.validation_level == "source-detection" { + f.validation_level = "ai-consensus".into(); + } } else if yes >= 1 || total == 0 { f.review_status = "needs-review".into(); f.review_reason = if total == 0 { "validator unavailable".into() } @@ -4652,6 +4681,7 @@ async fn finish(cfg: RunConfig, _lib: &Library, pool: &ModelPool, recon: String, f.confidence = f.confidence.max(c.probability); if f.payload.trim().is_empty() { f.payload = c.payload.clone(); } f.review_reason = format!("TypeSafe confirmation loop: {}", c.detail); + f.validation_level = "control-verification".into(); confirmed_by_agent += 1; } } @@ -5124,12 +5154,101 @@ fn persist(cfg: &RunConfig, recon: &str, transcript: &str, findings: &[Finding]) } fn findings_md(target: &str, findings: &[Finding]) -> String { - let mut s = format!("# NeuroSploit findings — {}\n\n{} validated finding(s).\n", target, findings.len()); + let is_sast = findings.iter().any(|f| { + f.finding_type == "sast" || f.detection_method.contains("static") + || f.endpoint.contains(':') && !f.endpoint.contains("://") + }); + let mode_label = if is_sast { "White-Box (SAST)" } else { "Dynamic (DAST)" }; + let mut s = format!( + "# NeuroSploit Findings — {}\n\n**Mode:** {} | **Findings:** {}\n\n---\n", + target, mode_label, findings.len() + ); for (i, f) in findings.iter().enumerate() { - s.push_str(&format!( - "\n## {}. [{}] {}\n- agent: `{}` CWE: {} CVSS: {} votes: {} confidence: {:.2}\n- endpoint: {}\n\n**Payload**\n```\n{}\n```\n\n**Evidence**\n{}\n\n**Impact:** {}\n\n**Remediation:** {}\n", - i + 1, f.severity, f.title, f.agent, f.cwe, f.cvss, f.votes, f.confidence, f.endpoint, f.payload, f.evidence, f.impact, f.remediation - )); + // Validation level display + let val_level = if !f.validation_level.is_empty() { + f.validation_level.clone() + } else if f.validated && !f.votes.is_empty() { + "L2 — AI Consensus".into() + } else if f.validated { + "L1 — Source Detection".into() + } else { + "Unconfirmed".into() + }; + + // Evidence type + let ev_type = if !f.evidence_type.is_empty() { + &f.evidence_type + } else if is_sast { + "source-code" + } else { + "observed" + }; + + s.push_str(&format!("\n## {}. [{}] {}\n\n", i + 1, f.severity, f.title)); + s.push_str(&format!("| Field | Value |\n|---|---|\n")); + s.push_str(&format!("| CWE | {} |\n", f.cwe)); + s.push_str(&format!("| CVSS | {} |\n", f.cvss)); + s.push_str(&format!("| Confidence | {:.0}% |\n", f.confidence * 100.0)); + s.push_str(&format!("| Validation | {} |\n", val_level)); + s.push_str(&format!("| Votes | {} |\n", if f.votes.is_empty() { "—" } else { &f.votes })); + if !f.detection_method.is_empty() { + s.push_str(&format!("| Detection | {} |\n", f.detection_method)); + } + if !f.exploitability.is_empty() { + s.push_str(&format!("| Exploitability | {} |\n", f.exploitability)); + } + + // Source location vs affected endpoint (the core SAST distinction) + let source_loc = if !f.source_file.is_empty() { + &f.source_file + } else if f.endpoint.contains(':') && !f.endpoint.contains("://") { + &f.endpoint + } else { + "" + }; + let http_endpoint = if !f.affected_endpoint.is_empty() { + f.affected_endpoint.as_str() + } else if f.endpoint.contains("://") || f.endpoint.starts_with('/') { + f.endpoint.as_str() + } else { + "" + }; + + if !source_loc.is_empty() { + s.push_str(&format!("\n**Source Location:** `{}`\n", source_loc)); + } + if !http_endpoint.is_empty() { + s.push_str(&format!("\n**Affected Endpoint:** `{}`\n", http_endpoint)); + } + + // Preconditions (critical for CSRF and similar) + if !f.preconditions_checked.is_empty() { + s.push_str(&format!("\n**Security Preconditions Checked:**\n{}\n", f.preconditions_checked)); + } + + s.push_str(&format!("\n**Evidence** (type: {})\n", ev_type)); + if is_sast && ev_type == "source-code" { + s.push_str(&format!("```\n{}\n```\n", f.evidence)); + } else { + s.push_str(&format!("{}\n", f.evidence)); + } + + if !f.payload.is_empty() { + s.push_str(&format!("\n**Payload / PoC**\n```\n{}\n```\n", f.payload)); + } + if !f.repro_steps.is_empty() { + s.push_str("\n**Reproduction Steps**\n"); + for (j, step) in f.repro_steps.iter().enumerate() { + s.push_str(&format!("{}. {}\n", j + 1, step)); + } + } + s.push_str(&format!("\n**Impact:** {}\n", f.impact)); + s.push_str(&format!("\n**Remediation:** {}\n", f.remediation)); + + if !f.location.is_empty() { + s.push_str(&format!("\n**Precise Location:** {}\n", f.location)); + } + s.push_str("\n---\n"); } s } @@ -5338,7 +5457,7 @@ pub(crate) fn extract_findings(text: &str, agent: &str) -> Vec { } }, agent: agent.to_string(), - title, + title: clean_finding_title(&title, agent), severity: norm_sev(&s(o, "severity")), cwe: s(o, "cwe"), cvss: s(o, "cvss"), @@ -5349,10 +5468,6 @@ pub(crate) fn extract_findings(text: &str, agent: &str) -> Vec { repro_steps: o.get("repro_steps").and_then(|v| v.as_array()) .map(|a| a.iter().filter_map(|x| x.as_str().map(|t| t.to_string())).collect()) .unwrap_or_default(), - // Structured artifacts for the deterministic validators. Without - // this the evidence contract in the prompt goes to an agent that - // dutifully fills it in and a parser that throws it away — the - // whole validation engine would sit idle on live runs. evidence_data: o.get("evidence_data").and_then(|v| serde_json::from_value(v.clone()).ok()), claims: parse_claims(o), impact: s(o, "impact"), @@ -5361,6 +5476,13 @@ pub(crate) fn extract_findings(text: &str, agent: &str) -> Vec { validated: false, votes: String::new(), screenshots: screenshot_refs(o), + finding_type: s(o, "finding_type"), + validation_level: s(o, "validation_level"), + detection_method: s(o, "detection_method"), + source_file: s(o, "source_file"), + affected_endpoint: s(o, "affected_endpoint"), + evidence_type: s(o, "evidence_type"), + preconditions_checked: s(o, "preconditions_checked"), ..Default::default() }) }) @@ -5820,6 +5942,29 @@ fn title_overlap(a: &str, b: &str) -> f64 { if union == 0.0 { 0.0 } else { inter / union } } +/// Strip internal agent names, "Source ... Reviewer at ..." patterns, and other +/// pipeline artifacts from finding titles. A title should read like a +/// vulnerability name, not an internal log line. +fn clean_finding_title(raw: &str, agent: &str) -> String { + let mut t = raw.to_string(); + // Remove agent name prefix/suffix (e.g. "Source CSRF-Disabled Reviewer at ...") + if !agent.is_empty() { + t = t.replace(agent, ""); + } + // Strip common noise patterns from SAST agent titles + let noise = [ + "Source ", "Reviewer at ", "Reviewer in ", " Reviewer", + " at /opt/", " at /tmp/", " at /home/", " at /var/", + " in /opt/", " in /tmp/", " in /home/", " in /var/", + ]; + for pat in noise { + t = t.replace(pat, ""); + } + // Remove leading/trailing dashes, spaces, colons + let t = t.trim_matches(|c: char| c == '-' || c == ' ' || c == ':' || c == '·').trim().to_string(); + if t.is_empty() { raw.to_string() } else { t } +} + fn norm_sev(s: &str) -> String { match s.to_lowercase().as_str() { x if x.starts_with("crit") => "Critical", diff --git a/neurosploit-rs/crates/harness/src/report.rs b/neurosploit-rs/crates/harness/src/report.rs index ccd8453..6740286 100644 --- a/neurosploit-rs/crates/harness/src/report.rs +++ b/neurosploit-rs/crates/harness/src/report.rs @@ -143,9 +143,12 @@ pub fn html_with_pocs(target: &str, findings: &[Finding], meta: &EngagementMeta, \ \ \ - \ + {source_row}\ + {aff_ep_row}\ + \ {authcell}\
Criticality{sev}Status{status}
OWASP / CWE{owaspcwe}Confidence{confline}
Location{endpoint}
Validation{val_level}Detection{det_method}
Agent{agent}
\ + {preconditions}\ {reviewnote}\

Where the problem is

{where_}

\

What it means

{impact}

\ @@ -158,7 +161,30 @@ pub fn html_with_pocs(target: &str, findings: &[Finding], meta: &EngagementMeta, agent = esc(&f.agent), owaspcwe = [esc(&f.owasp), esc(&f.cwe)].into_iter().filter(|s| !s.is_empty()).collect::>().join(" · "), confline = if f.votes.is_empty() { format!("conf {:.2}", f.confidence) } else { format!("{} · conf {:.2}", esc(&f.votes), f.confidence) }, - endpoint = esc(&f.endpoint), + source_row = { + let src = if !f.source_file.is_empty() { &f.source_file } + else if f.endpoint.contains(':') && !f.endpoint.contains("://") { &f.endpoint } + else { "" }; + if src.is_empty() { format!("Endpoint{}", esc(&f.endpoint)) } + else { format!("Source Location{}", esc(src)) } + }, + aff_ep_row = { + let ep = if !f.affected_endpoint.is_empty() { &f.affected_endpoint } + else if f.endpoint.contains("://") || f.endpoint.starts_with('/') { &f.endpoint } + else { "" }; + if ep.is_empty() { String::new() } + else { format!("Affected Endpoint{}", esc(ep)) } + }, + val_level = { + let vl = if !f.validation_level.is_empty() { &f.validation_level } + else if f.validated && !f.votes.is_empty() { "L2 — AI Consensus" } + else if f.validated { "L1 — Source Detection" } + else { "Unconfirmed" }; + esc(vl) + }, + det_method = if f.detection_method.is_empty() { "—".to_string() } else { esc(&f.detection_method) }, + preconditions = if f.preconditions_checked.is_empty() { String::new() } + else { format!("
Security preconditions checked: {}
", esc(&f.preconditions_checked)) }, where_ = esc(&location_line(f)), steps = { // Numbered, pasteable commands. A reader who cannot @@ -236,6 +262,7 @@ pub fn html_with_pocs(target: &str, findings: &[Finding], meta: &EngagementMeta, .shots{{display:flex;flex-wrap:wrap;gap:12px;margin:6px 0}}\ .shot{{margin:0;max-width:100%}}.shot img{{max-width:100%;border:0.5pt solid #ddd;border-radius:8px;display:block}}\ .shot figcaption{{color:#888;font-size:11px;margin-top:3px;font-family:ui-monospace,Menlo,monospace}}\ + .precond{{background:#fdf6e3;border:0.5pt solid #e0c97f;border-radius:6px;padding:8px 12px;margin:6px 0;font-size:12px;color:#5a4a1e}}\ .footer{{color:#888;font-size:11px;margin-top:24px;border-top:0.5pt solid #ddd;padding-top:10px}}\ \

NeuroSploit

Penetration Test Report
\ @@ -803,6 +830,12 @@ pub fn markdown(target: &str, findings: &[Finding], meta: &EngagementMeta) -> St } } + // --- Threat actor similarity --- + // TTP overlap with known intrusion sets, framed as prioritisation aid — + // the module itself refuses to render when the overlap is too thin to be + // defensible. + out.push_str(&crate::threat_actors::markdown(findings)); + // --- Vulnerability table --- out.push_str("## Vulnerability summary\n\n"); if confirmed.is_empty() && review.is_empty() { @@ -888,6 +921,7 @@ pub fn json_report(target: &str, findings: &[Finding], run_id: &str, meta: &Enga "needs_review": review.len(), "total": findings.len(), }, + "threat_actor_similarity": crate::threat_actors::match_actors(findings), "confirmed": confirmed, "needs_review": review, "findings": findings, diff --git a/neurosploit-rs/crates/harness/src/types.rs b/neurosploit-rs/crates/harness/src/types.rs index 1a8b348..82b9437 100644 --- a/neurosploit-rs/crates/harness/src/types.rs +++ b/neurosploit-rs/crates/harness/src/types.rs @@ -105,6 +105,38 @@ pub struct Finding { /// `crate::validation` judges the class from it without consulting a model. #[serde(default)] pub evidence_data: Option, + + // --- SAST / whitebox quality fields --- + + /// "sast" | "dast" | "manual" | "hybrid" — how the finding was detected. + #[serde(default)] + pub finding_type: String, + /// Validation depth reached: "source-detection" (L1), "ai-consensus" (L2), + /// "control-verification" (L3), "runtime-validation" (L4), "impact-confirmed" (L5). + #[serde(default)] + pub validation_level: String, + /// How the issue was found: "static-analysis" | "pattern-match" | + /// "dataflow-trace" | "dependency-scan" | "manual-review". + #[serde(default)] + pub detection_method: String, + /// Source file + line where the vulnerable code lives (SAST). Distinct from + /// `endpoint` which is the HTTP endpoint affected at runtime. + #[serde(default)] + pub source_file: String, + /// The HTTP endpoint affected by this vulnerability (may differ from + /// `endpoint` which agents historically overloaded for both source files + /// and HTTP paths). When set, the report uses this for "Affected Endpoint" + /// and `source_file` for "Source Location". + #[serde(default)] + pub affected_endpoint: String, + /// "source-code" | "http-response" | "log-output" | "configuration" — what + /// kind of evidence backs this finding. + #[serde(default)] + pub evidence_type: String, + /// Security preconditions checked and their results, e.g. for CSRF: + /// "SameSite=Lax (checked), no CSRF middleware (checked), CORS permissive (not checked)". + #[serde(default)] + pub preconditions_checked: String, } impl Default for Finding { @@ -141,6 +173,13 @@ impl Default for Finding { claims: None, evidence_data: None, observed_at: 0, + finding_type: String::new(), + validation_level: String::new(), + detection_method: String::new(), + source_file: String::new(), + affected_endpoint: String::new(), + evidence_type: String::new(), + preconditions_checked: String::new(), } } } diff --git a/web/public/app.js b/web/public/app.js index 11b8774..593dd36 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -1530,7 +1530,7 @@ function openFindingModal(f, pocs, runId) { // Technical evidence (endpoint/payload/curl) reads as code; prose // (description/impact/remediation) reads as a paragraph, not a code block. const codeBlock = (label, text) => text - ? `
${esc(text)}
` : ''; + ? `
${esc(text)}
` : ''; const proseBlock = (label, text) => text ? `
${esc(text)}
` : ''; @@ -1559,24 +1559,39 @@ function openFindingModal(f, pocs, runId) { // Scripts this finding cites are rendered inside the PoC block above; this // list is the run's remaining scripts, so nothing written is hidden. const citedIn = `${f.evidence || ''} ${f.payload || ''} ${(f.repro_steps || []).join(' ')}`; - const list = (pocs || []).filter((p) => !citedIn.includes(p)); + const allUncited = (pocs || []).filter((p) => !citedIn.includes(p)); + const fWords = [ + ...(f.title || '').toLowerCase().replace(/[^a-z0-9_.-]+/g, ' ').split(/\s+/).filter(w => w.length > 3), + ...(f.endpoint || '').toLowerCase().replace(/[^a-z0-9_./:-]+/g, ' ').split(/\s+/).filter(Boolean), + ...(f.location || '').toLowerCase().replace(/[^a-z0-9_./:-]+/g, ' ').split(/\s+/).filter(Boolean), + (f.agent || '').toLowerCase(), + (f.cwe || '').toLowerCase(), + ].filter(Boolean); + const list = allUncited.filter((p) => { + const low = p.toLowerCase(); + return fWords.some(w => low.includes(w)); + }); const pocRoot = $('#fmPocList'); + const pocSection = $('#fmPocSection'); if (!list.length) { - pocRoot.textContent = 'No other scripts from this run.'; + pocSection.hidden = true; + pocRoot.textContent = ''; } else { + pocSection.hidden = false; pocRoot.innerHTML = list.map((name) => ` -
- pocs/${esc(name)} - Open raw +
+ +
-
loading…
`).join(''); - for (const name of list) { - fetch(`/api/runs/${runId}/asset/pocs/${name}`).then((r) => r.text()).then((txt) => { - const pre = pocRoot.querySelector(`pre[data-poc="${CSS.escape(name)}"]`); - if (pre) pre.textContent = txt.slice(0, 4000); - }).catch(() => {}); - } } // Wire evidence — the real request/response pairs behind the finding, plus // its re-test history. Loaded on demand; the section hides itself when the @@ -1589,6 +1604,45 @@ function openFindingModal(f, pocs, runId) { $('#btnCloseFinding').addEventListener('click', () => show($('#findingModal'), false)); $('#findingModal').addEventListener('click', (e) => { if (e.target.id === 'findingModal') show($('#findingModal'), false); }); +function loadScriptContent(card, runId, name) { + const pre = card.querySelector(`pre[data-poc="${CSS.escape(name)}"]`) || card.querySelector(`pre[data-cited-poc="${CSS.escape(name)}"]`); + if (!pre || pre.dataset.loaded) return; + pre.textContent = 'loading…'; + pre.dataset.loaded = '1'; + fetch(`/api/runs/${runId}/asset/pocs/${name}`).then((r) => r.text()).then((txt) => { + pre.textContent = txt.slice(0, 8000); + }).catch(() => { pre.textContent = 'failed to load'; }); +} + +function copyScript(btn, runId, name) { + fetch(`/api/runs/${runId}/asset/pocs/${name}`).then((r) => r.text()).then((txt) => { + navigator.clipboard.writeText(txt).then(() => { + btn.textContent = 'Copied!'; + setTimeout(() => { btn.textContent = 'Copy'; }, 1500); + }); + }).catch(() => {}); +} + +$('#findingModal').addEventListener('click', (e) => { + const copyStep = e.target.closest('[data-copy-step]'); + if (copyStep) { + const pre = copyStep.closest('.step-wrap')?.querySelector('.step'); + if (pre) navigator.clipboard.writeText(pre.textContent).then(() => { + copyStep.textContent = 'Copied!'; + setTimeout(() => { copyStep.textContent = 'Copy'; }, 1500); + }); + return; + } + const copyPayload = e.target.closest('[data-copy-payload]'); + if (copyPayload) { + const pre = copyPayload.closest('.code-wrap')?.querySelector('.poc-pre'); + if (pre) navigator.clipboard.writeText(pre.textContent).then(() => { + copyPayload.textContent = 'Copied!'; + setTimeout(() => { copyPayload.textContent = 'Copy'; }, 1500); + }); + } +}); + // ---- wire evidence + per-finding re-test ----------------------------------- const PROV_LABEL = { @@ -1783,17 +1837,37 @@ function technicalEvidence(f) { /// The proof: numbered steps, then the payload, with any script offered as an /// extra artifact rather than as the proof itself. +function scriptLang(name) { + if (name.endsWith('.py')) return 'Python'; + if (name.endsWith('.sh') || name.endsWith('.bash')) return 'Shell'; + if (name.endsWith('.rb')) return 'Ruby'; + if (name.endsWith('.js')) return 'JavaScript'; + if (name.endsWith('.md')) return 'Markdown'; + if (name.endsWith('.yml') || name.endsWith('.yaml')) return 'YAML'; + return 'Script'; +} + function pocBlock(f, pocs, runId) { - const steps = reproSteps(f).map((s) => `
  • ${esc(s)}
  • `).join(''); + const steps = reproSteps(f).map((s, i) => `
  • ${esc(s)}
  • `).join(''); const payload = f.payload?.trim() - ? `
    ${esc(f.payload.trim())}
    ` : ''; + ? `
    ${esc(f.payload.trim())}
    ` : ''; const cited = `${f.evidence || ''} ${f.payload || ''} ${(f.repro_steps || []).join(' ')}`; const scripts = (pocs || []).filter((p) => cited.includes(p)); const scriptBlock = scripts.length - ? `
    -
    The steps above are the proof; this script automates them.
    - ${scripts.map((n) => `
    pocs/${esc(n)} - Open raw
    `).join('')}
    ` + ? `
    +
    These scripts automate the proof above.
    + ${scripts.map((n) => `
    + +
    click to expand…
    +
    `).join('')}
    ` : ''; return `
      ${steps}
    ${payload}${scriptBlock}`; diff --git a/web/public/index.html b/web/public/index.html index 48033b6..1d87f19 100644 --- a/web/public/index.html +++ b/web/public/index.html @@ -1299,8 +1299,8 @@
    -
    - +
    +
    —
    diff --git a/web/public/style.css b/web/public/style.css index 9426686..4467c71 100644 --- a/web/public/style.css +++ b/web/public/style.css @@ -666,7 +666,28 @@ textarea { resize: vertical; min-height: 72px; } } .poc-file { display: flex; align-items: center; gap: var(--sp-2); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: var(--sp-2) var(--sp-3); margin-bottom: var(--sp-2); } .poc-file .fn { font-family: var(--mono); font-size: var(--fs-sm); flex: 1; } -.poc-pre { background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: var(--sp-3); font-family: var(--mono); font-size: var(--fs-xs); max-height: 220px; overflow: auto; white-space: pre-wrap; word-break: break-word; margin-top: var(--sp-2); } +.poc-pre { background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: var(--sp-3); font-family: var(--mono); font-size: var(--fs-xs); max-height: 320px; overflow: auto; white-space: pre-wrap; word-break: break-word; margin-top: var(--sp-2); } +/* Script card — collapsible PoC scripts with header bar */ +.script-card { border: 1px solid var(--border); border-radius: var(--radius-sm); margin-bottom: var(--sp-3); overflow: hidden; } +.script-card-head { display: flex; align-items: center; gap: var(--sp-2); padding: var(--sp-2) var(--sp-3); background: var(--surface-2); cursor: pointer; user-select: none; } +.script-card-head:hover { background: var(--surface-3, var(--surface-2)); } +.script-card-head .script-icon { font-size: var(--fs-xs); color: var(--text-faint); transition: transform .15s; } +.script-card-head[aria-expanded="true"] .script-icon { transform: rotate(90deg); } +.script-card-head .script-name { flex: 1; font-family: var(--mono); font-size: var(--fs-sm); color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.script-card-head .script-lang { font-size: var(--fs-2xs); color: var(--text-faint); text-transform: uppercase; letter-spacing: .04em; padding: 1px 6px; border: 1px solid var(--border); border-radius: var(--radius-sm); } +.script-card-actions { display: flex; gap: var(--sp-1); margin-left: auto; } +.script-card-body { display: none; } +.script-card-body.open { display: block; } +.script-card-body .poc-pre { margin: 0; border: none; border-top: 1px solid var(--border); border-radius: 0; max-height: 400px; } +/* Copy button inside code blocks */ +.code-wrap { position: relative; } +.code-wrap .copy-btn { position: absolute; top: var(--sp-2); right: var(--sp-2); font-size: var(--fs-2xs); padding: 2px 8px; opacity: 0; transition: opacity .15s; } +.code-wrap:hover .copy-btn { opacity: 1; } +/* PoC steps improvements */ +.poc-steps li { position: relative; } +.poc-steps .step-wrap { position: relative; } +.poc-steps .step-wrap .copy-btn { position: absolute; top: 4px; right: 4px; font-size: var(--fs-2xs); padding: 2px 8px; opacity: 0; transition: opacity .15s; } +.poc-steps .step-wrap:hover .copy-btn { opacity: 1; } /* Evidence prose carries raw cookies, tokens and URLs — single "words" wider than the modal. Without a break they run under the modal's edge and the tail of the value is simply unreadable. */ @@ -698,7 +719,8 @@ textarea { resize: vertical; min-height: 72px; } .modal-overlay[hidden] { display: none; } .modal { width: 620px; max-width: calc(100vw - 40px); max-height: calc(100vh - 80px); max-height: calc(100dvh - 80px); background: var(--surface); border-radius: var(--radius-md); box-shadow: var(--shadow-float); display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--border); } .modal-sm { width: 520px; } -.modal-lg { width: 760px; } +.modal-lg { width: 960px; max-height: calc(100vh - 48px); max-height: calc(100dvh - 48px); } +@media (max-width: 1000px) { .modal-lg { width: calc(100vw - 32px); } } .modal-foot { display: flex; justify-content: flex-end; gap: var(--sp-2); padding: var(--sp-3) var(--sp-5); border-top: 1px solid var(--border); } .modal-head { display: flex; align-items: center; justify-content: space-between; padding: var(--sp-4) var(--sp-5); border-bottom: 1px solid var(--border); } .modal-head .title { font-size: var(--fs-lg); font-weight: 600; }