mirror of
https://github.com/CyberSecurityUP/NeuroSploit.git
synced 2026-12-05 02:24:17 +01:00
feat: real-browser capture feeds SPA APIs into recon
- Playwright Chromium records same-origin XHR/fetch, JS bundles and cookie names - raw capture saved under traffic/; compact endpoint block injected into recon - scope/auth/evasion UA honored; 60s timeout kills node + Chromium group - best-effort with NEUROSPLOIT_BROWSER_RECON=0 opt-out
This commit is contained in:
1 parent
40bfa2c9d3
commit
16c33e79f9
3 files changed
+344
No files matched your search
@@ -0,0 +1,335 @@
|
||||
//! Real-browser traffic capture (SPA / Cloudflare first-class).
|
||||
//!
|
||||
//! `curl` only sees the HTML shell of a JavaScript app; the API calls that the
|
||||
//! app actually makes are XHR/fetch from a real Chromium session. This module
|
||||
//! drives Playwright, records the same-origin requests/responses (plus the JS
|
||||
//! bundles and cookie names), saves the raw capture under `traffic/`, and hands
|
||||
//! the agents a compact endpoint list.
|
||||
//!
|
||||
//! It is best-effort and never fails a run: no node/playwright → skip; no
|
||||
//! browser → skip. Disable with `NEUROSPLOIT_BROWSER_RECON=0` (default auto).
|
||||
|
||||
use crate::pipeline::{default_user_agent, effective_scope};
|
||||
use crate::scope::{Action, Decision};
|
||||
use crate::types::RunConfig;
|
||||
use serde_json::Value;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::mpsc::Sender;
|
||||
|
||||
fn enabled() -> bool {
|
||||
!matches!(
|
||||
std::env::var("NEUROSPLOIT_BROWSER_RECON").ok().as_deref(),
|
||||
Some("0") | Some("off") | Some("false")
|
||||
)
|
||||
}
|
||||
|
||||
fn which(bin: &str) -> bool {
|
||||
std::env::var_os("PATH")
|
||||
.map(|p| std::env::split_paths(&p).any(|d| d.join(bin).is_file()))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn driver_js() -> &'static str {
|
||||
r#"
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
function loadPlaywright() {
|
||||
try { return require('playwright'); } catch (_) {}
|
||||
const roots = [];
|
||||
if (process.env.NODE_PATH) roots.push(...process.env.NODE_PATH.split(path.delimiter));
|
||||
roots.push(path.join(process.cwd(), 'node_modules'));
|
||||
roots.push('/opt/homebrew/lib/node_modules', '/usr/local/lib/node_modules');
|
||||
const npx = path.join(process.env.HOME || '', '.npm', '_npx');
|
||||
try { for (const d of fs.readdirSync(npx)) roots.push(path.join(npx, d, 'node_modules')); } catch (_) {}
|
||||
for (const r of roots) {
|
||||
const p = path.join(r, 'playwright');
|
||||
if (fs.existsSync(p)) { try { return require(p); } catch (_) {} }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const pw = loadPlaywright();
|
||||
if (!pw) {
|
||||
process.stdout.write('NSJSON' + JSON.stringify({ available: false, error: 'playwright not found' }) + 'NSEND');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const [,, target, waitMs, authJson, maxBody] = process.argv;
|
||||
const cap = Number(maxBody) || 65536;
|
||||
const out = { available: true, url: target, title: '', requests: 0, responses: 0, endpoints: [], api: [], scripts: [], cookies: [], storage_keys: [], notes: [] };
|
||||
const pending = [];
|
||||
let browser;
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
browser = await pw.chromium.launch({ args: ['--no-sandbox'] });
|
||||
let extra = {};
|
||||
try { extra = JSON.parse(authJson || '{}'); } catch (_) {}
|
||||
const ctx = await browser.newContext({
|
||||
ignoreHTTPSErrors: true,
|
||||
userAgent: process.env.NEUROSPLOIT_UA || undefined,
|
||||
extraHTTPHeaders: extra,
|
||||
});
|
||||
const page = await ctx.newPage();
|
||||
const origin = new URL(target).origin;
|
||||
const seen = new Set();
|
||||
|
||||
page.on('request', (req) => {
|
||||
out.requests += 1;
|
||||
const rt = req.resourceType();
|
||||
let post = '';
|
||||
try { post = req.postData() || ''; } catch (_) {}
|
||||
if (post.length > 2048) post = post.slice(0, 2048);
|
||||
if (rt === 'xhr' || rt === 'fetch' || post) {
|
||||
out.api.push({ method: req.method(), url: req.url(), resourceType: rt, postData: post });
|
||||
}
|
||||
});
|
||||
page.on('response', (res) => {
|
||||
pending.push((async () => {
|
||||
out.responses += 1;
|
||||
let body = '';
|
||||
const ct = (res.headers()['content-type'] || '');
|
||||
if (/json|text|javascript|xml|html/i.test(ct)) {
|
||||
try {
|
||||
const buf = await res.body();
|
||||
body = buf.slice(0, cap).toString('utf8');
|
||||
} catch (_) {}
|
||||
}
|
||||
const req = res.request();
|
||||
const rt = req.resourceType();
|
||||
if (!['document', 'xhr', 'fetch', 'script'].includes(rt)) return;
|
||||
const u = (() => { try { return new URL(res.url()); } catch (_) { return null; } })();
|
||||
if (!u || u.origin !== origin) return;
|
||||
const key = req.method() + ' ' + u.pathname;
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
out.endpoints.push({ method: req.method(), path: u.pathname, url: res.url(), status: res.status(), contentType: ct });
|
||||
}
|
||||
if (/json|xml|graphql/i.test(ct) || /graphql/i.test(u.pathname)) {
|
||||
out.api.push({ method: req.method(), path: u.pathname, status: res.status(), contentType: ct, body: body.slice(0, 1200) });
|
||||
}
|
||||
})());
|
||||
});
|
||||
page.on('console', (m) => { if (out.notes.length < 20) out.notes.push('console: ' + String(m.text()).slice(0, 180)); });
|
||||
page.on('pageerror', (e) => { if (out.notes.length < 20) out.notes.push('pageerror: ' + String(e).slice(0, 180)); });
|
||||
|
||||
await page.goto(target, { waitUntil: 'domcontentloaded', timeout: Number(waitMs) || 25000 }).catch((e) => out.notes.push('goto: ' + e.message));
|
||||
await page.waitForLoadState('networkidle', { timeout: Math.min(8000, Number(waitMs) || 8000) }).catch(() => {});
|
||||
await page.waitForTimeout(2500);
|
||||
out.title = await page.title().catch(() => '');
|
||||
try { out.scripts = await page.$$eval('script[src]', (els) => els.map((e) => e.src)); } catch (_) {}
|
||||
try { out.cookies = (await ctx.cookies()).map((c) => c.name); } catch (_) {}
|
||||
try {
|
||||
out.storage_keys = await page.evaluate(() => Object.keys(localStorage).slice(0, 50));
|
||||
} catch (_) {}
|
||||
await Promise.all(pending);
|
||||
} catch (e) {
|
||||
out.notes.push('browser error: ' + (e && e.message ? e.message : String(e)));
|
||||
} finally {
|
||||
try { if (browser) await browser.close(); } catch (_) {}
|
||||
process.stdout.write('NSJSON' + JSON.stringify(out) + 'NSEND');
|
||||
}
|
||||
})();
|
||||
"#
|
||||
}
|
||||
|
||||
fn parse(stdout: &str) -> Option<Value> {
|
||||
let start = stdout.find("NSJSON")? + "NSJSON".len();
|
||||
let end = stdout[start..].find("NSEND")? + start;
|
||||
serde_json::from_str(&stdout[start..end]).ok()
|
||||
}
|
||||
|
||||
fn auth_json(cfg: &RunConfig) -> String {
|
||||
let Some(auth) = cfg.auth.as_deref().filter(|s| !s.trim().is_empty()) else {
|
||||
return "{}".into();
|
||||
};
|
||||
match auth.split_once(':') {
|
||||
Some((k, v)) if !k.trim().is_empty() => {
|
||||
let mut m = serde_json::Map::new();
|
||||
m.insert(k.trim().to_string(), Value::String(v.trim().to_string()));
|
||||
Value::Object(m).to_string()
|
||||
}
|
||||
_ => "{}".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn traffic_dir(cfg: &RunConfig) -> Option<PathBuf> {
|
||||
let base = cfg.workdir.as_deref().map(PathBuf::from).unwrap_or_else(|| {
|
||||
std::env::temp_dir().join(format!("ns-browser-{}", std::process::id()))
|
||||
});
|
||||
let dir = base.join("traffic");
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
Some(dir)
|
||||
}
|
||||
|
||||
fn prompt_block(cap: &Value, saved: Option<&Path>) -> String {
|
||||
let mut s = String::from("\n\nBROWSER CAPTURE (real Chromium");
|
||||
let auth = cap.get("cookies").and_then(|c| c.as_array()).map(|a| a.len()).unwrap_or(0);
|
||||
if auth > 0 {
|
||||
s.push_str(", authenticated session");
|
||||
}
|
||||
s.push_str("):\n");
|
||||
if let Some(t) = cap.get("title").and_then(|v| v.as_str()).filter(|t| !t.is_empty()) {
|
||||
s.push_str(&format!("Title: {}\n", t.chars().take(160).collect::<String>()));
|
||||
}
|
||||
let endpoints = cap.get("endpoints").and_then(|e| e.as_array()).cloned().unwrap_or_default();
|
||||
s.push_str(&format!("Same-origin endpoints discovered: {}\n", endpoints.len()));
|
||||
for e in endpoints.iter().take(80) {
|
||||
let m = e.get("method").and_then(|v| v.as_str()).unwrap_or("GET");
|
||||
let p = e.get("path").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let st = e.get("status").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let ct = e.get("contentType").and_then(|v| v.as_str()).unwrap_or("");
|
||||
s.push_str(&format!("- {} {} [{}] {}\n", m, p, st, ct));
|
||||
}
|
||||
let api = cap.get("api").and_then(|e| e.as_array()).cloned().unwrap_or_default();
|
||||
let mut shown = 0;
|
||||
for a in &api {
|
||||
if shown >= 30 { break; }
|
||||
let m = a.get("method").and_then(|v| v.as_str()).unwrap_or("GET");
|
||||
let p = a.get("path").and_then(|v| v.as_str()).or_else(|| a.get("url").and_then(|v| v.as_str())).unwrap_or("");
|
||||
let st = a.get("status").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let ct = a.get("contentType").and_then(|v| v.as_str()).unwrap_or("");
|
||||
s.push_str(&format!("- API {} {} [{}] {}\n", m, p, st, ct));
|
||||
shown += 1;
|
||||
}
|
||||
if let Some(sc) = cap.get("scripts").and_then(|v| v.as_array()) {
|
||||
if !sc.is_empty() {
|
||||
s.push_str("JS bundles seen (fetch/analyze them):\n");
|
||||
for u in sc.iter().take(20) {
|
||||
if let Some(u) = u.as_str() { s.push_str(&format!("- {}\n", u)); }
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(c) = cap.get("cookies").and_then(|v| v.as_array()) {
|
||||
if !c.is_empty() {
|
||||
let names: Vec<&str> = c.iter().filter_map(|x| x.as_str()).take(20).collect();
|
||||
s.push_str(&format!("Session cookie names (values not shown): {}\n", names.join(", ")));
|
||||
}
|
||||
}
|
||||
if let Some(p) = saved {
|
||||
s.push_str(&format!("Raw capture (request/response bodies) saved: {}\n", p.display()));
|
||||
}
|
||||
s.push_str("Use these URLs/APIs as the real surface; do not re-guess endpoints the browser already called.\n");
|
||||
s
|
||||
}
|
||||
|
||||
/// Capture the target in a real browser and return a compact prompt block.
|
||||
pub async fn capture(cfg: &RunConfig, tx: &Sender<String>) -> Option<String> {
|
||||
if cfg.offline || !enabled() || !which("node") {
|
||||
return None;
|
||||
}
|
||||
if !(cfg.target.starts_with("http://") || cfg.target.starts_with("https://")) {
|
||||
return None;
|
||||
}
|
||||
let scope = effective_scope(cfg);
|
||||
if !matches!(scope.check(&cfg.target, Action::Probe), Decision::Allow) {
|
||||
return None;
|
||||
}
|
||||
let dir = traffic_dir(cfg)?;
|
||||
let script = dir.join("browser-capture.js");
|
||||
std::fs::write(&script, driver_js()).ok()?;
|
||||
|
||||
let _ = tx.send("🧭 browser capture: loading the SPA in a real Chromium…".into()).await;
|
||||
let wait_ms = std::env::var("NEUROSPLOIT_BROWSER_TIMEOUT_MS").ok()
|
||||
.and_then(|v| v.parse::<u64>().ok())
|
||||
.unwrap_or(25_000)
|
||||
.to_string();
|
||||
let mut cmd = tokio::process::Command::new("node");
|
||||
cmd.arg(&script)
|
||||
.arg(&cfg.target)
|
||||
.arg(&wait_ms)
|
||||
.arg(auth_json(cfg))
|
||||
.arg("65536")
|
||||
.env("NEUROSPLOIT_UA", cfg.user_agent.clone().unwrap_or_else(default_user_agent))
|
||||
.kill_on_drop(true)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped());
|
||||
#[cfg(unix)]
|
||||
unsafe {
|
||||
// New process group so a timeout also kills Chromium, not just node.
|
||||
cmd.pre_exec(|| {
|
||||
libc::setsid();
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let child = match cmd.spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
let _ = tx.send(format!("🧭 browser capture: node failed ({e}) — continuing without it")).await;
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let pid = child.id();
|
||||
let output = match tokio::time::timeout(Duration::from_secs(60), child.wait_with_output()).await {
|
||||
Ok(Ok(o)) => o,
|
||||
Ok(Err(e)) => {
|
||||
let _ = tx.send(format!("🧭 browser capture: node failed ({e}) — continuing without it")).await;
|
||||
return None;
|
||||
}
|
||||
Err(_) => {
|
||||
if let Some(pid) = pid {
|
||||
#[cfg(unix)]
|
||||
unsafe {
|
||||
libc::kill(-(pid as i32), libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
let _ = tx.send("🧭 browser capture: timed out — continuing without it".into()).await;
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let Some(cap) = parse(&stdout) else {
|
||||
let _ = tx.send("🧭 browser capture: no result from the browser driver".into()).await;
|
||||
return None;
|
||||
};
|
||||
if !cap.get("available").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||
let err = cap.get("error").and_then(|v| v.as_str()).unwrap_or("browser unavailable");
|
||||
let _ = tx.send(format!("🧭 browser capture: {err} — continuing without it")).await;
|
||||
return None;
|
||||
}
|
||||
|
||||
let raw_path = dir.join("browser-capture.json");
|
||||
if let Ok(body) = serde_json::to_vec_pretty(&cap) {
|
||||
let _ = std::fs::write(&raw_path, body);
|
||||
}
|
||||
let n = cap.get("endpoints").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0);
|
||||
let _ = tx.send(format!("🧭 browser capture: {n} same-origin endpoint(s) recorded")).await;
|
||||
Some(prompt_block(&cap, Some(&raw_path)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_the_driver_payload() {
|
||||
let j = parse("noise NSJSON{\"available\":true,\"title\":\"x\"}NSEND tail").unwrap();
|
||||
assert_eq!(j["available"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_block_lists_endpoints_and_apis() {
|
||||
let cap = serde_json::json!({
|
||||
"available": true, "title": "Shop",
|
||||
"endpoints": [{"method":"GET","path":"/api/products","status":200,"contentType":"application/json"}],
|
||||
"api": [{"method":"POST","path":"/api/login","status":200,"contentType":"application/json"}],
|
||||
"scripts": ["https://x/static/app.js"],
|
||||
"cookies": ["sid"]
|
||||
});
|
||||
let s = prompt_block(&cap, None);
|
||||
assert!(s.contains("/api/products"));
|
||||
assert!(s.contains("/api/login"));
|
||||
assert!(s.contains("app.js"));
|
||||
assert!(s.contains("sid"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_header_becomes_playwright_headers() {
|
||||
let mut cfg = RunConfig::new("https://x/");
|
||||
cfg.auth = Some("Authorization: Bearer abc".into());
|
||||
let j: Value = serde_json::from_str(&auth_json(&cfg)).unwrap();
|
||||
assert_eq!(j["Authorization"], "Bearer abc");
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ pub mod autoconfig;
|
||||
pub mod belief;
|
||||
pub mod gates;
|
||||
pub mod browser;
|
||||
pub mod browser_capture;
|
||||
pub mod budget;
|
||||
pub mod cache;
|
||||
pub mod capability;
|
||||
|
||||
@@ -2043,6 +2043,14 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender
|
||||
write_meta(&cfg, &p, &asset);
|
||||
crate::probe::probe_json(&p)
|
||||
};
|
||||
// Real-browser capture: the SPA's XHR/API surface that curl cannot see.
|
||||
// Best-effort; disable with NEUROSPLOIT_BROWSER_RECON=0.
|
||||
let browser_facts = if cfg.offline {
|
||||
String::new()
|
||||
} else {
|
||||
crate::browser_capture::capture(&cfg, &tx).await.unwrap_or_default()
|
||||
};
|
||||
let probe_facts = format!("{probe_facts}{browser_facts}");
|
||||
// Wildcard engagement: deterministically enumerate + liveness-filter the
|
||||
// in-scope subdomains and fold them into the surface, so the run tests the
|
||||
// whole authorized domain, not just the seed host.
|
||||
|
||||
Reference in new issue
Block a user