Skip to content

armgit / ARES

Public Imported from GitHub
0

ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.

feat: harden runtime state and add graph dashboard

Mafifrizi75efa3c7ee32
diff --git a/.gitignore b/.gitignore
index af228aa..fb62f0e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,6 +7,7 @@ build/
.env
*.log
.pytest_cache/
+.pytest-tmp/
.mypy_cache/
.ruff_cache/
htmlcov/
diff --git a/README.md b/README.md
index 848d26c..429add5 100644
--- a/README.md
+++ b/README.md
@@ -219,12 +219,14 @@ Common page inputs and outputs:
Telemetry note:
-The Overview telemetry panel is an in-memory operational snapshot for the
-currently running ARES API process. It shows module run totals, success/failure
-counts, latency, throughput, findings, hosts, queue depth, and worker health. It
-is useful while operating or recording a demo, but it is not the durable
-campaign database and resets when the API process restarts. Use Campaigns,
-Findings, and Reports for permanent engagement history.
+The Overview telemetry panel combines live process metrics with database-backed
+aggregates for module runs, confirmed findings, and discovered hosts. Queue
+depth and worker health remain process-local and reset on restart; campaign
+findings, credentials, module-run records, and graph snapshots remain durable.
+
+Graph data is hydrated from campaign records and a sanitized persisted graph
+snapshot. BloodHound/SharpHound imports are available to later graph requests;
+credential secrets are never included in graph or API payloads.
Planning modes:
diff --git a/ares/api/graph.py b/ares/api/graph.py
index b767221..44eff8a 100644
--- a/ares/api/graph.py
+++ b/ares/api/graph.py
@@ -110,6 +110,26 @@ _PRIVILEGE_COLORS = {
"user": "#6c757d",
}
+_GRAPH_SECRET_KEYS = {
+ "secret", "secret_enc", "password", "passwd", "token", "api_key",
+ "private_key", "hash_value", "nt_hash", "lm_hash", "cracked_value",
+}
+
+
+def _safe_graph_data(value: Any) -> Any:
+ """Defence in depth for graph snapshots originating outside the API process."""
+ if isinstance(value, dict):
+ return {
+ str(key): _safe_graph_data(item)
+ for key, item in value.items()
+ if str(key).lower() not in _GRAPH_SECRET_KEYS
+ }
+ if isinstance(value, list):
+ return [_safe_graph_data(item) for item in value]
+ if value is None or isinstance(value, (str, int, float, bool)):
+ return value
+ return str(value)
+
# ── Graph builder ──────────────────────────────────────────────────────────────
@@ -136,11 +156,23 @@ def build_campaign_graph(campaign: Any) -> dict[str, Any]:
session = getattr(campaign, "session", None) or getattr(campaign, "_session", None)
if session:
- hosts = getattr(session, "hosts", {})
- for ip, host in hosts.items():
+ session_hosts = getattr(session, "hosts", None)
+ if isinstance(session_hosts, dict):
+ host_items = list(session_hosts.items())
+ elif callable(getattr(session, "all_hosts", None)):
+ host_items = [
+ (str(getattr(host, "ip_address", "") or getattr(host, "hostname", "")), host)
+ for host in session.all_hosts()
+ ]
+ else:
+ host_items = []
+ for ip, host in host_items:
+ if not ip:
+ continue
c_level = getattr(getattr(host, "compromise_level", None), "value", "none")
is_dc = getattr(host, "is_dc", False)
hostname = getattr(host, "hostname", "") or ip
+ is_owned = bool(getattr(host, "owned", getattr(host, "is_owned", False)))
add_node(APIGraphNode(
id = f"host:{ip}",
@@ -153,11 +185,11 @@ def build_campaign_graph(campaign: Any) -> dict[str, Any]:
"is_dc": is_dc,
"open_ports": getattr(host, "open_ports", []),
"os_info": getattr(host, "os_info", ""),
- "owned": getattr(host, "is_owned", False),
+ "owned": is_owned,
},
color = _COMPROMISE_COLORS.get(c_level, "#6c757d"),
shape = "diamond" if is_dc else "circle",
- size = 35 if is_dc else (28 if getattr(host, "is_owned", False) else 20),
+ size = 35 if is_dc else (28 if is_owned else 20),
))
# Edges: discovery chain
@@ -190,9 +222,9 @@ def build_campaign_graph(campaign: Any) -> dict[str, Any]:
))
# ── Credentials ────────────────────────────────────────────────────────
- vault = getattr(campaign, "vault", None)
+ vault = getattr(campaign, "vault", None) or getattr(campaign, "_vault", None)
if vault:
- creds = getattr(vault, "_credentials", {})
+ creds = getattr(vault, "_store", None) or getattr(vault, "_credentials", {})
for cred_id, cred in creds.items():
username = getattr(cred, "username", "")
domain = getattr(cred, "domain", "")
@@ -353,6 +385,75 @@ def build_campaign_graph(campaign: Any) -> dict[str, Any]:
},
}
+
+def merge_durable_attack_graph(
+ campaign_graph: dict[str, Any],
+ artifact_graph: dict[str, Any] | None,
+) -> dict[str, Any]:
+ """Merge a persisted AttackGraph snapshot into the dashboard graph contract."""
+ if not artifact_graph:
+ campaign_graph["data_sources"] = {"campaign_runtime": True, "artifact_graph": False}
+ return campaign_graph
+
+ nodes = list(campaign_graph.get("nodes", []))
+ edges = list(campaign_graph.get("edges", []))
+ node_map: dict[str, str] = {}
+ for raw_node in artifact_graph.get("nodes", []):
+ if not isinstance(raw_node, dict) or not raw_node.get("id"):
+ continue
+ raw_id = str(raw_node["id"])
+ node_id = f"artifact:{raw_id}"
+ node_map[raw_id] = node_id
+ node_type = str(raw_node.get("type") or "artifact")
+ nodes.append(APIGraphNode(
+ id=node_id,
+ type=node_type,
+ label=str(raw_node.get("label") or raw_id),
+ data={
+ "risk": raw_node.get("risk", 0.0),
+ "is_target": bool(raw_node.get("is_target", False)),
+ "properties": _safe_graph_data(raw_node.get("properties", {})),
+ "source": "durable_artifact_graph",
+ },
+ color=str(raw_node.get("color") or "#64748b"),
+ shape="diamond" if bool(raw_node.get("is_target", False)) else "circle",
+ size=24 if bool(raw_node.get("is_target", False)) else 18,
+ ).to_dict())
+ for raw_edge in artifact_graph.get("links", []):
+ if not isinstance(raw_edge, dict):
+ continue
+ source = node_map.get(str(raw_edge.get("source") or ""))
+ target = node_map.get(str(raw_edge.get("target") or ""))
+ if not source or not target:
+ continue
+ edges.append(APIGraphEdge(
+ source=source,
+ target=target,
+ type=str(raw_edge.get("type") or "related"),
+ label=str(raw_edge.get("label") or ""),
+ weight=float(raw_edge.get("weight", 1.0) or 1.0),
+ data={
+ "properties": _safe_graph_data(raw_edge.get("properties", {})),
+ "source": "durable_artifact_graph",
+ },
+ ).to_dict())
+
+ merged = dict(campaign_graph)
+ merged["nodes"] = nodes
+ merged["edges"] = edges
+ stats = dict(merged.get("stats", {}))
+ stats["total_nodes"] = len(nodes)
+ stats["total_edges"] = len(edges)
+ stats["artifact_nodes"] = len(node_map)
+ stats["artifact_edges"] = sum(
+ 1 for edge in edges
+ if edge.get("data", {}).get("source") == "durable_artifact_graph"
+ )
+ merged["stats"] = stats
+ merged["layout_hint"] = "hierarchical" if len(nodes) < 20 else "force_directed"
+ merged["data_sources"] = {"campaign_runtime": True, "artifact_graph": True}
+ return merged
+
# Backward-compatible aliases
GraphNode = APIGraphNode
GraphEdge = APIGraphEdge
diff --git a/ares/api/server.py b/ares/api/server.py
index 06b61cc..eb48a5e 100644
--- a/ares/api/server.py
+++ b/ares/api/server.py
@@ -202,6 +202,29 @@ async def _campaign_for_report(db: AresDatabase, row: dict[str, Any]) -> Campaig
return campaign
+async def _hydrate_campaign_graph_data(
+ db: AresDatabase,
+ engine: AresEngine,
+ row: dict[str, Any],
+) -> tuple[Campaign, Any, list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
+ """Rebuild the safe campaign view used by both graph endpoints."""
+ campaign = _campaign_from_db_row(row)
+ finding_rows, _ = await db.list_findings(
+ campaign.id,
+ page=1,
+ per_page=10000,
+ false_positive=False,
+ )
+ campaign.findings = [
+ _finding_from_db_row(finding_row, report_confirmed=True)
+ for finding_row in finding_rows
+ ]
+ hosts = await db.get_hosts(campaign.id)
+ credentials = await db.get_credentials(campaign.id, decrypt=False)
+ runtime_state = await engine.ensure_campaign_runtime(campaign, db)
+ return campaign, runtime_state, finding_rows, hosts, credentials
+
+
def _setup_otel(app: FastAPI, settings: Any) -> None:
"""Initialize OpenTelemetry tracing if endpoint is configured."""
if not settings.ares_otel_endpoint:
@@ -222,6 +245,7 @@ _db: AresDatabase | None = None
# WebSocket connection registry: campaign_id → set of WebSocket connections
_ws_connections: dict[str, set[WebSocket]] = {}
_active_engagements: dict[str, str] = {} # engagement_id → campaign_id
+_engagement_tasks: dict[str, asyncio.Task[None]] = {}
_MAX_CONCURRENT_ENGAGEMENTS = 3 # operator-configurable via ARES_MAX_ENGAGEMENTS
# Asyncio lock for atomic engagement registration (prevents TOCTOU race)
@@ -294,7 +318,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
_RL["global"] = settings.ares_rate_limit_rpm
- _engine = AresEngine(settings=settings)
+ _engine = AresEngine(settings=settings, db=_db)
_engine.load_modules()
app.state.engine = _engine
@@ -556,6 +580,12 @@ def get_engine(request: Request) -> AresEngine:
engine = request.app.state.engine
if not engine:
raise HTTPException(503, "Engine not ready")
+ if isinstance(engine, AresEngine):
+ try:
+ engine.bind_database(request.app.state.db)
+ except RuntimeError as exc:
+ logger.error("engine_database_binding_mismatch", error=str(exc))
+ raise HTTPException(503, "Engine persistence is not ready") from exc
return engine
@@ -1158,6 +1188,7 @@ async def restore_campaign_vault(
request: Request,
campaign_id: str,
actor: AuthenticatedUser = Depends(require_operator()),
+ engine: AresEngine = Depends(get_engine),
db: AresDatabase = Depends(get_db),
) -> dict[str, Any]:
"""
@@ -1165,6 +1196,8 @@ async def restore_campaign_vault(
Returns count of credentials re-hydrated into memory.
The vault is attached to the running engine's campaign object.
"""
+ if isinstance(engine, AresEngine):
+ engine.bind_database(db)
ip = request.client.host if request.client else "unknown"
allowed, _ = await _limiter.is_allowed_async(
f"vault_restore:{ip}", RATE_LIMITS["vault_restore"]
@@ -1176,19 +1209,9 @@ async def restore_campaign_vault(
raise HTTPException(404, "Campaign not found")
await _require_campaign_access(c, actor)
- records = await db.load_credentials_raw(campaign_id)
- if not records:
- return {
- "restored": 0,
- "campaign_id": campaign_id,
- "message": "No credentials found in DB for this campaign",
- }
-
- from ares.credential.vault import CredentialVault
-
- settings = get_settings()
- vault = CredentialVault(encryption_key=settings.encryption_key_value)
- count = vault.restore_from_db_records(records)
+ # Restore into the engine-owned per-campaign state, rather than into a
+ # local vault object that disappears as soon as this request completes.
+ count = await engine.restore_campaign_vault(_campaign_from_db_row(c))
await db.audit(
actor.username,
@@ -1196,7 +1219,11 @@ async def restore_campaign_vault(
f"campaign={campaign_id} count={count}",
campaign_id,
)
- return {"restored": count, "campaign_id": campaign_id}
+ return {
+ "restored": count,
+ "campaign_id": campaign_id,
+ "message": "Vault restored into the active campaign runtime state",
+ }
@app.get("/campaigns/{campaign_id}/findings", tags=["campaigns"])
@@ -1309,6 +1336,9 @@ async def run_module(
"""Run module. HIGH_NOISE requires team_lead. Rate limited: 20/min."""
from ares.modules.base import OpsecLevel
+ if isinstance(engine, AresEngine):
+ engine.bind_database(db)
+
# Use the engine's already-loaded registry — avoids rescanning disk on every request
cls = engine.registry.get(module_id)
if cls and getattr(cls, "OPSEC_LEVEL", None) == OpsecLevel.HIGH_NOISE:
@@ -1370,69 +1400,12 @@ async def run_module(
if getattr(body, "dry_run", False):
return engine.dry_run_module(module_id, safe_params)
- run_started = time.monotonic()
- try:
- result = await engine.run_module(
- module_id, c_obj, safe_params, actor_role=actor.role
- )
- except Exception:
- await _record_module_run(
- db,
- body.campaign_id,
- module_id,
- outcome="error",
- success=False,
- duration_ms=(time.monotonic() - run_started) * 1000,
- )
- raise
-
- status = _module_outcome_value(getattr(result, "status", ""))
- outcome = _module_outcome_value(getattr(result, "outcome", "")) or status
- success = _is_successful_module_outcome(outcome)
- run_duration_ms = float(getattr(result, "duration_ms", 0.0) or 0.0)
- if run_duration_ms <= 0.0:
- run_duration_ms = max(0.0, (time.monotonic() - run_started) * 1000)
- result.duration_ms = run_duration_ms
- await _record_module_run(
- db,
- body.campaign_id,
- module_id,
- outcome=outcome or "unknown",
- success=success,
- duration_ms=run_duration_ms,
+ # The DB-bound engine owns finding, credential, module-run, audit, and
+ # telemetry persistence. Keeping this route read/response-only prevents
+ # duplicate rows for API-triggered executions.
+ result = await engine.run_module(
+ module_id, c_obj, safe_params, actor_role=actor.role
)
- await db.audit(
- actor.username, "module_run", f"module={module_id}", body.campaign_id, module_id
- )
-
- # Keep the operational telemetry panel in sync with API-triggered executions.
- try:
- from ares.telemetry.collector import get_collector
-
- get_collector().record_execution(
- module_id,
- run_duration_ms,
- success=success,
- campaign_id=body.campaign_id,
- )
- if result.findings:
- get_collector().record_finding(len(result.findings))
- except Exception as exc:
- logger.debug("telemetry_record_failed", module_id=module_id, error=str(exc))
-
- # Enrich findings with CVSS scores and trace ID before persisting
- from ares.core.cvss import enrich_finding_with_cvss
- from ares.core.tracing import get_current_trace_id
-
- _trace_id = get_current_trace_id() or ""
- for finding in result.findings:
- enrich_finding_with_cvss(finding)
- if _trace_id:
- finding.trace_id = _trace_id
-
- # Persist findings to DB
- for finding in result.findings:
- await db.save_finding(body.campaign_id, finding, module_id)
# Broadcast to WebSocket subscribers
await _broadcast_event(
@@ -1606,6 +1579,18 @@ async def start_autonomous_engagement(
if config_error:
raise HTTPException(status_code=422, detail=config_error)
+ campaign_data = await _db.get_campaign(body.campaign_id)
+ if not campaign_data:
+ raise HTTPException(
+ status_code=404, detail=f"Campaign {body.campaign_id!r} not found"
+ )
+ await _require_campaign_access(campaign_data, actor)
+ campaign = (
+ _campaign_from_db_row(campaign_data)
+ if isinstance(campaign_data, dict)
+ else campaign_data
+ )
+
# FIX 2: Concurrent engagement limit — atomic via asyncio.Lock (Issue 14)
_max = int(os.environ.get("ARES_MAX_ENGAGEMENTS", _MAX_CONCURRENT_ENGAGEMENTS))
_lock = await _get_engagement_lock()
@@ -1637,20 +1622,7 @@ async def start_autonomous_engagement(
engagement_id = f"engage_{body.campaign_id[:8]}_{int(_time_reg.time())}"
_active_engagements[engagement_id] = body.campaign_id
-
- campaign_data = await _db.get_campaign(body.campaign_id)
- if not campaign_data:
- raise HTTPException(
- status_code=404, detail=f"Campaign {body.campaign_id!r} not found"
- )
# Enforce campaign ownership — same as all other campaign endpoints
- await _require_campaign_access(campaign_data, actor)
- campaign = (
- _campaign_from_db_row(campaign_data)
- if isinstance(campaign_data, dict)
- else campaign_data
- )
-
async def _run() -> None:
from ares.strategy import OperatorNotifier, StrategyEngine
@@ -1702,11 +1674,13 @@ async def start_autonomous_engagement(
}
)
finally:
- _active_engagements.pop(engagement_id, None) # deregister on completion
-
- import asyncio as _aio
+ async with _lock:
+ _active_engagements.pop(engagement_id, None)
+ _engagement_tasks.pop(engagement_id, None)
- _aio.ensure_future(_run())
+ _engagement_tasks[engagement_id] = asyncio.create_task(
+ _run(), name=f"ares-strategy-{engagement_id}"
+ )
return {
"engagement_id": engagement_id,
"status": "started",
@@ -2221,18 +2195,22 @@ async def get_prometheus(
async def campaign_graph(
campaign_id: str,
actor: AuthenticatedUser = _api_key_read_dep,
+ engine: AresEngine = Depends(get_engine),
db: AresDatabase = Depends(get_db),
) -> dict[str, Any]:
- from ares.api.graph import build_campaign_graph
+ from ares.api.graph import build_campaign_graph, merge_durable_attack_graph
campaign = await db.get_campaign(campaign_id)
if not campaign:
raise HTTPException(404, "Campaign not found")
await _require_campaign_access(campaign, actor)
- from ares.core.campaign import Campaign as CM
-
- c_obj = CM(**{k: v for k, v in campaign.items() if k in CM.model_fields})
- return build_campaign_graph(c_obj)
+ c_obj, runtime_state, _findings, _hosts, _credentials = await _hydrate_campaign_graph_data(
+ db, engine, campaign
+ )
+ snapshot = await db.get_campaign_graph(campaign_id)
+ if snapshot is None and getattr(runtime_state, "attack_graph", None) is not None:
+ snapshot = runtime_state.attack_graph.to_d3_json()
+ return merge_durable_attack_graph(build_campaign_graph(c_obj), snapshot)
@app.get("/graph/{campaign_id}/attack-paths", tags=["visualization"])
@@ -2242,6 +2220,7 @@ async def campaign_attack_paths(
source: str | None = None,
target: str | None = None,
actor: AuthenticatedUser = _api_key_read_dep,
+ engine: AresEngine = Depends(get_engine),
db: AresDatabase = Depends(get_db),
) -> dict[str, Any]:
"""
@@ -2259,7 +2238,6 @@ async def campaign_attack_paths(
try:
from ares.graph.attack_graph import AttackGraph
- from ares.normalize.artifacts import ArtifactStore
except ImportError as e:
logger.warning(
"attack_graph_unavailable", error=str(e), hint="pip install networkx"
@@ -2270,25 +2248,21 @@ async def campaign_attack_paths(
"Ensure networkx is installed: pip install ares-redteam",
)
- # Build graph from campaign findings stored in DB
- rows, _ = await db.list_findings(campaign_id, page=1, per_page=10000)
- hosts = await db.get_hosts(campaign_id)
-
- store = ArtifactStore()
- from ares.normalize.artifacts import HostArtifact
-
- for h in hosts:
- store.add(
- HostArtifact(
- ip_address=h.get("ip_address", ""),
- hostname=h.get("hostname", ""),
- is_dc=h.get("is_dc", False),
- os=h.get("os", ""),
- )
- )
-
- graph = AttackGraph()
- graph.build_from_store(store)
+ _campaign, runtime_state, rows, hosts, credentials = await _hydrate_campaign_graph_data(
+ db, engine, campaign
+ )
+ snapshot = await db.get_campaign_graph(campaign_id)
+ if snapshot:
+ graph = AttackGraph.from_d3_json(snapshot)
+ elif getattr(runtime_state, "attack_graph", None) is not None:
+ graph = runtime_state.attack_graph
+ else:
+ graph = AttackGraph()
+ graph.build_from_store(runtime_state.artifact_store)
+ # These rows are durable evidence, not merely a preflight check. Add their
+ # safe metadata so attack-path queries cannot silently ignore persisted data.
+ graph.add_persisted_campaign_data(hosts, rows, credentials)
+ runtime_state.attack_graph = graph
if not graph.stats()["nodes"]:
return {
@@ -2386,17 +2360,6 @@ async def run_campaign_plan(
c_obj = _campaign_from_db_row(campaign)
results = await engine.run_plan(plan, c_obj, body.global_params, actor_role=actor.role)
- for module_id, result in results.items():
- status = _module_outcome_value(getattr(result, "status", ""))
- outcome = _module_outcome_value(getattr(result, "outcome", "")) or status
- await _record_module_run(
- db,
- campaign_id,
- module_id,
- outcome=outcome or "unknown",
- success=_is_successful_module_outcome(outcome),
- duration_ms=float(getattr(result, "duration_ms", 0.0) or 0.0),
- )
return {
"campaign_id": campaign_id,
"modules_run": len(results),
@@ -2616,12 +2579,15 @@ async def ingest_bloodhound(
campaign_id: str,
body: BloodhoundIngestRequest,
actor: AuthenticatedUser = Depends(require_operator()),
+ engine: AresEngine = Depends(get_engine),
db: AresDatabase = Depends(get_db),
) -> dict[str, Any]:
"""
Import BloodHound/SharpHound JSON into the campaign's attack graph.
After ingest, use GET /graph/{id}/attack-paths to compute paths to DA.
"""
+ if isinstance(engine, AresEngine):
+ engine.bind_database(db)
campaign = await db.get_campaign(campaign_id)
if not campaign:
raise HTTPException(404, "Campaign not found")
@@ -2637,7 +2603,17 @@ async def ingest_bloodhound(
try:
from ares.graph.attack_graph import AttackGraph
- graph = AttackGraph()
+ _campaign, runtime_state, _findings, _hosts, _credentials = await _hydrate_campaign_graph_data(
+ db, engine, campaign
+ )
+ snapshot = await db.get_campaign_graph(campaign_id)
+ if snapshot:
+ graph = AttackGraph.from_d3_json(snapshot)
+ elif getattr(runtime_state, "attack_graph", None) is not None:
+ graph = runtime_state.attack_graph
+ else:
+ graph = AttackGraph()
+ graph.build_from_store(runtime_state.artifact_store)
result = graph.ingest_bloodhound(safe_path)
if result.get("error"):
raise HTTPException(422, result["error"])
@@ -2651,6 +2627,8 @@ async def ingest_bloodhound(
f"nodes={result['nodes_added']} edges={result['edges_added']}",
campaign_id,
)
+ runtime_state.attack_graph = graph
+ await db.save_campaign_graph(campaign_id, graph.to_d3_json())
return {
"campaign_id": campaign_id,
"ingest_result": result,
@@ -2659,6 +2637,8 @@ async def ingest_bloodhound(
}
except ImportError:
raise HTTPException(503, "networkx required — pip install networkx")
+ except HTTPException:
+ raise
except Exception as exc:
raise HTTPException(500, f"Bloodhound ingest failed: {str(exc)[:200]}")
diff --git a/ares/core/context.py b/ares/core/context.py
index c1cd4d9..ac79688 100644
--- a/ares/core/context.py
+++ b/ares/core/context.py
@@ -86,6 +86,8 @@ class ExecutionContext:
# These are references — mutations visible to engine after execution
session: Any = None # OperatorSession
vault: Any = None # CredentialVault
+ artifact_store: Any = None # ArtifactStore
+ runtime_state: Any = None # CampaignRuntimeState
# ── Engine references ─────────────────────────────────────────────────
settings: Any = None # AresSettings
@@ -180,6 +182,7 @@ class ExecutionContext:
"tags": self.tags,
"has_credentials": len(self.credentials) > 0,
"has_session": self.session is not None,
+ "has_artifact_store": self.artifact_store is not None,
}
@classmethod
@@ -195,6 +198,8 @@ class ExecutionContext:
credentials: list[Any] | None = None,
session: Any = None,
vault: Any = None,
+ artifact_store: Any = None,
+ runtime_state: Any = None,
settings: Any = None,
noise: Any = None,
telemetry: Any = None,
@@ -218,6 +223,8 @@ class ExecutionContext:
credentials = credentials or [],
session = session,
vault = vault,
+ artifact_store = artifact_store,
+ runtime_state = runtime_state,
settings = settings,
campaign = campaign,
noise = noise,
diff --git a/ares/core/engine.py b/ares/core/engine.py
index caa4e7e..1d65829 100644
--- a/ares/core/engine.py
+++ b/ares/core/engine.py
@@ -22,6 +22,7 @@ from ares.core.logger import audit, setup_logger
from ares.core.noise import NoiseController
from ares.core.notifier import build_notifier_from_settings
from ares.core.plugin.loader import ModuleRegistry, PluginLoader
+from ares.core.runtime_state import CampaignRuntimeState, CampaignRuntimeStateStore
from ares.core.validator import FindingValidator, ValidationResult, build_default_validator
logger = get_logger("ares.engine")
@@ -45,11 +46,33 @@ MODULE_OUTCOMES = (
"unsupported",
"module_error",
)
+_SUCCESSFUL_MODULE_OUTCOMES = {
+ "modulestatus.done",
+ "done",
+ "success",
+ "partial",
+ "confirmed_findings",
+ "completed_no_findings",
+ "dry_run_ok",
+}
_SECRET_ERROR_PATTERN = re.compile(
r"(?i)\b(password|passwd|secret|token|api[_-]?key|nt_hash|lm_hash|krbtgt_hash)\b\s*([:=])\s*([^\s,;]+)"
)
+def module_outcome_value(value: Any) -> str:
+ """Normalize enum/string result values for durable outcome handling."""
+ enum_value = getattr(value, "value", None)
+ if enum_value is not None:
+ value = enum_value
+ return str(value or "").strip().lower()
+
+
+def is_successful_module_outcome(value: Any) -> bool:
+ """Return whether an engine outcome represents a completed execution."""
+ return module_outcome_value(value) in _SUCCESSFUL_MODULE_OUTCOMES
+
+
def redact_error_message(error: str | None) -> str | None:
"""Bound and redact common secret key/value forms in engine errors."""
if not error:
@@ -312,6 +335,13 @@ class AresEngine:
self._registry: ModuleRegistry | None = None
self._semaphore: asyncio.Semaphore | None = None
self.notifier = build_notifier_from_settings(self.settings)
+ from ares.telemetry.collector import get_collector
+
+ self.telemetry = get_collector()
+ self._runtime_states = CampaignRuntimeStateStore(
+ self.settings.encryption_key_value,
+ telemetry=self.telemetry,
+ )
setup_logger(self.settings.ares_log_level, self.settings.ares_log_file)
# ── Loading ────────────────────────────────────────────────────────────
@@ -337,6 +367,34 @@ class AresEngine:
def list_modules(self) -> list[dict[str, Any]]:
return self.registry.list_metadata()
+ async def ensure_campaign_runtime(
+ self,
+ campaign: Campaign,
+ db: Any | None = None,
+ ) -> CampaignRuntimeState:
+ """Attach the campaign's shared state and rehydrate safe durable state."""
+ return await self._runtime_states.ensure(campaign, self.db if db is None else db)
+
+ def bind_database(self, db: Any) -> None:
+ """Bind the active API database once, rejecting accidental split persistence."""
+ if self.db is None:
+ self.db = db
+ return
+ if self.db is not db:
+ raise RuntimeError("AresEngine is already bound to a different database")
+
+ async def restore_campaign_vault(self, campaign: Campaign) -> int:
+ """Restore encrypted credential records into the shared campaign state."""
+ if self.db is None:
+ raise RuntimeError("Credential restore requires an active database")
+ return await self._runtime_states.restore_vault(campaign, self.db)
+
+ def campaign_runtime_state(self, campaign_id: str) -> CampaignRuntimeState | None:
+ return self._runtime_states.get(campaign_id)
+
+ def discard_campaign_runtime(self, campaign_id: str) -> None:
+ self._runtime_states.discard(campaign_id)
+
# ── Single module ──────────────────────────────────────────────────────
async def run_module(
@@ -348,25 +406,26 @@ class AresEngine:
timeout_seconds: int = 120,
actor_role: str = "operator",
) -> EngineModuleResult:
+ runtime_state = await self.ensure_campaign_runtime(campaign)
if module_id not in self.registry:
- return EngineModuleResult(
+ return await self._finalize_module_result(campaign, module_id, EngineModuleResult(
module_id=module_id,
status=ModuleStatus.FAILED,
error=f"Module '{module_id}' not found. Run: ares module list",
- )
+ ))
# ── RBAC check — role must be allowed to run this module ──────────
from ares.collab.manager import can_role_run_module
if not can_role_run_module(actor_role, module_id, self.registry):
audit("module_rbac_denied", actor=campaign.operator,
detail=f"role={actor_role} module={module_id}")
- return EngineModuleResult(
+ return await self._finalize_module_result(campaign, module_id, EngineModuleResult(
module_id=module_id,
status=ModuleStatus.FAILED,
error=(f"Role '{actor_role}' is not permitted to run "
f"'{module_id}'. Check ROLE_PERMISSIONS in collab/manager.py."),
- )
+ ))
# ── Scope pre-check — enforce before any module code runs ────────
# Cloud/reporting modules use API credentials, not host IPs — skip scope check
@@ -378,12 +437,12 @@ class AresEngine:
from ares.core.errors import ScopeError
audit("module_scope_violation", actor=campaign.operator,
detail=f"module={module_id} target={_target!r} not in scope")
- return EngineModuleResult(
+ return await self._finalize_module_result(campaign, module_id, EngineModuleResult(
module_id=module_id,
status=ModuleStatus.FAILED,
error=f"Target {_target!r} is not in campaign scope {[s.cidr for s in campaign.scope]}. "
"Add the target CIDR to scope or use a different target.",
- )
+ ))
cls = self.registry.get(module_id)
noise = NoiseController(campaign)
@@ -411,8 +470,14 @@ class AresEngine:
domain = params.get("domain", ""),
params = params,
operator = campaign.operator,
+ credentials=runtime_state.safe_credentials(),
+ session = runtime_state.session,
+ vault = runtime_state.vault,
+ artifact_store=runtime_state.artifact_store,
+ runtime_state=runtime_state,
settings = self.settings,
noise = noise,
+ telemetry = runtime_state.telemetry,
)
@@ -430,12 +495,12 @@ class AresEngine:
duration_ms = round((time.monotonic() - t0) * 1000, 2)
audit("module_validation_failed", actor=campaign.operator,
detail=f"module={module_id} reason=timeout")
- return EngineModuleResult(
+ return await self._finalize_module_result(campaign, module_id, EngineModuleResult(
module_id = module_id,
status = ModuleStatus.FAILED,
error = f"Module '{module_id}' validate() timed out (>10s)",
duration_ms = duration_ms,
- )
+ ))
except Exception as val_exc:
duration_ms = round((time.monotonic() - t0) * 1000, 2)
err_msg = str(val_exc)
@@ -443,12 +508,12 @@ class AresEngine:
module_id=module_id, error=err_msg[:200])
audit("module_validation_failed", actor=campaign.operator,
detail=f"module={module_id} error={err_msg[:100]}")
- return EngineModuleResult(
+ return await self._finalize_module_result(campaign, module_id, EngineModuleResult(
module_id = module_id,
status = ModuleStatus.FAILED,
error = f"Validation failed: {err_msg[:300]}",
duration_ms = duration_ms,
- )
+ ))
# ── end validate ───────────────────────────────────────────
# Call execute(ctx) — preferred interface.
@@ -508,8 +573,14 @@ class AresEngine:
domain = params.get("domain", ""),
params = params,
operator = campaign.operator,
+ credentials=runtime_state.safe_credentials(),
+ session = runtime_state.session,
+ vault = runtime_state.vault,
+ artifact_store=runtime_state.artifact_store,
+ runtime_state=runtime_state,
settings = self.settings,
noise = noise,
+ telemetry = runtime_state.telemetry,
)
module_result2 = await asyncio.wait_for(
module2.execute(ctx2), timeout=effective_timeout
@@ -540,11 +611,11 @@ class AresEngine:
if _last_exc is not None:
status = (ModuleStatus.TIMEOUT if _was_timeout
else ModuleStatus.FAILED)
- return EngineModuleResult(
+ return await self._finalize_module_result(campaign, module_id, EngineModuleResult(
module_id=module_id, status=status,
error=str(_last_exc)[:300],
duration_ms=round((time.monotonic() - t0) * 1000, 2),
- )
+ ))
duration_ms = round((time.monotonic() - t0) * 1000, 2)
@@ -558,9 +629,17 @@ class AresEngine:
# Persist confirmed findings
confirmed: list[Finding] = []
+ from ares.core.cvss import enrich_finding_with_cvss
+ from ares.core.tracing import get_current_trace_id
+
+ trace_id = get_current_trace_id() or ""
for f in findings:
if not f.false_positive:
f.validated = True
+ f.module_id = f.module_id or module_id
+ enrich_finding_with_cvss(f)
+ if trace_id:
+ f.trace_id = trace_id
campaign.add_finding(f)
confirmed.append(f)
if self.db:
@@ -598,7 +677,7 @@ class AresEngine:
f"confirmed={len(confirmed)} fp={fp_count}"))
# ── Persist vault credentials to DB ───────────────────────────────
- if self.db and getattr(campaign, "_vault", None) is not None:
+ if self.db and runtime_state.vault is not None:
try:
await self._persist_vault_credentials(campaign)
except Exception as _ve:
@@ -612,16 +691,12 @@ class AresEngine:
cls_ref = self.registry.get(module_id)
outputs = getattr(cls_ref, "OUTPUTS", []) if cls_ref else []
if outputs and raw:
- # Retrieve or create campaign artifact store
- if not hasattr(campaign, "_artifact_store"):
- from ares.normalize.artifacts import ArtifactStore
- campaign._artifact_store = ArtifactStore() # type: ignore[attr-defined]
normalizer = ArtifactNormalizer()
artifact_count = normalizer.normalize(
module_id=module_id,
outputs=outputs,
raw=raw,
- store=campaign._artifact_store, # type: ignore[attr-defined]
+ store=runtime_state.artifact_store,
)
if artifact_count > 0:
logger.debug(
@@ -632,12 +707,16 @@ class AresEngine:
except Exception as _norm_exc:
logger.debug("artifact_normalization_skipped", error=str(_norm_exc)[:80])
- return EngineModuleResult(
+ if self.db:
+ await self._persist_runtime_hosts(campaign, runtime_state)
+ await self._persist_runtime_graph(campaign, runtime_state)
+
+ return await self._finalize_module_result(campaign, module_id, EngineModuleResult(
module_id=module_id, status=ModuleStatus.DONE,
findings=confirmed,
validation_results=validation_results,
raw_output=raw, duration_ms=duration_ms,
- )
+ ))
# ── Parallel plan ──────────────────────────────────────────────────────
@@ -967,6 +1046,137 @@ class AresEngine:
],
}
+ async def _finalize_module_result(
+ self,
+ campaign: Campaign,
+ module_id: str,
+ result: EngineModuleResult,
+ ) -> EngineModuleResult:
+ """Persist one safe execution record after the engine has a final result."""
+ if self.db is None:
+ return result
+
+ outcome = module_outcome_value(result.outcome) or module_outcome_value(result.status)
+ success = is_successful_module_outcome(outcome)
+ duration_ms = max(0.0, float(result.duration_ms or 0.0))
+
+ try:
+ await self.db.record_module_run(
+ campaign_id=campaign.id,
+ module_id=module_id,
+ outcome=(outcome or "unknown")[:64],
+ success=success,
+ duration_ms=duration_ms,
+ )
+ except Exception as exc:
+ logger.warning(
+ "engine_module_run_persist_failed",
+ module_id=module_id,
+ error=str(exc)[:120],
+ )
+
+ try:
+ await self.db.audit(
+ campaign.operator,
+ "module_run",
+ f"module={module_id} outcome={outcome or 'unknown'}",
+ campaign.id,
+ module_id,
+ )
+ except Exception as exc:
+ logger.warning(
+ "engine_module_audit_persist_failed",
+ module_id=module_id,
+ error=str(exc)[:120],
+ )
+
+ try:
+ self.telemetry.record_execution(
+ module_id,
+ duration_ms,
+ success=success,
+ campaign_id=campaign.id,
+ )
+ if result.findings:
+ self.telemetry.record_finding(len(result.findings))
+ except Exception as exc:
+ logger.debug("engine_telemetry_record_failed", module_id=module_id, error=str(exc)[:120])
+ return result
+
+ async def _persist_runtime_hosts(
+ self,
+ campaign: Campaign,
+ runtime_state: CampaignRuntimeState,
+ ) -> None:
+ """Persist discovered host metadata without serializing runtime/session secrets."""
+ if self.db is None or not hasattr(self.db, "upsert_host"):
+ return
+
+ from ares.db.database import Host
+
+ for artifact in runtime_state.artifact_store.hosts():
+ if artifact.ip_address:
+ runtime_state.session.add_host(
+ artifact.ip_address,
+ hostname=artifact.hostname,
+ fqdn=artifact.fqdn,
+ os=artifact.os,
+ os_version=artifact.os_version,
+ domain=artifact.domain,
+ is_dc=artifact.is_dc,
+ open_ports=list(artifact.open_ports),
+ )
+
+ for host in runtime_state.session.all_hosts():
+ if not host.ip_address:
+ continue
+ try:
+ await self.db.upsert_host(Host(
+ campaign_id=campaign.id,
+ ip_address=host.ip_address,
+ hostname=host.hostname or None,
+ fqdn=host.fqdn or None,
+ os=host.os or None,
+ os_version=host.os_version or None,
+ domain=host.domain or None,
+ is_dc=host.is_dc,
+ open_ports=list(host.open_ports),
+ tags=list(host.tags),
+ ))
+ except Exception as exc:
+ logger.debug(
+ "engine_host_persist_failed",
+ campaign_id=campaign.id[:8],
+ error=str(exc)[:120],
+ )
+
+ async def _persist_runtime_graph(
+ self,
+ campaign: Campaign,
+ runtime_state: CampaignRuntimeState,
+ ) -> None:
+ """Checkpoint a safe artifact graph using the existing encrypted loot store.
+
+ The snapshot intentionally contains graph metadata only. It never
+ serializes vault values or artifact raw payloads, so rehydration cannot
+ expose credential secrets through the graph API.
+ """
+ if self.db is None or not hasattr(self.db, "save_campaign_graph"):
+ return
+ try:
+ from ares.graph.attack_graph import AttackGraph
+
+ graph = AttackGraph()
+ graph.build_from_store(runtime_state.artifact_store)
+ runtime_state.attack_graph = graph
+ await self.db.save_campaign_graph(campaign.id, graph.to_d3_json())
+ except Exception as exc:
+ logger.debug(
+ "engine_graph_snapshot_persist_failed",
+ campaign_id=campaign.id[:8],
+ error=str(exc)[:120],
+ )
+
async def _persist_vault_credentials(self, campaign: "Campaign") -> int:
"""
Sync in-memory CredentialVault to the DB after each module run.
diff --git a/ares/core/plugin/loader.py b/ares/core/plugin/loader.py
index 06a617d..1d6f8b3 100644
--- a/ares/core/plugin/loader.py
+++ b/ares/core/plugin/loader.py
@@ -32,7 +32,7 @@ import inspect
import os as _os
import sys
from pathlib import Path
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, Iterable
from ares.core.logger import get_logger
@@ -195,9 +195,18 @@ class PluginLoader:
ENTRY_POINT_GROUP = "ares.modules"
EXTERNAL_DIR_ENV = "ARES_PLUGIN_DIR"
- def __init__(self) -> None:
+ def __init__(
+ self,
+ *,
+ trusted_external_roots: Iterable[str | Path] | None = None,
+ ) -> None:
self.registry = ModuleRegistry()
self._errors: list[dict[str, str]] = []
+ # Explicit process-local injection for controlled embedding/tests only;
+ # it never expands the production environment/default allowlist.
+ self._trusted_external_roots = tuple(
+ Path(root).resolve() for root in (trusted_external_roots or ())
+ )
# ── Public API ─────────────────────────────────────────────────────────
@@ -311,6 +320,7 @@ class PluginLoader:
_allowed_bases = [
Path.home().resolve(),
+ *self._trusted_external_roots,
Path("/tmp").resolve(), # noqa: S108 — sandbox staging area
]
if not any(
diff --git a/ares/core/runtime_state.py b/ares/core/runtime_state.py
new file mode 100644
index 0000000..1769f3e
--- /dev/null
+++ b/ares/core/runtime_state.py
@@ -0,0 +1,159 @@
+"""Small, server-side runtime state shared by all executions in a campaign."""
+from __future__ import annotations
+
+import asyncio
+import json
+from dataclasses import dataclass
+from typing import Any
+
+from ares.credential.vault import CredentialVault
+from ares.normalize.artifacts import ArtifactStore
+from ares.state.target_state import OperatorSession
+
+
+@dataclass
+class CampaignRuntimeState:
+ """Non-response state that is safe to share across a campaign's modules."""
+
+ campaign_id: str
+ vault: CredentialVault
+ session: OperatorSession
+ artifact_store: ArtifactStore
+ telemetry: Any = None
+ attack_graph: Any = None
+ hydrated: bool = False
+
+ def safe_credentials(self) -> list[Any]:
+ """Return encrypted credential objects suitable for module context only."""
+ return self.vault.credentials_for_reuse(campaign_id=self.campaign_id)
+
+
+class CampaignRuntimeStateStore:
+ """Owns one in-memory runtime state object per campaign for an engine."""
+
+ def __init__(self, encryption_key: str | bytes | None, telemetry: Any = None) -> None:
+ self._encryption_key = encryption_key
+ self._telemetry = telemetry
+ self._states: dict[str, CampaignRuntimeState] = {}
+ self._locks: dict[str, asyncio.Lock] = {}
+
+ def get(self, campaign_id: str) -> CampaignRuntimeState | None:
+ return self._states.get(campaign_id)
+
+ def discard(self, campaign_id: str) -> None:
+ self._states.pop(campaign_id, None)
+ self._locks.pop(campaign_id, None)
+
+ async def ensure(self, campaign: Any, db: Any = None) -> CampaignRuntimeState:
+ """Attach shared state and hydrate durable credentials/hosts once when possible."""
+ campaign_id = str(getattr(campaign, "id", ""))
+ if not campaign_id:
+ raise ValueError("Campaign runtime state requires a campaign id")
+
+ state = self._states.get(campaign_id)
+ if state is None:
+ state = self._build_state(campaign)
+ self._states[campaign_id] = state
+ self._attach(campaign, state)
+
+ if db is None or state.hydrated:
+ return state
+
+ lock = self._locks.setdefault(campaign_id, asyncio.Lock())
+ async with lock:
+ if not state.hydrated:
+ await self._hydrate_from_db(campaign, state, db)
+ state.hydrated = True
+ return state
+
+ async def restore_vault(self, campaign: Any, db: Any) -> int:
+ """Replace a campaign vault with its durable encrypted credential records."""
+ # Hydrate the rest of the state first as well. In particular this keeps
+ # host metadata available to graph requests after a vault-only restore.
+ state = await self.ensure(campaign, db)
+ records = await db.load_credentials_raw(state.campaign_id)
+ vault = CredentialVault(self._encryption_key)
+ restored = vault.restore_from_db_records(records if isinstance(records, list) else [])
+ state.vault = vault
+ state.hydrated = True
+ self._attach(campaign, state)
+ return restored
+
+ def _build_state(self, campaign: Any) -> CampaignRuntimeState:
+ vault = getattr(campaign, "_vault", None)
+ if not isinstance(vault, CredentialVault):
+ vault = CredentialVault(self._encryption_key)
+
+ session = getattr(campaign, "_session", None)
+ if not isinstance(session, OperatorSession):
+ session = OperatorSession(
+ campaign_id=str(getattr(campaign, "id", "")),
+ operator=str(getattr(campaign, "operator", "unknown")),
+ )
+
+ artifact_store = getattr(campaign, "_artifact_store", None)
+ if not isinstance(artifact_store, ArtifactStore):
+ artifact_store = ArtifactStore()
+
+ state = CampaignRuntimeState(
+ campaign_id=str(getattr(campaign, "id", "")),
+ vault=vault,
+ session=session,
+ artifact_store=artifact_store,
+ telemetry=self._telemetry,
+ )
+ return state
+
+ def _attach(self, campaign: Any, state: CampaignRuntimeState) -> None:
+ """Keep legacy campaign attributes in sync without exposing runtime state."""
+ campaign._runtime_state = state
+ campaign._vault = state.vault
+ campaign._session = state.session
+ campaign._artifact_store = state.artifact_store
+ state.session.artifact_store = state.artifact_store
+
+ async def _hydrate_from_db(
+ self,
+ campaign: Any,
+ state: CampaignRuntimeState,
+ db: Any,
+ ) -> None:
+ """Rehydrate only encrypted credential records and safe host metadata."""
+ try:
+ records = await db.load_credentials_raw(state.campaign_id)
+ if isinstance(records, list):
+ state.vault.restore_from_db_records(records)
+ except (AttributeError, TypeError):
+ # Lightweight test doubles may intentionally omit durable vault support.
+ pass
+
+ try:
+ hosts = await db.get_hosts(state.campaign_id)
+ except (AttributeError, TypeError):
+ return
+
+ if not isinstance(hosts, list):
+ return
+ for row in hosts:
+ if not isinstance(row, dict):
+ continue
+ ip_address = str(row.get("ip_address", ""))
+ if not ip_address:
+ continue
+ raw_ports = row.get("open_ports_json", [])
+ if isinstance(raw_ports, str):
+ try:
+ raw_ports = json.loads(raw_ports)
+ except (TypeError, ValueError):
+ raw_ports = []
+ ports = [int(port) for port in raw_ports if isinstance(port, (int, float, str)) and str(port).isdigit()]
+ state.session.add_host(
+ ip_address,
+ hostname=str(row.get("hostname") or ""),
+ fqdn=str(row.get("fqdn") or ""),
+ os=str(row.get("os") or ""),
+ os_version=str(row.get("os_version") or ""),
+ domain=str(row.get("domain") or ""),
+ is_dc=bool(row.get("is_dc", False)),
+ open_ports=ports,
+ )
diff --git a/ares/db/database.py b/ares/db/database.py
index f65f9d3..0858e15 100644
--- a/ares/db/database.py
+++ b/ares/db/database.py
@@ -707,6 +707,55 @@ class AresDatabase:
result.append(d)
return result
+ async def save_campaign_graph(self, campaign_id: str, graph: dict[str, Any]) -> None:
+ """Persist a sanitized graph snapshot without adding a new schema dependency."""
+ graph_id = f"campaign_graph:{campaign_id}"
+ payload = json.dumps(graph, separators=(",", ":"))
+ await self._conn.execute(
+ """
+ INSERT INTO loot
+ (id,campaign_id,loot_type,name,description,content_enc,source_module,tags_json)
+ VALUES(?,?,?,?,?,?,?,?)
+ ON CONFLICT(id) DO UPDATE SET
+ description=excluded.description,
+ content_enc=excluded.content_enc,
+ source_module=excluded.source_module,
+ tags_json=excluded.tags_json,
+ captured_at=datetime('now')
+ """,
+ (
+ graph_id,
+ campaign_id,
+ "campaign_graph",
+ "durable_attack_graph",
+ "Sanitized artifact and BloodHound graph snapshot",
+ self._enc_val(payload),
+ "core.graph",
+ json.dumps(["runtime", "safe-metadata"]),
+ ),
+ )
+ await self._conn.commit()
+
+ async def get_campaign_graph(self, campaign_id: str) -> dict[str, Any] | None:
+ """Load the latest safe graph snapshot, returning no decrypted loot to callers."""
+ async with self._conn.execute(
+ """
+ SELECT content_enc FROM loot
+ WHERE id=? AND campaign_id=? AND loot_type='campaign_graph'
+ """,
+ (f"campaign_graph:{campaign_id}", campaign_id),
+ ) as cur:
+ row = await cur.fetchone()
+ if not row or not row["content_enc"]:
+ return None
+ try:
+ decoded = self._dec_val(row["content_enc"])
+ parsed = json.loads(decoded) if decoded else None
+ return parsed if isinstance(parsed, dict) else None
+ except (TypeError, ValueError):
+ logger.warning("campaign_graph_snapshot_invalid", campaign_id=campaign_id[:8])
+ return None
+
# ── Audit log ─────────────────────────────────────────────────────────────
async def audit(self, actor: str, action: str, detail: str = "",
diff --git a/ares/db/postgres.py b/ares/db/postgres.py
index fe7cb6f..a72aaf0 100644
--- a/ares/db/postgres.py
+++ b/ares/db/postgres.py
@@ -669,6 +669,54 @@ class PostgresDatabase:
result.append(d)
return result
+ async def save_campaign_graph(self, campaign_id: str, graph: dict[str, Any]) -> None:
+ """Persist a sanitized graph snapshot in the existing encrypted loot store."""
+ graph_id = f"campaign_graph:{campaign_id}"
+ payload = json.dumps(graph, separators=(",", ":"))
+ async with self._pool.acquire() as conn:
+ await conn.execute(
+ """
+ INSERT INTO loot
+ (id,campaign_id,loot_type,name,description,content_enc,source_module,tags_json)
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8)
+ ON CONFLICT(id) DO UPDATE SET
+ description=EXCLUDED.description,
+ content_enc=EXCLUDED.content_enc,
+ source_module=EXCLUDED.source_module,
+ tags_json=EXCLUDED.tags_json,
+ captured_at=now()
+ """,
+ graph_id,
+ campaign_id,
+ "campaign_graph",
+ "durable_attack_graph",
+ "Sanitized artifact and BloodHound graph snapshot",
+ self._enc_val(payload),
+ "core.graph",
+ json.dumps(["runtime", "safe-metadata"]),
+ )
+
+ async def get_campaign_graph(self, campaign_id: str) -> dict[str, Any] | None:
+ """Load the safe graph snapshot without returning general decrypted loot."""
+ async with self._pool.acquire() as conn:
+ row = await conn.fetchrow(
+ """
+ SELECT content_enc FROM loot
+ WHERE id=$1 AND campaign_id=$2 AND loot_type='campaign_graph'
+ """,
+ f"campaign_graph:{campaign_id}",
+ campaign_id,
+ )
+ if not row or not row["content_enc"]:
+ return None
+ try:
+ decoded = self._dec_val(row["content_enc"])
+ parsed = json.loads(decoded) if decoded else None
+ return parsed if isinstance(parsed, dict) else None
+ except (TypeError, ValueError):
+ logger.warning("campaign_graph_snapshot_invalid", campaign_id=campaign_id[:8])
+ return None
+
async def campaign_summary(self, campaign_id: str) -> dict[str, Any]:
findings = await self.get_findings(campaign_id)
hosts = await self.get_hosts(campaign_id)
diff --git a/ares/graph/attack_graph.py b/ares/graph/attack_graph.py
index cfbaa91..3b3b323 100644
--- a/ares/graph/attack_graph.py
+++ b/ares/graph/attack_graph.py
@@ -41,6 +41,26 @@ except ImportError:
logger = get_logger("ares.graph")
+_GRAPH_SECRET_KEYS = {
+ "secret", "secret_enc", "password", "passwd", "token", "api_key",
+ "private_key", "hash_value", "nt_hash", "lm_hash", "cracked_value",
+}
+
+
+def _safe_graph_value(value: Any) -> Any:
+ """Drop secret-bearing fields before graph data is persisted or returned."""
+ if isinstance(value, dict):
+ return {
+ str(key): _safe_graph_value(item)
+ for key, item in value.items()
+ if str(key).lower() not in _GRAPH_SECRET_KEYS
+ }
+ if isinstance(value, list):
+ return [_safe_graph_value(item) for item in value]
+ if isinstance(value, (str, int, float, bool)) or value is None:
+ return value
+ return str(value)
+
# ── Edge types ────────────────────────────────────────────────────────────────
@@ -125,6 +145,112 @@ class AttackGraph:
self._nodes: dict[str, GraphNode] = {}
self._edges: list[GraphEdge] = []
+ @classmethod
+ def from_d3_json(cls, payload: dict[str, Any]) -> "AttackGraph":
+ """Rehydrate a graph snapshot produced by :meth:`to_d3_json`."""
+ graph = cls()
+ graph.load_d3_json(payload)
+ return graph
+
+ def load_d3_json(self, payload: dict[str, Any]) -> "AttackGraph":
+ """Load safe D3 graph metadata into this graph instance."""
+ for raw_node in payload.get("nodes", []):
+ if not isinstance(raw_node, dict) or not raw_node.get("id"):
+ continue
+ node = GraphNode(
+ node_id=str(raw_node["id"]),
+ label=str(raw_node.get("label") or raw_node["id"]),
+ node_type=str(raw_node.get("type") or "unknown"),
+ properties=_safe_graph_value(raw_node.get("properties", {})),
+ risk_score=float(raw_node.get("risk", 0.0) or 0.0),
+ is_target=bool(raw_node.get("is_target", False)),
+ )
+ self._add_node(node)
+ for raw_edge in payload.get("links", []):
+ if not isinstance(raw_edge, dict):
+ continue
+ source, target = raw_edge.get("source"), raw_edge.get("target")
+ if not source or not target:
+ continue
+ self._add_edge(GraphEdge(
+ source=str(source),
+ target=str(target),
+ edge_type=str(raw_edge.get("type") or "related"),
+ label=str(raw_edge.get("label") or ""),
+ weight=float(raw_edge.get("weight", 1.0) or 1.0),
+ properties=_safe_graph_value(raw_edge.get("properties", {})),
+ ))
+ return self
+
+ def add_persisted_campaign_data(
+ self,
+ hosts: list[dict[str, Any]],
+ findings: list[dict[str, Any]],
+ credentials: list[dict[str, Any]],
+ ) -> "AttackGraph":
+ """Add durable host/finding/credential metadata without any secret values."""
+ host_ids: dict[str, str] = {}
+ for host in hosts:
+ ip = str(host.get("ip_address") or "")
+ if not ip:
+ continue
+ node_id = f"host:{ip}"
+ host_ids[ip] = node_id
+ label = str(host.get("hostname") or ip)
+ self._add_node(GraphNode(
+ node_id=node_id,
+ label=label,
+ node_type="domain_controller" if host.get("is_dc") else "host",
+ properties={
+ "ip": ip,
+ "hostname": host.get("hostname") or "",
+ "os": host.get("os") or "",
+ "domain": host.get("domain") or "",
+ "open_ports": host.get("open_ports_json") or [],
+ },
+ risk_score=4.0 if host.get("is_dc") else 2.0,
+ is_target=bool(host.get("is_dc")),
+ ))
+ for finding in findings:
+ finding_id = str(finding.get("id") or "")
+ title = str(finding.get("title") or "Finding")
+ node_id = f"finding:{finding_id or title[:80]}"
+ self._add_node(GraphNode(
+ node_id=node_id,
+ label=title,
+ node_type="finding",
+ properties={
+ "severity": finding.get("severity") or "info",
+ "module_id": finding.get("module_id") or "",
+ "cvss_score": finding.get("cvss_score") or 0.0,
+ "mitre_technique": finding.get("mitre_technique") or "",
+ "trace_id": finding.get("trace_id") or "",
+ },
+ risk_score=float(finding.get("cvss_score") or 0.0),
+ ))
+ host = str(finding.get("host") or "")
+ if host in host_ids:
+ self._add_edge(GraphEdge(
+ source=host_ids[host], target=node_id,
+ edge_type="finding", label="finding", weight=1.0,
+ ))
+ for credential in credentials:
+ cred_id = str(credential.get("id") or "")
+ username = str(credential.get("username") or "credential")
+ domain = str(credential.get("domain") or "")
+ self._add_node(GraphNode(
+ node_id=f"credential:{cred_id or username}",
+ label=f"{domain}\\{username}" if domain else username,
+ node_type="credential",
+ properties={
+ "cred_type": credential.get("cred_type") or "",
+ "source_module": credential.get("source_module") or "",
+ "cracked": bool(credential.get("cracked", False)),
+ },
+ risk_score=2.0,
+ ))
+ return self
+
# ── Build from artifact store ──────────────────────────────────────────
def build_from_store(self, store: ArtifactStore) -> "AttackGraph":
@@ -445,7 +571,17 @@ class AttackGraph:
def high_value_nodes(self) -> list[GraphNode]:
"""Return all high-value target nodes (DC, Domain Admins, krbtgt, etc.)."""
return [
- self._nodes[nid]
+ self._nodes.get(
+ nid,
+ GraphNode(
+ node_id=nid,
+ label=str(data.get("label", nid)),
+ node_type=str(data.get("node_type", "unknown")),
+ properties=_safe_graph_value(data.get("properties", {})),
+ risk_score=float(data.get("risk_score", 0.0) or 0.0),
+ is_target=True,
+ ),
+ )
for nid, data in self._g.nodes(data=True)
if data.get("is_target")
]
@@ -498,7 +634,7 @@ class AttackGraph:
"color": self.NODE_COLORS.get(ntype, "#94a3b8"),
"risk": data.get("risk_score", 1.0),
"is_target": data.get("is_target", False),
- "properties": data.get("properties", {}),
+ "properties": _safe_graph_value(data.get("properties", {})),
})
links = []
@@ -509,7 +645,7 @@ class AttackGraph:
"label": data.get("label", ""),
"type": data.get("edge_type", ""),
"weight": data.get("weight", 1.0),
- "properties": data.get("properties", {}),
+ "properties": _safe_graph_value(data.get("properties", {})),
})
return {"nodes": nodes, "links": links}
diff --git a/ares/strategy/engine.py b/ares/strategy/engine.py
index 1f0e425..d5f8a2c 100644
--- a/ares/strategy/engine.py
+++ b/ares/strategy/engine.py
@@ -96,6 +96,12 @@ class StrategyEngine:
logger.info("strategy_engine_start", goal=goal, max_rounds=max_rounds,
llm_backend=llm_backend, consensus=bool(secondary_backend))
+ # Strategy executions must share the same campaign vault, session, and
+ # artifact store as API and plan executions. The engine owns the
+ # rehydration boundary, including durable credentials and hosts.
+ if self._engine and hasattr(self._engine, "ensure_campaign_runtime"):
+ await self._engine.ensure_campaign_runtime(campaign)
+
for round_num in range(1, max_rounds + 1):
logger.info("strategy_round_start", round=round_num, goal=goal)
@@ -325,41 +331,63 @@ class StrategyEngine:
if isinstance(result, Exception):
success = False
findings_count = 0
+ quality = 0.0
+ evidence = f"module_error: {str(result)[:160]}"
logger.warning("strategy_module_error", module=mid,
error=str(result)[:100])
else:
- success = getattr(result, "status", "") in ("success", "partial")
- findings_count = len(getattr(result, "findings", []))
+ from ares.core.engine import is_successful_module_outcome
- quality = getattr(result, "effective_quality", 0.5 if success else 0.0)
- evidence = getattr(result, "outcome_evidence", "")
+ status = getattr(result, "status", "")
+ outcome_value = getattr(result, "outcome", "") or status
+ success = is_successful_module_outcome(outcome_value)
+ findings_count = len(getattr(result, "findings", []))
+ validations = list(getattr(result, "validation_results", []) or [])
+ passed_confidence = [
+ float(getattr(validation, "confidence", 0.0))
+ for validation in validations
+ if bool(getattr(validation, "passed", False))
+ ]
+ if passed_confidence:
+ quality = sum(passed_confidence) / len(passed_confidence)
+ elif findings_count:
+ # EngineModuleResult.findings contains only confirmed findings.
+ quality = 0.6
+ else:
+ # ModuleStatus.DONE is a successful, evidence-light result.
+ quality = 0.5 if success else 0.0
+ evidence = str(
+ getattr(result, "outcome_message", "")
+ or getattr(result, "error", "")
+ or getattr(result, "outcome", "")
+ or ""
+ )[:200]
outcome = ModuleOutcome(
- module_id=mid, success=quality >= 0.5,
+ module_id=mid, success=success and quality >= 0.5,
quality=quality, evidence=evidence,
edr_vendor=edr_vendor, bypass_used=bypass_name,
findings_count=findings_count,
)
round_outcomes.append(outcome)
self._kb.record_outcome(
- mid, success=quality >= 0.5, quality=quality,
+ mid, success=outcome.success, quality=quality,
evidence=evidence, edr_vendor=edr_vendor, bypass_used=bypass_name
)
# Persist bypass outcome to DB for cross-session learning
- if bypass_name and self._engine and hasattr(self._engine, "_db"):
- _db_ref = getattr(self._engine, "_db", None)
+ if bypass_name and self._engine:
+ _db_ref = getattr(self._engine, "db", None)
if _db_ref and hasattr(_db_ref, "save_bypass_outcome"):
try:
- import asyncio as _aio
- _aio.ensure_future(_db_ref.save_bypass_outcome(
+ await _db_ref.save_bypass_outcome(
technique_id=bypass_name,
edr_vendor=edr_vendor,
edr_version="",
- success=quality >= 0.5,
+ success=outcome.success,
campaign_id=getattr(campaign, "id", ""),
notes=evidence[:200] if evidence else "",
- ))
- except Exception:
- pass # DB persistence is best-effort
+ )
+ except Exception as exc:
+ logger.debug("strategy_bypass_outcome_persist_failed", error=str(exc)[:100])
# Update per-host state memory
# AD modules use "dc" key, Linux use "host", others use "target"
_mp = stage_params.get(mid, {}) if isinstance(stage_params, dict) else {}
@@ -371,7 +399,7 @@ class StrategyEngine:
if target_hint and not isinstance(result, Exception):
self._target_state.update_from_result(mid, target_hint, result)
- if success:
+ if outcome.success:
succeeded.append(mid)
else:
failed.append(mid)
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 5d8e7b7..8d3ec39 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -421,14 +421,12 @@ Clear generated report artifacts for the campaign.
### `GET /telemetry`
-Get current operational telemetry snapshot.
+Get the current operational telemetry snapshot.
-Telemetry is an in-memory runtime view of the current API process. It records
-API-triggered module runs, success/failure counts, latency, throughput, queue
-depth, worker health, findings, hosts, and other operator metrics. It is useful
-for live monitoring and demos, but it is not durable campaign history and
-resets when the API process restarts. Use the database-backed campaign,
-findings, and report endpoints for permanent records.
+The response combines live process metrics with database-backed aggregates for
+module runs, confirmed findings, and discovered hosts. Queue depth and worker
+health remain process-local; use the campaign, finding, report, and graph
+endpoints for durable engagement records.
```json
{
@@ -472,15 +470,19 @@ List all users.
### `GET /graph/{campaign_id}`
-Get the attack graph for a campaign.
+Get the attack graph for a campaign. The response hydrates persisted hosts,
+findings, safe credential metadata, and the campaign graph snapshot.
+Credential secrets are never returned.
### `GET /graph/{campaign_id}/attack-paths`
-Get identified attack paths sorted by severity.
+Get identified attack paths sorted by severity from persisted campaign data and
+the campaign graph snapshot.
### `POST /graph/{campaign_id}/bloodhound`
-Ingest BloodHound/SharpHound JSON from an allowed local path.
+Ingest BloodHound/SharpHound JSON from an allowed local path and persist a
+sanitized campaign graph snapshot for later requests.
---
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index efb24f1..e5aecf7 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -9,6 +9,7 @@
"version": "6.0.0",
"dependencies": {
"@tanstack/react-query": "^5.91.2",
+ "@xyflow/react": "^12.11.2",
"lucide-react": "^0.468.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
@@ -1757,6 +1758,55 @@
"@babel/types": "^7.28.2"
}
},
+ "node_modules/@types/d3-color": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-drag": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",
+ "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-interpolate": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-color": "*"
+ }
+ },
+ "node_modules/@types/d3-selection": {
+ "version": "3.0.11",
+ "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz",
+ "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-transition": {
+ "version": "3.0.9",
+ "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",
+ "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-zoom": {
+ "version": "3.0.8",
+ "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz",
+ "integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-interpolate": "*",
+ "@types/d3-selection": "*"
+ }
+ },
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
@@ -1785,14 +1835,14 @@
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
- "dev": true,
+ "devOptional": true,
"license": "MIT"
},
"node_modules/@types/react": {
"version": "18.3.31",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz",
"integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==",
- "dev": true,
+ "devOptional": true,
"license": "MIT",
"dependencies": {
"@types/prop-types": "*",
@@ -1803,7 +1853,7 @@
"version": "18.3.7",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
- "dev": true,
+ "devOptional": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^18.0.0"
@@ -2211,6 +2261,48 @@
"url": "https://opencollective.com/vitest"
}
},
+ "node_modules/@xyflow/react": {
+ "version": "12.11.2",
+ "resolved": "https://registry.npmjs.org/@xyflow/react/-/react-12.11.2.tgz",
+ "integrity": "sha512-eLAlDWJfWnQEhJwGMjlWdAXO9eYllKpliUmPQlAmOLxz6mExXuzMVDUKLMquixgkrtmMFFtug3jGKmYYld12cA==",
+ "license": "MIT",
+ "dependencies": {
+ "@xyflow/system": "0.0.79",
+ "classcat": "^5.0.3",
+ "zustand": "^4.4.0"
+ },
+ "peerDependencies": {
+ "@types/react": ">=17",
+ "@types/react-dom": ">=17",
+ "react": ">=17",
+ "react-dom": ">=17"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@xyflow/system": {
+ "version": "0.0.79",
+ "resolved": "https://registry.npmjs.org/@xyflow/system/-/system-0.0.79.tgz",
+ "integrity": "sha512-czLyOh91NF0hIzbNzwi8I6GlqG23BHh2435OddfI6uiaLH3xdrdygO93gqgH1Bv9mhy8XPFQJOBn1FTq4LvEWA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-drag": "^3.0.7",
+ "@types/d3-interpolate": "^3.0.4",
+ "@types/d3-selection": "^3.0.10",
+ "@types/d3-transition": "^3.0.8",
+ "@types/d3-zoom": "^3.0.8",
+ "d3-drag": "^3.0.0",
+ "d3-interpolate": "^3.0.1",
+ "d3-selection": "^3.0.0",
+ "d3-zoom": "^3.0.0"
+ }
+ },
"node_modules/acorn": {
"version": "8.16.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
@@ -2625,6 +2717,12 @@
"node": ">= 6"
}
},
+ "node_modules/classcat": {
+ "version": "5.0.5",
+ "resolved": "https://registry.npmjs.org/classcat/-/classcat-5.0.5.tgz",
+ "integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==",
+ "license": "MIT"
+ },
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -2742,9 +2840,114 @@
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
- "dev": true,
+ "devOptional": true,
"license": "MIT"
},
+ "node_modules/d3-color": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-dispatch": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",
+ "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-drag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",
+ "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-selection": "3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-ease": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-interpolate": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-selection": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
+ "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-timer": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-transition": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",
+ "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3",
+ "d3-dispatch": "1 - 3",
+ "d3-ease": "1 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-timer": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "peerDependencies": {
+ "d3-selection": "2 - 3"
+ }
+ },
+ "node_modules/d3-zoom": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",
+ "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-drag": "2 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-selection": "2 - 3",
+ "d3-transition": "2 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/data-urls": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz",
@@ -5250,6 +5453,15 @@
"punycode": "^2.1.0"
}
},
+ "node_modules/use-sync-external-store": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
+ "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
+ "license": "MIT",
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
@@ -6621,6 +6833,34 @@
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
+ },
+ "node_modules/zustand": {
+ "version": "4.5.7",
+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",
+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",
+ "license": "MIT",
+ "dependencies": {
+ "use-sync-external-store": "^1.2.2"
+ },
+ "engines": {
+ "node": ">=12.7.0"
+ },
+ "peerDependencies": {
+ "@types/react": ">=16.8",
+ "immer": ">=9.0.6",
+ "react": ">=16.8"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "immer": {
+ "optional": true
+ },
+ "react": {
+ "optional": true
+ }
+ }
}
}
}
diff --git a/frontend/package.json b/frontend/package.json
index 04d492f..55f1124 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -13,6 +13,7 @@
},
"dependencies": {
"@tanstack/react-query": "^5.91.2",
+ "@xyflow/react": "^12.11.2",
"lucide-react": "^0.468.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
diff --git a/frontend/src/App.test.tsx b/frontend/src/App.test.tsx
new file mode 100644
index 0000000..1855ec7
--- /dev/null
+++ b/frontend/src/App.test.tsx
@@ -0,0 +1,21 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import "@testing-library/jest-dom/vitest";
+import { render, screen } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { describe, expect, it } from "vitest";
+import App from "./App";
+
+describe("protected dashboard routing", () => {
+ it("redirects an unauthenticated dashboard route to the existing login page", () => {
+ const queryClient = new QueryClient();
+ render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={["/campaigns"]}>
+ <App />
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+
+ expect(screen.getByRole("heading", { name: "ARES Dashboard" })).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index d7ef2a4..2e9d19c 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,3559 +1,10 @@
-import {
- AlertTriangle,
- Bell,
- Boxes,
- CheckCircle2,
- Copy,
- Database,
- Download,
- Eye,
- FileText,
- GitGraph,
- KeyRound,
- Layers,
- LayoutDashboard,
- ListChecks,
- Loader2,
- LogOut,
- Menu,
- Play,
- Radio,
- Search,
- Server,
- ShieldAlert,
- ShieldCheck,
- Target,
- Trash2,
- TrendingUp,
- UserCog,
- type LucideIcon,
- Workflow
-} from "lucide-react";
-import {
- ChangeEvent,
- createContext,
- Dispatch,
- FormEvent,
- KeyboardEvent,
- ReactNode,
- SetStateAction,
- useContext,
- useEffect,
- useMemo,
- useRef,
- useState
-} from "react";
-import { NavLink, Navigate, Route, Routes, useNavigate } from "react-router-dom";
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import {
- ApiError,
- api,
- buildModuleRunPayload,
- campaignEventsPath,
- clearTokens,
- getAccessToken,
- getRefreshToken,
- login as loginRequest,
- logout as logoutRequest,
- refreshAccessToken
-} from "./api/client";
-import type { ApiKeyMeta, Campaign, ExecutionChain, Finding, ModuleMeta, MonthlyFindingStats, ParamField, ReportItem, UserProfile } from "./api/types";
+import { AuthProvider } from "./features/auth/AuthProvider";
+import { DashboardRouter } from "./features/dashboard/DashboardRouter";
-interface AuthState {
- user: UserProfile | null;
- loading: boolean;
- login: (username: string, password: string) => Promise<void>;
- logout: () => Promise<void>;
-}
-
-const AuthContext = createContext<AuthState | null>(null);
-
-function useAuth(): AuthState {
- const value = useContext(AuthContext);
- if (!value) {
- throw new Error("AuthContext missing");
- }
- return value;
-}
-
-interface DashboardUiState {
- selectedCampaignId: string;
- setSelectedCampaignId: Dispatch<SetStateAction<string>>;
- liveCampaignId: string;
- setLiveCampaignId: Dispatch<SetStateAction<string>>;
- liveConnected: boolean;
- setLiveConnected: Dispatch<SetStateAction<boolean>>;
- liveEvents: unknown[];
- clearLiveEvents: () => void;
-}
-
-interface ModuleRunRecord {
- campaignId: string;
- moduleId: string;
- payload: unknown;
- isError?: boolean;
-}
-
-interface PersistedResult {
- key: string;
- payload: unknown;
- isError?: boolean;
-}
-
-interface GeneratedApiKey {
- id?: string;
- key: string;
- note?: string;
- prefix?: string;
-}
-
-type ApiKeyCopyStatus = "idle" | "copied" | "manual";
-
-interface SearchResult {
- id: string;
- label: string;
- detail: string;
- route: string;
- onSelect?: () => void;
-}
-
-interface DashboardNotification {
- id: string;
- title: string;
- detail: string;
- tone: "info" | "warn" | "danger";
-}
-
-const DashboardUiContext = createContext<DashboardUiState | null>(null);
-
-function useDashboardUi(): DashboardUiState {
- const value = useContext(DashboardUiContext);
- if (!value) {
- throw new Error("DashboardUiContext missing");
- }
- return value;
-}
-
-function readSessionState<T>(key: string, initialValue: T): T {
- try {
- const stored = window.sessionStorage.getItem(key);
- return stored ? JSON.parse(stored) as T : initialValue;
- } catch {
- return initialValue;
- }
-}
-
-function useSessionState<T>(key: string, initialValue: T): readonly [T, Dispatch<SetStateAction<T>>] {
- const [value, setValue] = useState<T>(() => readSessionState(key, initialValue));
-
- useEffect(() => {
- try {
- const serialized = JSON.stringify(value);
- if (serialized === undefined) {
- window.sessionStorage.removeItem(key);
- } else {
- window.sessionStorage.setItem(key, serialized);
- }
- } catch {
- // Session persistence is a UX aid; storage failures should never block the dashboard.
- }
- }, [key, value]);
-
- return [value, setValue] as const;
-}
-
-const REQUIRED_FIELD_MESSAGE = "This field is required.";
-
-type ValidatableElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
-type TelemetryMetricMap = Record<string, boolean | number | string | null | undefined>;
-interface TelemetrySnapshot {
- modules?: TelemetryMetricMap;
- queue?: TelemetryMetricMap;
- workers?: TelemetryMetricMap;
- latency_ms?: TelemetryMetricMap;
- throughput?: TelemetryMetricMap;
- findings?: number;
- credentials?: number;
- hosts?: TelemetryMetricMap;
- campaign_id?: string;
- timestamp?: number;
- [key: string]: unknown;
-}
-
-interface TemplatePlanStage {
- name?: string;
- modules?: string[];
- params?: Record<string, unknown>;
-}
-
-interface TemplatePlanResponse {
- template?: string;
- description?: string;
- plan?: {
- stages?: TemplatePlanStage[];
- };
- global_params?: Record<string, unknown>;
- note?: string;
-}
-
-function setRequiredMessage<T extends ValidatableElement>(event: FormEvent<T>) {
- event.currentTarget.setCustomValidity(REQUIRED_FIELD_MESSAGE);
-}
-
-function clearValidationMessage<T extends ValidatableElement>(event: ChangeEvent<T>) {
- event.currentTarget.setCustomValidity("");
-}
-
-function AuthProvider({ children }: { children: ReactNode }) {
- const [user, setUser] = useState<UserProfile | null>(null);
- const [loading, setLoading] = useState(Boolean(getRefreshToken()));
- const queryClient = useQueryClient();
-
- useEffect(() => {
- let active = true;
- if (!getRefreshToken()) {
- setLoading(false);
- return;
- }
- (async () => {
- try {
- if (!(await refreshAccessToken())) {
- if (active) {
- setUser(null);
- }
- return;
- }
- const profile = await api.me();
- if (active) {
- setUser(profile);
- }
- } catch {
- clearTokens();
- if (active) {
- setUser(null);
- }
- } finally {
- if (active) {
- setLoading(false);
- }
- }
- })();
- return () => {
- active = false;
- };
- }, []);
-
- const value = useMemo<AuthState>(
- () => ({
- user,
- loading,
- login: async (username, password) => {
- await loginRequest(username, password);
- const profile = await api.me();
- setUser(profile);
- },
- logout: async () => {
- await logoutRequest();
- setUser(null);
- queryClient.clear();
- }
- }),
- [loading, queryClient, user]
- );
-
- return (
- <AuthContext.Provider value={value}>
- {loading ? <ScreenMessage title="ARES" body="Loading session" /> : children}
- </AuthContext.Provider>
- );
-}
-
-const navItems = [
- { to: "/", label: "Overview", icon: LayoutDashboard },
- { to: "/campaigns", label: "Campaigns", icon: ListChecks },
- { to: "/modules", label: "Modules", icon: Boxes },
- { to: "/reports", label: "Reports", icon: FileText },
- { to: "/graph", label: "Graph", icon: GitGraph },
- { to: "/templates", label: "Templates", icon: Workflow },
- { to: "/strategy", label: "Strategy", icon: ShieldCheck },
- { to: "/security", label: "Security", icon: UserCog },
- { to: "/edr", label: "EDR/OPSEC", icon: ShieldAlert },
- { to: "/live", label: "Live", icon: Radio }
-];
-
-const navGroups = [
- { label: "Core", items: navItems.slice(0, 1) },
- { label: "Operations", items: navItems.slice(1, 4) },
- { label: "Intelligence", items: navItems.slice(4, 7) },
- { label: "Control", items: navItems.slice(7) }
-];
-
-const pageMeta: Record<string, { icon: LucideIcon; eyebrow: string; description: string }> = {
- Overview: {
- icon: LayoutDashboard,
- eyebrow: "Dashboard",
- description: "Health, telemetry, campaigns, and activity."
- },
- Campaigns: {
- icon: ListChecks,
- eyebrow: "Operations",
- description: "Scopes, status, findings, and comparisons."
- },
- Modules: {
- icon: Boxes,
- eyebrow: "Operations",
- description: "Catalog, OPSEC, and authorized runs."
- },
- Reports: {
- icon: FileText,
- eyebrow: "Operations",
- description: "Evidence packages and artifacts."
- },
- Graph: {
- icon: GitGraph,
- eyebrow: "Intelligence",
- description: "Entities, relationships, and attack paths."
- },
- Templates: {
- icon: Workflow,
- eyebrow: "Intelligence",
- description: "Reusable campaign plans."
- },
- Strategy: {
- icon: ShieldCheck,
- eyebrow: "Intelligence",
- description: "Authorized objective planning."
- },
- Security: {
- icon: UserCog,
- eyebrow: "Control",
- description: "Account, API keys, audit, and users."
- },
- "EDR/OPSEC": {
- icon: ShieldAlert,
- eyebrow: "Control",
- description: "Detection outcomes and OPSEC feedback."
- },
- "Live Events": {
- icon: Radio,
- eyebrow: "Control",
- description: "Campaign events as they arrive."
- }
-};
-
-const brandLogoPath = "/dashboard/brand/ares-logo.png";
-const brandMarkPath = "/dashboard/brand/ares-mark.png";
-
-function formatRole(role?: string): string {
- const labels: Record<string, string> = {
- team_lead: "Team Lead",
- operator: "Operator",
- recon: "Recon",
- reporter: "Reporter"
- };
- if (!role) {
- return "";
- }
- return labels[role] ?? role.replace(/_/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
-}
-
-function App() {
+export default function App() {
return (
<AuthProvider>
- <Routes>
- <Route path="/login" element={<LoginPage />} />
- <Route path="/*" element={<ProtectedShell />} />
- </Routes>
+ <DashboardRouter />
</AuthProvider>
);
}
-
-function ProtectedShell() {
- const { user, loading, logout } = useAuth();
- const navigate = useNavigate();
- const [selectedCampaignId, setSelectedCampaignId] = useSessionState("ares.dashboard.selectedCampaignId", "");
- const [liveCampaignId, setLiveCampaignId] = useSessionState("ares.dashboard.live.campaignId", "");
- const [liveEvents, setLiveEvents] = useSessionState<unknown[]>("ares.dashboard.live.events", []);
- const [liveConnected, setLiveConnected] = useState(false);
- const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
- const [searchTerm, setSearchTerm] = useState("");
- const [searchOpen, setSearchOpen] = useState(false);
- const [notificationsOpen, setNotificationsOpen] = useState(false);
- const [readNotificationIds, setReadNotificationIds] = useState<string[]>([]);
- const [deletedNotificationIds, setDeletedNotificationIds] = useState<string[]>([]);
- const liveSocketRef = useRef<WebSocket | null>(null);
- const health = useQuery({ queryKey: ["health"], queryFn: api.health });
- const telemetry = useQuery({ queryKey: ["telemetry"], queryFn: api.telemetry });
- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
- const modules = useQuery({ queryKey: ["modules"], queryFn: api.modules });
- const templates = useQuery({ queryKey: ["templates"], queryFn: api.templates });
- const reports = useQuery({
- queryKey: ["reports", selectedCampaignId],
- queryFn: () => api.reports(selectedCampaignId),
- enabled: Boolean(selectedCampaignId)
- });
-
- useEffect(() => {
- const accessToken = getAccessToken();
- if (!liveConnected || !liveCampaignId || !accessToken) {
- if (liveSocketRef.current) {
- liveSocketRef.current.close();
- liveSocketRef.current = null;
- }
- return;
- }
-
- const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
- const socket = new WebSocket(`${protocol}//${window.location.host}${campaignEventsPath(liveCampaignId, accessToken)}`);
- liveSocketRef.current = socket;
- socket.onmessage = (event) => {
- try {
- setLiveEvents((items) => [JSON.parse(event.data), ...items].slice(0, 100));
- } catch {
- setLiveEvents((items) => [event.data, ...items].slice(0, 100));
- }
- };
- socket.onclose = () => {
- if (liveSocketRef.current === socket) {
- liveSocketRef.current = null;
- setLiveConnected(false);
- }
- };
-
- return () => {
- socket.onclose = null;
- socket.close();
- if (liveSocketRef.current === socket) {
- liveSocketRef.current = null;
- }
- };
- }, [liveCampaignId, liveConnected, setLiveEvents]);
-
- const dashboardUi = useMemo<DashboardUiState>(
- () => ({
- selectedCampaignId,
- setSelectedCampaignId,
- liveCampaignId,
- setLiveCampaignId,
- liveConnected,
- setLiveConnected,
- liveEvents,
- clearLiveEvents: () => setLiveEvents([])
- }),
- [
- liveCampaignId,
- liveConnected,
- liveEvents,
- selectedCampaignId,
- setLiveCampaignId,
- setLiveConnected,
- setLiveEvents,
- setSelectedCampaignId
- ]
- );
- const searchResults = useMemo<SearchResult[]>(() => {
- const term = searchTerm.trim().toLowerCase();
- if (!term) return [];
- const results: SearchResult[] = [];
- const addIfMatch = (result: SearchResult, haystack: string) => {
- if (haystack.toLowerCase().includes(term)) {
- results.push(result);
- }
- };
-
- navItems.forEach((item) => {
- addIfMatch(
- {
- id: `page:${item.to}`,
- label: item.label,
- detail: `Open ${item.to === "/" ? "Overview" : item.to}`,
- route: item.to
- },
- `${item.label} ${item.to}`
- );
- });
-
- (campaigns.data ?? []).forEach((campaign) => {
- addIfMatch(
- {
- id: `campaign:${campaign.id}`,
- label: campaign.name || campaign.id,
- detail: `Campaign ${campaign.id.slice(0, 12)}`,
- route: "/campaigns",
- onSelect: () => {
- setSelectedCampaignId(campaign.id);
- window.sessionStorage.setItem("ares.dashboard.campaigns.tab", JSON.stringify("Scope"));
- }
- },
- `${campaign.name ?? ""} ${campaign.id} ${campaign.client ?? ""} ${campaign.status ?? ""}`
- );
- });
-
- (modules.data ?? []).forEach((module) => {
- addIfMatch(
- {
- id: `module:${module.id}`,
- label: module.id,
- detail: module.description || "Module",
- route: "/modules",
- onSelect: () => {
- window.sessionStorage.setItem("ares.dashboard.modules.selectedId", JSON.stringify(module.id));
- window.sessionStorage.setItem("ares.dashboard.modules.tab", JSON.stringify("Run Panel"));
- }
- },
- `${module.id} ${module.name ?? ""} ${module.description ?? ""} ${module.category ?? ""} ${module.mitre ?? ""}`
- );
- });
-
- const reportItems = reports.data?.reports ?? [];
- reportItems.forEach((report) => {
- addIfMatch(
- {
- id: `report:${report.filename}`,
- label: report.filename,
- detail: `${report.format || "report"} artifact`,
- route: "/reports",
- onSelect: () => {
- window.sessionStorage.setItem("ares.dashboard.reports.tab", JSON.stringify("Library"));
- }
- },
- `${report.filename} ${report.format ?? ""}`
- );
- });
-
- const templateItems = Array.isArray(templates.data) ? templates.data as Array<Record<string, unknown>> : [];
- templateItems.forEach((template, index) => {
- const templateName = String(template.name ?? template.id ?? index);
- addIfMatch(
- {
- id: `template:${templateName}`,
- label: templateName,
- detail: String(template.description ?? "Campaign template"),
- route: "/templates",
- onSelect: () => {
- window.sessionStorage.setItem("ares.dashboard.templates.name", JSON.stringify(templateName));
- window.sessionStorage.setItem("ares.dashboard.templates.tab", JSON.stringify("Plan Builder"));
- }
- },
- `${templateName} ${String(template.description ?? "")}`
- );
- });
-
- return results.slice(0, 8);
- }, [campaigns.data, modules.data, reports.data, searchTerm, setSelectedCampaignId, templates.data]);
-
- const notifications = useMemo<DashboardNotification[]>(() => {
- const items: DashboardNotification[] = [];
- const snapshot = telemetry.data as TelemetrySnapshot | undefined;
- const healthSnapshot = health.data as Record<string, unknown> | undefined;
- const healthStatus = String(healthSnapshot?.status ?? "").toLowerCase();
-
- if (health.isError) {
- items.push({ id: "health:error", title: "Backend health check failed", detail: "ARES API health is not reachable.", tone: "danger" });
- } else if (health.isSuccess && healthStatus && !["ok", "healthy", "online"].includes(healthStatus)) {
- items.push({ id: `health:status:${healthStatus}`, title: "Backend status needs attention", detail: String(healthSnapshot?.status), tone: "warn" });
- }
- if (telemetry.isError) {
- items.push({ id: "telemetry:error", title: "Telemetry unavailable", detail: "Runtime telemetry could not be loaded.", tone: "warn" });
- }
- if (campaigns.isError) {
- items.push({ id: "campaigns:error", title: "Campaign list unavailable", detail: "Campaign data could not be loaded.", tone: "warn" });
- }
- if (modules.isError) {
- items.push({ id: "modules:error", title: "Module catalog unavailable", detail: "Module metadata could not be loaded.", tone: "warn" });
- }
- if (reports.isError && selectedCampaignId) {
- items.push({ id: `reports:error:${selectedCampaignId}`, title: "Report library unavailable", detail: "Selected campaign reports could not be loaded.", tone: "warn" });
- }
-
- const failedRuns = metricNumber(snapshot?.modules, "failed");
- const errorRate = metricNumber(snapshot?.modules, "error_rate");
- const unhealthyWorkers = metricNumber(snapshot?.workers, "unhealthy");
- const queueDepth = metricNumber(snapshot?.queue, "depth");
- if (failedRuns > 0) {
- items.push({ id: `telemetry:failed-runs:${failedRuns}`, title: "Failed module runs", detail: `${failedRuns} failed module run(s) reported by telemetry.`, tone: "warn" });
- }
- if (errorRate > 0) {
- items.push({ id: `telemetry:error-rate:${errorRate}`, title: "Runtime error rate above zero", detail: `${formatRate(errorRate)} module error rate.`, tone: "warn" });
- }
- if (unhealthyWorkers > 0) {
- items.push({ id: `telemetry:workers:${unhealthyWorkers}`, title: "Unhealthy worker detected", detail: `${unhealthyWorkers} worker(s) unhealthy.`, tone: "danger" });
- }
- if (queueDepth > 0) {
- items.push({ id: `telemetry:queue:${queueDepth}`, title: "Queue has pending work", detail: `${queueDepth} queued task(s).`, tone: "info" });
- }
- return items;
- }, [campaigns.isError, health.data, health.isError, health.isSuccess, modules.isError, reports.isError, selectedCampaignId, telemetry.data, telemetry.isError]);
-
- const activeNotificationKey = useMemo(() => notifications.map((item) => item.id).join("|"), [notifications]);
- const visibleNotifications = useMemo(
- () => notifications.filter((item) => !deletedNotificationIds.includes(item.id)),
- [deletedNotificationIds, notifications]
- );
- const unreadNotificationCount = visibleNotifications.filter((item) => !readNotificationIds.includes(item.id)).length;
-
- useEffect(() => {
- const activeIds = activeNotificationKey ? activeNotificationKey.split("|") : [];
- setReadNotificationIds((current) => current.filter((id) => activeIds.includes(id)));
- setDeletedNotificationIds((current) => current.filter((id) => activeIds.includes(id)));
- }, [activeNotificationKey]);
-
- function markVisibleNotificationsRead(): void {
- const visibleIds = visibleNotifications.map((item) => item.id);
- if (visibleIds.length === 0) return;
- setReadNotificationIds((current) => unique([...current, ...visibleIds]));
- }
-
- function toggleNotifications(): void {
- const nextOpen = !notificationsOpen;
- if (nextOpen) {
- markVisibleNotificationsRead();
- }
- setNotificationsOpen(nextOpen);
- }
-
- function deleteNotification(id: string): void {
- setDeletedNotificationIds((current) => unique([...current, id]));
- setReadNotificationIds((current) => unique([...current, id]));
- }
-
- function clearNotifications(): void {
- const visibleIds = visibleNotifications.map((item) => item.id);
- setDeletedNotificationIds((current) => unique([...current, ...visibleIds]));
- setReadNotificationIds((current) => unique([...current, ...visibleIds]));
- }
-
- function selectSearchResult(result: SearchResult): void {
- result.onSelect?.();
- navigate(result.route);
- setSearchTerm("");
- setSearchOpen(false);
- }
-
- if (loading) {
- return <ScreenMessage title="ARES" body="Loading session" />;
- }
- if (!user) {
- return <Navigate to="/login" replace />;
- }
- return (
- <DashboardUiContext.Provider value={dashboardUi}>
- <div className={sidebarCollapsed ? "app-shell sidebar-collapsed" : "app-shell"}>
- <aside className="sidebar">
- <div className="sidebar-brand">
- <img className="sidebar-mark" src={brandMarkPath} alt="" aria-hidden="true" />
- <div className="min-w-0">
- <div className="sidebar-title">ARES</div>
- <div className="sidebar-subtitle">Security dashboard</div>
- </div>
- </div>
- <nav className="sidebar-nav" aria-label="Dashboard navigation">
- {navGroups.map((group) => (
- <div className="nav-group" key={group.label}>
- <div className="nav-group-label">{group.label}</div>
- <div className="grid gap-1">
- {group.items.map((item) => {
- const Icon = item.icon;
- return (
- <NavLink key={item.to} to={item.to} end={item.to === "/"} className="nav-link" title={sidebarCollapsed ? item.label : undefined}>
- <Icon size={16} />
- <span>{item.label}</span>
- </NavLink>
- );
- })}
- </div>
- </div>
- ))}
- </nav>
- </aside>
- <main className="main-shell">
- <header className="topbar">
- <div className="topbar-left">
- <button
- className="icon-button"
- aria-label={sidebarCollapsed ? "Expand navigation" : "Collapse navigation"}
- aria-pressed={sidebarCollapsed}
- onClick={() => setSidebarCollapsed((value) => !value)}
- type="button"
- >
- <Menu size={17} />
- </button>
- <div className="topbar-search-wrap">
- <label className="topbar-search" aria-label="Dashboard search">
- <Search size={16} />
- <input
- aria-label="Search dashboard"
- onBlur={() => window.setTimeout(() => setSearchOpen(false), 120)}
- onChange={(event) => {
- setSearchTerm(event.target.value);
- setSearchOpen(true);
- }}
- onFocus={() => setSearchOpen(true)}
- onKeyDown={(event) => {
- if (event.key === "Escape") {
- setSearchOpen(false);
- }
- if (event.key === "Enter" && searchResults.length > 0) {
- event.preventDefault();
- selectSearchResult(searchResults[0]);
- }
- }}
- placeholder="Search campaigns, modules, reports"
- value={searchTerm}
- />
- </label>
- {searchOpen && (
- <div className="search-results" role="listbox">
- {searchTerm.trim() ? (
- searchResults.length > 0 ? (
- searchResults.map((result) => (
- <button key={result.id} onMouseDown={(event) => event.preventDefault()} onClick={() => selectSearchResult(result)} type="button">
- <strong>{result.label}</strong>
- <span>{result.detail}</span>
- </button>
- ))
- ) : (
- <div className="search-empty">No matches</div>
- )
- ) : (
- <div className="search-empty">Type to search dashboard</div>
- )}
- </div>
- )}
- </div>
- </div>
- <div className="topbar-right">
- <button
- className="icon-button has-badge"
- aria-expanded={notificationsOpen}
- aria-label="Notifications"
- onClick={toggleNotifications}
- type="button"
- >
- <Bell size={16} />
- {unreadNotificationCount > 0 ? <span>{unreadNotificationCount}</span> : null}
- </button>
- {notificationsOpen && (
- <aside className="notification-drawer" aria-label="Notifications">
- <SectionHeader
- title="Notifications"
- action={visibleNotifications.length > 0 ? (
- <button className="btn btn-compact" onClick={clearNotifications} type="button">
- Clear all
- </button>
- ) : <span className="badge">0</span>}
- />
- {visibleNotifications.length > 0 ? (
- <div className="notification-list">
- {visibleNotifications.map((item) => (
- <div className={`notification-item notification-${item.tone}`} key={item.id}>
- <div className="notification-item-header">
- <strong>{item.title}</strong>
- <button className="icon-button icon-button-small" aria-label={`Dismiss ${item.title}`} onClick={() => deleteNotification(item.id)} type="button">
- <Trash2 size={14} />
- </button>
- </div>
- <p>{item.detail}</p>
- </div>
- ))}
- </div>
- ) : (
- <EmptyState text="No notifications." />
- )}
- </aside>
- )}
- <span className="user-chip">
- <span className="user-chip-avatar">{user.username.slice(0, 1).toUpperCase()}</span>
- <span className="user-chip-copy">
- <strong>{user.username}</strong>
- <small>{formatRole(user.role)}</small>
- </span>
- </span>
- <button className="btn btn-topbar" onClick={() => void logout()}>
- <LogOut size={16} /> Logout
- </button>
- </div>
- </header>
- <div className="content-shell">
- <Routes>
- <Route path="/" element={<OverviewPage />} />
- <Route path="/playbooks" element={<Navigate to="/modules" replace />} />
- <Route path="/campaigns" element={<CampaignsPage />} />
- <Route path="/modules" element={<ModulesPage />} />
- <Route path="/reports" element={<ReportsPage />} />
- <Route path="/graph" element={<GraphPage />} />
- <Route path="/templates" element={<TemplatesPage />} />
- <Route path="/strategy" element={<StrategyPage />} />
- <Route path="/security" element={<SecurityPage />} />
- <Route path="/edr" element={<EdrPage />} />
- <Route path="/live" element={<LivePage />} />
- </Routes>
- </div>
- </main>
- </div>
- </DashboardUiContext.Provider>
- );
-}
-
-function LoginPage() {
- const [username, setUsername] = useState("");
- const [password, setPassword] = useState("");
- const [error, setError] = useState("");
- const { login, user } = useAuth();
- const navigate = useNavigate();
-
- if (user) {
- return <Navigate to="/" replace />;
- }
-
- async function submit(event: FormEvent) {
- event.preventDefault();
- setError("");
- try {
- await login(username, password);
- navigate("/");
- } catch (exc) {
- setError(exc instanceof Error ? exc.message : "Login failed");
- }
- }
-
- return (
- <div className="grid min-h-screen place-items-center bg-slate-100 p-4">
- <form className="panel w-full max-w-sm p-5" onSubmit={(event) => void submit(event)}>
- <div className="mb-5 text-center">
- <img className="mx-auto mb-4 h-28 w-auto max-w-full object-contain" src={brandLogoPath} alt="ARES" />
- <h1 className="text-xl font-bold">ARES Dashboard</h1>
- <p className="text-sm text-slate-600">Authorized access</p>
- </div>
- <label className="mb-3 block text-sm font-semibold">
- Username
- <input className="field mt-1" value={username} onChange={(e) => setUsername(e.target.value)} />
- </label>
- <label className="mb-4 block text-sm font-semibold">
- Password
- <input
- className="field mt-1"
- type="password"
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- />
- </label>
- {error && <div className="mb-3 rounded-md border border-red-200 bg-red-50 p-2 text-sm text-red-800">{error}</div>}
- <button className="btn btn-primary w-full" type="submit">
- <KeyRound size={16} /> Login
- </button>
- </form>
- </div>
- );
-}
-
-function OverviewPage() {
- const telemetry = useQuery({ queryKey: ["telemetry"], queryFn: api.telemetry });
- const monthlyStats = useQuery({ queryKey: ["monthlyStats"], queryFn: api.monthlyStats });
- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
- const snapshot = telemetry.data as TelemetrySnapshot | undefined;
- const monthlyData = monthlyStats.data as MonthlyFindingStats | undefined;
- const campaignList = campaigns.data ?? [];
- const activeCampaigns = campaignList.filter((campaign) => String(campaign.status ?? "").toLowerCase() !== "deleted").length;
- const findings = typeof monthlyData?.confirmed_findings === "number" ? monthlyData.confirmed_findings : 0;
- const monthlyTotal = typeof monthlyData?.total === "number" ? monthlyData.total : 0;
- const monthlySeries = normalizeMonthlySeries(monthlyData?.period, monthlyData?.series);
- return (
- <Page
- title="Overview"
- >
- <div className="dashboard-grid">
- <TelemetryPanel snapshot={snapshot} loading={telemetry.isLoading} confirmedFindings={findings} />
- <div className="side-stack">
- <section className="panel p-4">
- <SectionHeader title="Highlights" />
- <div className="highlight-list">
- <HighlightRow label="Active campaigns" value={String(activeCampaigns)} tone="low" detail="available engagements" />
- <HighlightRow label="Findings" value={String(findings)} tone={findings > 0 ? "medium" : "low"} detail="confirmed observations" />
- <HighlightRow label="Runtime" value={telemetry.isSuccess ? "Online" : "Pending"} tone={telemetry.isSuccess ? "low" : "medium"} detail="telemetry feed" />
- </div>
- </section>
- <section className="panel p-4">
- <SectionHeader title="Monthly Statistics" />
- <div className="monthly-stat">
- <span>{formatMetric(monthlyTotal)}</span>
- <small>{monthlyData?.label ?? "Security signals this cycle"}</small>
- </div>
- {monthlyStats.isPending ? <p className="text-sm text-slate-500">Loading monthly activity...</p> : null}
- {monthlyStats.isError ? <p className="text-sm text-slate-500">Monthly activity unavailable.</p> : null}
- {!monthlyStats.isPending && !monthlyStats.isError && monthlyTotal === 0 ? (
- <p className="text-sm text-slate-500">No monthly activity yet</p>
- ) : null}
- {!monthlyStats.isPending && !monthlyStats.isError && monthlyTotal > 0 && monthlySeries.some((value) => value.count > 0) ? (
- <SparklineBars values={monthlySeries} />
- ) : null}
- </section>
- </div>
- </div>
- <CampaignTable campaigns={campaignList} />
- </Page>
- );
-}
-
-function normalizeMonthlySeries(
- period: string | undefined,
- series: MonthlyFindingStats["series"] | undefined
-): MonthlyFindingStats["series"] {
- if (!period || !/^\d{4}-\d{2}$/.test(period)) return [];
- const [yearText, monthText] = period.split("-");
- const year = Number(yearText);
- const month = Number(monthText);
- if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12) return [];
-
- const counts = new Map<string, number>();
- for (const item of series ?? []) {
- const count = Number(item.count);
- if (item.date && Number.isFinite(count)) counts.set(item.date, Math.max(0, count));
- }
-
- const daysInMonth = new Date(year, month, 0).getDate();
- return Array.from({ length: daysInMonth }, (_, index) => {
- const date = `${period}-${String(index + 1).padStart(2, "0")}`;
- return { date, count: counts.get(date) ?? 0 };
- });
-}
-
-function CampaignsPage() {
- const queryClient = useQueryClient();
- const { selectedCampaignId: selected, setSelectedCampaignId: setSelected } = useDashboardUi();
- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
- const [name, setName] = useSessionState("ares.dashboard.campaigns.create.name", "");
- const [client, setClient] = useSessionState("ares.dashboard.campaigns.create.client", "Internal");
- const [targets, setTargets] = useSessionState("ares.dashboard.campaigns.create.targets", "");
- const [scope, setScope] = useSessionState("ares.dashboard.campaigns.create.scope", "");
- const [noiseProfile, setNoiseProfile] = useSessionState("ares.dashboard.campaigns.create.noiseProfile", "stealth");
- const [createWarning, setCreateWarning] = useState("");
- const [otherId, setOtherId] = useSessionState("ares.dashboard.campaigns.compareId", "");
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.campaigns.tab", "List");
- const detail = useQuery({
- queryKey: ["campaign", selected],
- queryFn: () => api.campaign(selected),
- enabled: Boolean(selected)
- });
- const findings = useQuery({
- queryKey: ["findings", selected],
- queryFn: () => api.findings(selected),
- enabled: Boolean(selected)
- });
- const cvss = useQuery({
- queryKey: ["cvss", selected],
- queryFn: () => api.cvss(selected),
- enabled: Boolean(selected)
- });
- const diff = useQuery({
- queryKey: ["diff", selected, otherId],
- queryFn: () => api.diffCampaign(selected, otherId),
- enabled: Boolean(selected && otherId)
- });
- const create = useMutation({
- mutationFn: () =>
- api.createCampaign({
- name: name.trim(),
- client: client.trim(),
- targets: splitLines(targets),
- scope_cidrs: splitLines(scope),
- noise_profile: noiseProfile
- }),
- onSuccess: (campaign) => {
- setSelected(campaign.id);
- setName("");
- setTargets("");
- setScope("");
- setNoiseProfile("stealth");
- setCreateWarning("");
- setActiveTab("Scope");
- void queryClient.invalidateQueries({ queryKey: ["campaigns"] });
- }
- });
- const restore = useMutation({ mutationFn: () => api.restoreVault(selected) });
- const run = useMutation({
- mutationFn: () => api.runCampaign(selected, { plan: { stages: [] }, global_params: {}, dry_run: true })
- });
- const remove = useMutation({
- mutationFn: () => api.deleteCampaign(selected),
- onSuccess: () => {
- const deleted = selected;
- setSelected("");
- setOtherId("");
- void queryClient.invalidateQueries({ queryKey: ["campaigns"] });
- void queryClient.removeQueries({ queryKey: ["campaign", deleted] });
- void queryClient.removeQueries({ queryKey: ["findings", deleted] });
- void queryClient.removeQueries({ queryKey: ["cvss", deleted] });
- void queryClient.removeQueries({ queryKey: ["reports", deleted] });
- }
- });
-
- const campaignList = campaigns.data ?? [];
-
- return (
- <Page
- title="Campaigns"
- actions={<span className="status-pill">{campaignList.length} campaigns</span>}
- tabs={["List", "Scope", "Findings"]}
- activeTab={activeTab}
- onTabChange={setActiveTab}
- >
- {activeTab === "List" && (
- <>
- <section className="panel p-4">
- <SectionHeader title="Create Campaign" />
- <form className="grid gap-3" onSubmit={(e) => {
- e.preventDefault();
- if (!e.currentTarget.reportValidity()) return;
- const invalidScopeEntries = findInvalidScopeEntries(scope);
- if (invalidScopeEntries.length > 0) {
- setCreateWarning(`Scope CIDRs must be valid IPv4 CIDR/IP entries. Invalid: ${invalidScopeEntries.slice(0, 3).join(", ")}. Example: 10.0.0.0/24`);
- return;
- }
- setCreateWarning("");
- create.mutate();
- }}>
- <div className="grid gap-3 sm:grid-cols-2">
- <input className="field" required placeholder="Name" value={name} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setName(e.target.value); }} />
- <input className="field" required placeholder="Client" value={client} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setClient(e.target.value); }} />
- </div>
- <select className="field" value={noiseProfile} onChange={(e) => { setCreateWarning(""); setNoiseProfile(e.target.value); }}>
- <option value="stealth">Stealth</option>
- <option value="normal">Normal</option>
- <option value="aggressive">Aggressive</option>
- </select>
- <textarea className="field min-h-20" required placeholder="Targets" value={targets} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setTargets(e.target.value); }} />
- <textarea className="field min-h-20" required placeholder="Scope CIDRs" value={scope} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setScope(e.target.value); }} />
- {createWarning && <p className="notice notice-danger">{createWarning}</p>}
- <button className="btn btn-primary" disabled={create.isPending} type="submit">
- <ListChecks size={16} /> Create
- </button>
- </form>
- <DataPanel title="Create Error" data={create.error} />
- </section>
- <CampaignTable campaigns={campaignList} />
- <DataPanel title="Campaign Error" data={campaigns.error} />
- </>
- )}
- {activeTab === "Scope" && (
- <>
- <section className="panel p-4">
- <SectionHeader title="Campaign Detail" />
- <CampaignPicker campaigns={campaignList} value={selected} onChange={setSelected} />
- <CampaignScopeSummary campaign={detail.data ?? campaigns.data?.find((item) => item.id === selected)} loading={detail.isFetching} />
- <div className="mt-3 flex flex-wrap gap-2">
- <button className="btn" disabled={!selected} onClick={() => restore.mutate()}>
- <ShieldCheck size={16} /> Restore Vault
- </button>
- <button className="btn" disabled={!selected} onClick={() => run.mutate()}>
- <Play size={16} /> Dry Run Plan
- </button>
- <button
- className="btn btn-danger"
- disabled={!selected || remove.isPending}
- onClick={() => {
- if (window.confirm("Delete this campaign and its stored findings, hosts, credentials, and loot?")) {
- remove.mutate();
- }
- }}
- >
- <Trash2 size={16} /> Delete
- </button>
- <input className="field max-w-xs" placeholder="Compare campaign ID" value={otherId} onChange={(e) => setOtherId(e.target.value)} />
- </div>
- </section>
- <DataPanel title="Delete Error" data={remove.error} />
- <DataPanel title="Campaign Detail Error" data={detail.error} />
- <DataPanel title="CVSS Error" data={cvss.error} />
- <DataPanel title="Campaign Diff Error" data={diff.error} />
- <DataPanel title="Campaign Detail" data={detail.data} />
- <DataPanel title="CVSS Summary" data={cvss.data} />
- <DataPanel title="Diff" data={diff.data} />
- </>
- )}
- {activeTab === "Findings" && (
- <section className="grid gap-4">
- <section className="panel p-4">
- <SectionHeader title="Campaign Findings" />
- <CampaignPicker campaigns={campaignList} value={selected} onChange={setSelected} />
- {!selected ? <EmptyState text="Select a campaign to review findings." /> : null}
- </section>
- {selected ? <DataPanel title="Findings Error" data={findings.error} /> : null}
- {selected ? <FindingsTable findings={findings.data ?? []} /> : null}
- </section>
- )}
- </Page>
- );
-}
-
-function ExecutionChainsPanel({
- chains,
- moduleIds,
- onSelectModule
-}: {
- chains: ExecutionChain[];
- moduleIds: Set<string>;
- onSelectModule: (moduleId: string) => void;
-}) {
- if (chains.length === 0) {
- return <EmptyState text="No execution chains are available." />;
- }
- return (
- <section className="grid gap-3">
- {chains.map((chain) => (
- <article className="panel p-4" key={chain.id}>
- <SectionHeader
- title={chain.title}
- eyebrow={chain.category}
- description={chain.description}
- action={<span className="badge">{chain.stages.length} stages</span>}
- />
- <div className="grid gap-3">
- {chain.stages.map((stage) => (
- <div className="compact-row" key={`${chain.id}-${stage.order}`}>
- <div className="flex flex-wrap items-center justify-between gap-2">
- <div className="flex flex-wrap items-center gap-2">
- <span className="badge">Step {stage.order}</span>
- <strong>{stage.title}</strong>
- {stage.final_goal && <span className="badge badge-low">Final goal</span>}
- </div>
- <span className="text-xs font-medium text-slate-500">
- {stage.uses_previous_output ? "Uses prior output" : "Starts from campaign inputs"}
- </span>
- </div>
- <p className="mt-2 text-sm text-slate-600">{stage.purpose}</p>
- {stage.module_ids.length > 0 && (
- <div className="mt-3 flex flex-wrap items-center gap-2">
- <strong className="text-sm">Run</strong>
- {stage.module_ids.map((moduleId) => (
- <button
- className="btn btn-compact"
- disabled={!moduleIds.has(moduleId)}
- key={moduleId}
- onClick={() => onSelectModule(moduleId)}
- title={moduleIds.has(moduleId) ? `Open ${moduleId} in the run panel` : "Module is not available in the current catalog"}
- type="button"
- >
- <Play size={13} /> {moduleId}
- </button>
- ))}
- </div>
- )}
- <div className="mt-3 grid gap-1 text-xs text-slate-500">
- <span><strong>Inputs:</strong> {stage.required_inputs.join(", ") || "none"}</span>
- <span><strong>Produces:</strong> {stage.produces.join("; ") || "none"}</span>
- <span><strong>Next:</strong> {stage.next_action}</span>
- </div>
- </div>
- ))}
- </div>
- </article>
- ))}
- </section>
- );
-}
-
-function ModulesPage() {
- const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId } = useDashboardUi();
- const queryClient = useQueryClient();
- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
- const modules = useQuery({ queryKey: ["modules"], queryFn: api.modules });
- const executionChains = useQuery({ queryKey: ["executionChains"], queryFn: api.executionChains });
- const [selectedId, setSelectedId] = useSessionState("ares.dashboard.modules.selectedId", "");
- const [search, setSearch] = useSessionState("ares.dashboard.modules.search", "");
- const [category, setCategory] = useSessionState("ares.dashboard.modules.category", "");
- const [opsec, setOpsec] = useSessionState("ares.dashboard.modules.opsec", "");
- const [dryRun, setDryRun] = useSessionState("ares.dashboard.modules.dryRun", true);
- const [confirmed, setConfirmed] = useSessionState("ares.dashboard.modules.confirmed", false);
- const [params, setParams] = useSessionState<Record<string, unknown>>("ares.dashboard.modules.params", {});
- const [lastRunRecord, setLastRunRecord] = useSessionState<ModuleRunRecord | null>("ares.dashboard.modules.lastRun", null);
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.modules.tab", "Catalog");
- const previousSelectedId = useRef(selectedId);
- const campaignDetail = useQuery({
- queryKey: ["campaign", campaignId],
- queryFn: () => api.campaign(campaignId),
- enabled: Boolean(campaignId)
- });
- const run = useMutation({
- mutationFn: () => api.runModule(selectedId, buildModuleRunPayload(campaignId, params, dryRun)),
- onSuccess: (payload) => {
- setLastRunRecord({ campaignId, moduleId: selectedId, payload });
- setActiveTab("Results");
- if (!dryRun) {
- void queryClient.invalidateQueries({ queryKey: ["telemetry"] });
- void queryClient.invalidateQueries({ queryKey: ["monthlyStats"] });
- }
- },
- onError: (error) => {
- setLastRunRecord({ campaignId, moduleId: selectedId, payload: serializeError(error), isError: true });
- setActiveTab("Results");
- if (!dryRun) {
- void queryClient.invalidateQueries({ queryKey: ["telemetry"] });
- void queryClient.invalidateQueries({ queryKey: ["monthlyStats"] });
- }
- }
- });
- const list = modules.data ?? [];
- const moduleIds = useMemo(() => new Set(list.map((item) => item.id)), [list]);
- const relatedChainsByModule = useMemo(() => {
- const related = new Map<string, string[]>();
- for (const chain of executionChains.data ?? []) {
- for (const stage of chain.stages) {
- for (const moduleId of stage.module_ids) {
- const current = related.get(moduleId) ?? [];
- if (!current.includes(chain.title)) {
- current.push(chain.title);
- }
- related.set(moduleId, current);
- }
- }
- }
- return related;
- }, [executionChains.data]);
- const selected = list.find((item) => item.id === selectedId);
- const selectedCampaign = campaignDetail.data ?? (campaigns.data ?? []).find((item) => item.id === campaignId);
- const scopeWarning = moduleScopeWarning(selected, selectedCampaign, params, dryRun);
- const categories = unique(list.map((item) => item.category || ""));
- const visible = list.filter((item) => {
- const haystack = `${item.id} ${item.name ?? ""} ${item.description ?? ""} ${item.mitre ?? ""}`.toLowerCase();
- return (
- (!search || haystack.includes(search.toLowerCase())) &&
- (!category || item.category === category) &&
- (!opsec || item.opsec_level === opsec)
- );
- });
- const sensitive = isSensitiveModule(selected);
- const dryRunSupported = selected?.dry_run_supported !== false;
- const kerberoastTargetMissing = selected?.id === "ad.kerberoast" && !String(params.target_user ?? "").trim();
- const canRun = Boolean(campaignId && selectedId) && (!sensitive || confirmed) && !run.isPending && (!dryRun || dryRunSupported);
- const runBlocked = !canRun || Boolean(scopeWarning) || kerberoastTargetMissing;
- const runHint = moduleRunHint(campaignId, selected, selectedCampaign, sensitive, confirmed, dryRun);
- const persistedRun = lastRunRecord?.campaignId === campaignId && lastRunRecord.moduleId === selectedId ? lastRunRecord : null;
- const runResult = (run.data ?? (!persistedRun?.isError ? persistedRun?.payload : undefined)) as Record<string, unknown> | undefined;
- const runError = run.error ?? (persistedRun?.isError ? persistedRun.payload : undefined);
-
- useEffect(() => {
- if (previousSelectedId.current === selectedId) {
- return;
- }
- previousSelectedId.current = selectedId;
- setParams({});
- setConfirmed(false);
- setDryRun(true);
- }, [selectedId, setConfirmed, setDryRun, setParams]);
-
- return (
- <Page
- title="Modules"
- actions={<span className="status-pill">{visible.length} shown</span>}
- tabs={["Catalog", "Execution Chains", "Run Panel", "Results"]}
- activeTab={activeTab}
- onTabChange={setActiveTab}
- >
- {activeTab === "Catalog" && (
- <section className="panel p-4">
- <SectionHeader title="Module Catalog" />
- <div className="mb-3 grid gap-2 sm:grid-cols-3">
- <label className="field-with-icon sm:col-span-3">
- <Search size={15} />
- <input placeholder="Search modules, MITRE, descriptions" value={search} onChange={(e) => setSearch(e.target.value)} />
- </label>
- <select className="field" value={category} onChange={(e) => setCategory(e.target.value)}>
- <option value="">Category</option>
- {categories.map((item) => <option key={item} value={item}>{item}</option>)}
- </select>
- <select className="field" value={opsec} onChange={(e) => setOpsec(e.target.value)}>
- <option value="">OPSEC</option>
- {unique(list.map((item) => item.opsec_level || "")).map((item) => <option key={item} value={item}>{item}</option>)}
- </select>
- </div>
- <div className="grid max-h-[640px] gap-2 overflow-auto">
- {visible.map((item) => (
- <button
- className={`catalog-card ${selectedId === item.id ? "active" : ""}`}
- key={item.id}
- onClick={() => {
- setSelectedId(item.id);
- setActiveTab("Run Panel");
- }}
- >
- <div className="flex items-start justify-between gap-3">
- <div>
- <div className="font-bold">{item.id}</div>
- <div className="text-sm text-slate-600">{item.description}</div>
- </div>
- <span className={opsecBadge(item.opsec_level)}>{item.opsec_level || "n/a"}</span>
- </div>
- <div className="mt-2 flex flex-wrap gap-1">
- {(item.mitre_list ?? []).slice(0, 4).map((technique) => <span className="badge" key={technique}>{technique}</span>)}
- {(relatedChainsByModule.get(item.id) ?? []).slice(0, 2).map((chainTitle) => (
- <span className="badge" key={chainTitle}>Chain: {chainTitle}</span>
- ))}
- </div>
- </button>
- ))}
- {visible.length === 0 && (
- <EmptyState text="No modules match the current search and filters." />
- )}
- </div>
- <DataPanel title="Module Catalog Error" data={modules.error} />
- </section>
- )}
- {activeTab === "Execution Chains" && (
- <>
- {executionChains.isPending && <EmptyState text="Loading execution chains..." />}
- {executionChains.error && <DataPanel title="Execution Chain Error" data={executionChains.error} />}
- {!executionChains.isPending && !executionChains.error && (
- <ExecutionChainsPanel
- chains={executionChains.data ?? []}
- moduleIds={moduleIds}
- onSelectModule={(moduleId) => {
- setSelectedId(moduleId);
- setActiveTab("Run Panel");
- }}
- />
- )}
- </>
- )}
- {activeTab === "Run Panel" && (
- <section className="panel p-4">
- <SectionHeader
- title="Run Panel"
- eyebrow={selected ? selected.id : "Select module"}
- action={selected ? <span className={opsecBadge(selected.opsec_level)}>{selected.opsec_level || "n/a"}</span> : null}
- />
- {selected?.description && <p className="text-sm text-slate-600">{selected.description}</p>}
- {selected && (selected.capability_flags?.length || selected.supported_modes?.length) ? (
- <div className="mt-2 flex flex-wrap gap-1">
- {(selected.capability_flags ?? []).map((flag) => <span className="badge" key={flag}>{flag}</span>)}
- {(selected.supported_modes ?? []).map((mode) => <span className="badge" key={mode}>mode: {mode}</span>)}
- </div>
- ) : null}
- {selected?.dependency_notes?.length ? (
- <p className="notice mt-3">Dependencies: {selected.dependency_notes.join("; ")}</p>
- ) : null}
- {selected && !dryRunSupported && (
- <p className="notice notice-danger mt-3">Dry-run is unavailable for this module. No preview will be generated.</p>
- )}
- <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={setCampaignId} />
- {campaignId && campaignDetail.isFetching && (
- <div className="notice mt-3">
- <Loader2 className="spin" size={16} /> Loading campaign scope...
- </div>
- )}
- <DataPanel title="Campaign Scope Error" data={campaignDetail.error} />
- {selected ? (
- <form
- aria-busy={run.isPending}
- className="mt-4 grid gap-3"
- onSubmit={(e) => {
- e.preventDefault();
- if (runBlocked) {
- return;
- }
- run.mutate();
- }}
- >
- <ParamForm
- schema={selected.param_schema}
- values={params}
- onChange={setParams}
- requiredOverrides={selected.id === "ad.kerberoast" ? { target_user: true } : undefined}
- />
- {runHint && (
- <p className="notice">
- {runHint}
- </p>
- )}
- {scopeWarning && (
- <p className="notice notice-danger">
- {scopeWarning}
- </p>
- )}
- <label className="toggle-row">
- <input type="checkbox" checked={dryRun} onChange={(e) => setDryRun(e.target.checked)} />
- {dryRunSupported ? "Dry run" : "Dry run unavailable"}
- </label>
- {sensitive && (
- <label className="notice notice-danger">
- <input className="mr-2" type="checkbox" checked={confirmed} onChange={(e) => setConfirmed(e.target.checked)} />
- Confirm authorized high-noise or sensitive execution
- </label>
- )}
- <button className="btn btn-primary" type="submit" disabled={runBlocked}>
- {run.isPending ? (
- <>
- <Loader2 className="spin" size={16} /> Running...
- </>
- ) : (
- <>
- <Play size={16} /> Run
- </>
- )}
- </button>
- {run.isPending && (
- <div className="notice notice-danger" role="status" aria-live="polite">
- <Loader2 className="spin shrink-0" size={18} />
- Module execution in progress. Keep this page open while ARES validates the target and collects results.
- </div>
- )}
- </form>
- ) : (
- <EmptyState text="Select a module" />
- )}
- </section>
- )}
- {activeTab === "Results" && (
- <section className="panel p-4">
- <SectionHeader
- title="Run Results"
- eyebrow={selected ? selected.id : undefined}
- action={persistedRun ? <span className={persistedRun.isError ? "badge badge-high" : "badge badge-low"}>{persistedRun.isError ? "error" : "latest"}</span> : null}
- />
- {runResult || runError ? (
- <>
- <ModuleRunSummary result={runResult} error={runError} />
- <DataPanel title={runError ? "Run Error" : "Run Result"} data={runError ?? runResult} />
- </>
- ) : (
- <EmptyState text="Run a selected module to see results here." />
- )}
- </section>
- )}
- </Page>
- );
-}
-
-function ReportsPage() {
- const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId } = useDashboardUi();
- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
- const [format, setFormat] = useSessionState("ares.dashboard.reports.format", "html");
- const [warning, setWarning] = useState("");
- const [libraryError, setLibraryError] = useState("");
- const [lastGenerateResult, setLastGenerateResult] = useSessionState<PersistedResult | null>("ares.dashboard.reports.lastGenerate", null);
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.reports.tab", "Generate");
- const queryClient = useQueryClient();
- const reports = useQuery({
- queryKey: ["reports", campaignId],
- queryFn: () => api.reports(campaignId),
- enabled: Boolean(campaignId)
- });
- const reportItems = reports.data?.reports ?? [];
- const reportResultKey = `${campaignId}:${format}`;
- const generate = useMutation({
- mutationFn: () => api.generateReport(campaignId, format),
- onSuccess: (payload) => {
- setLastGenerateResult({ key: reportResultKey, payload });
- setActiveTab("Library");
- void queryClient.invalidateQueries({ queryKey: ["reports", campaignId] });
- },
- onError: (error) => {
- setLastGenerateResult({ key: reportResultKey, payload: serializeError(error), isError: true });
- setActiveTab("Generate");
- }
- });
- const persistedGenerateResult = lastGenerateResult?.key === reportResultKey ? lastGenerateResult : null;
- const generateIssue = generate.error ?? (persistedGenerateResult?.isError ? persistedGenerateResult.payload : undefined);
- const pdfIssueHint = format === "pdf" ? pdfFailureHint(generateIssue) : "";
- const download = useMutation({
- mutationFn: async (item: ReportItem) => {
- const blob = await api.downloadReport(campaignId, item.filename);
- const url = URL.createObjectURL(blob);
- const link = document.createElement("a");
- link.href = url;
- link.download = item.filename;
- document.body.appendChild(link);
- link.click();
- link.remove();
- window.setTimeout(() => URL.revokeObjectURL(url), 1000);
- }
- });
- const deleteReport = useMutation({
- mutationFn: (item: ReportItem) => api.deleteReport(campaignId, item.filename),
- onSuccess: (_payload, item) => {
- queryClient.setQueryData<{ campaign_id: string; reports: ReportItem[] }>(
- ["reports", campaignId],
- (current) => current
- ? {
- ...current,
- reports: current.reports.filter((report) => report.filename !== item.filename)
- }
- : current
- );
- setLibraryError("");
- },
- onError: (error) => {
- setLibraryError(readableError(error, "Report could not be deleted."));
- }
- });
- const clearReports = useMutation({
- mutationFn: () => api.clearReports(campaignId),
- onSuccess: () => {
- queryClient.setQueryData<{ campaign_id: string; reports: ReportItem[] }>(
- ["reports", campaignId],
- (current) => current ? { ...current, reports: [] } : current
- );
- setLibraryError("");
- },
- onError: (error) => {
- setLibraryError(readableError(error, "Report library could not be cleared."));
- }
- });
- const deleteDisabled = deleteReport.isPending || clearReports.isPending;
- return (
- <Page
- title="Reports"
- actions={<span className="status-pill">{reports.data?.reports?.length ?? 0} artifacts</span>}
- tabs={["Generate", "Library"]}
- activeTab={activeTab}
- onTabChange={setActiveTab}
- >
- {activeTab === "Generate" && (
- <section className="panel p-4">
- <SectionHeader
- title="Generate Report"
- description="Export findings, scope, and remediation."
- />
- <div className="compact-form-row">
- <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={(id) => { setCampaignId(id); setWarning(""); }} />
- <select className="field" value={format} onChange={(e) => setFormat(e.target.value)}>
- {["html", "pdf", "markdown", "json"].map((item) => <option key={item} value={item}>{item}</option>)}
- </select>
- <button
- className="btn btn-primary"
- disabled={generate.isPending}
- onClick={() => {
- if (!campaignId) {
- setWarning("Campaign is required.");
- return;
- }
- setWarning("");
- generate.mutate();
- }}
- >
- {generate.isPending ? (
- <>
- <Loader2 className="spin" size={16} /> Generating...
- </>
- ) : (
- <>
- <FileText size={16} /> Generate
- </>
- )}
- </button>
- </div>
- {warning && <p className="notice notice-danger mt-3">{warning}</p>}
- {pdfIssueHint && (
- <p className="notice notice-danger mt-3">
- <AlertTriangle size={16} />
- {pdfIssueHint}
- </p>
- )}
- <DataPanel
- title={generateIssue ? "Generate Error" : "Generate Result"}
- data={generate.error ?? generate.data ?? persistedGenerateResult?.payload}
- />
- </section>
- )}
- {activeTab === "Library" && (
- <section className="panel table-panel">
- <SectionHeader
- title="Report Library"
- action={campaignId && reportItems.length > 0 ? (
- <button
- className="btn btn-danger"
- disabled={deleteDisabled}
- onClick={() => {
- if (!window.confirm(`Delete all ${reportItems.length} report artifacts for this campaign? This cannot be undone.`)) {
- return;
- }
- setLibraryError("");
- clearReports.mutate();
- }}
- >
- {clearReports.isPending ? (
- <Loader2 className="spin" size={15} />
- ) : (
- <Trash2 size={15} />
- )}
- Delete all
- </button>
- ) : null}
- />
- <div className="table-scroll">
- <table className="table">
- <thead><tr><th>Filename</th><th>Format</th><th>Size</th><th>Modified</th><th>Actions</th></tr></thead>
- <tbody>
- {reportItems.map((item) => (
- <tr key={item.filename}>
- <td className="font-medium text-slate-900">{item.filename}</td>
- <td><span className="badge">{item.format}</span></td>
- <td>{formatBytes(item.size_bytes)}</td>
- <td>{formatReportDate(item.modified_at)}</td>
- <td>
- <button className="btn" disabled={download.isPending || deleteDisabled} onClick={() => download.mutate(item)}>
- <Download size={15} /> Download
- </button>
- <button
- className="btn btn-danger"
- disabled={deleteDisabled}
- onClick={() => {
- if (!window.confirm(`Delete report artifact "${item.filename}"? This cannot be undone.`)) {
- return;
- }
- setLibraryError("");
- deleteReport.mutate(item);
- }}
- >
- <Trash2 size={15} /> Delete
- </button>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- {libraryError && (
- <p className="notice notice-danger mt-3">
- <AlertTriangle size={16} />
- {libraryError}
- </p>
- )}
- <DataPanel title="Report Library Error" data={reports.error} />
- {campaignId && reportItems.length === 0 && (
- <EmptyState text="No reports generated for this campaign yet." />
- )}
- {!campaignId && <EmptyState text="Select a campaign to list reports." />}
- <DataPanel title="Download Result" data={download.error} />
- </section>
- )}
- </Page>
- );
-}
-
-function GraphPage() {
- const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId } = useDashboardUi();
- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
- const [jsonPath, setJsonPath] = useSessionState("ares.dashboard.graph.jsonPath", "");
- const [warning, setWarning] = useState("");
- const [lastIngestResult, setLastIngestResult] = useSessionState<PersistedResult | null>("ares.dashboard.graph.lastIngest", null);
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.graph.tab", "Entities");
- const graph = useQuery({ queryKey: ["graph", campaignId], queryFn: () => api.graph(campaignId), enabled: Boolean(campaignId) });
- const paths = useQuery({ queryKey: ["attack-paths", campaignId], queryFn: () => api.attackPaths(campaignId), enabled: Boolean(campaignId) });
- const ingestResultKey = `${campaignId}:${jsonPath.trim()}`;
- const ingest = useMutation({
- mutationFn: () => api.ingestBloodhound(campaignId, jsonPath),
- onSuccess: (payload) => setLastIngestResult({ key: ingestResultKey, payload }),
- onError: (error) => setLastIngestResult({ key: ingestResultKey, payload: serializeError(error), isError: true })
- });
- const persistedIngestResult = lastIngestResult?.key === ingestResultKey ? lastIngestResult : null;
- const nodes = Array.isArray(graph.data?.nodes) ? graph.data.nodes : [];
- const links = Array.isArray(graph.data?.links) ? graph.data.links : [];
- return (
- <Page
- title="Graph"
- actions={<span className="status-pill">{nodes.length} nodes / {links.length} links</span>}
- tabs={["Entities", "Attack Paths", "Ingest"]}
- activeTab={activeTab}
- onTabChange={setActiveTab}
- >
- {activeTab === "Entities" && (
- <section className="panel min-h-[360px] p-4">
- <SectionHeader
- title="Attack Graph"
- description="Hosts, identities, and relationships."
- action={(
- <div className="flex gap-2">
- <span className="badge">{nodes.length} nodes</span>
- <span className="badge">{links.length} links</span>
- </div>
- )}
- />
- <div className="mb-4 max-w-sm">
- <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={(id) => { setCampaignId(id); setWarning(""); }} />
- </div>
- {nodes.length > 0 ? (
- <div className="grid gap-3 md:grid-cols-2 lg:grid-cols-3">
- {nodes.slice(0, 24).map((node: any, index) => (
- <div className="entity-card" key={node.id ?? index}>
- <Server size={16} />
- <div className="font-bold">{node.label ?? node.id ?? `Node ${index + 1}`}</div>
- <div className="text-sm text-slate-600">{node.type ?? "artifact"}</div>
- </div>
- ))}
- </div>
- ) : (
- <EmptyState text={campaignId ? "No graph nodes yet. Run discovery modules or ingest BloodHound JSON." : "Select a campaign to load graph data."} />
- )}
- <DataPanel title="Graph Error" data={graph.error} />
- </section>
- )}
- {activeTab === "Attack Paths" && (
- <section className="panel p-4">
- <SectionHeader
- title="Attack Paths"
- description="Calculated paths for the selected campaign."
- />
- <div className="mb-4 max-w-sm">
- <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={(id) => { setCampaignId(id); setWarning(""); }} />
- </div>
- {!campaignId ? (
- <EmptyState text="Select a campaign to load attack paths." />
- ) : paths.error ? (
- <DataPanel title="Attack Path Error" data={paths.error} />
- ) : paths.data ? (
- <DataPanel title="Attack Paths" data={paths.data} />
- ) : (
- <EmptyState text="No attack paths available for this campaign yet." />
- )}
- </section>
- )}
- {activeTab === "Ingest" && (
- <section className="panel p-4">
- <SectionHeader
- title="BloodHound Ingest"
- description="Import a server-local JSON path."
- />
- <div className="mb-3 max-w-sm">
- <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={(id) => { setCampaignId(id); setWarning(""); }} />
- </div>
- <form className="grid gap-2" onSubmit={(e) => {
- e.preventDefault();
- if (!campaignId) {
- setWarning("Campaign is required.");
- return;
- }
- if (!jsonPath.trim()) {
- setWarning("BloodHound JSON path is required.");
- return;
- }
- setWarning("");
- ingest.mutate();
- }}>
- <input className="field" required placeholder="C:\\labs\\bloodhound\\results.json" value={jsonPath} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setJsonPath(e.target.value); setWarning(""); }} />
- <button className="btn" disabled={ingest.isPending} type="submit">
- {ingest.isPending ? (
- <>
- <Loader2 className="spin" size={16} /> Ingesting...
- </>
- ) : (
- <>
- <GitGraph size={16} /> Ingest
- </>
- )}
- </button>
- </form>
- {warning && <p className="notice notice-danger mt-3">{warning}</p>}
- <DataPanel title="Attack Paths" data={paths.data} />
- <DataPanel title="Attack Path Error" data={paths.error} />
- <DataPanel
- title={(ingest.error ?? (persistedIngestResult?.isError ? persistedIngestResult.payload : undefined)) ? "Ingest Error" : "Ingest Result"}
- data={ingest.data ?? ingest.error ?? persistedIngestResult?.payload}
- />
- </section>
- )}
- </Page>
- );
-}
-
-function TemplatesPage() {
- const templates = useQuery({ queryKey: ["templates"], queryFn: api.templates });
- const [name, setName] = useSessionState("ares.dashboard.templates.name", "");
- const [params, setParams] = useSessionState("ares.dashboard.templates.params", "{}");
- const [warning, setWarning] = useState("");
- const [lastPlanResult, setLastPlanResult] = useSessionState<PersistedResult | null>("ares.dashboard.templates.lastPlan", null);
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.templates.tab", "Templates");
- const templatePlanKey = `${name.trim()}:${params}`;
- const plan = useMutation({
- mutationFn: () => api.templatePlan(name, safeJson(params)),
- onSuccess: (payload) => setLastPlanResult({ key: templatePlanKey, payload }),
- onError: (error) => setLastPlanResult({ key: templatePlanKey, payload: serializeError(error), isError: true })
- });
- const selected = (templates.data ?? []).find((item) => item.name === name);
- const persistedPlanResult = lastPlanResult?.key === templatePlanKey ? lastPlanResult : null;
- const generated = (plan.data ?? (!persistedPlanResult?.isError ? persistedPlanResult?.payload : undefined)) as TemplatePlanResponse | undefined;
- const paramsValid = isJsonObject(params);
- return (
- <Page
- title="Templates"
- actions={<span className="status-pill">{templates.data?.length ?? 0} templates</span>}
- tabs={["Templates", "Plan Builder"]}
- activeTab={activeTab}
- onTabChange={setActiveTab}
- >
- <DataPanel title="Template Error" data={templates.error} />
- {activeTab === "Templates" && (
- <section className="panel p-4">
- <SectionHeader
- title="Campaign Templates"
- description="Pick a template and generate a plan."
- />
- <div className="grid gap-2">
- {(templates.data ?? []).map((item, index) => {
- const templateName = String(item.name ?? item.id ?? index);
- return (
- <button
- className={`template-card ${name === templateName ? "active" : ""}`}
- key={templateName}
- onClick={() => {
- setName(templateName);
- setWarning("");
- setLastPlanResult(null);
- plan.reset();
- setActiveTab("Plan Builder");
- }}
- >
- <span className="font-bold">{templateName}</span>
- <small>{item.description ?? "Campaign execution template"}</small>
- <span className="mt-2 flex flex-wrap gap-2">
- <span className="badge">{item.stages ?? 0} stages</span>
- <span className="badge">{item.modules ?? 0} modules</span>
- </span>
- </button>
- );
- })}
- </div>
- </section>
- )}
- {activeTab === "Plan Builder" && (
- <section className="panel p-4">
- <SectionHeader title="Plan Builder" action={name ? <span className="badge">{name}</span> : null} />
- <input className="field" placeholder="Template name" value={name} onChange={(e) => {
- setName(e.target.value);
- setWarning("");
- setLastPlanResult(null);
- }} />
- {selected ? (
- <div className="preview-card mt-3">
- <div className="font-bold">{selected.name}</div>
- <p className="mt-1 text-sm text-slate-600">{selected.description}</p>
- <div className="mt-2 flex flex-wrap gap-2">
- <span className="badge">{selected.stages ?? 0} stages</span>
- <span className="badge">{selected.modules ?? 0} modules</span>
- </div>
- </div>
- ) : (
- <EmptyState text="Select a template from the left panel." />
- )}
- <label className="mt-3 block text-sm font-semibold">
- Global parameters
- <textarea
- className="field mt-1 min-h-32"
- value={params}
- placeholder={'{"target":"127.0.0.1","domain":"corp.local","dc":"10.0.0.5"}'}
- onChange={(e) => {
- setParams(e.target.value);
- setWarning("");
- }}
- />
- </label>
- <p className="mt-1 text-xs text-slate-500">JSON object. Leave {"{}"} for defaults.</p>
- {(warning || !paramsValid) && (
- <p className="notice notice-danger mt-2">
- {warning || "Global parameters must be a valid JSON object."}
- </p>
- )}
- <button
- className="btn btn-primary mt-3"
- disabled={!name || plan.isPending || !paramsValid}
- onClick={() => {
- if (!name.trim()) {
- setWarning("Template name is required.");
- return;
- }
- if (!paramsValid) {
- setWarning("Global parameters must be a valid JSON object.");
- return;
- }
- setWarning("");
- plan.mutate();
- }}
- >
- {plan.isPending ? (
- <>
- <Loader2 className="spin" size={16} /> Generating...
- </>
- ) : (
- <>
- <Workflow size={16} /> Generate Plan
- </>
- )}
- </button>
- <TemplatePlanSummary plan={generated} />
- <DataPanel
- title={(plan.error ?? (persistedPlanResult?.isError ? persistedPlanResult.payload : undefined)) ? "Plan Error" : "Plan Details"}
- data={plan.error ?? plan.data ?? persistedPlanResult?.payload}
- />
- </section>
- )}
- </Page>
- );
-}
-
-function StrategyPage() {
- const { user } = useAuth();
- const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId } = useDashboardUi();
- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
- const active = useQuery({ queryKey: ["strategy-active"], queryFn: api.activeStrategy });
- const [goal, setGoal] = useSessionState("ares.dashboard.strategy.goal", "domain_admin");
- const [llmBackend, setLlmBackend] = useSessionState("ares.dashboard.strategy.llmBackend", "claude");
- const [authorizations, setAuthorizations] = useSessionState("ares.dashboard.strategy.authorizations", "");
- const [lastEngageResult, setLastEngageResult] = useSessionState<PersistedResult | null>("ares.dashboard.strategy.lastEngage", null);
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.strategy.tab", "Objective");
- const strategyResultKey = `${campaignId}:${goal}:${llmBackend}:${authorizations}`;
- const engage = useMutation({
- mutationFn: () =>
- api.engageStrategy({
- campaign_id: campaignId,
- goal,
- llm_backend: llmBackend,
- max_rounds: 5,
- authorizations: splitLines(authorizations)
- }),
- onSuccess: (payload) => {
- setLastEngageResult({ key: strategyResultKey, payload });
- setActiveTab("Result");
- },
- onError: (error) => {
- setLastEngageResult({ key: strategyResultKey, payload: serializeError(error), isError: true });
- setActiveTab("Result");
- }
- });
- const persistedEngageResult = lastEngageResult?.key === strategyResultKey ? lastEngageResult : null;
- const allowed = user?.role === "team_lead" || user?.role === "operator";
- return (
- <Page
- title="Strategy"
- actions={<span className={allowed ? "status-pill status-low" : "status-pill status-high"}>{allowed ? "Authorized" : "Restricted"}</span>}
- tabs={["Objective", "Active", "Result"]}
- activeTab={activeTab}
- onTabChange={setActiveTab}
- >
- {activeTab === "Objective" && (
- <section className="panel p-4">
- <SectionHeader title="Objective Builder" />
- <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={setCampaignId} />
- <select className="field mt-3" value={goal} onChange={(e) => setGoal(e.target.value)}>
- {["domain_admin", "enterprise_admin", "cloud_admin", "data_exfil", "persistence", "full_compromise"].map((item) => <option key={item} value={item}>{item}</option>)}
- </select>
- <select className="field mt-3" value={llmBackend} onChange={(e) => setLlmBackend(e.target.value)}>
- <option value="claude">Claude / ANTHROPIC_API_KEY</option>
- <option value="openai">OpenAI / OPENAI_API_KEY</option>
- <option value="local">Local Ollama</option>
- </select>
- <p className="notice mt-2">
- {strategyBackendHint(llmBackend)}
- </p>
- <textarea
- className="field mt-3 min-h-28"
- placeholder="Authorization notes, one per line"
- value={authorizations}
- onChange={(e) => setAuthorizations(e.target.value)}
- />
- {!allowed && (
- <p className="notice notice-danger mt-2">
- Strategy engagement requires operator or team lead role.
- </p>
- )}
- {!campaignId && (
- <p className="notice mt-2">
- Select a scoped campaign before starting Strategy.
- </p>
- )}
- <button className="btn btn-primary mt-3" disabled={!allowed || !campaignId || engage.isPending} onClick={() => engage.mutate()}>
- {engage.isPending ? (
- <>
- <Loader2 className="spin" size={16} /> Engaging...
- </>
- ) : (
- <>
- <ShieldCheck size={16} /> Engage
- </>
- )}
- </button>
- </section>
- )}
- {activeTab === "Active" && (
- <section className="grid gap-4">
- <section className="panel p-4">
- <SectionHeader title="Planning Snapshot" />
- <div className="mini-stat-grid">
- <MiniStat title="Goal" value={goal} />
- <MiniStat title="Backend" value={llmBackend} />
- <MiniStat title="Authorization" value={allowed ? "ready" : "restricted"} />
- </div>
- </section>
- {active.error ? <DataPanel title="Active Strategy Error" data={active.error} /> : active.data ? <DataPanel title="Active" data={active.data} /> : <EmptyState text="No active strategy state is available yet." />}
- </section>
- )}
- {activeTab === "Result" && (
- <section className="panel p-4">
- <SectionHeader title="Engagement Result" />
- {(engage.data ?? engage.error ?? persistedEngageResult?.payload) ? (
- <DataPanel
- title={(engage.error ?? (persistedEngageResult?.isError ? persistedEngageResult.payload : undefined)) ? "Engagement Error" : "Engagement Result"}
- data={engage.data ?? engage.error ?? persistedEngageResult?.payload}
- />
- ) : (
- <EmptyState text="Engage a strategy objective to see results here." />
- )}
- </section>
- )}
- </Page>
- );
-}
-
-function apiKeyVisibleIdentifier(key: ApiKeyMeta): string {
- const prefix = typeof key.key_prefix === "string" && key.key_prefix
- ? key.key_prefix
- : typeof key.prefix === "string" && key.prefix
- ? key.prefix
- : "";
- return prefix ? `Prefix: ${prefix}` : `ID: ${key.id.slice(0, 12)}`;
-}
-
-function apiKeyOwnerLabel(key: ApiKeyMeta): string {
- const owner = key.owner ?? key.owner_username ?? key.username ?? key.role;
- return typeof owner === "string" && owner.trim() ? owner : "";
-}
-
-function formatDateTime(value: string): string {
- const date = new Date(value);
- return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
-}
-
-function SecurityPage() {
- const { user } = useAuth();
- const keys = useQuery({ queryKey: ["api-keys"], queryFn: api.apiKeys });
- const audit = useQuery({ queryKey: ["security-audit"], queryFn: api.securityAudit, enabled: user?.role === "team_lead" });
- const users = useQuery({ queryKey: ["security-users"], queryFn: api.users, enabled: user?.role === "team_lead" });
- const queryClient = useQueryClient();
- const secretKeyInputRef = useRef<HTMLInputElement | null>(null);
- const [currentPassword, setCurrentPassword] = useState("");
- const [newPassword, setNewPassword] = useState("");
- const [keyName, setKeyName] = useState("");
- const [scopes, setScopes] = useState("read");
- const [creatingApiKey, setCreatingApiKey] = useState(false);
- const [generatedApiKey, setGeneratedApiKey] = useState<GeneratedApiKey | null>(null);
- const [apiKeyError, setApiKeyError] = useState<unknown>(null);
- const [copyStatus, setCopyStatus] = useState<ApiKeyCopyStatus>("idle");
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.security.tab", "Account");
- const change = useMutation({
- mutationFn: () => api.changePassword({ current_password: currentPassword, new_password: newPassword }),
- onSuccess: () => {
- setCurrentPassword("");
- setNewPassword("");
- }
- });
- const remove = useMutation({
- mutationFn: (id: string) => api.deleteApiKey(id),
- onSuccess: () => {
- void queryClient.invalidateQueries({ queryKey: ["api-keys"] });
- }
- });
-
- useEffect(() => {
- if (generatedApiKey) {
- secretKeyInputRef.current?.focus();
- }
- }, [generatedApiKey]);
-
- async function handleCreateApiKey(event: FormEvent<HTMLFormElement>): Promise<void> {
- event.preventDefault();
- if (!event.currentTarget.reportValidity()) return;
- setApiKeyError(null);
- setGeneratedApiKey(null);
- setCopyStatus("idle");
- setCreatingApiKey(true);
- try {
- const response = await api.createApiKey({ name: keyName, scopes });
- if (!response.key) {
- throw new Error("API key created, but the secret was not returned by the API.");
- }
- setGeneratedApiKey({
- id: response.id,
- key: response.key,
- note: response.note,
- prefix: response.prefix ?? response.key_prefix
- });
- setKeyName("");
- void queryClient.invalidateQueries({ queryKey: ["api-keys"] });
- } catch (error) {
- setApiKeyError(error);
- } finally {
- setCreatingApiKey(false);
- }
- }
-
- async function copyGeneratedKey(): Promise<void> {
- if (!generatedApiKey?.key) return;
-
- let copied = false;
- if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
- try {
- await navigator.clipboard.writeText(generatedApiKey.key);
- copied = true;
- } catch {
- copied = false;
- }
- }
-
- if (!copied && secretKeyInputRef.current) {
- secretKeyInputRef.current.focus();
- secretKeyInputRef.current.select();
- try {
- copied = document.execCommand("copy");
- } catch {
- copied = false;
- }
- }
-
- setCopyStatus(copied ? "copied" : "manual");
- }
-
- function closeGeneratedKeyModal(): void {
- setGeneratedApiKey(null);
- setCopyStatus("idle");
- }
-
- return (
- <Page
- title="Security"
- actions={<span className="status-pill">{formatRole(user?.role)}</span>}
- tabs={["Account", "API Keys", "Audit"]}
- activeTab={activeTab}
- onTabChange={setActiveTab}
- >
- {activeTab === "Account" && (
- <section className="panel p-4">
- <SectionHeader title="Account" />
- <div className="profile-row mb-3">
- <span className="profile-avatar-light">{user?.username?.slice(0, 1).toUpperCase() ?? "A"}</span>
- <div>
- <div className="font-semibold text-slate-950">{user?.username}</div>
- <div className="text-xs text-slate-500">{formatRole(user?.role)}</div>
- </div>
- </div>
- <form className="grid gap-2" onSubmit={(event) => {
- event.preventDefault();
- if (!event.currentTarget.reportValidity()) return;
- change.mutate();
- }}>
- <input className="field" required type="password" placeholder="Current password" value={currentPassword} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCurrentPassword(e.target.value); }} />
- <input className="field" required minLength={12} type="password" placeholder="New password" value={newPassword} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setNewPassword(e.target.value); }} />
- <button className="btn" disabled={change.isPending} type="submit">
- {change.isPending ? <Loader2 className="spin" size={16} /> : <KeyRound size={16} />}
- Change Password
- </button>
- </form>
- <DataPanel title="Password Result" data={change.data ?? change.error} />
- </section>
- )}
- {activeTab === "API Keys" && (
- <section className="panel p-4">
- <SectionHeader
- title="API Keys"
- action={<span className="badge">{keys.data?.length ?? 0} active</span>}
- description="Metadata only; new secrets are shown once."
- />
- <form className="mb-3 grid gap-2 sm:grid-cols-[1fr_120px_auto]" onSubmit={(event) => void handleCreateApiKey(event)}>
- <input className="field" required placeholder="Name" value={keyName} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setKeyName(e.target.value); }} />
- <select className="field" value={scopes} onChange={(e) => setScopes(e.target.value)}>
- <option value="read">read</option>
- <option value="write">write</option>
- <option value="admin">admin</option>
- </select>
- <button className="btn" disabled={creatingApiKey} type="submit">
- {creatingApiKey ? <Loader2 className="spin" size={16} /> : <KeyRound size={16} />}
- Create
- </button>
- </form>
- {(keys.data ?? []).map((key) => (
- <div className="key-row" key={key.id}>
- <div className="min-w-0">
- <div className="font-semibold text-slate-950">{key.name ?? "Unnamed API key"}</div>
- <div className="mt-1 flex flex-wrap gap-2 text-xs font-semibold text-slate-600">
- <span className="font-mono">{apiKeyVisibleIdentifier(key)}</span>
- {key.scopes ? <span className="badge">Scope: {key.scopes}</span> : null}
- {apiKeyOwnerLabel(key) ? <span>Owner: {apiKeyOwnerLabel(key)}</span> : null}
- </div>
- <div className="mt-1 flex flex-wrap gap-2 text-xs text-slate-500">
- {key.created_at ? <span>Created: {formatDateTime(key.created_at)}</span> : null}
- {key.expires_at ? <span>Expires: {formatDateTime(key.expires_at)}</span> : <span>No expiry</span>}
- </div>
- </div>
- <button className="btn btn-danger" disabled={remove.isPending} onClick={() => remove.mutate(key.id)}>Delete</button>
- </div>
- ))}
- {(keys.data ?? []).length === 0 && <EmptyState text="No API keys yet." />}
- <DataPanel title="API Key Error" data={apiKeyError ?? remove.error ?? keys.error} />
- </section>
- )}
- {activeTab === "Audit" && (
- <section className="grid gap-4">
- {user?.role === "team_lead" ? (
- <>
- {audit.error ? <DataPanel title="Security Audit Error" data={audit.error} /> : audit.data ? <DataPanel title="Security Audit" data={audit.data} /> : <EmptyState text="No security audit data loaded yet." />}
- {users.error ? <DataPanel title="Users Error" data={users.error} /> : users.data ? <DataPanel title="Users" data={users.data} /> : <EmptyState text="No user records loaded yet." />}
- </>
- ) : (
- <EmptyState text="Audit data is available to team leads." />
- )}
- </section>
- )}
- {generatedApiKey && (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/60 p-4">
- <section
- aria-labelledby="api-key-dialog-title"
- aria-modal="true"
- className="panel w-full max-w-2xl p-5 shadow-2xl"
- role="dialog"
- >
- <div className="mb-4 flex flex-wrap items-start justify-between gap-3">
- <div>
- <h2 className="text-lg font-bold text-slate-950" id="api-key-dialog-title">Save your key</h2>
- <p className="mt-1 text-sm text-slate-600">Copy this secret key now and store it somewhere safe.</p>
- </div>
- {generatedApiKey.prefix ? <span className="badge font-mono">{generatedApiKey.prefix}</span> : null}
- </div>
- <p className="mb-4 rounded-md border border-amber-200 bg-amber-50 p-3 text-sm font-semibold text-amber-900">
- This secret key is shown only once. After you close this dialog, ARES will not show the full key again.
- </p>
- <label className="block text-sm font-semibold text-slate-800">
- Secret key
- <div className="mt-2 grid gap-2 sm:grid-cols-[1fr_auto]">
- <input
- aria-label="Generated API key secret"
- className="field font-mono text-sm"
- onFocus={(event) => event.currentTarget.select()}
- readOnly
- ref={secretKeyInputRef}
- value={generatedApiKey.key}
- />
- <button className="btn" onClick={() => void copyGeneratedKey()} type="button">
- {copyStatus === "copied" ? <CheckCircle2 size={16} /> : <Copy size={16} />}
- {copyStatus === "copied" ? "Copied" : "Copy"}
- </button>
- </div>
- </label>
- {copyStatus === "manual" && (
- <p className="mt-2 rounded-md border border-slate-200 bg-slate-50 p-3 text-sm text-slate-700">
- Clipboard access was blocked. The key field is selected; press Ctrl+C to copy it manually.
- </p>
- )}
- {generatedApiKey.note ? <p className="mt-3 text-sm text-slate-600">{generatedApiKey.note}</p> : null}
- <div className="mt-5 flex justify-end">
- <button className="btn btn-primary" onClick={closeGeneratedKeyModal} type="button">Done</button>
- </div>
- </section>
- </div>
- )}
- </Page>
- );
-}
-
-function EdrPage() {
- const stats = useQuery({ queryKey: ["edr-stats"], queryFn: api.edrStats });
- const [techniqueId, setTechniqueId] = useSessionState("ares.dashboard.edr.techniqueId", "");
- const [vendor, setVendor] = useSessionState("ares.dashboard.edr.vendor", "");
- const [version, setVersion] = useSessionState("ares.dashboard.edr.version", "");
- const [success, setSuccess] = useSessionState("ares.dashboard.edr.success", false);
- const [notes, setNotes] = useSessionState("ares.dashboard.edr.notes", "");
- const [lastReportResult, setLastReportResult] = useSessionState<PersistedResult | null>("ares.dashboard.edr.lastReport", null);
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.edr.tab", "Knowledge Base");
- const edrReportKey = `${techniqueId.trim()}:${vendor.trim()}:${version.trim()}:${success}:${notes.trim()}`;
- const report = useMutation({
- mutationFn: () =>
- api.reportBypass({
- technique_id: techniqueId.trim(),
- edr_vendor: vendor.trim(),
- edr_version: version.trim(),
- success,
- notes: notes.trim()
- }),
- onSuccess: (payload) => setLastReportResult({ key: edrReportKey, payload }),
- onError: (error) => setLastReportResult({ key: edrReportKey, payload: serializeError(error), isError: true })
- });
- const persistedReportResult = lastReportResult?.key === edrReportKey ? lastReportResult : null;
- return (
- <Page
- title="EDR/OPSEC"
- actions={<span className={success ? "status-pill status-low" : "status-pill status-medium"}>{success ? "Successful" : "Blocked / detected"}</span>}
- tabs={["Knowledge Base", "Report Outcome"]}
- activeTab={activeTab}
- onTabChange={setActiveTab}
- >
- {activeTab === "Knowledge Base" && (
- <>
- <section className="panel p-4">
- <SectionHeader
- title="Bypass Knowledge Base"
- description="Track outcomes by technique and vendor."
- />
- <div className="mt-3 grid gap-3 md:grid-cols-3">
- <div className="telemetry-strip">
- <span>Technique</span>
- <strong>{String(stats.data?.technique_id ?? "all")}</strong>
- </div>
- <div className="telemetry-strip">
- <span>Vendor</span>
- <strong>{String(stats.data?.edr_vendor ?? "all")}</strong>
- </div>
- <div className="telemetry-strip">
- <span>Current rate</span>
- <strong>{formatRate(stats.data?.success_rate)}</strong>
- </div>
- </div>
- <p className="mt-3 text-sm text-slate-600">{String(stats.data?.message ?? "No historical sample loaded yet.")}</p>
- </section>
- <DataPanel title="Stats Details" data={stats.data} />
- <DataPanel title="Stats Error" data={stats.error} />
- </>
- )}
- {activeTab === "Report Outcome" && (
- <>
- <section className="panel p-4">
- <SectionHeader title="Report Outcome" />
- <form className="grid gap-3" onSubmit={(event) => {
- event.preventDefault();
- if (!event.currentTarget.reportValidity()) return;
- report.mutate();
- }}>
- <div className="grid gap-3 md:grid-cols-2">
- <label className="block text-sm font-semibold">
- Technique ID <span className="text-red-700">*</span>
- <input className="field mt-1" required placeholder="edr.bypass_adaptive / amsi-patch-reflection" value={techniqueId} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setTechniqueId(e.target.value); }} />
- </label>
- <label className="block text-sm font-semibold">
- EDR vendor <span className="text-red-700">*</span>
- <input className="field mt-1" required placeholder="crowdstrike, defender_atp, sentinelone" value={vendor} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setVendor(e.target.value); }} />
- </label>
- <label className="block text-sm font-semibold">
- EDR version
- <input className="field mt-1" placeholder="optional" value={version} onChange={(e) => setVersion(e.target.value)} />
- </label>
- <label className="block text-sm font-semibold">
- Outcome
- <select className="field mt-1" value={success ? "success" : "blocked"} onChange={(e) => setSuccess(e.target.value === "success")}>
- <option value="blocked">Blocked / detected</option>
- <option value="success">Successful</option>
- </select>
- </label>
- </div>
- <label className="block text-sm font-semibold">
- Notes
- <textarea className="field mt-1 min-h-24" placeholder="Signal observed, lab context, or detection notes" value={notes} onChange={(e) => setNotes(e.target.value)} />
- </label>
- <button className="btn btn-primary" disabled={report.isPending} type="submit">
- {report.isPending ? (
- <>
- <Loader2 className="spin" size={16} /> Saving...
- </>
- ) : (
- <>
- <ShieldAlert size={16} /> Report Outcome
- </>
- )}
- </button>
- </form>
- </section>
- <DataPanel
- title={(report.error ?? (persistedReportResult?.isError ? persistedReportResult.payload : undefined)) ? "Outcome Error" : "Outcome Result"}
- data={report.data ?? report.error ?? persistedReportResult?.payload}
- />
- </>
- )}
- </Page>
- );
-}
-
-function LivePage() {
- const {
- selectedCampaignId,
- setSelectedCampaignId,
- liveCampaignId,
- setLiveCampaignId,
- liveConnected,
- setLiveConnected,
- liveEvents,
- clearLiveEvents
- } = useDashboardUi();
- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
- const campaignId = liveCampaignId || selectedCampaignId;
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.live.tab", "Stream");
- const streamEvents = liveEvents.slice(0, 10);
-
- return (
- <Page
- title="Live Events"
- actions={<span className={liveConnected ? "status-pill status-low" : "status-pill"}>{liveConnected ? "Listening" : "Offline"}</span>}
- tabs={["Stream", "Buffer"]}
- activeTab={activeTab}
- onTabChange={setActiveTab}
- >
- {activeTab === "Stream" && (
- <>
- <div className="panel p-4">
- <SectionHeader
- title="Campaign Event Stream"
- action={<span className="badge">{liveEvents.length} buffered</span>}
- description="Watch selected campaign events."
- />
- <CampaignPicker
- campaigns={campaigns.data ?? []}
- value={campaignId}
- onChange={(id) => {
- setLiveCampaignId(id);
- setSelectedCampaignId(id);
- }}
- />
- <div className="mt-3 flex flex-wrap items-center gap-2">
- <button className="btn btn-primary" disabled={!campaignId || liveConnected} onClick={() => {
- if (!liveCampaignId && campaignId) {
- setLiveCampaignId(campaignId);
- }
- setLiveConnected(true);
- }}>
- <Radio size={16} /> {liveConnected ? "Connected" : "Connect"}
- </button>
- {liveConnected && (
- <button className="btn" onClick={() => setLiveConnected(false)}>
- Disconnect
- </button>
- )}
- <span className={liveConnected ? "badge badge-low" : "badge"}>{liveConnected ? "listening" : "offline"}</span>
- </div>
- </div>
- <section className="panel p-4">
- <SectionHeader title="Current Stream" action={<span className="badge">{streamEvents.length} newest</span>} />
- {streamEvents.length > 0 ? (
- <div className="grid gap-2">
- {streamEvents.map((event, index) => (
- <LiveEventCard event={event} index={index} key={index} />
- ))}
- </div>
- ) : (
- <EmptyState text={liveConnected ? "Connected. Waiting for events." : "Select a campaign and connect."} />
- )}
- </section>
- </>
- )}
- {activeTab === "Buffer" && (
- <section className="panel p-4">
- <SectionHeader
- title="Buffered Events"
- action={liveEvents.length > 0 ? <button className="btn" onClick={clearLiveEvents}>Clear Events</button> : <span className="badge">0 retained</span>}
- />
- {liveEvents.length > 0 ? (
- <div className="grid gap-2">
- {liveEvents.map((event, index) => (
- <LiveEventCard event={event} index={index} key={index} />
- ))}
- </div>
- ) : (
- <EmptyState text="No events retained in the buffer." />
- )}
- </section>
- )}
- </Page>
- );
-}
-
-function Page({
- title,
- actions,
- tabs,
- activeTab,
- onTabChange,
- children
-}: {
- title: string;
- actions?: ReactNode;
- tabs?: string[];
- activeTab?: string;
- onTabChange?: (tab: string) => void;
- children: ReactNode;
-}) {
- const [fallbackTab, setFallbackTab] = useState(tabs?.[0] ?? "");
- const meta = pageMeta[title] ?? {
- icon: LayoutDashboard,
- eyebrow: "ARES",
- description: "Security dashboard workspace."
- };
- const Icon = meta.icon;
- const selectedTab = activeTab ?? fallbackTab;
- const setTab = onTabChange ?? setFallbackTab;
-
- function handleTabKeyDown(event: KeyboardEvent<HTMLDivElement>) {
- if (!tabs || tabs.length === 0 || !["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) {
- return;
- }
- event.preventDefault();
- const currentIndex = Math.max(0, tabs.indexOf(selectedTab));
- if (event.key === "Home") {
- setTab(tabs[0]);
- return;
- }
- if (event.key === "End") {
- setTab(tabs[tabs.length - 1]);
- return;
- }
- const offset = event.key === "ArrowRight" ? 1 : -1;
- const nextIndex = (currentIndex + offset + tabs.length) % tabs.length;
- setTab(tabs[nextIndex]);
- }
-
- return (
- <div className="page">
- <section className="page-header">
- <div className="page-heading">
- <span className="page-icon">
- <Icon size={19} />
- </span>
- <div>
- <p className="page-eyebrow">{meta.eyebrow}</p>
- <h1>{title}</h1>
- <p>{meta.description}</p>
- </div>
- </div>
- {actions ? <div className="page-actions">{actions}</div> : null}
- </section>
- {tabs ? (
- <div className="page-tabs" aria-label={`${title} sections`} onKeyDown={handleTabKeyDown} role="tablist">
- {tabs.map((tab) => (
- <button
- aria-selected={tab === selectedTab}
- className={tab === selectedTab ? "active" : ""}
- key={tab}
- onClick={() => setTab(tab)}
- role="tab"
- tabIndex={tab === selectedTab ? 0 : -1}
- type="button"
- >
- {tab}
- </button>
- ))}
- </div>
- ) : null}
- <div className="page-content">{children}</div>
- </div>
- );
-}
-
-function SectionHeader({
- title,
- eyebrow,
- description,
- action
-}: {
- title: string;
- eyebrow?: string;
- description?: string;
- action?: ReactNode;
-}) {
- return (
- <div className="section-header">
- <div>
- {eyebrow ? <p className="section-eyebrow">{eyebrow}</p> : null}
- <h2>{title}</h2>
- {description ? <p>{description}</p> : null}
- </div>
- {action ? <div className="section-action">{action}</div> : null}
- </div>
- );
-}
-
-function MiniStat({ title, value, detail, icon }: { title: string; value: string; detail?: string; icon?: ReactNode }) {
- return (
- <div className="mini-stat">
- <div>
- <span>{title}</span>
- <strong>{value}</strong>
- {detail ? <small>{detail}</small> : null}
- </div>
- {icon ? <div className="mini-stat-icon">{icon}</div> : null}
- </div>
- );
-}
-
-function HighlightRow({
- label,
- value,
- detail,
- tone = "neutral"
-}: {
- label: string;
- value: string;
- detail: string;
- tone?: "low" | "medium" | "high" | "neutral";
-}) {
- return (
- <div className="highlight-row">
- <div>
- <strong>{label}</strong>
- <span>{detail}</span>
- </div>
- <span className={`highlight-value highlight-${tone}`}>{value}</span>
- </div>
- );
-}
-
-function SparklineBars({ values }: { values: MonthlyFindingStats["series"] }) {
- const max = Math.max(...values.map((value) => value.count), 1);
- const labelDays = new Set([1, 7, 14, 21, 28, values.length]);
- return (
- <>
- <div className="sparkline" aria-hidden="true">
- {values.map((value) => (
- <span
- key={value.date}
- title={`${formatMonthlyDate(value.date)} — ${value.count} ${value.count === 1 ? "security signal" : "security signals"}`}
- style={{ height: value.count > 0 ? `${Math.max(6, (value.count / max) * 100)}%` : "0%" }}
- />
- ))}
- </div>
- <div className="sparkline-axis" aria-hidden="true">
- {values.map((value) => {
- const day = Number(value.date.slice(-2));
- return <span key={value.date}>{labelDays.has(day) ? formatMonthlyDate(value.date) : null}</span>;
- })}
- </div>
- </>
- );
-}
-
-function formatMonthlyDate(date: string): string {
- const [year, month, day] = date.split("-").map(Number);
- return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", timeZone: "UTC" }).format(
- new Date(Date.UTC(year, month - 1, day))
- );
-}
-
-function metricNumber(map: TelemetryMetricMap | undefined, key: string): number {
- return metricNumberOrNull(map, key) ?? 0;
-}
-
-function metricNumberOrNull(map: TelemetryMetricMap | undefined, key: string): number | null {
- const value = map?.[key];
- if (typeof value === "number" && Number.isFinite(value)) return value;
- if (typeof value === "string" && value.trim()) {
- const parsed = Number(value);
- return Number.isFinite(parsed) ? parsed : null;
- }
- return null;
-}
-
-function formatMetric(value: number, suffix = ""): string {
- if (!Number.isFinite(value)) return `0${suffix}`;
- if (Number.isInteger(value)) return `${value}${suffix}`;
- return `${value.toFixed(1)}${suffix}`;
-}
-
-function formatRate(value: unknown): string {
- if (typeof value !== "number" || !Number.isFinite(value)) {
- return "not enough data";
- }
- const normalized = value <= 1 ? value * 100 : value;
- return `${Math.round(normalized)}%`;
-}
-
-function formatTimestamp(value: number | undefined): string {
- if (!value) return "No runtime sample yet";
- return new Date(value * 1000).toLocaleString();
-}
-
-function formatBytes(value: number): string {
- if (!Number.isFinite(value)) return "n/a";
- if (value < 1024) return `${value} B`;
- const units = ["KB", "MB", "GB", "TB"];
- let size = value / 1024;
- let unitIndex = 0;
- while (size >= 1024 && unitIndex < units.length - 1) {
- size /= 1024;
- unitIndex += 1;
- }
- return `${size >= 10 ? size.toFixed(0) : size.toFixed(1)} ${units[unitIndex]}`;
-}
-
-function formatReportDate(value: number): string {
- if (!Number.isFinite(value)) return "n/a";
- const timestamp = value > 10_000_000_000 ? value : value * 1000;
- return new Date(timestamp).toLocaleString();
-}
-
-function TelemetryPanel({ snapshot, loading, confirmedFindings }: { snapshot?: TelemetrySnapshot; loading: boolean; confirmedFindings: number }) {
- const total = metricNumber(snapshot?.modules, "total");
- const success = metricNumber(snapshot?.modules, "success");
- const failed = metricNumber(snapshot?.modules, "failed");
- const findings = confirmedFindings;
- const successRate = total > 0 ? Math.round((success / total) * 100) : null;
- const errorRate = total > 0 ? Math.min(100, Math.round(metricNumber(snapshot?.modules, "error_rate") * 100)) : null;
- const p95 = metricNumberOrNull(snapshot?.latency_ms, "p95");
- const queueDepth = metricNumber(snapshot?.queue, "depth");
- const activeWorkers = metricNumber(snapshot?.workers, "active");
- const unhealthyWorkers = metricNumber(snapshot?.workers, "unhealthy");
- const hostsDiscovered = metricNumber(snapshot?.hosts, "discovered");
- const hostsOwned = metricNumberOrNull(snapshot?.hosts, "owned");
- const tasksPerMin = metricNumberOrNull(snapshot?.throughput, "tasks_per_min");
- const workerTotal = activeWorkers + unhealthyWorkers;
- const workerCapacity = workerTotal > 0 ? Math.round((activeWorkers / workerTotal) * 100) : null;
- const hostsAvailable = snapshot?.hosts?.available === true;
- const hostOwnership = hostsAvailable && hostsDiscovered > 0 && hostsOwned !== null
- ? Math.round((hostsOwned / hostsDiscovered) * 100)
- : null;
- const throughputValue = tasksPerMin === null ? "n/a" : `${formatMetric(tasksPerMin)}/min`;
- const latencyDetail = p95 === null ? "no run timing data" : `${formatMetric(p95, " ms")} p95`;
-
- return (
- <section className="panel telemetry-panel">
- <SectionHeader
- title="Telemetry Report"
- description={loading ? "Waiting for metrics." : `Last sample: ${formatTimestamp(snapshot?.timestamp)}`}
- action={<span className={snapshot ? "badge badge-low" : "badge badge-medium"}>{snapshot ? "online" : "pending"}</span>}
- />
-
- <div className="telemetry-chart" aria-label="Runtime telemetry chart">
- <TelemetryBar label="Success rate" value={successRate} />
- <TelemetryBar label="Error rate" value={errorRate} tone="danger" />
- <TelemetryBar label="Worker capacity" value={workerCapacity} />
- <TelemetryBar label="Host ownership" value={hostOwnership} tone={hostsOwned !== null && hostsOwned > 0 ? "danger" : "ok"} />
- </div>
-
- <div className="mini-stat-grid mt-4">
- <MiniStat title="Module runs" value={formatMetric(total)} detail={`${success} success / ${failed} failed`} icon={<Database size={16} />} />
- <MiniStat title="Findings" value={formatMetric(findings)} icon={<ShieldAlert size={16} />} />
- <MiniStat title="Queue" value={formatMetric(queueDepth)} detail={`${activeWorkers} active workers`} icon={<Layers size={16} />} />
- <MiniStat title="Throughput" value={throughputValue} detail={latencyDetail} icon={<TrendingUp size={16} />} />
- </div>
-
- <div className="telemetry-footer">
- <span><Target size={14} /> Scope: {snapshot?.campaign_id ? `campaign ${snapshot.campaign_id}` : "global"}</span>
- <span>{hostsAvailable ? `${hostsDiscovered} discovered / ${hostsOwned ?? 0} owned hosts` : "Host ownership unavailable"}</span>
- <span>{workerTotal === 0 ? "no worker sample" : unhealthyWorkers === 0 ? "workers healthy" : `${unhealthyWorkers} unhealthy workers`}</span>
- </div>
-
- <details className="advanced-details">
- <summary>Details</summary>
- <pre className="json-box">{JSON.stringify(snapshot ?? {}, null, 2)}</pre>
- </details>
- </section>
- );
-}
-
-function TelemetryBar({ label, value, tone = "ok" }: { label: string; value: number | null; tone?: "ok" | "danger" }) {
- const clamped = value === null ? 0 : Math.max(0, Math.min(100, value));
- return (
- <div className="telemetry-bar" title={value === null ? "Not enough telemetry data" : undefined}>
- <span>{label}</span>
- <div className="telemetry-bar-track">
- <div className={tone === "danger" ? "telemetry-bar-fill danger" : "telemetry-bar-fill"} style={{ width: `${clamped}%` }} />
- </div>
- <strong>{value === null ? "n/a" : `${clamped}%`}</strong>
- </div>
- );
-}
-
-function DataPanel({ title, data }: { title: string; data: unknown }) {
- if (!data) {
- return null;
- }
- const isError = data instanceof Error || data instanceof ApiError;
- return (
- <section className="panel detail-panel">
- <SectionHeader
- title={title}
- eyebrow={isError ? "Needs attention" : undefined}
- action={isError ? <span className="badge badge-high">error</span> : <span className="badge">details</span>}
- />
- {isError ? (
- <p className="notice notice-danger">
- <AlertTriangle size={16} />
- {data instanceof ApiError ? String(data.detail) : data instanceof Error ? data.message : "The request failed."}
- </p>
- ) : null}
- <details className="advanced-details">
- <summary>Details</summary>
- <pre className="json-box">{JSON.stringify(serializeError(data), null, 2)}</pre>
- </details>
- </section>
- );
-}
-
-function ModuleRunSummary({ result, error }: { result?: Record<string, unknown>; error?: unknown }) {
- if (!result && !error) {
- return null;
- }
- if (error) {
- return (
- <section className="inline-summary mt-4">
- <SectionHeader title="Execution Summary" action={<span className="badge badge-high">failed</span>} />
- <p className="notice notice-danger">
- <AlertTriangle size={16} />
- {error instanceof ApiError ? String(error.detail) : error instanceof Error ? error.message : "Module run failed."}
- </p>
- </section>
- );
- }
-
- const findings = Array.isArray(result?.findings) ? result.findings as Finding[] : [];
- const validationCount = Array.isArray(result?.validation_results) ? result.validation_results.length : 0;
- const duration = typeof result?.duration_ms === "number" ? formatMetric(result.duration_ms, " ms") : "n/a";
- const status = String(result?.status ?? "unknown");
- const moduleId = String(result?.module_id ?? "module");
- const runError = typeof result?.error === "string" ? result.error : "";
- const outcome = String(result?.outcome ?? "");
- const outcomeMessage = String(result?.outcome_message ?? "");
- const displayOutcome = outcome || status;
- const dryRun = result?.dry_run === true || status.startsWith("dry_run_");
- const warnings = Array.isArray(result?.warnings) ? result.warnings.map(String) : [];
- const nextSteps = Array.isArray(result?.operator_next_steps) ? result.operator_next_steps.map(String) : [];
- const hasOutcomeError = ["operator_error", "dependency_error", "network_error", "unsupported", "module_error", "failed", "timeout"].includes(displayOutcome);
- const emptyText = dryRun
- ? "No live execution was performed."
- : outcome === "completed_no_findings"
- ? "No confirmed findings. The module completed without observing an exploitable condition."
- : runError
- ? "No findings recorded because execution failed."
- : "No findings returned.";
-
- return (
- <section className="inline-summary mt-4">
- <SectionHeader
- title="Execution Summary"
- action={(
- <div className="flex flex-wrap gap-2">
- <span className="badge">{moduleId}</span>
- <span className={hasOutcomeError ? "badge badge-high" : displayOutcome === "confirmed_findings" || displayOutcome === "completed_no_findings" || displayOutcome === "dry_run_ok" || displayOutcome === "done" ? "badge badge-low" : "badge badge-medium"}>{displayOutcome}</span>
- <span className="badge">{duration}</span>
- </div>
- )}
- />
- {(outcomeMessage || runError) && (
- <p className={`notice mb-3 ${hasOutcomeError || runError ? "notice-danger" : ""}`}>
- {hasOutcomeError || runError ? <AlertTriangle size={16} /> : null}
- {outcomeMessage || runError}
- </p>
- )}
- {warnings.length > 0 && (
- <div className="notice mb-3">
- <strong>{dryRun ? "Dry-run notes" : "Notes"}</strong>
- <ul className="mt-1 list-disc pl-5">{warnings.map((warning) => <li key={warning}>{warning}</li>)}</ul>
- </div>
- )}
- {nextSteps.length > 0 && (
- <div className="notice mb-3">
- <strong>Next steps</strong>
- <ul className="mt-1 list-disc pl-5">{nextSteps.map((step) => <li key={step}>{step}</li>)}</ul>
- </div>
- )}
- <div className="mini-stat-grid mb-3">
- <MiniStat title="Findings" value={String(findings.length)} detail="returned observations" />
- <MiniStat title="Validation" value={String(validationCount)} detail="post-run checks" />
- <MiniStat title="Duration" value={duration} detail="server execution" />
- </div>
- {findings.length > 0 ? (
- <div className="compact-list">
- {findings.map((finding, index) => (
- <div className="compact-row" key={finding.id ?? index}>
- <div className="flex flex-wrap items-start justify-between gap-2">
- <div>
- <div className="font-bold">{finding.title ?? `Finding ${index + 1}`}</div>
- <div className="mt-1 text-sm text-slate-600">{String(finding.description ?? "")}</div>
- </div>
- <span className={opsecBadge(finding.severity)}>{finding.severity ?? "info"}</span>
- </div>
- <div className="mt-2 flex flex-wrap gap-2">
- {finding.host && <span className="badge">Host: {finding.host}</span>}
- {finding.mitre_technique && <span className="badge">{finding.mitre_technique}</span>}
- {typeof finding.confidence === "number" && <span className="badge">Confidence: {formatRate(finding.confidence)}</span>}
- </div>
- {finding.remediation ? (
- <p className="mt-2 text-sm text-slate-700">
- <strong>Remediation:</strong> {String(finding.remediation)}
- </p>
- ) : null}
- </div>
- ))}
- </div>
- ) : (
- <EmptyState text={emptyText} />
- )}
- </section>
- );
-}
-
-function TemplatePlanSummary({ plan }: { plan?: TemplatePlanResponse }) {
- const stages = plan?.plan?.stages ?? [];
- if (!plan || stages.length === 0) {
- return null;
- }
- const moduleCount = stages.reduce((total, stage) => total + (stage.modules?.length ?? 0), 0);
- return (
- <section className="inline-summary mt-4">
- <SectionHeader
- title={plan.template ?? "Generated Plan"}
- description={plan.description}
- action={(
- <div className="flex flex-wrap gap-2">
- <span className="badge">{stages.length} stages</span>
- <span className="badge">{moduleCount} modules</span>
- </div>
- )}
- />
- <div className="compact-list">
- {stages.map((stage, index) => (
- <div className="compact-row" key={`${stage.name ?? "stage"}-${index}`}>
- <div className="flex flex-wrap items-center justify-between gap-2">
- <span className="font-bold">{index + 1}. {stage.name ?? "stage"}</span>
- <span className="text-xs font-semibold text-slate-500">{stage.modules?.length ?? 0} modules</span>
- </div>
- <div className="mt-2 flex flex-wrap gap-1">
- {(stage.modules ?? []).map((moduleId) => <span className="badge" key={moduleId}>{moduleId}</span>)}
- </div>
- </div>
- ))}
- </div>
- <p className="mt-3 text-sm text-slate-500">Ready for campaign dry-run structure.</p>
- </section>
- );
-}
-
-function CampaignScopeSummary({ campaign, loading }: { campaign?: Campaign; loading?: boolean }) {
- if (loading) {
- return (
- <div className="detail-summary mt-3">
- <div className="loading-row">
- <Loader2 className="spin" size={16} /> Loading campaign...
- </div>
- </div>
- );
- }
- if (!campaign) {
- return <EmptyState text="Select a campaign to review scope and findings." />;
- }
- const targets = campaignTargets(campaign);
- const scope = campaignScopeEntries(campaign);
- return (
- <div className="detail-summary mt-3">
- <div className="mb-3 flex flex-wrap items-start justify-between gap-3">
- <div>
- <h3 className="text-base font-bold">{campaign.name}</h3>
- <p className="text-sm text-slate-600">{campaign.client ?? "No client"} &middot; {campaign.status ?? "created"}</p>
- </div>
- <span className="badge">{campaign.operator ?? "operator"}</span>
- </div>
- <div className="mini-stat-grid">
- <MiniStat title="Targets" value={String(targets.length)} detail={targets.slice(0, 3).join(", ") || "none declared"} />
- <MiniStat title="Scope CIDRs" value={String(scope.length)} detail={scope.slice(0, 3).join(", ") || "none declared"} />
- <MiniStat title="Noise Profile" value={String(campaign.noise_profile ?? "stealth")} detail="OPSEC guardrail" />
- <MiniStat title="Campaign ID" value={campaign.id.slice(0, 8)} detail="API/report key" />
- </div>
- </div>
- );
-}
-
-function CampaignPicker({
- campaigns,
- value,
- onChange
-}: {
- campaigns: Campaign[];
- value: string;
- onChange: (id: string) => void;
-}) {
- return (
- <select className="field" value={value} onChange={(event) => onChange(event.target.value)}>
- <option value="">Select campaign</option>
- {campaigns.map((campaign) => (
- <option key={campaign.id} value={campaign.id}>
- {campaign.name || campaign.id}
- </option>
- ))}
- </select>
- );
-}
-
-function CampaignTable({ campaigns }: { campaigns: Campaign[] }) {
- return (
- <section className="panel table-panel">
- <SectionHeader
- title="Campaign Activity"
- action={<span className="badge">{campaigns.length} records</span>}
- />
- {campaigns.length > 0 ? (
- <div className="table-scroll">
- <table className="table">
- <thead><tr><th>#</th><th>Name</th><th>Client</th><th>Status</th><th>Noise</th><th>Operator</th></tr></thead>
- <tbody>
- {campaigns.map((campaign, index) => (
- <tr key={campaign.id}>
- <td className="muted-cell">#{String(index + 1).padStart(2, "0")}</td>
- <td>
- <div className="font-medium text-slate-950">{campaign.name}</div>
- <div className="mt-1 flex items-center gap-1 text-xs text-slate-500"><Eye size={13} /> {campaign.id.slice(0, 12)}</div>
- </td>
- <td>{campaign.client || "Internal"}</td>
- <td><span className={statusBadge(campaign.status)}>{campaign.status ?? "created"}</span></td>
- <td><span className={opsecBadge(campaign.noise_profile)}>{campaign.noise_profile ?? "stealth"}</span></td>
- <td>{campaign.operator || "operator"}</td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- ) : (
- <EmptyState text="No campaigns yet. Create one from the Campaigns page to unlock modules, reports, and graph views." />
- )}
- </section>
- );
-}
-
-function FindingsTable({ findings }: { findings: any[] }) {
- return (
- <section className="panel table-panel">
- <SectionHeader
- title="Findings"
- action={<span className="badge">{findings.length} records</span>}
- />
- {findings.length > 0 ? (
- <div className="table-scroll">
- <table className="table">
- <thead><tr><th>Severity</th><th>Title</th><th>Module</th><th>MITRE</th><th>Host</th></tr></thead>
- <tbody>
- {findings.map((finding, index) => (
- <tr key={finding.id ?? index}>
- <td><span className={opsecBadge(finding.severity)}>{finding.severity ?? "info"}</span></td>
- <td className="font-medium text-slate-950">{finding.title ?? `Finding ${index + 1}`}</td>
- <td>{finding.module_id ?? "n/a"}</td>
- <td>{finding.mitre_technique ?? "n/a"}</td>
- <td>{finding.host ?? "n/a"}</td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- ) : (
- <EmptyState text="No findings recorded for this campaign." />
- )}
- </section>
- );
-}
-
-function LiveEventCard({ event, index }: { event: unknown; index: number }) {
- const record = event && typeof event === "object" && !Array.isArray(event) ? event as Record<string, unknown> : null;
- const type = String(record?.type ?? record?.event ?? record?.name ?? `event.${index + 1}`);
- const message = String(record?.message ?? record?.status ?? record?.detail ?? "Campaign event received.");
- const campaign = typeof record?.campaign_id === "string" ? record.campaign_id : "";
- const moduleId = typeof record?.module_id === "string" ? record.module_id : "";
- const created = typeof record?.timestamp === "number"
- ? formatTimestamp(record.timestamp)
- : typeof record?.created_at === "string"
- ? formatDateTime(record.created_at)
- : "";
-
- return (
- <article className="event-card">
- <div className="event-marker" aria-hidden="true" />
- <div className="min-w-0">
- <div className="flex flex-wrap items-center gap-2">
- <strong>{type}</strong>
- {campaign ? <span className="badge">Campaign {campaign.slice(0, 8)}</span> : null}
- {moduleId ? <span className="badge">{moduleId}</span> : null}
- </div>
- <p>{message}</p>
- {created ? <small>{created}</small> : null}
- <details className="advanced-details compact">
- <summary>Details</summary>
- <pre className="json-box">{JSON.stringify(serializeError(event), null, 2)}</pre>
- </details>
- </div>
- </article>
- );
-}
-
-function ParamForm({
- schema,
- values,
- onChange,
- requiredOverrides
-}: {
- schema: ModuleMeta["param_schema"];
- values: Record<string, unknown>;
- onChange: (values: Record<string, unknown>) => void;
- requiredOverrides?: Record<string, boolean>;
-}) {
- const entries = Object.entries(schema ?? {});
- if (entries.length === 0) {
- return <EmptyState text="No parameters" />;
- }
- return (
- <div className="grid gap-3">
- {entries.map(([name, field]) => {
- const required = requiredOverrides?.[name] ?? field.required;
- const inputField = required === field.required ? field : { ...field, required };
- const description = fieldDescription(name, field);
- return (
- <label className="block text-sm font-semibold" key={name}>
- <span className="flex items-center gap-2">
- <span>
- {name}
- {required && <span className="text-red-700"> *</span>}
- </span>
- {!required && <span className="badge">optional</span>}
- </span>
- <ParamInput
- name={name}
- field={inputField}
- value={values[name]}
- onChange={(value) => {
- const next = { ...values };
- if (!required && isEmptyParamValue(value)) {
- delete next[name];
- } else {
- next[name] = value;
- }
- onChange(next);
- }}
- />
- {description && <span className="mt-1 block text-xs text-slate-600">{description}</span>}
- {fieldDefaultHint(field) && (
- <span className="mt-1 block text-xs font-medium text-slate-500">{fieldDefaultHint(field)}</span>
- )}
- </label>
- );
- })}
- </div>
- );
-}
-
-function ParamInput({
- name,
- field,
- value,
- onChange
-}: {
- name: string;
- field: ParamField;
- value: unknown;
- onChange: (value: unknown) => void;
-}) {
- if (field.type === "boolean") {
- return (
- <input
- className="ml-2"
- type="checkbox"
- checked={Boolean(value)}
- required={field.required}
- onChange={(event) => onChange(event.target.checked)}
- />
- );
- }
- if (field.type === "array") {
- return (
- <textarea
- className="field mt-1 min-h-20"
- value={Array.isArray(value) ? value.join(", ") : String(value ?? "")}
- placeholder={paramPlaceholder(name, field)}
- required={field.required}
- onInvalid={setRequiredMessage}
- onChange={(event) => {
- clearValidationMessage(event);
- onChange(parseArrayParam(event.target.value, field));
- }}
- />
- );
- }
- const type = field.secret ? "password" : field.type === "integer" || field.type === "number" ? "number" : "text";
- return (
- <input
- className="field mt-1"
- type={type}
- value={String(value ?? "")}
- min={field.min}
- max={field.max}
- placeholder={paramPlaceholder(name, field)}
- required={field.required}
- onInvalid={setRequiredMessage}
- onChange={(event) => {
- clearValidationMessage(event);
- if (type === "number") {
- onChange(event.target.value === "" ? undefined : Number(event.target.value));
- return;
- }
- onChange(event.target.value === "" ? undefined : event.target.value);
- }}
- />
- );
-}
-
-function fieldDefaultHint(field: ParamField): string {
- if (field.secret || field.default === undefined) {
- return "";
- }
- const value = formatDefaultValue(field.default);
- return value ? `Default: ${value}` : "";
-}
-
-function paramPlaceholder(name: string, field: ParamField): string {
- if (!field.secret) {
- const value = formatDefaultValue(field.default);
- if (value) {
- return value;
- }
- }
- const lower = name.toLowerCase();
- if (lower === "target_user" && field.description === "Required target user or SPN; run ad.enum_spn first") {
- return "svc-sql or MSSQLSvc/sql01.lab.local:1433";
- }
- if (lower.includes("target")) {
- return "127.0.0.1";
- }
- if (lower.includes("port")) {
- return "80, 443, 8080, 8443, 8888";
- }
- if (lower.includes("domain")) {
- return "corp.local";
- }
- return field.required ? "" : "Leave blank to use the module default";
-}
-
-function fieldDescription(name: string, field: ParamField): string | undefined {
- if (name === "target_user" && field.description === "Required target user or SPN; run ad.enum_spn first") {
- return "Required target user or SPN; run ad.enum_spn first.";
- }
- return field.description;
-}
-
-function formatDefaultValue(value: unknown): string {
- if (value === undefined || value === null || value === "") {
- return "";
- }
- if (Array.isArray(value)) {
- return value.join(", ");
- }
- if (typeof value === "boolean") {
- return value ? "true" : "false";
- }
- if (typeof value === "object") {
- return JSON.stringify(value);
- }
- return String(value);
-}
-
-function ScreenMessage({ title, body }: { title: string; body: string }) {
- return (
- <div className="grid min-h-screen place-items-center bg-slate-100 p-4">
- <div className="panel p-5 text-center">
- <h1 className="text-xl font-bold">{title}</h1>
- <p className="mt-1 text-sm text-slate-600">{body}</p>
- </div>
- </div>
- );
-}
-
-function EmptyState({ text }: { text: string }) {
- return <div className="empty-state">{text}</div>;
-}
-
-function strategyBackendHint(backend: string): string {
- if (backend === "openai") {
- return "OpenAI planning requires OPENAI_API_KEY in the ARES server environment. Security-page API keys do not count as LLM provider keys.";
- }
- if (backend === "local") {
- return "Local planning uses Ollama from the ARES server host, usually http://localhost:11434. No cloud LLM key is required.";
- }
- return "Claude planning requires ANTHROPIC_API_KEY in the ARES server environment. Security-page API keys only authenticate callers to ARES.";
-}
-
-function moduleRunHint(
- campaignId: string,
- module: ModuleMeta | undefined,
- campaign: Campaign | undefined,
- sensitive: boolean,
- confirmed: boolean,
- dryRun: boolean
-): string {
- if (!campaignId) {
- return "Select a campaign before running a module.";
- }
- if (!module) {
- return "Select a module from the catalog.";
- }
- if (!campaign) {
- return "Campaign details are still loading.";
- }
- if (sensitive && !confirmed) {
- return "Confirm authorization before running high-noise or sensitive modules.";
- }
- if (!dryRun && "target" in (module.param_schema ?? {}) && campaignScopeEntries(campaign).length === 0) {
- return "Live target modules require campaign scope CIDRs. Add a scope such as 127.0.0.1/32 before running.";
- }
- return "";
-}
-
-function splitLines(value: string): string[] {
- return value
- .split(/\r?\n|,/)
- .map((item) => item.trim())
- .filter(Boolean);
-}
-
-function findInvalidScopeEntries(value: string): string[] {
- return splitLines(value).filter((entry) => !looksLikeScopeEntry(entry));
-}
-
-function looksLikeScopeEntry(entry: string): boolean {
- if (entry.includes(":")) {
- return true;
- }
- const [address, prefix] = entry.split("/");
- if (!isIpv4Address(address)) {
- return false;
- }
- if (prefix === undefined) {
- return true;
- }
- if (!/^\d{1,2}$/.test(prefix)) {
- return false;
- }
- const value = Number(prefix);
- return value >= 0 && value <= 32;
-}
-
-function parseArrayParam(value: string, field: ParamField): unknown[] | undefined {
- const entries = splitLines(value);
- if (entries.length === 0) {
- return undefined;
- }
- const itemType = field.items?.type ?? "string";
- if (itemType === "integer" || itemType === "number") {
- const numericEntries = entries.map((entry) => Number(entry));
- return numericEntries.every((entry) => Number.isFinite(entry)) ? numericEntries : entries;
- }
- return entries;
-}
-
-function isEmptyParamValue(value: unknown): boolean {
- return value === undefined || value === "" || (Array.isArray(value) && value.length === 0);
-}
-
-function moduleScopeWarning(
- module: ModuleMeta | undefined,
- campaign: Campaign | undefined,
- values: Record<string, unknown>,
- dryRun: boolean
-): string {
- if (!module || !campaign || dryRun || !("target" in (module.param_schema ?? {}))) {
- return "";
- }
- const target = typeof values.target === "string" ? values.target.trim() : "";
- if (!target) {
- return "";
- }
- const scope = campaignScopeEntries(campaign);
- if (scope.length === 0) {
- return "Selected campaign has no scope CIDRs. Add a scoped campaign such as 127.0.0.1/32 before running target modules.";
- }
- if (isIpv4Address(target) && scope.every(looksLikeScopeEntry) && !scope.some((entry) => ipv4InScope(target, entry))) {
- return `Target ${target} is outside the selected campaign scope (${scope.join(", ")}).`;
- }
- return "";
-}
-
-function campaignScopeEntries(campaign: Campaign): string[] {
- if (Array.isArray(campaign.scope_cidrs)) {
- return campaign.scope_cidrs.filter((entry): entry is string => typeof entry === "string" && entry.trim() !== "");
- }
- const rawScope = campaign.scope;
- if (Array.isArray(rawScope)) {
- return rawScope
- .map((entry) => {
- if (typeof entry === "string") {
- return entry;
- }
- if (entry && typeof entry === "object" && "cidr" in entry && typeof entry.cidr === "string") {
- return entry.cidr;
- }
- return "";
- })
- .filter(Boolean);
- }
- if (typeof campaign.scope_json === "string" && campaign.scope_json.trim()) {
- try {
- const parsed = JSON.parse(campaign.scope_json) as unknown;
- if (Array.isArray(parsed)) {
- return parsed
- .map((entry) => {
- if (typeof entry === "string") {
- return entry;
- }
- if (entry && typeof entry === "object" && "cidr" in entry && typeof entry.cidr === "string") {
- return entry.cidr;
- }
- return "";
- })
- .filter(Boolean);
- }
- } catch {
- return [];
- }
- }
- return [];
-}
-
-function campaignTargets(campaign: Campaign): string[] {
- if (Array.isArray(campaign.targets)) {
- return campaign.targets.filter((entry): entry is string => typeof entry === "string" && entry.trim() !== "");
- }
- if (typeof campaign.targets_json === "string" && campaign.targets_json.trim()) {
- try {
- const parsed = JSON.parse(campaign.targets_json) as unknown;
- if (Array.isArray(parsed)) {
- return parsed.filter((entry): entry is string => typeof entry === "string" && entry.trim() !== "");
- }
- } catch {
- return [];
- }
- }
- return [];
-}
-
-function ipv4InScope(ip: string, cidr: string): boolean {
- const [network, prefixText = "32"] = cidr.split("/");
- if (!isIpv4Address(network) || !/^\d{1,2}$/.test(prefixText)) {
- return false;
- }
- const prefix = Number(prefixText);
- if (prefix < 0 || prefix > 32) {
- return false;
- }
- const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;
- return (ipv4ToNumber(ip) & mask) === (ipv4ToNumber(network) & mask);
-}
-
-function ipv4ToNumber(ip: string): number {
- return ip.split(".").reduce((acc, part) => ((acc << 8) + Number(part)) >>> 0, 0);
-}
-
-function isIpv4Address(value: string): boolean {
- const parts = value.split(".");
- return parts.length === 4 && parts.every((part) => {
- if (!/^\d{1,3}$/.test(part)) {
- return false;
- }
- const number = Number(part);
- return number >= 0 && number <= 255;
- });
-}
-
-function unique(values: string[]): string[] {
- return [...new Set(values.filter(Boolean))].sort();
-}
-
-function safeJson(value: string): Record<string, unknown> {
- try {
- const parsed = JSON.parse(value) as unknown;
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : {};
- } catch {
- return {};
- }
-}
-
-function isJsonObject(value: string): boolean {
- try {
- const parsed = JSON.parse(value) as unknown;
- return Boolean(parsed && typeof parsed === "object" && !Array.isArray(parsed));
- } catch {
- return false;
- }
-}
-
-function isSensitiveModule(module?: ModuleMeta): boolean {
- if (!module) {
- return false;
- }
- const text = `${module.id} ${module.category ?? ""} ${module.opsec_level ?? ""}`.toLowerCase();
- return (
- text.includes("high_noise") ||
- text.includes("credential") ||
- text.includes("persistence") ||
- text.includes("edr") ||
- text.includes("dcsync")
- );
-}
-
-function statusBadge(status?: string): string {
- const normalized = String(status ?? "").toLowerCase();
- if (["active", "running", "ready", "restored", "complete", "completed"].some((item) => normalized.includes(item))) {
- return "badge badge-low";
- }
- if (["failed", "deleted", "blocked", "error"].some((item) => normalized.includes(item))) {
- return "badge badge-high";
- }
- if (["paused", "pending", "draft", "created"].some((item) => normalized.includes(item))) {
- return "badge badge-medium";
- }
- return "badge";
-}
-
-function opsecBadge(level?: string): string {
- const normalized = String(level ?? "").toLowerCase();
- if (normalized.includes("high") || normalized.includes("critical")) {
- return "badge badge-high";
- }
- if (normalized.includes("medium") || normalized.includes("moderate")) {
- return "badge badge-medium";
- }
- return "badge badge-low";
-}
-
-function serializeError(value: unknown): unknown {
- if (value instanceof ApiError) {
- return { name: value.name, status: value.status, detail: value.detail };
- }
- if (value instanceof Error) {
- return { name: value.name, message: value.message };
- }
- return value;
-}
-
-function readableError(value: unknown, fallback: string): string {
- if (value instanceof ApiError) {
- if (typeof value.detail === "string") {
- return value.detail;
- }
- return value.message || fallback;
- }
- if (value instanceof Error) {
- return value.message || fallback;
- }
- if (typeof value === "string") {
- return value;
- }
- return fallback;
-}
-
-function pdfFailureHint(value: unknown): string {
- if (!value) return "";
- const serialized = serializeError(value);
- const text = typeof serialized === "string"
- ? serialized
- : JSON.stringify(serialized);
- const normalized = text.toLowerCase();
- if (normalized.includes("elevated windows") || normalized.includes("administrator powershell")) {
- return "PDF export is blocked from this elevated Windows session. Run PowerShell normally, or set ARES_PDF_BROWSER to a working non-Edge browser.";
- }
- if (
- normalized.includes("gtk")
- || normalized.includes("pango")
- || normalized.includes("libgobject")
- ) {
- return "WeasyPrint needs native GTK/Pango libraries on Windows. Use the browser fallback from normal PowerShell or install those native libraries.";
- }
- if (normalized.includes("no downloadable pdf") || normalized.includes("pdf smoke")) {
- return "PDF export did not create a valid artifact. Run ares doctor --pdf-smoke to verify the local PDF backend and browser fallback.";
- }
- return "";
-}
-
-export default App;
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index e1a932b..e92c3a3 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -1,281 +1,10 @@
-import type {
- ApiKeyCreateResponse,
- ApiKeyMeta,
- Campaign,
- ExecutionChain,
- Finding,
- ModuleMeta,
- MonthlyFindingStats,
- ReportItem,
- TemplateMeta,
- TokenResponse,
- UserProfile
-} from "./types";
-
-const REFRESH_TOKEN_KEY = "ares.refreshToken";
-
-let accessToken: string | null = null;
-
-export function setAccessToken(token: string | null): void {
- accessToken = token;
-}
-
-export function getAccessToken(): string | null {
- return accessToken;
-}
-
-export function setRefreshToken(token: string | null): void {
- if (token) {
- sessionStorage.setItem(REFRESH_TOKEN_KEY, token);
- return;
- }
- sessionStorage.removeItem(REFRESH_TOKEN_KEY);
-}
-
-export function getRefreshToken(): string | null {
- return sessionStorage.getItem(REFRESH_TOKEN_KEY);
-}
-
-export function clearTokens(): void {
- accessToken = null;
- setRefreshToken(null);
-}
-
-export class ApiError extends Error {
- readonly status: number;
- readonly detail: unknown;
-
- constructor(status: number, detail: unknown) {
- super(typeof detail === "string" ? detail : `Request failed with ${status}`);
- this.status = status;
- this.detail = detail;
- }
-}
-
-async function parseResponse(response: Response): Promise<unknown> {
- const text = await response.text();
- if (!text) {
- return null;
- }
- try {
- return JSON.parse(text);
- } catch {
- return text;
- }
-}
-
-export async function refreshAccessToken(): Promise<boolean> {
- const refreshToken = getRefreshToken();
- if (!refreshToken) {
- return false;
- }
-
- try {
- const response = await fetch("/auth/refresh", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ refresh_token: refreshToken })
- });
- if (!response.ok) {
- clearTokens();
- return false;
- }
- const token = (await response.json()) as TokenResponse;
- if (!token.access_token || !token.refresh_token) {
- clearTokens();
- return false;
- }
- setAccessToken(token.access_token);
- setRefreshToken(token.refresh_token);
- return true;
- } catch {
- clearTokens();
- return false;
- }
-}
-
-export async function apiRequest<T>(
- path: string,
- init: RequestInit = {},
- retry = true
-): Promise<T> {
- const headers = new Headers(init.headers);
- if (accessToken) {
- headers.set("Authorization", `Bearer ${accessToken}`);
- }
- const response = await fetch(path, { ...init, headers });
- if (response.status === 401 && retry && (await refreshAccessToken())) {
- return apiRequest<T>(path, init, false);
- }
- const body = await parseResponse(response);
- if (!response.ok) {
- throw new ApiError(response.status, (body as any)?.detail ?? body);
- }
- return body as T;
-}
-
-async function apiBlobRequest(
- path: string,
- init: RequestInit = {},
- retry = true
-): Promise<Blob> {
- const headers = new Headers(init.headers);
- if (accessToken) {
- headers.set("Authorization", `Bearer ${accessToken}`);
- }
- const response = await fetch(path, { ...init, headers });
- if (response.status === 401 && retry && (await refreshAccessToken())) {
- return apiBlobRequest(path, init, false);
- }
- if (!response.ok) {
- const body = await parseResponse(response);
- throw new ApiError(response.status, (body as any)?.detail ?? body);
- }
- return response.blob();
-}
-
-export async function login(username: string, password: string): Promise<TokenResponse> {
- const body = new URLSearchParams();
- body.set("username", username);
- body.set("password", password);
- const token = await apiRequest<TokenResponse>(
- "/auth/token",
- {
- method: "POST",
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
- body
- },
- false
- );
- setAccessToken(token.access_token);
- setRefreshToken(token.refresh_token);
- return token;
-}
-
-export async function logout(): Promise<void> {
- try {
- await apiRequest<{ status: string }>("/auth/logout", { method: "POST" }, false);
- } finally {
- clearTokens();
- }
-}
-
-export function campaignEventsPath(campaignId: string, token: string): string {
- return `/ws/campaigns/${encodeURIComponent(campaignId)}/events?token=${encodeURIComponent(token)}`;
-}
-
-export function buildModuleRunPayload(
- campaignId: string,
- params: Record<string, unknown>,
- dryRun = true
-): { campaign_id: string; params: Record<string, unknown>; dry_run: boolean } {
- return { campaign_id: campaignId, params, dry_run: dryRun };
-}
-
-export const api = {
- me: () => apiRequest<UserProfile>("/auth/me"),
- health: () => apiRequest<Record<string, unknown>>("/health"),
- telemetry: () => apiRequest<Record<string, unknown>>("/telemetry"),
- monthlyStats: () => apiRequest<MonthlyFindingStats>("/stats/monthly"),
- campaigns: () => apiRequest<Campaign[]>("/campaigns"),
- createCampaign: (body: { name: string; client: string; targets: string[]; scope_cidrs: string[]; noise_profile: string }) =>
- apiRequest<Campaign>("/campaigns", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body)
- }),
- campaign: (id: string) => apiRequest<Campaign>(`/campaigns/${encodeURIComponent(id)}`),
- deleteCampaign: (id: string) =>
- apiRequest<Record<string, string>>(`/campaigns/${encodeURIComponent(id)}`, { method: "DELETE" }),
- findings: (id: string) => apiRequest<Finding[]>(`/campaigns/${encodeURIComponent(id)}/findings`),
- cvss: (id: string) => apiRequest<Record<string, unknown>>(`/campaigns/${encodeURIComponent(id)}/cvss`),
- restoreVault: (id: string) =>
- apiRequest<Record<string, unknown>>(`/campaigns/${encodeURIComponent(id)}/restore-vault`, { method: "POST" }),
- runCampaign: (id: string, body: Record<string, unknown>) =>
- apiRequest<Record<string, unknown>>(`/campaigns/${encodeURIComponent(id)}/run`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body)
- }),
- diffCampaign: (id: string, otherId: string) =>
- apiRequest<Record<string, unknown>>(
- `/campaigns/${encodeURIComponent(id)}/diff/${encodeURIComponent(otherId)}`
- ),
- modules: () => apiRequest<ModuleMeta[]>("/modules"),
- executionChains: () => apiRequest<ExecutionChain[]>("/modules/execution-chains"),
- runModule: (moduleId: string, payload: ReturnType<typeof buildModuleRunPayload>) =>
- apiRequest<Record<string, unknown>>(`/modules/${encodeURIComponent(moduleId)}/run`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(payload)
- }),
- generateReport: (campaignId: string, format: string) =>
- apiRequest<Record<string, string>>(
- `/reports/${encodeURIComponent(campaignId)}?fmt=${encodeURIComponent(format)}`,
- { method: "POST" }
- ),
- reports: (campaignId: string) =>
- apiRequest<{ campaign_id: string; reports: ReportItem[] }>(`/reports/${encodeURIComponent(campaignId)}`),
- reportDownloadUrl: (campaignId: string, filename: string) =>
- `/reports/${encodeURIComponent(campaignId)}/files/${encodeURIComponent(filename)}`,
- downloadReport: (campaignId: string, filename: string) =>
- apiBlobRequest(`/reports/${encodeURIComponent(campaignId)}/files/${encodeURIComponent(filename)}`),
- deleteReport: (campaignId: string, filename: string) =>
- apiRequest<Record<string, string>>(
- `/reports/${encodeURIComponent(campaignId)}/files/${encodeURIComponent(filename)}`,
- { method: "DELETE" }
- ),
- clearReports: (campaignId: string) =>
- apiRequest<{ status: string; campaign_id: string; deleted: number }>(
- `/reports/${encodeURIComponent(campaignId)}`,
- { method: "DELETE" }
- ),
- graph: (campaignId: string) => apiRequest<Record<string, any>>(`/graph/${encodeURIComponent(campaignId)}`),
- attackPaths: (campaignId: string) =>
- apiRequest<Record<string, any>>(`/graph/${encodeURIComponent(campaignId)}/attack-paths`),
- ingestBloodhound: (campaignId: string, jsonPath: string) =>
- apiRequest<Record<string, unknown>>(`/graph/${encodeURIComponent(campaignId)}/bloodhound`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ json_path: jsonPath })
- }),
- templates: () => apiRequest<TemplateMeta[]>("/templates"),
- templatePlan: (name: string, globalParams: Record<string, unknown>) =>
- apiRequest<Record<string, unknown>>(`/templates/${encodeURIComponent(name)}/plan`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ global_params: globalParams })
- }),
- activeStrategy: () => apiRequest<Record<string, unknown>>("/strategy/active"),
- engageStrategy: (body: Record<string, unknown>) =>
- apiRequest<Record<string, unknown>>("/strategy/engage", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body)
- }),
- changePassword: (body: { current_password: string; new_password: string }) =>
- apiRequest<Record<string, string>>("/auth/change-password", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body)
- }),
- apiKeys: () => apiRequest<ApiKeyMeta[]>("/auth/api-keys"),
- createApiKey: (body: { name: string; scopes: string; expires_days?: number }) =>
- apiRequest<ApiKeyCreateResponse>("/auth/api-keys", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body)
- }),
- deleteApiKey: (id: string) => apiRequest<Record<string, string>>(`/auth/api-keys/${encodeURIComponent(id)}`, {
- method: "DELETE"
- }),
- securityAudit: () => apiRequest<Record<string, unknown>>("/security/audit"),
- users: () => apiRequest<Record<string, unknown>[]>("/security/users"),
- edrStats: () => apiRequest<Record<string, unknown>>("/edr/bypass/stats"),
- reportBypass: (body: Record<string, unknown>) =>
- apiRequest<Record<string, unknown>>("/edr/bypass/report", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body)
- })
-};
+// Compatibility facade: existing feature imports continue to use this stable public API.
+export { apiBlobRequest, apiRequest, ApiError, refreshAccessToken } from "./http";
+export { api, buildModuleRunPayload, campaignEventsPath, login, logout } from "./endpoints";
+export {
+ clearTokens,
+ getAccessToken,
+ getRefreshToken,
+ setAccessToken,
+ setRefreshToken
+} from "./session";
diff --git a/frontend/src/api/endpoints.ts b/frontend/src/api/endpoints.ts
new file mode 100644
index 0000000..50020a6
--- /dev/null
+++ b/frontend/src/api/endpoints.ts
@@ -0,0 +1,163 @@
+import type {
+ ApiKeyCreateResponse,
+ ApiKeyMeta,
+ AttackPathsResponse,
+ Campaign,
+ CampaignGraph,
+ ExecutionChain,
+ Finding,
+ ModuleMeta,
+ MonthlyFindingStats,
+ ReportItem,
+ TemplateMeta,
+ TokenResponse,
+ UserProfile
+} from "./types";
+import { apiBlobRequest, apiRequest } from "./http";
+import { clearTokens, setAccessToken, setRefreshToken } from "./session";
+
+export async function login(username: string, password: string): Promise<TokenResponse> {
+ const body = new URLSearchParams();
+ body.set("username", username);
+ body.set("password", password);
+ const token = await apiRequest<TokenResponse>(
+ "/auth/token",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body
+ },
+ false
+ );
+ setAccessToken(token.access_token);
+ setRefreshToken(token.refresh_token);
+ return token;
+}
+
+export async function logout(): Promise<void> {
+ try {
+ await apiRequest<{ status: string }>("/auth/logout", { method: "POST" }, false);
+ } finally {
+ clearTokens();
+ }
+}
+
+export function campaignEventsPath(campaignId: string, token: string): string {
+ return `/ws/campaigns/${encodeURIComponent(campaignId)}/events?token=${encodeURIComponent(token)}`;
+}
+
+export function buildModuleRunPayload(
+ campaignId: string,
+ params: Record<string, unknown>,
+ dryRun = true
+): { campaign_id: string; params: Record<string, unknown>; dry_run: boolean } {
+ return { campaign_id: campaignId, params, dry_run: dryRun };
+}
+
+export const api = {
+ me: () => apiRequest<UserProfile>("/auth/me"),
+ health: () => apiRequest<Record<string, unknown>>("/health"),
+ telemetry: () => apiRequest<Record<string, unknown>>("/telemetry"),
+ monthlyStats: () => apiRequest<MonthlyFindingStats>("/stats/monthly"),
+ campaigns: () => apiRequest<Campaign[]>("/campaigns"),
+ createCampaign: (body: { name: string; client: string; targets: string[]; scope_cidrs: string[]; noise_profile: string }) =>
+ apiRequest<Campaign>("/campaigns", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ }),
+ campaign: (id: string) => apiRequest<Campaign>(`/campaigns/${encodeURIComponent(id)}`),
+ deleteCampaign: (id: string) =>
+ apiRequest<Record<string, string>>(`/campaigns/${encodeURIComponent(id)}`, { method: "DELETE" }),
+ findings: (id: string) => apiRequest<Finding[]>(`/campaigns/${encodeURIComponent(id)}/findings`),
+ cvss: (id: string) => apiRequest<Record<string, unknown>>(`/campaigns/${encodeURIComponent(id)}/cvss`),
+ restoreVault: (id: string) =>
+ apiRequest<Record<string, unknown>>(`/campaigns/${encodeURIComponent(id)}/restore-vault`, { method: "POST" }),
+ runCampaign: (id: string, body: Record<string, unknown>) =>
+ apiRequest<Record<string, unknown>>(`/campaigns/${encodeURIComponent(id)}/run`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ }),
+ diffCampaign: (id: string, otherId: string) =>
+ apiRequest<Record<string, unknown>>(
+ `/campaigns/${encodeURIComponent(id)}/diff/${encodeURIComponent(otherId)}`
+ ),
+ modules: () => apiRequest<ModuleMeta[]>("/modules"),
+ executionChains: () => apiRequest<ExecutionChain[]>("/modules/execution-chains"),
+ runModule: (moduleId: string, payload: ReturnType<typeof buildModuleRunPayload>) =>
+ apiRequest<Record<string, unknown>>(`/modules/${encodeURIComponent(moduleId)}/run`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload)
+ }),
+ generateReport: (campaignId: string, format: string) =>
+ apiRequest<Record<string, string>>(
+ `/reports/${encodeURIComponent(campaignId)}?fmt=${encodeURIComponent(format)}`,
+ { method: "POST" }
+ ),
+ reports: (campaignId: string) =>
+ apiRequest<{ campaign_id: string; reports: ReportItem[] }>(`/reports/${encodeURIComponent(campaignId)}`),
+ reportDownloadUrl: (campaignId: string, filename: string) =>
+ `/reports/${encodeURIComponent(campaignId)}/files/${encodeURIComponent(filename)}`,
+ downloadReport: (campaignId: string, filename: string) =>
+ apiBlobRequest(`/reports/${encodeURIComponent(campaignId)}/files/${encodeURIComponent(filename)}`),
+ deleteReport: (campaignId: string, filename: string) =>
+ apiRequest<Record<string, string>>(
+ `/reports/${encodeURIComponent(campaignId)}/files/${encodeURIComponent(filename)}`,
+ { method: "DELETE" }
+ ),
+ clearReports: (campaignId: string) =>
+ apiRequest<{ status: string; campaign_id: string; deleted: number }>(
+ `/reports/${encodeURIComponent(campaignId)}`,
+ { method: "DELETE" }
+ ),
+ graph: (campaignId: string) => apiRequest<CampaignGraph>(`/graph/${encodeURIComponent(campaignId)}`),
+ attackPaths: (campaignId: string) =>
+ apiRequest<AttackPathsResponse>(`/graph/${encodeURIComponent(campaignId)}/attack-paths`),
+ ingestBloodhound: (campaignId: string, jsonPath: string) =>
+ apiRequest<Record<string, unknown>>(`/graph/${encodeURIComponent(campaignId)}/bloodhound`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ json_path: jsonPath })
+ }),
+ templates: () => apiRequest<TemplateMeta[]>("/templates"),
+ templatePlan: (name: string, globalParams: Record<string, unknown>) =>
+ apiRequest<Record<string, unknown>>(`/templates/${encodeURIComponent(name)}/plan`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ global_params: globalParams })
+ }),
+ activeStrategy: () => apiRequest<Record<string, unknown>>("/strategy/active"),
+ engageStrategy: (body: Record<string, unknown>) =>
+ apiRequest<Record<string, unknown>>("/strategy/engage", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ }),
+ changePassword: (body: { current_password: string; new_password: string }) =>
+ apiRequest<Record<string, string>>("/auth/change-password", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ }),
+ apiKeys: () => apiRequest<ApiKeyMeta[]>("/auth/api-keys"),
+ createApiKey: (body: { name: string; scopes: string; expires_days?: number }) =>
+ apiRequest<ApiKeyCreateResponse>("/auth/api-keys", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ }),
+ deleteApiKey: (id: string) => apiRequest<Record<string, string>>(`/auth/api-keys/${encodeURIComponent(id)}`, {
+ method: "DELETE"
+ }),
+ securityAudit: () => apiRequest<Record<string, unknown>>("/security/audit"),
+ users: () => apiRequest<Record<string, unknown>[]>("/security/users"),
+ edrStats: () => apiRequest<Record<string, unknown>>("/edr/bypass/stats"),
+ reportBypass: (body: Record<string, unknown>) =>
+ apiRequest<Record<string, unknown>>("/edr/bypass/report", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ })
+};
diff --git a/frontend/src/api/http.test.ts b/frontend/src/api/http.test.ts
new file mode 100644
index 0000000..9975543
--- /dev/null
+++ b/frontend/src/api/http.test.ts
@@ -0,0 +1,44 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { apiRequest } from "./http";
+import { clearTokens, getAccessToken, setAccessToken, setRefreshToken } from "./session";
+
+describe("HTTP auth boundary", () => {
+ beforeEach(() => {
+ clearTokens();
+ sessionStorage.clear();
+ vi.unstubAllGlobals();
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("refreshes once and retries the original request with the refreshed access token", async () => {
+ setAccessToken("expired-access");
+ setRefreshToken("refresh-token");
+ const fetchMock = vi.fn(async (path: string, init?: RequestInit) => {
+ if (path === "/auth/refresh") {
+ expect(init?.method).toBe("POST");
+ return new Response(JSON.stringify({
+ access_token: "fresh-access",
+ refresh_token: "fresh-refresh",
+ token_type: "bearer",
+ expires_in: 3600,
+ role: "operator"
+ }), { status: 200 });
+ }
+ const authorization = new Headers(init?.headers).get("Authorization");
+ if (authorization === "Bearer expired-access") {
+ return new Response(null, { status: 401 });
+ }
+ expect(authorization).toBe("Bearer fresh-access");
+ return new Response(JSON.stringify({ status: "ok" }), { status: 200 });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ await expect(apiRequest<{ status: string }>("/protected")).resolves.toEqual({ status: "ok" });
+
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(getAccessToken()).toBe("fresh-access");
+ });
+});
diff --git a/frontend/src/api/http.ts b/frontend/src/api/http.ts
new file mode 100644
index 0000000..2ba680e
--- /dev/null
+++ b/frontend/src/api/http.ts
@@ -0,0 +1,104 @@
+import type { TokenResponse } from "./types";
+import { clearTokens, getAccessToken, getRefreshToken, setAccessToken, setRefreshToken } from "./session";
+
+export class ApiError extends Error {
+ readonly status: number;
+ readonly detail: unknown;
+
+ constructor(status: number, detail: unknown) {
+ super(typeof detail === "string" ? detail : `Request failed with ${status}`);
+ this.status = status;
+ this.detail = detail;
+ }
+}
+
+async function parseResponse(response: Response): Promise<unknown> {
+ const text = await response.text();
+ if (!text) {
+ return null;
+ }
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+}
+
+function errorDetail(body: unknown): unknown {
+ if (typeof body === "object" && body !== null && "detail" in body) {
+ return body.detail ?? body;
+ }
+ return body;
+}
+
+export async function refreshAccessToken(): Promise<boolean> {
+ const refreshToken = getRefreshToken();
+ if (!refreshToken) {
+ return false;
+ }
+
+ try {
+ const response = await fetch("/auth/refresh", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ refresh_token: refreshToken })
+ });
+ if (!response.ok) {
+ clearTokens();
+ return false;
+ }
+ const token = (await response.json()) as TokenResponse;
+ if (!token.access_token || !token.refresh_token) {
+ clearTokens();
+ return false;
+ }
+ setAccessToken(token.access_token);
+ setRefreshToken(token.refresh_token);
+ return true;
+ } catch {
+ clearTokens();
+ return false;
+ }
+}
+
+export async function apiRequest<T>(
+ path: string,
+ init: RequestInit = {},
+ retry = true
+): Promise<T> {
+ const headers = new Headers(init.headers);
+ const accessToken = getAccessToken();
+ if (accessToken) {
+ headers.set("Authorization", `Bearer ${accessToken}`);
+ }
+ const response = await fetch(path, { ...init, headers });
+ if (response.status === 401 && retry && (await refreshAccessToken())) {
+ return apiRequest<T>(path, init, false);
+ }
+ const body = await parseResponse(response);
+ if (!response.ok) {
+ throw new ApiError(response.status, errorDetail(body));
+ }
+ return body as T;
+}
+
+export async function apiBlobRequest(
+ path: string,
+ init: RequestInit = {},
+ retry = true
+): Promise<Blob> {
+ const headers = new Headers(init.headers);
+ const accessToken = getAccessToken();
+ if (accessToken) {
+ headers.set("Authorization", `Bearer ${accessToken}`);
+ }
+ const response = await fetch(path, { ...init, headers });
+ if (response.status === 401 && retry && (await refreshAccessToken())) {
+ return apiBlobRequest(path, init, false);
+ }
+ if (!response.ok) {
+ const body = await parseResponse(response);
+ throw new ApiError(response.status, errorDetail(body));
+ }
+ return response.blob();
+}
diff --git a/frontend/src/api/session.ts b/frontend/src/api/session.ts
new file mode 100644
index 0000000..d99a2c5
--- /dev/null
+++ b/frontend/src/api/session.ts
@@ -0,0 +1,28 @@
+const REFRESH_TOKEN_KEY = "ares.refreshToken";
+
+let accessToken: string | null = null;
+
+export function setAccessToken(token: string | null): void {
+ accessToken = token;
+}
+
+export function getAccessToken(): string | null {
+ return accessToken;
+}
+
+export function setRefreshToken(token: string | null): void {
+ if (token) {
+ sessionStorage.setItem(REFRESH_TOKEN_KEY, token);
+ return;
+ }
+ sessionStorage.removeItem(REFRESH_TOKEN_KEY);
+}
+
+export function getRefreshToken(): string | null {
+ return sessionStorage.getItem(REFRESH_TOKEN_KEY);
+}
+
+export function clearTokens(): void {
+ accessToken = null;
+ setRefreshToken(null);
+}
diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts
index 8019a7b..486c072 100644
--- a/frontend/src/api/types.ts
+++ b/frontend/src/api/types.ts
@@ -135,3 +135,63 @@ export interface ApiKeyCreateResponse extends ApiKeyMeta {
key: string;
note?: string;
}
+
+export type SafeGraphValue = boolean | number | string | null | SafeGraphValue[] | { [key: string]: SafeGraphValue };
+
+export interface GraphNodePayload {
+ id: string;
+ type: string;
+ label: string;
+ color?: string;
+ data?: Record<string, SafeGraphValue>;
+ style?: {
+ color?: string;
+ shape?: string;
+ size?: number;
+ };
+}
+
+export interface GraphEdgePayload {
+ source: string;
+ target: string;
+ type?: string;
+ label?: string;
+ weight?: number;
+ data?: Record<string, SafeGraphValue>;
+ style?: {
+ color?: string;
+ dashed?: boolean;
+ };
+}
+
+export interface CampaignGraph {
+ nodes: GraphNodePayload[];
+ edges: GraphEdgePayload[];
+ stats?: Record<string, SafeGraphValue>;
+ data_sources?: Record<string, SafeGraphValue>;
+}
+
+export interface AttackPathStep {
+ from: string;
+ to: string;
+ edge?: string;
+ attack?: string;
+ weight?: number;
+}
+
+export interface AttackPath {
+ path_length?: number;
+ total_score?: number;
+ steps: AttackPathStep[];
+ attack_modules?: string[];
+ start?: string;
+ end?: string;
+}
+
+export interface AttackPathsResponse {
+ paths?: AttackPath[];
+ path?: AttackPath | null;
+ paths_found?: number;
+ message?: string;
+ stats?: Record<string, SafeGraphValue>;
+}
diff --git a/frontend/src/features/auth/AuthProvider.tsx b/frontend/src/features/auth/AuthProvider.tsx
new file mode 100644
index 0000000..5ad6c23
--- /dev/null
+++ b/frontend/src/features/auth/AuthProvider.tsx
@@ -0,0 +1,83 @@
+import { useQueryClient } from "@tanstack/react-query";
+import { ReactNode, useEffect, useMemo, useState } from "react";
+import {
+ api,
+ clearTokens,
+ getRefreshToken,
+ login as loginRequest,
+ logout as logoutRequest,
+ refreshAccessToken
+} from "../../api/client";
+import type { UserProfile } from "../../api/types";
+import { AuthContext, type AuthState } from "./authContext";
+
+function LoadingSession() {
+ return (
+ <div className="grid min-h-screen place-items-center bg-slate-100 p-4">
+ <div className="panel p-5 text-center">
+ <h1 className="text-xl font-bold">ARES</h1>
+ <p className="mt-1 text-sm text-slate-600">Loading session</p>
+ </div>
+ </div>
+ );
+}
+
+export function AuthProvider({ children }: { children: ReactNode }) {
+ const [user, setUser] = useState<UserProfile | null>(null);
+ const [loading, setLoading] = useState(Boolean(getRefreshToken()));
+ const queryClient = useQueryClient();
+
+ useEffect(() => {
+ let active = true;
+ if (!getRefreshToken()) {
+ setLoading(false);
+ return;
+ }
+ (async () => {
+ try {
+ if (!(await refreshAccessToken())) {
+ if (active) {
+ setUser(null);
+ }
+ return;
+ }
+ const profile = await api.me();
+ if (active) {
+ setUser(profile);
+ }
+ } catch {
+ clearTokens();
+ if (active) {
+ setUser(null);
+ }
+ } finally {
+ if (active) {
+ setLoading(false);
+ }
+ }
+ })();
+ return () => {
+ active = false;
+ };
+ }, []);
+
+ const value = useMemo<AuthState>(
+ () => ({
+ user,
+ loading,
+ login: async (username, password) => {
+ await loginRequest(username, password);
+ const profile = await api.me();
+ setUser(profile);
+ },
+ logout: async () => {
+ await logoutRequest();
+ setUser(null);
+ queryClient.clear();
+ }
+ }),
+ [loading, queryClient, user]
+ );
+
+ return <AuthContext.Provider value={value}>{loading ? <LoadingSession /> : children}</AuthContext.Provider>;
+}
diff --git a/frontend/src/features/auth/LoginPage.tsx b/frontend/src/features/auth/LoginPage.tsx
new file mode 100644
index 0000000..889c15e
--- /dev/null
+++ b/frontend/src/features/auth/LoginPage.tsx
@@ -0,0 +1,58 @@
+import { KeyRound } from "lucide-react";
+import { FormEvent, useState } from "react";
+import { Navigate, useNavigate } from "react-router-dom";
+import { useAuth } from "./authContext";
+
+const brandLogoPath = "/dashboard/brand/ares-logo.png";
+
+export function LoginPage() {
+ const [username, setUsername] = useState("");
+ const [password, setPassword] = useState("");
+ const [error, setError] = useState("");
+ const { login, user } = useAuth();
+ const navigate = useNavigate();
+
+ if (user) {
+ return <Navigate to="/" replace />;
+ }
+
+ async function submit(event: FormEvent) {
+ event.preventDefault();
+ setError("");
+ try {
+ await login(username, password);
+ navigate("/");
+ } catch (exc) {
+ setError(exc instanceof Error ? exc.message : "Login failed");
+ }
+ }
+
+ return (
+ <div className="grid min-h-screen place-items-center bg-slate-100 p-4">
+ <form className="panel w-full max-w-sm p-5" onSubmit={(event) => void submit(event)}>
+ <div className="mb-5 text-center">
+ <img className="mx-auto mb-4 h-28 w-auto max-w-full object-contain" src={brandLogoPath} alt="ARES" />
+ <h1 className="text-xl font-bold">ARES Dashboard</h1>
+ <p className="text-sm text-slate-600">Authorized access</p>
+ </div>
+ <label className="mb-3 block text-sm font-semibold">
+ Username
+ <input className="field mt-1" value={username} onChange={(e) => setUsername(e.target.value)} />
+ </label>
+ <label className="mb-4 block text-sm font-semibold">
+ Password
+ <input
+ className="field mt-1"
+ type="password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ />
+ </label>
+ {error && <div className="mb-3 rounded-md border border-red-200 bg-red-50 p-2 text-sm text-red-800">{error}</div>}
+ <button className="btn btn-primary w-full" type="submit">
+ <KeyRound size={16} /> Login
+ </button>
+ </form>
+ </div>
+ );
+}
diff --git a/frontend/src/features/auth/authContext.ts b/frontend/src/features/auth/authContext.ts
new file mode 100644
index 0000000..64e3fff
--- /dev/null
+++ b/frontend/src/features/auth/authContext.ts
@@ -0,0 +1,19 @@
+import { createContext, useContext } from "react";
+import type { UserProfile } from "../../api/types";
+
+export interface AuthState {
+ user: UserProfile | null;
+ loading: boolean;
+ login: (username: string, password: string) => Promise<void>;
+ logout: () => Promise<void>;
+}
+
+export const AuthContext = createContext<AuthState | null>(null);
+
+export function useAuth(): AuthState {
+ const value = useContext(AuthContext);
+ if (!value) {
+ throw new Error("AuthContext missing");
+ }
+ return value;
+}
diff --git a/frontend/src/features/dashboard/DashboardPages.tsx b/frontend/src/features/dashboard/DashboardPages.tsx
new file mode 100644
index 0000000..1789b8a
--- /dev/null
+++ b/frontend/src/features/dashboard/DashboardPages.tsx
@@ -0,0 +1,3211 @@
+import {
+ AlertTriangle,
+ Bell,
+ Boxes,
+ CheckCircle2,
+ Copy,
+ Database,
+ Download,
+ Eye,
+ FileText,
+ GitGraph,
+ KeyRound,
+ Layers,
+ LayoutDashboard,
+ ListChecks,
+ Loader2,
+ LogOut,
+ Menu,
+ Play,
+ Radio,
+ Search,
+ ShieldAlert,
+ ShieldCheck,
+ Target,
+ Trash2,
+ TrendingUp,
+ UserCog,
+ type LucideIcon,
+ Workflow
+} from "lucide-react";
+import {
+ ChangeEvent,
+ FormEvent,
+ KeyboardEvent,
+ ReactNode,
+ useEffect,
+ useMemo,
+ useRef,
+ useState
+} from "react";
+import { NavLink, Navigate, useNavigate } from "react-router-dom";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { ApiError, api, buildModuleRunPayload, campaignEventsPath, getAccessToken } from "../../api/client";
+import type { ApiKeyMeta, Campaign, ExecutionChain, Finding, ModuleMeta, MonthlyFindingStats, ParamField, ReportItem } from "../../api/types";
+import { useAuth } from "../auth/authContext";
+import { DashboardUiProvider } from "./dashboardUi";
+import { type DashboardUiState, useDashboardUi, useSessionState } from "./dashboardUiState";
+
+interface ModuleRunRecord {
+ campaignId: string;
+ moduleId: string;
+ payload: unknown;
+ isError?: boolean;
+}
+
+interface PersistedResult {
+ key: string;
+ payload: unknown;
+ isError?: boolean;
+}
+
+interface GeneratedApiKey {
+ id?: string;
+ key: string;
+ note?: string;
+ prefix?: string;
+}
+
+type ApiKeyCopyStatus = "idle" | "copied" | "manual";
+
+interface SearchResult {
+ id: string;
+ label: string;
+ detail: string;
+ route: string;
+ onSelect?: () => void;
+}
+
+interface DashboardNotification {
+ id: string;
+ title: string;
+ detail: string;
+ tone: "info" | "warn" | "danger";
+}
+
+const REQUIRED_FIELD_MESSAGE = "This field is required.";
+
+type ValidatableElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
+type TelemetryMetricMap = Record<string, boolean | number | string | null | undefined>;
+interface TelemetrySnapshot {
+ modules?: TelemetryMetricMap;
+ queue?: TelemetryMetricMap;
+ workers?: TelemetryMetricMap;
+ latency_ms?: TelemetryMetricMap;
+ throughput?: TelemetryMetricMap;
+ findings?: number;
+ credentials?: number;
+ hosts?: TelemetryMetricMap;
+ campaign_id?: string;
+ timestamp?: number;
+ [key: string]: unknown;
+}
+
+interface TemplatePlanStage {
+ name?: string;
+ modules?: string[];
+ params?: Record<string, unknown>;
+}
+
+interface TemplatePlanResponse {
+ template?: string;
+ description?: string;
+ plan?: {
+ stages?: TemplatePlanStage[];
+ };
+ global_params?: Record<string, unknown>;
+ note?: string;
+}
+
+function setRequiredMessage<T extends ValidatableElement>(event: FormEvent<T>) {
+ event.currentTarget.setCustomValidity(REQUIRED_FIELD_MESSAGE);
+}
+
+function clearValidationMessage<T extends ValidatableElement>(event: ChangeEvent<T>) {
+ event.currentTarget.setCustomValidity("");
+}
+
+const navItems = [
+ { to: "/", label: "Overview", icon: LayoutDashboard },
+ { to: "/campaigns", label: "Campaigns", icon: ListChecks },
+ { to: "/modules", label: "Modules", icon: Boxes },
+ { to: "/reports", label: "Reports", icon: FileText },
+ { to: "/graph", label: "Graph", icon: GitGraph },
+ { to: "/templates", label: "Templates", icon: Workflow },
+ { to: "/strategy", label: "Strategy", icon: ShieldCheck },
+ { to: "/security", label: "Security", icon: UserCog },
+ { to: "/edr", label: "EDR/OPSEC", icon: ShieldAlert },
+ { to: "/live", label: "Live", icon: Radio }
+];
+
+const navGroups = [
+ { label: "Core", items: navItems.slice(0, 1) },
+ { label: "Operations", items: navItems.slice(1, 4) },
+ { label: "Intelligence", items: navItems.slice(4, 7) },
+ { label: "Control", items: navItems.slice(7) }
+];
+
+const pageMeta: Record<string, { icon: LucideIcon; eyebrow: string; description: string }> = {
+ Overview: {
+ icon: LayoutDashboard,
+ eyebrow: "Dashboard",
+ description: "Health, telemetry, campaigns, and activity."
+ },
+ Campaigns: {
+ icon: ListChecks,
+ eyebrow: "Operations",
+ description: "Scopes, status, findings, and comparisons."
+ },
+ Modules: {
+ icon: Boxes,
+ eyebrow: "Operations",
+ description: "Catalog, OPSEC, and authorized runs."
+ },
+ Reports: {
+ icon: FileText,
+ eyebrow: "Operations",
+ description: "Evidence packages and artifacts."
+ },
+ Graph: {
+ icon: GitGraph,
+ eyebrow: "Intelligence",
+ description: "Entities, relationships, and attack paths."
+ },
+ Templates: {
+ icon: Workflow,
+ eyebrow: "Intelligence",
+ description: "Reusable campaign plans."
+ },
+ Strategy: {
+ icon: ShieldCheck,
+ eyebrow: "Intelligence",
+ description: "Authorized objective planning."
+ },
+ Security: {
+ icon: UserCog,
+ eyebrow: "Control",
+ description: "Account, API keys, audit, and users."
+ },
+ "EDR/OPSEC": {
+ icon: ShieldAlert,
+ eyebrow: "Control",
+ description: "Detection outcomes and OPSEC feedback."
+ },
+ "Live Events": {
+ icon: Radio,
+ eyebrow: "Control",
+ description: "Campaign events as they arrive."
+ }
+};
+
+const brandMarkPath = "/dashboard/brand/ares-mark.png";
+
+function formatRole(role?: string): string {
+ const labels: Record<string, string> = {
+ team_lead: "Team Lead",
+ operator: "Operator",
+ recon: "Recon",
+ reporter: "Reporter"
+ };
+ if (!role) {
+ return "";
+ }
+ return labels[role] ?? role.replace(/_/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
+}
+
+export function DashboardShell({ children }: { children: ReactNode }) {
+ const { user, loading, logout } = useAuth();
+ const navigate = useNavigate();
+ const [selectedCampaignId, setSelectedCampaignId] = useSessionState("ares.dashboard.selectedCampaignId", "");
+ const [liveCampaignId, setLiveCampaignId] = useSessionState("ares.dashboard.live.campaignId", "");
+ const [liveEvents, setLiveEvents] = useSessionState<unknown[]>("ares.dashboard.live.events", []);
+ const [liveConnected, setLiveConnected] = useState(false);
+ const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
+ const [searchTerm, setSearchTerm] = useState("");
+ const [searchOpen, setSearchOpen] = useState(false);
+ const [notificationsOpen, setNotificationsOpen] = useState(false);
+ const [readNotificationIds, setReadNotificationIds] = useState<string[]>([]);
+ const [deletedNotificationIds, setDeletedNotificationIds] = useState<string[]>([]);
+ const liveSocketRef = useRef<WebSocket | null>(null);
+ const health = useQuery({ queryKey: ["health"], queryFn: api.health });
+ const telemetry = useQuery({ queryKey: ["telemetry"], queryFn: api.telemetry });
+ const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
+ const modules = useQuery({ queryKey: ["modules"], queryFn: api.modules });
+ const templates = useQuery({ queryKey: ["templates"], queryFn: api.templates });
+ const reports = useQuery({
+ queryKey: ["reports", selectedCampaignId],
+ queryFn: () => api.reports(selectedCampaignId),
+ enabled: Boolean(selectedCampaignId)
+ });
+
+ useEffect(() => {
+ const accessToken = getAccessToken();
+ if (!liveConnected || !liveCampaignId || !accessToken) {
+ if (liveSocketRef.current) {
+ liveSocketRef.current.close();
+ liveSocketRef.current = null;
+ }
+ return;
+ }
+
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+ const socket = new WebSocket(`${protocol}//${window.location.host}${campaignEventsPath(liveCampaignId, accessToken)}`);
+ liveSocketRef.current = socket;
+ socket.onmessage = (event) => {
+ try {
+ setLiveEvents((items) => [JSON.parse(event.data), ...items].slice(0, 100));
+ } catch {
+ setLiveEvents((items) => [event.data, ...items].slice(0, 100));
+ }
+ };
+ socket.onclose = () => {
+ if (liveSocketRef.current === socket) {
+ liveSocketRef.current = null;
+ setLiveConnected(false);
+ }
+ };
+
+ return () => {
+ socket.onclose = null;
+ socket.close();
+ if (liveSocketRef.current === socket) {
+ liveSocketRef.current = null;
+ }
+ };
+ }, [liveCampaignId, liveConnected, setLiveEvents]);
+
+ const dashboardUi = useMemo<DashboardUiState>(
+ () => ({
+ selectedCampaignId,
+ setSelectedCampaignId,
+ liveCampaignId,
+ setLiveCampaignId,
+ liveConnected,
+ setLiveConnected,
+ liveEvents,
+ clearLiveEvents: () => setLiveEvents([])
+ }),
+ [
+ liveCampaignId,
+ liveConnected,
+ liveEvents,
+ selectedCampaignId,
+ setLiveCampaignId,
+ setLiveConnected,
+ setLiveEvents,
+ setSelectedCampaignId
+ ]
+ );
+ const searchResults = useMemo<SearchResult[]>(() => {
+ const term = searchTerm.trim().toLowerCase();
+ if (!term) return [];
+ const results: SearchResult[] = [];
+ const addIfMatch = (result: SearchResult, haystack: string) => {
+ if (haystack.toLowerCase().includes(term)) {
+ results.push(result);
+ }
+ };
+
+ navItems.forEach((item) => {
+ addIfMatch(
+ {
+ id: `page:${item.to}`,
+ label: item.label,
+ detail: `Open ${item.to === "/" ? "Overview" : item.to}`,
+ route: item.to
+ },
+ `${item.label} ${item.to}`
+ );
+ });
+
+ (campaigns.data ?? []).forEach((campaign) => {
+ addIfMatch(
+ {
+ id: `campaign:${campaign.id}`,
+ label: campaign.name || campaign.id,
+ detail: `Campaign ${campaign.id.slice(0, 12)}`,
+ route: "/campaigns",
+ onSelect: () => {
+ setSelectedCampaignId(campaign.id);
+ window.sessionStorage.setItem("ares.dashboard.campaigns.tab", JSON.stringify("Scope"));
+ }
+ },
+ `${campaign.name ?? ""} ${campaign.id} ${campaign.client ?? ""} ${campaign.status ?? ""}`
+ );
+ });
+
+ (modules.data ?? []).forEach((module) => {
+ addIfMatch(
+ {
+ id: `module:${module.id}`,
+ label: module.id,
+ detail: module.description || "Module",
+ route: "/modules",
+ onSelect: () => {
+ window.sessionStorage.setItem("ares.dashboard.modules.selectedId", JSON.stringify(module.id));
+ window.sessionStorage.setItem("ares.dashboard.modules.tab", JSON.stringify("Run Panel"));
+ }
+ },
+ `${module.id} ${module.name ?? ""} ${module.description ?? ""} ${module.category ?? ""} ${module.mitre ?? ""}`
+ );
+ });
+
+ const reportItems = reports.data?.reports ?? [];
+ reportItems.forEach((report) => {
+ addIfMatch(
+ {
+ id: `report:${report.filename}`,
+ label: report.filename,
+ detail: `${report.format || "report"} artifact`,
+ route: "/reports",
+ onSelect: () => {
+ window.sessionStorage.setItem("ares.dashboard.reports.tab", JSON.stringify("Library"));
+ }
+ },
+ `${report.filename} ${report.format ?? ""}`
+ );
+ });
+
+ const templateItems = Array.isArray(templates.data) ? templates.data as Array<Record<string, unknown>> : [];
+ templateItems.forEach((template, index) => {
+ const templateName = String(template.name ?? template.id ?? index);
+ addIfMatch(
+ {
+ id: `template:${templateName}`,
+ label: templateName,
+ detail: String(template.description ?? "Campaign template"),
+ route: "/templates",
+ onSelect: () => {
+ window.sessionStorage.setItem("ares.dashboard.templates.name", JSON.stringify(templateName));
+ window.sessionStorage.setItem("ares.dashboard.templates.tab", JSON.stringify("Plan Builder"));
+ }
+ },
+ `${templateName} ${String(template.description ?? "")}`
+ );
+ });
+
+ return results.slice(0, 8);
+ }, [campaigns.data, modules.data, reports.data, searchTerm, setSelectedCampaignId, templates.data]);
+
+ const notifications = useMemo<DashboardNotification[]>(() => {
+ const items: DashboardNotification[] = [];
+ const snapshot = telemetry.data as TelemetrySnapshot | undefined;
+ const healthSnapshot = health.data as Record<string, unknown> | undefined;
+ const healthStatus = String(healthSnapshot?.status ?? "").toLowerCase();
+
+ if (health.isError) {
+ items.push({ id: "health:error", title: "Backend health check failed", detail: "ARES API health is not reachable.", tone: "danger" });
+ } else if (health.isSuccess && healthStatus && !["ok", "healthy", "online"].includes(healthStatus)) {
+ items.push({ id: `health:status:${healthStatus}`, title: "Backend status needs attention", detail: String(healthSnapshot?.status), tone: "warn" });
+ }
+ if (telemetry.isError) {
+ items.push({ id: "telemetry:error", title: "Telemetry unavailable", detail: "Runtime telemetry could not be loaded.", tone: "warn" });
+ }
+ if (campaigns.isError) {
+ items.push({ id: "campaigns:error", title: "Campaign list unavailable", detail: "Campaign data could not be loaded.", tone: "warn" });
+ }
+ if (modules.isError) {
+ items.push({ id: "modules:error", title: "Module catalog unavailable", detail: "Module metadata could not be loaded.", tone: "warn" });
+ }
+ if (reports.isError && selectedCampaignId) {
+ items.push({ id: `reports:error:${selectedCampaignId}`, title: "Report library unavailable", detail: "Selected campaign reports could not be loaded.", tone: "warn" });
+ }
+
+ const failedRuns = metricNumber(snapshot?.modules, "failed");
+ const errorRate = metricNumber(snapshot?.modules, "error_rate");
+ const unhealthyWorkers = metricNumber(snapshot?.workers, "unhealthy");
+ const queueDepth = metricNumber(snapshot?.queue, "depth");
+ if (failedRuns > 0) {
+ items.push({ id: `telemetry:failed-runs:${failedRuns}`, title: "Failed module runs", detail: `${failedRuns} failed module run(s) reported by telemetry.`, tone: "warn" });
+ }
+ if (errorRate > 0) {
+ items.push({ id: `telemetry:error-rate:${errorRate}`, title: "Runtime error rate above zero", detail: `${formatRate(errorRate)} module error rate.`, tone: "warn" });
+ }
+ if (unhealthyWorkers > 0) {
+ items.push({ id: `telemetry:workers:${unhealthyWorkers}`, title: "Unhealthy worker detected", detail: `${unhealthyWorkers} worker(s) unhealthy.`, tone: "danger" });
+ }
+ if (queueDepth > 0) {
+ items.push({ id: `telemetry:queue:${queueDepth}`, title: "Queue has pending work", detail: `${queueDepth} queued task(s).`, tone: "info" });
+ }
+ return items;
+ }, [campaigns.isError, health.data, health.isError, health.isSuccess, modules.isError, reports.isError, selectedCampaignId, telemetry.data, telemetry.isError]);
+
+ const activeNotificationKey = useMemo(() => notifications.map((item) => item.id).join("|"), [notifications]);
+ const visibleNotifications = useMemo(
+ () => notifications.filter((item) => !deletedNotificationIds.includes(item.id)),
+ [deletedNotificationIds, notifications]
+ );
+ const unreadNotificationCount = visibleNotifications.filter((item) => !readNotificationIds.includes(item.id)).length;
+
+ useEffect(() => {
+ const activeIds = activeNotificationKey ? activeNotificationKey.split("|") : [];
+ setReadNotificationIds((current) => current.filter((id) => activeIds.includes(id)));
+ setDeletedNotificationIds((current) => current.filter((id) => activeIds.includes(id)));
+ }, [activeNotificationKey]);
+
+ function markVisibleNotificationsRead(): void {
+ const visibleIds = visibleNotifications.map((item) => item.id);
+ if (visibleIds.length === 0) return;
+ setReadNotificationIds((current) => unique([...current, ...visibleIds]));
+ }
+
+ function toggleNotifications(): void {
+ const nextOpen = !notificationsOpen;
+ if (nextOpen) {
+ markVisibleNotificationsRead();
+ }
+ setNotificationsOpen(nextOpen);
+ }
+
+ function deleteNotification(id: string): void {
+ setDeletedNotificationIds((current) => unique([...current, id]));
+ setReadNotificationIds((current) => unique([...current, id]));
+ }
+
+ function clearNotifications(): void {
+ const visibleIds = visibleNotifications.map((item) => item.id);
+ setDeletedNotificationIds((current) => unique([...current, ...visibleIds]));
+ setReadNotificationIds((current) => unique([...current, ...visibleIds]));
+ }
+
+ function selectSearchResult(result: SearchResult): void {
+ result.onSelect?.();
+ navigate(result.route);
+ setSearchTerm("");
+ setSearchOpen(false);
+ }
+
+ if (loading) {
+ return <ScreenMessage title="ARES" body="Loading session" />;
+ }
+ if (!user) {
+ return <Navigate to="/login" replace />;
+ }
+ return (
+ <DashboardUiProvider value={dashboardUi}>
+ <div className={sidebarCollapsed ? "app-shell sidebar-collapsed" : "app-shell"}>
+ <aside className="sidebar">
+ <div className="sidebar-brand">
+ <img className="sidebar-mark" src={brandMarkPath} alt="" aria-hidden="true" />
+ <div className="min-w-0">
+ <div className="sidebar-title">ARES</div>
+ <div className="sidebar-subtitle">Security dashboard</div>
+ </div>
+ </div>
+ <nav className="sidebar-nav" aria-label="Dashboard navigation">
+ {navGroups.map((group) => (
+ <div className="nav-group" key={group.label}>
+ <div className="nav-group-label">{group.label}</div>
+ <div className="grid gap-1">
+ {group.items.map((item) => {
+ const Icon = item.icon;
+ return (
+ <NavLink key={item.to} to={item.to} end={item.to === "/"} className="nav-link" title={sidebarCollapsed ? item.label : undefined}>
+ <Icon size={16} />
+ <span>{item.label}</span>
+ </NavLink>
+ );
+ })}
+ </div>
+ </div>
+ ))}
+ </nav>
+ </aside>
+ <main className="main-shell">
+ <header className="topbar">
+ <div className="topbar-left">
+ <button
+ className="icon-button"
+ aria-label={sidebarCollapsed ? "Expand navigation" : "Collapse navigation"}
+ aria-pressed={sidebarCollapsed}
+ onClick={() => setSidebarCollapsed((value) => !value)}
+ type="button"
+ >
+ <Menu size={17} />
+ </button>
+ <div className="topbar-search-wrap">
+ <label className="topbar-search" aria-label="Dashboard search">
+ <Search size={16} />
+ <input
+ aria-label="Search dashboard"
+ onBlur={() => window.setTimeout(() => setSearchOpen(false), 120)}
+ onChange={(event) => {
+ setSearchTerm(event.target.value);
+ setSearchOpen(true);
+ }}
+ onFocus={() => setSearchOpen(true)}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ setSearchOpen(false);
+ }
+ if (event.key === "Enter" && searchResults.length > 0) {
+ event.preventDefault();
+ selectSearchResult(searchResults[0]);
+ }
+ }}
+ placeholder="Search campaigns, modules, reports"
+ value={searchTerm}
+ />
+ </label>
+ {searchOpen && (
+ <div className="search-results" role="listbox">
+ {searchTerm.trim() ? (
+ searchResults.length > 0 ? (
+ searchResults.map((result) => (
+ <button key={result.id} onMouseDown={(event) => event.preventDefault()} onClick={() => selectSearchResult(result)} type="button">
+ <strong>{result.label}</strong>
+ <span>{result.detail}</span>
+ </button>
+ ))
+ ) : (
+ <div className="search-empty">No matches</div>
+ )
+ ) : (
+ <div className="search-empty">Type to search dashboard</div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ <div className="topbar-right">
+ <button
+ className="icon-button has-badge"
+ aria-expanded={notificationsOpen}
+ aria-label="Notifications"
+ onClick={toggleNotifications}
+ type="button"
+ >
+ <Bell size={16} />
+ {unreadNotificationCount > 0 ? <span>{unreadNotificationCount}</span> : null}
+ </button>
+ {notificationsOpen && (
+ <aside className="notification-drawer" aria-label="Notifications">
+ <SectionHeader
+ title="Notifications"
+ action={visibleNotifications.length > 0 ? (
+ <button className="btn btn-compact" onClick={clearNotifications} type="button">
+ Clear all
+ </button>
+ ) : <span className="badge">0</span>}
+ />
+ {visibleNotifications.length > 0 ? (
+ <div className="notification-list">
+ {visibleNotifications.map((item) => (
+ <div className={`notification-item notification-${item.tone}`} key={item.id}>
+ <div className="notification-item-header">
+ <strong>{item.title}</strong>
+ <button className="icon-button icon-button-small" aria-label={`Dismiss ${item.title}`} onClick={() => deleteNotification(item.id)} type="button">
+ <Trash2 size={14} />
+ </button>
+ </div>
+ <p>{item.detail}</p>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <EmptyState text="No notifications." />
+ )}
+ </aside>
+ )}
+ <span className="user-chip">
+ <span className="user-chip-avatar">{user.username.slice(0, 1).toUpperCase()}</span>
+ <span className="user-chip-copy">
+ <strong>{user.username}</strong>
+ <small>{formatRole(user.role)}</small>
+ </span>
+ </span>
+ <button className="btn btn-topbar" onClick={() => void logout()}>
+ <LogOut size={16} /> Logout
+ </button>
+ </div>
+ </header>
+ <div className="content-shell">{children}</div>
+ </main>
+ </div>
+ </DashboardUiProvider>
+ );
+}
+
+export function OverviewPage() {
+ const telemetry = useQuery({ queryKey: ["telemetry"], queryFn: api.telemetry });
+ const monthlyStats = useQuery({ queryKey: ["monthlyStats"], queryFn: api.monthlyStats });
+ const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
+ const snapshot = telemetry.data as TelemetrySnapshot | undefined;
+ const monthlyData = monthlyStats.data as MonthlyFindingStats | undefined;
+ const campaignList = campaigns.data ?? [];
+ const activeCampaigns = campaignList.filter((campaign) => String(campaign.status ?? "").toLowerCase() !== "deleted").length;
+ const findings = typeof monthlyData?.confirmed_findings === "number" ? monthlyData.confirmed_findings : 0;
+ const monthlyTotal = typeof monthlyData?.total === "number" ? monthlyData.total : 0;
+ const monthlySeries = normalizeMonthlySeries(monthlyData?.period, monthlyData?.series);
+ return (
+ <Page
+ title="Overview"
+ >
+ <div className="dashboard-grid">
+ <TelemetryPanel snapshot={snapshot} loading={telemetry.isLoading} confirmedFindings={findings} />
+ <div className="side-stack">
+ <section className="panel p-4">
+ <SectionHeader title="Highlights" />
+ <div className="highlight-list">
+ <HighlightRow label="Active campaigns" value={String(activeCampaigns)} tone="low" detail="available engagements" />
+ <HighlightRow label="Findings" value={String(findings)} tone={findings > 0 ? "medium" : "low"} detail="confirmed observations" />
+ <HighlightRow label="Runtime" value={telemetry.isSuccess ? "Online" : "Pending"} tone={telemetry.isSuccess ? "low" : "medium"} detail="telemetry feed" />
+ </div>
+ </section>
+ <section className="panel p-4">
+ <SectionHeader title="Monthly Statistics" />
+ <div className="monthly-stat">
+ <span>{formatMetric(monthlyTotal)}</span>
+ <small>{monthlyData?.label ?? "Security signals this cycle"}</small>
+ </div>
+ {monthlyStats.isPending ? <p className="text-sm text-slate-500">Loading monthly activity...</p> : null}
+ {monthlyStats.isError ? <p className="text-sm text-slate-500">Monthly activity unavailable.</p> : null}
+ {!monthlyStats.isPending && !monthlyStats.isError && monthlyTotal === 0 ? (
+ <p className="text-sm text-slate-500">No monthly activity yet</p>
+ ) : null}
+ {!monthlyStats.isPending && !monthlyStats.isError && monthlyTotal > 0 && monthlySeries.some((value) => value.count > 0) ? (
+ <SparklineBars values={monthlySeries} />
+ ) : null}
+ </section>
+ </div>
+ </div>
+ <CampaignTable campaigns={campaignList} />
+ </Page>
+ );
+}
+
+function normalizeMonthlySeries(
+ period: string | undefined,
+ series: MonthlyFindingStats["series"] | undefined
+): MonthlyFindingStats["series"] {
+ if (!period || !/^\d{4}-\d{2}$/.test(period)) return [];
+ const [yearText, monthText] = period.split("-");
+ const year = Number(yearText);
+ const month = Number(monthText);
+ if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12) return [];
+
+ const counts = new Map<string, number>();
+ for (const item of series ?? []) {
+ const count = Number(item.count);
+ if (item.date && Number.isFinite(count)) counts.set(item.date, Math.max(0, count));
+ }
+
+ const daysInMonth = new Date(year, month, 0).getDate();
+ return Array.from({ length: daysInMonth }, (_, index) => {
+ const date = `${period}-${String(index + 1).padStart(2, "0")}`;
+ return { date, count: counts.get(date) ?? 0 };
+ });
+}
+
+export function CampaignsPage() {
+ const queryClient = useQueryClient();
+ const { selectedCampaignId: selected, setSelectedCampaignId: setSelected } = useDashboardUi();
+ const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
+ const [name, setName] = useSessionState("ares.dashboard.campaigns.create.name", "");
+ const [client, setClient] = useSessionState("ares.dashboard.campaigns.create.client", "Internal");
+ const [targets, setTargets] = useSessionState("ares.dashboard.campaigns.create.targets", "");
+ const [scope, setScope] = useSessionState("ares.dashboard.campaigns.create.scope", "");
+ const [noiseProfile, setNoiseProfile] = useSessionState("ares.dashboard.campaigns.create.noiseProfile", "stealth");
+ const [createWarning, setCreateWarning] = useState("");
+ const [otherId, setOtherId] = useSessionState("ares.dashboard.campaigns.compareId", "");
+ const [activeTab, setActiveTab] = useSessionState("ares.dashboard.campaigns.tab", "List");
+ const detail = useQuery({
+ queryKey: ["campaign", selected],
+ queryFn: () => api.campaign(selected),
+ enabled: Boolean(selected)
+ });
+ const findings = useQuery({
+ queryKey: ["findings", selected],
+ queryFn: () => api.findings(selected),
+ enabled: Boolean(selected)
+ });
+ const cvss = useQuery({
+ queryKey: ["cvss", selected],
+ queryFn: () => api.cvss(selected),
+ enabled: Boolean(selected)
+ });
+ const diff = useQuery({
+ queryKey: ["diff", selected, otherId],
+ queryFn: () => api.diffCampaign(selected, otherId),
+ enabled: Boolean(selected && otherId)
+ });
+ const create = useMutation({
+ mutationFn: () =>
+ api.createCampaign({
+ name: name.trim(),
+ client: client.trim(),
+ targets: splitLines(targets),
+ scope_cidrs: splitLines(scope),
+ noise_profile: noiseProfile
+ }),
+ onSuccess: (campaign) => {
+ setSelected(campaign.id);
+ setName("");
+ setTargets("");
+ setScope("");
+ setNoiseProfile("stealth");
+ setCreateWarning("");
+ setActiveTab("Scope");
+ void queryClient.invalidateQueries({ queryKey: ["campaigns"] });
+ }
+ });
+ const restore = useMutation({ mutationFn: () => api.restoreVault(selected) });
+ const run = useMutation({
+ mutationFn: () => api.runCampaign(selected, { plan: { stages: [] }, global_params: {}, dry_run: true })
+ });
+ const remove = useMutation({
+ mutationFn: () => api.deleteCampaign(selected),
+ onSuccess: () => {
+ const deleted = selected;
+ setSelected("");
+ setOtherId("");
+ void queryClient.invalidateQueries({ queryKey: ["campaigns"] });
+ void queryClient.removeQueries({ queryKey: ["campaign", deleted] });
+ void queryClient.removeQueries({ queryKey: ["findings", deleted] });
+ void queryClient.removeQueries({ queryKey: ["cvss", deleted] });
+ void queryClient.removeQueries({ queryKey: ["reports", deleted] });
+ }
+ });
+
+ const campaignList = campaigns.data ?? [];
+
+ return (
+ <Page
+ title="Campaigns"
+ actions={<span className="status-pill">{campaignList.length} campaigns</span>}
+ tabs={["List", "Scope", "Findings"]}
+ activeTab={activeTab}
+ onTabChange={setActiveTab}
+ >
+ {activeTab === "List" && (
+ <>
+ <section className="panel p-4">
+ <SectionHeader title="Create Campaign" />
+ <form className="grid gap-3" onSubmit={(e) => {
+ e.preventDefault();
+ if (!e.currentTarget.reportValidity()) return;
+ const invalidScopeEntries = findInvalidScopeEntries(scope);
+ if (invalidScopeEntries.length > 0) {
+ setCreateWarning(`Scope CIDRs must be valid IPv4 CIDR/IP entries. Invalid: ${invalidScopeEntries.slice(0, 3).join(", ")}. Example: 10.0.0.0/24`);
+ return;
+ }
+ setCreateWarning("");
+ create.mutate();
+ }}>
+ <div className="grid gap-3 sm:grid-cols-2">
+ <input className="field" required placeholder="Name" value={name} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setName(e.target.value); }} />
+ <input className="field" required placeholder="Client" value={client} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setClient(e.target.value); }} />
+ </div>
+ <select className="field" value={noiseProfile} onChange={(e) => { setCreateWarning(""); setNoiseProfile(e.target.value); }}>
+ <option value="stealth">Stealth</option>
+ <option value="normal">Normal</option>
+ <option value="aggressive">Aggressive</option>
+ </select>
+ <textarea className="field min-h-20" required placeholder="Targets" value={targets} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setTargets(e.target.value); }} />
+ <textarea className="field min-h-20" required placeholder="Scope CIDRs" value={scope} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setScope(e.target.value); }} />
+ {createWarning && <p className="notice notice-danger">{createWarning}</p>}
+ <button className="btn btn-primary" disabled={create.isPending} type="submit">
+ <ListChecks size={16} /> Create
+ </button>
+ </form>
+ <DataPanel title="Create Error" data={create.error} />
+ </section>
+ <CampaignTable campaigns={campaignList} />
+ <DataPanel title="Campaign Error" data={campaigns.error} />
+ </>
+ )}
+ {activeTab === "Scope" && (
+ <>
+ <section className="panel p-4">
+ <SectionHeader title="Campaign Detail" />
+ <CampaignPicker campaigns={campaignList} value={selected} onChange={setSelected} />
+ <CampaignScopeSummary campaign={detail.data ?? campaigns.data?.find((item) => item.id === selected)} loading={detail.isFetching} />
+ <div className="mt-3 flex flex-wrap gap-2">
+ <button className="btn" disabled={!selected} onClick={() => restore.mutate()}>
+ <ShieldCheck size={16} /> Restore Vault
+ </button>
+ <button className="btn" disabled={!selected} onClick={() => run.mutate()}>
+ <Play size={16} /> Dry Run Plan
+ </button>
+ <button
+ className="btn btn-danger"
+ disabled={!selected || remove.isPending}
+ onClick={() => {
+ if (window.confirm("Delete this campaign and its stored findings, hosts, credentials, and loot?")) {
+ remove.mutate();
+ }
+ }}
+ >
+ <Trash2 size={16} /> Delete
+ </button>
+ <input className="field max-w-xs" placeholder="Compare campaign ID" value={otherId} onChange={(e) => setOtherId(e.target.value)} />
+ </div>
+ </section>
+ <DataPanel title="Delete Error" data={remove.error} />
+ <DataPanel title="Campaign Detail Error" data={detail.error} />
+ <DataPanel title="CVSS Error" data={cvss.error} />
+ <DataPanel title="Campaign Diff Error" data={diff.error} />
+ <DataPanel title="Campaign Detail" data={detail.data} />
+ <DataPanel title="CVSS Summary" data={cvss.data} />
+ <DataPanel title="Diff" data={diff.data} />
+ </>
+ )}
+ {activeTab === "Findings" && (
+ <section className="grid gap-4">
+ <section className="panel p-4">
+ <SectionHeader title="Campaign Findings" />
+ <CampaignPicker campaigns={campaignList} value={selected} onChange={setSelected} />
+ {!selected ? <EmptyState text="Select a campaign to review findings." /> : null}
+ </section>
+ {selected ? <DataPanel title="Findings Error" data={findings.error} /> : null}
+ {selected ? <FindingsTable findings={findings.data ?? []} /> : null}
+ </section>
+ )}
+ </Page>
+ );
+}
+
+function ExecutionChainsPanel({
+ chains,
+ moduleIds,
+ onSelectModule
+}: {
+ chains: ExecutionChain[];
+ moduleIds: Set<string>;
+ onSelectModule: (moduleId: string) => void;
+}) {
+ if (chains.length === 0) {
+ return <EmptyState text="No execution chains are available." />;
+ }
+ return (
+ <section className="grid gap-3">
+ {chains.map((chain) => (
+ <article className="panel p-4" key={chain.id}>
+ <SectionHeader
+ title={chain.title}
+ eyebrow={chain.category}
+ description={chain.description}
+ action={<span className="badge">{chain.stages.length} stages</span>}
+ />
+ <div className="grid gap-3">
+ {chain.stages.map((stage) => (
+ <div className="compact-row" key={`${chain.id}-${stage.order}`}>
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="badge">Step {stage.order}</span>
+ <strong>{stage.title}</strong>
+ {stage.final_goal && <span className="badge badge-low">Final goal</span>}
+ </div>
+ <span className="text-xs font-medium text-slate-500">
+ {stage.uses_previous_output ? "Uses prior output" : "Starts from campaign inputs"}
+ </span>
+ </div>
+ <p className="mt-2 text-sm text-slate-600">{stage.purpose}</p>
+ {stage.module_ids.length > 0 && (
+ <div className="mt-3 flex flex-wrap items-center gap-2">
+ <strong className="text-sm">Run</strong>
+ {stage.module_ids.map((moduleId) => (
+ <button
+ className="btn btn-compact"
+ disabled={!moduleIds.has(moduleId)}
+ key={moduleId}
+ onClick={() => onSelectModule(moduleId)}
+ title={moduleIds.has(moduleId) ? `Open ${moduleId} in the run panel` : "Module is not available in the current catalog"}
+ type="button"
+ >
+ <Play size={13} /> {moduleId}
+ </button>
+ ))}
+ </div>
+ )}
+ <div className="mt-3 grid gap-1 text-xs text-slate-500">
+ <span><strong>Inputs:</strong> {stage.required_inputs.join(", ") || "none"}</span>
+ <span><strong>Produces:</strong> {stage.produces.join("; ") || "none"}</span>
+ <span><strong>Next:</strong> {stage.next_action}</span>
+ </div>
+ </div>
+ ))}
+ </div>
+ </article>
+ ))}
+ </section>
+ );
+}
+
+export function ModulesPage() {
+ const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId } = useDashboardUi();
+ const queryClient = useQueryClient();
+ const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
+ const modules = useQuery({ queryKey: ["modules"], queryFn: api.modules });
+ const executionChains = useQuery({ queryKey: ["executionChains"], queryFn: api.executionChains });
+ const [selectedId, setSelectedId] = useSessionState("ares.dashboard.modules.selectedId", "");
+ const [search, setSearch] = useSessionState("ares.dashboard.modules.search", "");
+ const [category, setCategory] = useSessionState("ares.dashboard.modules.category", "");
+ const [opsec, setOpsec] = useSessionState("ares.dashboard.modules.opsec", "");
+ const [dryRun, setDryRun] = useSessionState("ares.dashboard.modules.dryRun", true);
+ const [confirmed, setConfirmed] = useSessionState("ares.dashboard.modules.confirmed", false);
+ const [params, setParams] = useSessionState<Record<string, unknown>>("ares.dashboard.modules.params", {});
+ const [lastRunRecord, setLastRunRecord] = useSessionState<ModuleRunRecord | null>("ares.dashboard.modules.lastRun", null);
+ const [activeTab, setActiveTab] = useSessionState("ares.dashboard.modules.tab", "Catalog");
+ const previousSelectedId = useRef(selectedId);
+ const campaignDetail = useQuery({
+ queryKey: ["campaign", campaignId],
+ queryFn: () => api.campaign(campaignId),
+ enabled: Boolean(campaignId)
+ });
+ const run = useMutation({
+ mutationFn: () => api.runModule(selectedId, buildModuleRunPayload(campaignId, params, dryRun)),
+ onSuccess: (payload) => {
+ setLastRunRecord({ campaignId, moduleId: selectedId, payload });
+ setActiveTab("Results");
+ if (!dryRun) {
+ void queryClient.invalidateQueries({ queryKey: ["telemetry"] });
+ void queryClient.invalidateQueries({ queryKey: ["monthlyStats"] });
+ }
+ },
+ onError: (error) => {
+ setLastRunRecord({ campaignId, moduleId: selectedId, payload: serializeError(error), isError: true });
+ setActiveTab("Results");
+ if (!dryRun) {
+ void queryClient.invalidateQueries({ queryKey: ["telemetry"] });
+ void queryClient.invalidateQueries({ queryKey: ["monthlyStats"] });
+ }
+ }
+ });
+ const list = useMemo(() => modules.data ?? [], [modules.data]);
+ const moduleIds = useMemo(() => new Set(list.map((item) => item.id)), [list]);
+ const relatedChainsByModule = useMemo(() => {
+ const related = new Map<string, string[]>();
+ for (const chain of executionChains.data ?? []) {
+ for (const stage of chain.stages) {
+ for (const moduleId of stage.module_ids) {
+ const current = related.get(moduleId) ?? [];
+ if (!current.includes(chain.title)) {
+ current.push(chain.title);
+ }
+ related.set(moduleId, current);
+ }
+ }
+ }
+ return related;
+ }, [executionChains.data]);
+ const selected = list.find((item) => item.id === selectedId);
+ const selectedCampaign = campaignDetail.data ?? (campaigns.data ?? []).find((item) => item.id === campaignId);
+ const scopeWarning = moduleScopeWarning(selected, selectedCampaign, params, dryRun);
+ const categories = unique(list.map((item) => item.category || ""));
+ const visible = list.filter((item) => {
+ const haystack = `${item.id} ${item.name ?? ""} ${item.description ?? ""} ${item.mitre ?? ""}`.toLowerCase();
+ return (
+ (!search || haystack.includes(search.toLowerCase())) &&
+ (!category || item.category === category) &&
+ (!opsec || item.opsec_level === opsec)
+ );
+ });
+ const sensitive = isSensitiveModule(selected);
+ const dryRunSupported = selected?.dry_run_supported !== false;
+ const kerberoastTargetMissing = selected?.id === "ad.kerberoast" && !String(params.target_user ?? "").trim();
+ const canRun = Boolean(campaignId && selectedId) && (!sensitive || confirmed) && !run.isPending && (!dryRun || dryRunSupported);
+ const runBlocked = !canRun || Boolean(scopeWarning) || kerberoastTargetMissing;
+ const runHint = moduleRunHint(campaignId, selected, selectedCampaign, sensitive, confirmed, dryRun);
+ const persistedRun = lastRunRecord?.campaignId === campaignId && lastRunRecord.moduleId === selectedId ? lastRunRecord : null;
+ const runResult = (run.data ?? (!persistedRun?.isError ? persistedRun?.payload : undefined)) as Record<string, unknown> | undefined;
+ const runError = run.error ?? (persistedRun?.isError ? persistedRun.payload : undefined);
+
+ useEffect(() => {
+ if (previousSelectedId.current === selectedId) {
+ return;
+ }
+ previousSelectedId.current = selectedId;
+ setParams({});
+ setConfirmed(false);
+ setDryRun(true);
+ }, [selectedId, setConfirmed, setDryRun, setParams]);
+
+ return (
+ <Page
+ title="Modules"
+ actions={<span className="status-pill">{visible.length} shown</span>}
+ tabs={["Catalog", "Execution Chains", "Run Panel", "Results"]}
+ activeTab={activeTab}
+ onTabChange={setActiveTab}
+ >
+ {activeTab === "Catalog" && (
+ <section className="panel p-4">
+ <SectionHeader title="Module Catalog" />
+ <div className="mb-3 grid gap-2 sm:grid-cols-3">
+ <label className="field-with-icon sm:col-span-3">
+ <Search size={15} />
+ <input placeholder="Search modules, MITRE, descriptions" value={search} onChange={(e) => setSearch(e.target.value)} />
+ </label>
+ <select className="field" value={category} onChange={(e) => setCategory(e.target.value)}>
+ <option value="">Category</option>
+ {categories.map((item) => <option key={item} value={item}>{item}</option>)}
+ </select>
+ <select className="field" value={opsec} onChange={(e) => setOpsec(e.target.value)}>
+ <option value="">OPSEC</option>
+ {unique(list.map((item) => item.opsec_level || "")).map((item) => <option key={item} value={item}>{item}</option>)}
+ </select>
+ </div>
+ <div className="grid max-h-[640px] gap-2 overflow-auto">
+ {visible.map((item) => (
+ <button
+ className={`catalog-card ${selectedId === item.id ? "active" : ""}`}
+ key={item.id}
+ onClick={() => {
+ setSelectedId(item.id);
+ setActiveTab("Run Panel");
+ }}
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <div className="font-bold">{item.id}</div>
+ <div className="text-sm text-slate-600">{item.description}</div>
+ </div>
+ <span className={opsecBadge(item.opsec_level)}>{item.opsec_level || "n/a"}</span>
+ </div>
+ <div className="mt-2 flex flex-wrap gap-1">
+ {(item.mitre_list ?? []).slice(0, 4).map((technique) => <span className="badge" key={technique}>{technique}</span>)}
+ {(relatedChainsByModule.get(item.id) ?? []).slice(0, 2).map((chainTitle) => (
+ <span className="badge" key={chainTitle}>Chain: {chainTitle}</span>
+ ))}
+ </div>
+ </button>
+ ))}
+ {visible.length === 0 && (
+ <EmptyState text="No modules match the current search and filters." />
+ )}
+ </div>
+ <DataPanel title="Module Catalog Error" data={modules.error} />
+ </section>
+ )}
+ {activeTab === "Execution Chains" && (
+ <>
+ {executionChains.isPending && <EmptyState text="Loading execution chains..." />}
+ {executionChains.error && <DataPanel title="Execution Chain Error" data={executionChains.error} />}
+ {!executionChains.isPending && !executionChains.error && (
+ <ExecutionChainsPanel
+ chains={executionChains.data ?? []}
+ moduleIds={moduleIds}
+ onSelectModule={(moduleId) => {
+ setSelectedId(moduleId);
+ setActiveTab("Run Panel");
+ }}
+ />
+ )}
+ </>
+ )}
+ {activeTab === "Run Panel" && (
+ <section className="panel p-4">
+ <SectionHeader
+ title="Run Panel"
+ eyebrow={selected ? selected.id : "Select module"}
+ action={selected ? <span className={opsecBadge(selected.opsec_level)}>{selected.opsec_level || "n/a"}</span> : null}
+ />
+ {selected?.description && <p className="text-sm text-slate-600">{selected.description}</p>}
+ {selected && (selected.capability_flags?.length || selected.supported_modes?.length) ? (
+ <div className="mt-2 flex flex-wrap gap-1">
+ {(selected.capability_flags ?? []).map((flag) => <span className="badge" key={flag}>{flag}</span>)}
+ {(selected.supported_modes ?? []).map((mode) => <span className="badge" key={mode}>mode: {mode}</span>)}
+ </div>
+ ) : null}
+ {selected?.dependency_notes?.length ? (
+ <p className="notice mt-3">Dependencies: {selected.dependency_notes.join("; ")}</p>
+ ) : null}
+ {selected && !dryRunSupported && (
+ <p className="notice notice-danger mt-3">Dry-run is unavailable for this module. No preview will be generated.</p>
+ )}
+ <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={setCampaignId} />
+ {campaignId && campaignDetail.isFetching && (
+ <div className="notice mt-3">
+ <Loader2 className="spin" size={16} /> Loading campaign scope...
+ </div>
+ )}
+ <DataPanel title="Campaign Scope Error" data={campaignDetail.error} />
+ {selected ? (
+ <form
+ aria-busy={run.isPending}
+ className="mt-4 grid gap-3"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (runBlocked) {
+ return;
+ }
+ run.mutate();
+ }}
+ >
+ <ParamForm
+ schema={selected.param_schema}
+ values={params}
+ onChange={setParams}
+ requiredOverrides={selected.id === "ad.kerberoast" ? { target_user: true } : undefined}
+ />
+ {runHint && (
+ <p className="notice">
+ {runHint}
+ </p>
+ )}
+ {scopeWarning && (
+ <p className="notice notice-danger">
+ {scopeWarning}
+ </p>
+ )}
+ <label className="toggle-row">
+ <input type="checkbox" checked={dryRun} onChange={(e) => setDryRun(e.target.checked)} />
+ {dryRunSupported ? "Dry run" : "Dry run unavailable"}
+ </label>
+ {sensitive && (
+ <label className="notice notice-danger">
+ <input className="mr-2" type="checkbox" checked={confirmed} onChange={(e) => setConfirmed(e.target.checked)} />
+ Confirm authorized high-noise or sensitive execution
+ </label>
+ )}
+ <button className="btn btn-primary" type="submit" disabled={runBlocked}>
+ {run.isPending ? (
+ <>
+ <Loader2 className="spin" size={16} /> Running...
+ </>
+ ) : (
+ <>
+ <Play size={16} /> Run
+ </>
+ )}
+ </button>
+ {run.isPending && (
+ <div className="notice notice-danger" role="status" aria-live="polite">
+ <Loader2 className="spin shrink-0" size={18} />
+ Module execution in progress. Keep this page open while ARES validates the target and collects results.
+ </div>
+ )}
+ </form>
+ ) : (
+ <EmptyState text="Select a module" />
+ )}
+ </section>
+ )}
+ {activeTab === "Results" && (
+ <section className="panel p-4">
+ <SectionHeader
+ title="Run Results"
+ eyebrow={selected ? selected.id : undefined}
+ action={persistedRun ? <span className={persistedRun.isError ? "badge badge-high" : "badge badge-low"}>{persistedRun.isError ? "error" : "latest"}</span> : null}
+ />
+ {runResult || runError ? (
+ <>
+ <ModuleRunSummary result={runResult} error={runError} />
+ <DataPanel title={runError ? "Run Error" : "Run Result"} data={runError ?? runResult} />
+ </>
+ ) : (
+ <EmptyState text="Run a selected module to see results here." />
+ )}
+ </section>
+ )}
+ </Page>
+ );
+}
+
+export function ReportsPage() {
+ const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId } = useDashboardUi();
+ const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
+ const [format, setFormat] = useSessionState("ares.dashboard.reports.format", "html");
+ const [warning, setWarning] = useState("");
+ const [libraryError, setLibraryError] = useState("");
+ const [lastGenerateResult, setLastGenerateResult] = useSessionState<PersistedResult | null>("ares.dashboard.reports.lastGenerate", null);
+ const [activeTab, setActiveTab] = useSessionState("ares.dashboard.reports.tab", "Generate");
+ const queryClient = useQueryClient();
+ const reports = useQuery({
+ queryKey: ["reports", campaignId],
+ queryFn: () => api.reports(campaignId),
+ enabled: Boolean(campaignId)
+ });
+ const reportItems = reports.data?.reports ?? [];
+ const reportResultKey = `${campaignId}:${format}`;
+ const generate = useMutation({
+ mutationFn: () => api.generateReport(campaignId, format),
+ onSuccess: (payload) => {
+ setLastGenerateResult({ key: reportResultKey, payload });
+ setActiveTab("Library");
+ void queryClient.invalidateQueries({ queryKey: ["reports", campaignId] });
+ },
+ onError: (error) => {
+ setLastGenerateResult({ key: reportResultKey, payload: serializeError(error), isError: true });
+ setActiveTab("Generate");
+ }
+ });
+ const persistedGenerateResult = lastGenerateResult?.key === reportResultKey ? lastGenerateResult : null;
+ const generateIssue = generate.error ?? (persistedGenerateResult?.isError ? persistedGenerateResult.payload : undefined);
+ const pdfIssueHint = format === "pdf" ? pdfFailureHint(generateIssue) : "";
+ const download = useMutation({
+ mutationFn: async (item: ReportItem) => {
+ const blob = await api.downloadReport(campaignId, item.filename);
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = item.filename;
+ document.body.appendChild(link);
+ link.click();
+ link.remove();
+ window.setTimeout(() => URL.revokeObjectURL(url), 1000);
+ }
+ });
+ const deleteReport = useMutation({
+ mutationFn: (item: ReportItem) => api.deleteReport(campaignId, item.filename),
+ onSuccess: (_payload, item) => {
+ queryClient.setQueryData<{ campaign_id: string; reports: ReportItem[] }>(
+ ["reports", campaignId],
+ (current) => current
+ ? {
+ ...current,
+ reports: current.reports.filter((report) => report.filename !== item.filename)
+ }
+ : current
+ );
+ setLibraryError("");
+ },
+ onError: (error) => {
+ setLibraryError(readableError(error, "Report could not be deleted."));
+ }
+ });
+ const clearReports = useMutation({
+ mutationFn: () => api.clearReports(campaignId),
+ onSuccess: () => {
+ queryClient.setQueryData<{ campaign_id: string; reports: ReportItem[] }>(
+ ["reports", campaignId],
+ (current) => current ? { ...current, reports: [] } : current
+ );
+ setLibraryError("");
+ },
+ onError: (error) => {
+ setLibraryError(readableError(error, "Report library could not be cleared."));
+ }
+ });
+ const deleteDisabled = deleteReport.isPending || clearReports.isPending;
+ return (
+ <Page
+ title="Reports"
+ actions={<span className="status-pill">{reports.data?.reports?.length ?? 0} artifacts</span>}
+ tabs={["Generate", "Library"]}
+ activeTab={activeTab}
+ onTabChange={setActiveTab}
+ >
+ {activeTab === "Generate" && (
+ <section className="panel p-4">
+ <SectionHeader
+ title="Generate Report"
+ description="Export findings, scope, and remediation."
+ />
+ <div className="compact-form-row">
+ <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={(id) => { setCampaignId(id); setWarning(""); }} />
+ <select className="field" value={format} onChange={(e) => setFormat(e.target.value)}>
+ {["html", "pdf", "markdown", "json"].map((item) => <option key={item} value={item}>{item}</option>)}
+ </select>
+ <button
+ className="btn btn-primary"
+ disabled={generate.isPending}
+ onClick={() => {
+ if (!campaignId) {
+ setWarning("Campaign is required.");
+ return;
+ }
+ setWarning("");
+ generate.mutate();
+ }}
+ >
+ {generate.isPending ? (
+ <>
+ <Loader2 className="spin" size={16} /> Generating...
+ </>
+ ) : (
+ <>
+ <FileText size={16} /> Generate
+ </>
+ )}
+ </button>
+ </div>
+ {warning && <p className="notice notice-danger mt-3">{warning}</p>}
+ {pdfIssueHint && (
+ <p className="notice notice-danger mt-3">
+ <AlertTriangle size={16} />
+ {pdfIssueHint}
+ </p>
+ )}
+ <DataPanel
+ title={generateIssue ? "Generate Error" : "Generate Result"}
+ data={generate.error ?? generate.data ?? persistedGenerateResult?.payload}
+ />
+ </section>
+ )}
+ {activeTab === "Library" && (
+ <section className="panel table-panel">
+ <SectionHeader
+ title="Report Library"
+ action={campaignId && reportItems.length > 0 ? (
+ <button
+ className="btn btn-danger"
+ disabled={deleteDisabled}
+ onClick={() => {
+ if (!window.confirm(`Delete all ${reportItems.length} report artifacts for this campaign? This cannot be undone.`)) {
+ return;
+ }
+ setLibraryError("");
+ clearReports.mutate();
+ }}
+ >
+ {clearReports.isPending ? (
+ <Loader2 className="spin" size={15} />
+ ) : (
+ <Trash2 size={15} />
+ )}
+ Delete all
+ </button>
+ ) : null}
+ />
+ <div className="table-scroll">
+ <table className="table">
+ <thead><tr><th>Filename</th><th>Format</th><th>Size</th><th>Modified</th><th>Actions</th></tr></thead>
+ <tbody>
+ {reportItems.map((item) => (
+ <tr key={item.filename}>
+ <td className="font-medium text-slate-900">{item.filename}</td>
+ <td><span className="badge">{item.format}</span></td>
+ <td>{formatBytes(item.size_bytes)}</td>
+ <td>{formatReportDate(item.modified_at)}</td>
+ <td>
+ <button className="btn" disabled={download.isPending || deleteDisabled} onClick={() => download.mutate(item)}>
+ <Download size={15} /> Download
+ </button>
+ <button
+ className="btn btn-danger"
+ disabled={deleteDisabled}
+ onClick={() => {
+ if (!window.confirm(`Delete report artifact "${item.filename}"? This cannot be undone.`)) {
+ return;
+ }
+ setLibraryError("");
+ deleteReport.mutate(item);
+ }}
+ >
+ <Trash2 size={15} /> Delete
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ {libraryError && (
+ <p className="notice notice-danger mt-3">
+ <AlertTriangle size={16} />
+ {libraryError}
+ </p>
+ )}
+ <DataPanel title="Report Library Error" data={reports.error} />
+ {campaignId && reportItems.length === 0 && (
+ <EmptyState text="No reports generated for this campaign yet." />
+ )}
+ {!campaignId && <EmptyState text="Select a campaign to list reports." />}
+ <DataPanel title="Download Result" data={download.error} />
+ </section>
+ )}
+ </Page>
+ );
+}
+
+export function TemplatesPage() {
+ const templates = useQuery({ queryKey: ["templates"], queryFn: api.templates });
+ const [name, setName] = useSessionState("ares.dashboard.templates.name", "");
+ const [params, setParams] = useSessionState("ares.dashboard.templates.params", "{}");
+ const [warning, setWarning] = useState("");
+ const [lastPlanResult, setLastPlanResult] = useSessionState<PersistedResult | null>("ares.dashboard.templates.lastPlan", null);
+ const [activeTab, setActiveTab] = useSessionState("ares.dashboard.templates.tab", "Templates");
+ const templatePlanKey = `${name.trim()}:${params}`;
+ const plan = useMutation({
+ mutationFn: () => api.templatePlan(name, safeJson(params)),
+ onSuccess: (payload) => setLastPlanResult({ key: templatePlanKey, payload }),
+ onError: (error) => setLastPlanResult({ key: templatePlanKey, payload: serializeError(error), isError: true })
+ });
+ const selected = (templates.data ?? []).find((item) => item.name === name);
+ const persistedPlanResult = lastPlanResult?.key === templatePlanKey ? lastPlanResult : null;
+ const generated = (plan.data ?? (!persistedPlanResult?.isError ? persistedPlanResult?.payload : undefined)) as TemplatePlanResponse | undefined;
+ const paramsValid = isJsonObject(params);
+ return (
+ <Page
+ title="Templates"
+ actions={<span className="status-pill">{templates.data?.length ?? 0} templates</span>}
+ tabs={["Templates", "Plan Builder"]}
+ activeTab={activeTab}
+ onTabChange={setActiveTab}
+ >
+ <DataPanel title="Template Error" data={templates.error} />
+ {activeTab === "Templates" && (
+ <section className="panel p-4">
+ <SectionHeader
+ title="Campaign Templates"
+ description="Pick a template and generate a plan."
+ />
+ <div className="grid gap-2">
+ {(templates.data ?? []).map((item, index) => {
+ const templateName = String(item.name ?? item.id ?? index);
+ return (
+ <button
+ className={`template-card ${name === templateName ? "active" : ""}`}
+ key={templateName}
+ onClick={() => {
+ setName(templateName);
+ setWarning("");
+ setLastPlanResult(null);
+ plan.reset();
+ setActiveTab("Plan Builder");
+ }}
+ >
+ <span className="font-bold">{templateName}</span>
+ <small>{item.description ?? "Campaign execution template"}</small>
+ <span className="mt-2 flex flex-wrap gap-2">
+ <span className="badge">{item.stages ?? 0} stages</span>
+ <span className="badge">{item.modules ?? 0} modules</span>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </section>
+ )}
+ {activeTab === "Plan Builder" && (
+ <section className="panel p-4">
+ <SectionHeader title="Plan Builder" action={name ? <span className="badge">{name}</span> : null} />
+ <input className="field" placeholder="Template name" value={name} onChange={(e) => {
+ setName(e.target.value);
+ setWarning("");
+ setLastPlanResult(null);
+ }} />
+ {selected ? (
+ <div className="preview-card mt-3">
+ <div className="font-bold">{selected.name}</div>
+ <p className="mt-1 text-sm text-slate-600">{selected.description}</p>
+ <div className="mt-2 flex flex-wrap gap-2">
+ <span className="badge">{selected.stages ?? 0} stages</span>
+ <span className="badge">{selected.modules ?? 0} modules</span>
+ </div>
+ </div>
+ ) : (
+ <EmptyState text="Select a template from the left panel." />
+ )}
+ <label className="mt-3 block text-sm font-semibold">
+ Global parameters
+ <textarea
+ className="field mt-1 min-h-32"
+ value={params}
+ placeholder={'{"target":"127.0.0.1","domain":"corp.local","dc":"10.0.0.5"}'}
+ onChange={(e) => {
+ setParams(e.target.value);
+ setWarning("");
+ }}
+ />
+ </label>
+ <p className="mt-1 text-xs text-slate-500">JSON object. Leave {"{}"} for defaults.</p>
+ {(warning || !paramsValid) && (
+ <p className="notice notice-danger mt-2">
+ {warning || "Global parameters must be a valid JSON object."}
+ </p>
+ )}
+ <button
+ className="btn btn-primary mt-3"
+ disabled={!name || plan.isPending || !paramsValid}
+ onClick={() => {
+ if (!name.trim()) {
+ setWarning("Template name is required.");
+ return;
+ }
+ if (!paramsValid) {
+ setWarning("Global parameters must be a valid JSON object.");
+ return;
+ }
+ setWarning("");
+ plan.mutate();
+ }}
+ >
+ {plan.isPending ? (
+ <>
+ <Loader2 className="spin" size={16} /> Generating...
+ </>
+ ) : (
+ <>
+ <Workflow size={16} /> Generate Plan
+ </>
+ )}
+ </button>
+ <TemplatePlanSummary plan={generated} />
+ <DataPanel
+ title={(plan.error ?? (persistedPlanResult?.isError ? persistedPlanResult.payload : undefined)) ? "Plan Error" : "Plan Details"}
+ data={plan.error ?? plan.data ?? persistedPlanResult?.payload}
+ />
+ </section>
+ )}
+ </Page>
+ );
+}
+
+export function StrategyPage() {
+ const { user } = useAuth();
+ const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId } = useDashboardUi();
+ const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
+ const active = useQuery({ queryKey: ["strategy-active"], queryFn: api.activeStrategy });
+ const [goal, setGoal] = useSessionState("ares.dashboard.strategy.goal", "domain_admin");
+ const [llmBackend, setLlmBackend] = useSessionState("ares.dashboard.strategy.llmBackend", "claude");
+ const [authorizations, setAuthorizations] = useSessionState("ares.dashboard.strategy.authorizations", "");
+ const [lastEngageResult, setLastEngageResult] = useSessionState<PersistedResult | null>("ares.dashboard.strategy.lastEngage", null);
+ const [activeTab, setActiveTab] = useSessionState("ares.dashboard.strategy.tab", "Objective");
+ const strategyResultKey = `${campaignId}:${goal}:${llmBackend}:${authorizations}`;
+ const engage = useMutation({
+ mutationFn: () =>
+ api.engageStrategy({
+ campaign_id: campaignId,
+ goal,
+ llm_backend: llmBackend,
+ max_rounds: 5,
+ authorizations: splitLines(authorizations)
+ }),
+ onSuccess: (payload) => {
+ setLastEngageResult({ key: strategyResultKey, payload });
+ setActiveTab("Result");
+ },
+ onError: (error) => {
+ setLastEngageResult({ key: strategyResultKey, payload: serializeError(error), isError: true });
+ setActiveTab("Result");
+ }
+ });
+ const persistedEngageResult = lastEngageResult?.key === strategyResultKey ? lastEngageResult : null;
+ const allowed = user?.role === "team_lead" || user?.role === "operator";
+ return (
+ <Page
+ title="Strategy"
+ actions={<span className={allowed ? "status-pill status-low" : "status-pill status-high"}>{allowed ? "Authorized" : "Restricted"}</span>}
+ tabs={["Objective", "Active", "Result"]}
+ activeTab={activeTab}
+ onTabChange={setActiveTab}
+ >
+ {activeTab === "Objective" && (
+ <section className="panel p-4">
+ <SectionHeader title="Objective Builder" />
+ <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={setCampaignId} />
+ <select className="field mt-3" value={goal} onChange={(e) => setGoal(e.target.value)}>
+ {["domain_admin", "enterprise_admin", "cloud_admin", "data_exfil", "persistence", "full_compromise"].map((item) => <option key={item} value={item}>{item}</option>)}
+ </select>
+ <select className="field mt-3" value={llmBackend} onChange={(e) => setLlmBackend(e.target.value)}>
+ <option value="claude">Claude / ANTHROPIC_API_KEY</option>
+ <option value="openai">OpenAI / OPENAI_API_KEY</option>
+ <option value="local">Local Ollama</option>
+ </select>
+ <p className="notice mt-2">
+ {strategyBackendHint(llmBackend)}
+ </p>
+ <textarea
+ className="field mt-3 min-h-28"
+ placeholder="Authorization notes, one per line"
+ value={authorizations}
+ onChange={(e) => setAuthorizations(e.target.value)}
+ />
+ {!allowed && (
+ <p className="notice notice-danger mt-2">
+ Strategy engagement requires operator or team lead role.
+ </p>
+ )}
+ {!campaignId && (
+ <p className="notice mt-2">
+ Select a scoped campaign before starting Strategy.
+ </p>
+ )}
+ <button className="btn btn-primary mt-3" disabled={!allowed || !campaignId || engage.isPending} onClick={() => engage.mutate()}>
+ {engage.isPending ? (
+ <>
+ <Loader2 className="spin" size={16} /> Engaging...
+ </>
+ ) : (
+ <>
+ <ShieldCheck size={16} /> Engage
+ </>
+ )}
+ </button>
+ </section>
+ )}
+ {activeTab === "Active" && (
+ <section className="grid gap-4">
+ <section className="panel p-4">
+ <SectionHeader title="Planning Snapshot" />
+ <div className="mini-stat-grid">
+ <MiniStat title="Goal" value={goal} />
+ <MiniStat title="Backend" value={llmBackend} />
+ <MiniStat title="Authorization" value={allowed ? "ready" : "restricted"} />
+ </div>
+ </section>
+ {active.error ? <DataPanel title="Active Strategy Error" data={active.error} /> : active.data ? <DataPanel title="Active" data={active.data} /> : <EmptyState text="No active strategy state is available yet." />}
+ </section>
+ )}
+ {activeTab === "Result" && (
+ <section className="panel p-4">
+ <SectionHeader title="Engagement Result" />
+ {(engage.data ?? engage.error ?? persistedEngageResult?.payload) ? (
+ <DataPanel
+ title={(engage.error ?? (persistedEngageResult?.isError ? persistedEngageResult.payload : undefined)) ? "Engagement Error" : "Engagement Result"}
+ data={engage.data ?? engage.error ?? persistedEngageResult?.payload}
+ />
+ ) : (
+ <EmptyState text="Engage a strategy objective to see results here." />
+ )}
+ </section>
+ )}
+ </Page>
+ );
+}
+
+function apiKeyVisibleIdentifier(key: ApiKeyMeta): string {
+ const prefix = typeof key.key_prefix === "string" && key.key_prefix
+ ? key.key_prefix
+ : typeof key.prefix === "string" && key.prefix
+ ? key.prefix
+ : "";
+ return prefix ? `Prefix: ${prefix}` : `ID: ${key.id.slice(0, 12)}`;
+}
+
+function apiKeyOwnerLabel(key: ApiKeyMeta): string {
+ const owner = key.owner ?? key.owner_username ?? key.username ?? key.role;
+ return typeof owner === "string" && owner.trim() ? owner : "";
+}
+
+function formatDateTime(value: string): string {
+ const date = new Date(value);
+ return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
+}
+
+export function SecurityPage() {
+ const { user } = useAuth();
+ const keys = useQuery({ queryKey: ["api-keys"], queryFn: api.apiKeys });
+ const audit = useQuery({ queryKey: ["security-audit"], queryFn: api.securityAudit, enabled: user?.role === "team_lead" });
+ const users = useQuery({ queryKey: ["security-users"], queryFn: api.users, enabled: user?.role === "team_lead" });
+ const queryClient = useQueryClient();
+ const secretKeyInputRef = useRef<HTMLInputElement | null>(null);
+ const [currentPassword, setCurrentPassword] = useState("");
+ const [newPassword, setNewPassword] = useState("");
+ const [keyName, setKeyName] = useState("");
+ const [scopes, setScopes] = useState("read");
+ const [creatingApiKey, setCreatingApiKey] = useState(false);
+ const [generatedApiKey, setGeneratedApiKey] = useState<GeneratedApiKey | null>(null);
+ const [apiKeyError, setApiKeyError] = useState<unknown>(null);
+ const [copyStatus, setCopyStatus] = useState<ApiKeyCopyStatus>("idle");
+ const [activeTab, setActiveTab] = useSessionState("ares.dashboard.security.tab", "Account");
+ const change = useMutation({
+ mutationFn: () => api.changePassword({ current_password: currentPassword, new_password: newPassword }),
+ onSuccess: () => {
+ setCurrentPassword("");
+ setNewPassword("");
+ }
+ });
+ const remove = useMutation({
+ mutationFn: (id: string) => api.deleteApiKey(id),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: ["api-keys"] });
+ }
+ });
+
+ useEffect(() => {
+ if (generatedApiKey) {
+ secretKeyInputRef.current?.focus();
+ }
+ }, [generatedApiKey]);
+
+ async function handleCreateApiKey(event: FormEvent<HTMLFormElement>): Promise<void> {
+ event.preventDefault();
+ if (!event.currentTarget.reportValidity()) return;
+ setApiKeyError(null);
+ setGeneratedApiKey(null);
+ setCopyStatus("idle");
+ setCreatingApiKey(true);
+ try {
+ const response = await api.createApiKey({ name: keyName, scopes });
+ if (!response.key) {
+ throw new Error("API key created, but the secret was not returned by the API.");
+ }
+ setGeneratedApiKey({
+ id: response.id,
+ key: response.key,
+ note: response.note,
+ prefix: response.prefix ?? response.key_prefix
+ });
+ setKeyName("");
+ void queryClient.invalidateQueries({ queryKey: ["api-keys"] });
+ } catch (error) {
+ setApiKeyError(error);
+ } finally {
+ setCreatingApiKey(false);
+ }
+ }
+
+ async function copyGeneratedKey(): Promise<void> {
+ if (!generatedApiKey?.key) return;
+
+ let copied = false;
+ if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
+ try {
+ await navigator.clipboard.writeText(generatedApiKey.key);
+ copied = true;
+ } catch {
+ copied = false;
+ }
+ }
+
+ if (!copied && secretKeyInputRef.current) {
+ secretKeyInputRef.current.focus();
+ secretKeyInputRef.current.select();
+ try {
+ copied = document.execCommand("copy");
+ } catch {
+ copied = false;
+ }
+ }
+
+ setCopyStatus(copied ? "copied" : "manual");
+ }
+
+ function closeGeneratedKeyModal(): void {
+ setGeneratedApiKey(null);
+ setCopyStatus("idle");
+ }
+
+ return (
+ <Page
+ title="Security"
+ actions={<span className="status-pill">{formatRole(user?.role)}</span>}
+ tabs={["Account", "API Keys", "Audit"]}
+ activeTab={activeTab}
+ onTabChange={setActiveTab}
+ >
+ {activeTab === "Account" && (
+ <section className="panel p-4">
+ <SectionHeader title="Account" />
+ <div className="profile-row mb-3">
+ <span className="profile-avatar-light">{user?.username?.slice(0, 1).toUpperCase() ?? "A"}</span>
+ <div>
+ <div className="font-semibold text-slate-950">{user?.username}</div>
+ <div className="text-xs text-slate-500">{formatRole(user?.role)}</div>
+ </div>
+ </div>
+ <form className="grid gap-2" onSubmit={(event) => {
+ event.preventDefault();
+ if (!event.currentTarget.reportValidity()) return;
+ change.mutate();
+ }}>
+ <input className="field" required type="password" placeholder="Current password" value={currentPassword} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCurrentPassword(e.target.value); }} />
+ <input className="field" required minLength={12} type="password" placeholder="New password" value={newPassword} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setNewPassword(e.target.value); }} />
+ <button className="btn" disabled={change.isPending} type="submit">
+ {change.isPending ? <Loader2 className="spin" size={16} /> : <KeyRound size={16} />}
+ Change Password
+ </button>
+ </form>
+ <DataPanel title="Password Result" data={change.data ?? change.error} />
+ </section>
+ )}
+ {activeTab === "API Keys" && (
+ <section className="panel p-4">
+ <SectionHeader
+ title="API Keys"
+ action={<span className="badge">{keys.data?.length ?? 0} active</span>}
+ description="Metadata only; new secrets are shown once."
+ />
+ <form className="mb-3 grid gap-2 sm:grid-cols-[1fr_120px_auto]" onSubmit={(event) => void handleCreateApiKey(event)}>
+ <input className="field" required placeholder="Name" value={keyName} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setKeyName(e.target.value); }} />
+ <select className="field" value={scopes} onChange={(e) => setScopes(e.target.value)}>
+ <option value="read">read</option>
+ <option value="write">write</option>
+ <option value="admin">admin</option>
+ </select>
+ <button className="btn" disabled={creatingApiKey} type="submit">
+ {creatingApiKey ? <Loader2 className="spin" size={16} /> : <KeyRound size={16} />}
+ Create
+ </button>
+ </form>
+ {(keys.data ?? []).map((key) => (
+ <div className="key-row" key={key.id}>
+ <div className="min-w-0">
+ <div className="font-semibold text-slate-950">{key.name ?? "Unnamed API key"}</div>
+ <div className="mt-1 flex flex-wrap gap-2 text-xs font-semibold text-slate-600">
+ <span className="font-mono">{apiKeyVisibleIdentifier(key)}</span>
+ {key.scopes ? <span className="badge">Scope: {key.scopes}</span> : null}
+ {apiKeyOwnerLabel(key) ? <span>Owner: {apiKeyOwnerLabel(key)}</span> : null}
+ </div>
+ <div className="mt-1 flex flex-wrap gap-2 text-xs text-slate-500">
+ {key.created_at ? <span>Created: {formatDateTime(key.created_at)}</span> : null}
+ {key.expires_at ? <span>Expires: {formatDateTime(key.expires_at)}</span> : <span>No expiry</span>}
+ </div>
+ </div>
+ <button className="btn btn-danger" disabled={remove.isPending} onClick={() => remove.mutate(key.id)}>Delete</button>
+ </div>
+ ))}
+ {(keys.data ?? []).length === 0 && <EmptyState text="No API keys yet." />}
+ <DataPanel title="API Key Error" data={apiKeyError ?? remove.error ?? keys.error} />
+ </section>
+ )}
+ {activeTab === "Audit" && (
+ <section className="grid gap-4">
+ {user?.role === "team_lead" ? (
+ <>
+ {audit.error ? <DataPanel title="Security Audit Error" data={audit.error} /> : audit.data ? <DataPanel title="Security Audit" data={audit.data} /> : <EmptyState text="No security audit data loaded yet." />}
+ {users.error ? <DataPanel title="Users Error" data={users.error} /> : users.data ? <DataPanel title="Users" data={users.data} /> : <EmptyState text="No user records loaded yet." />}
+ </>
+ ) : (
+ <EmptyState text="Audit data is available to team leads." />
+ )}
+ </section>
+ )}
+ {generatedApiKey && (
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/60 p-4">
+ <section
+ aria-labelledby="api-key-dialog-title"
+ aria-modal="true"
+ className="panel w-full max-w-2xl p-5 shadow-2xl"
+ role="dialog"
+ >
+ <div className="mb-4 flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <h2 className="text-lg font-bold text-slate-950" id="api-key-dialog-title">Save your key</h2>
+ <p className="mt-1 text-sm text-slate-600">Copy this secret key now and store it somewhere safe.</p>
+ </div>
+ {generatedApiKey.prefix ? <span className="badge font-mono">{generatedApiKey.prefix}</span> : null}
+ </div>
+ <p className="mb-4 rounded-md border border-amber-200 bg-amber-50 p-3 text-sm font-semibold text-amber-900">
+ This secret key is shown only once. After you close this dialog, ARES will not show the full key again.
+ </p>
+ <label className="block text-sm font-semibold text-slate-800">
+ Secret key
+ <div className="mt-2 grid gap-2 sm:grid-cols-[1fr_auto]">
+ <input
+ aria-label="Generated API key secret"
+ className="field font-mono text-sm"
+ onFocus={(event) => event.currentTarget.select()}
+ readOnly
+ ref={secretKeyInputRef}
+ value={generatedApiKey.key}
+ />
+ <button className="btn" onClick={() => void copyGeneratedKey()} type="button">
+ {copyStatus === "copied" ? <CheckCircle2 size={16} /> : <Copy size={16} />}
+ {copyStatus === "copied" ? "Copied" : "Copy"}
+ </button>
+ </div>
+ </label>
+ {copyStatus === "manual" && (
+ <p className="mt-2 rounded-md border border-slate-200 bg-slate-50 p-3 text-sm text-slate-700">
+ Clipboard access was blocked. The key field is selected; press Ctrl+C to copy it manually.
+ </p>
+ )}
+ {generatedApiKey.note ? <p className="mt-3 text-sm text-slate-600">{generatedApiKey.note}</p> : null}
+ <div className="mt-5 flex justify-end">
+ <button className="btn btn-primary" onClick={closeGeneratedKeyModal} type="button">Done</button>
+ </div>
+ </section>
+ </div>
+ )}
+ </Page>
+ );
+}
+
+export function EdrPage() {
+ const stats = useQuery({ queryKey: ["edr-stats"], queryFn: api.edrStats });
+ const [techniqueId, setTechniqueId] = useSessionState("ares.dashboard.edr.techniqueId", "");
+ const [vendor, setVendor] = useSessionState("ares.dashboard.edr.vendor", "");
+ const [version, setVersion] = useSessionState("ares.dashboard.edr.version", "");
+ const [success, setSuccess] = useSessionState("ares.dashboard.edr.success", false);
+ const [notes, setNotes] = useSessionState("ares.dashboard.edr.notes", "");
+ const [lastReportResult, setLastReportResult] = useSessionState<PersistedResult | null>("ares.dashboard.edr.lastReport", null);
+ const [activeTab, setActiveTab] = useSessionState("ares.dashboard.edr.tab", "Knowledge Base");
+ const edrReportKey = `${techniqueId.trim()}:${vendor.trim()}:${version.trim()}:${success}:${notes.trim()}`;
+ const report = useMutation({
+ mutationFn: () =>
+ api.reportBypass({
+ technique_id: techniqueId.trim(),
+ edr_vendor: vendor.trim(),
+ edr_version: version.trim(),
+ success,
+ notes: notes.trim()
+ }),
+ onSuccess: (payload) => setLastReportResult({ key: edrReportKey, payload }),
+ onError: (error) => setLastReportResult({ key: edrReportKey, payload: serializeError(error), isError: true })
+ });
+ const persistedReportResult = lastReportResult?.key === edrReportKey ? lastReportResult : null;
+ return (
+ <Page
+ title="EDR/OPSEC"
+ actions={<span className={success ? "status-pill status-low" : "status-pill status-medium"}>{success ? "Successful" : "Blocked / detected"}</span>}
+ tabs={["Knowledge Base", "Report Outcome"]}
+ activeTab={activeTab}
+ onTabChange={setActiveTab}
+ >
+ {activeTab === "Knowledge Base" && (
+ <>
+ <section className="panel p-4">
+ <SectionHeader
+ title="Bypass Knowledge Base"
+ description="Track outcomes by technique and vendor."
+ />
+ <div className="mt-3 grid gap-3 md:grid-cols-3">
+ <div className="telemetry-strip">
+ <span>Technique</span>
+ <strong>{String(stats.data?.technique_id ?? "all")}</strong>
+ </div>
+ <div className="telemetry-strip">
+ <span>Vendor</span>
+ <strong>{String(stats.data?.edr_vendor ?? "all")}</strong>
+ </div>
+ <div className="telemetry-strip">
+ <span>Current rate</span>
+ <strong>{formatRate(stats.data?.success_rate)}</strong>
+ </div>
+ </div>
+ <p className="mt-3 text-sm text-slate-600">{String(stats.data?.message ?? "No historical sample loaded yet.")}</p>
+ </section>
+ <DataPanel title="Stats Details" data={stats.data} />
+ <DataPanel title="Stats Error" data={stats.error} />
+ </>
+ )}
+ {activeTab === "Report Outcome" && (
+ <>
+ <section className="panel p-4">
+ <SectionHeader title="Report Outcome" />
+ <form className="grid gap-3" onSubmit={(event) => {
+ event.preventDefault();
+ if (!event.currentTarget.reportValidity()) return;
+ report.mutate();
+ }}>
+ <div className="grid gap-3 md:grid-cols-2">
+ <label className="block text-sm font-semibold">
+ Technique ID <span className="text-red-700">*</span>
+ <input className="field mt-1" required placeholder="edr.bypass_adaptive / amsi-patch-reflection" value={techniqueId} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setTechniqueId(e.target.value); }} />
+ </label>
+ <label className="block text-sm font-semibold">
+ EDR vendor <span className="text-red-700">*</span>
+ <input className="field mt-1" required placeholder="crowdstrike, defender_atp, sentinelone" value={vendor} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setVendor(e.target.value); }} />
+ </label>
+ <label className="block text-sm font-semibold">
+ EDR version
+ <input className="field mt-1" placeholder="optional" value={version} onChange={(e) => setVersion(e.target.value)} />
+ </label>
+ <label className="block text-sm font-semibold">
+ Outcome
+ <select className="field mt-1" value={success ? "success" : "blocked"} onChange={(e) => setSuccess(e.target.value === "success")}>
+ <option value="blocked">Blocked / detected</option>
+ <option value="success">Successful</option>
+ </select>
+ </label>
+ </div>
+ <label className="block text-sm font-semibold">
+ Notes
+ <textarea className="field mt-1 min-h-24" placeholder="Signal observed, lab context, or detection notes" value={notes} onChange={(e) => setNotes(e.target.value)} />
+ </label>
+ <button className="btn btn-primary" disabled={report.isPending} type="submit">
+ {report.isPending ? (
+ <>
+ <Loader2 className="spin" size={16} /> Saving...
+ </>
+ ) : (
+ <>
+ <ShieldAlert size={16} /> Report Outcome
+ </>
+ )}
+ </button>
+ </form>
+ </section>
+ <DataPanel
+ title={(report.error ?? (persistedReportResult?.isError ? persistedReportResult.payload : undefined)) ? "Outcome Error" : "Outcome Result"}
+ data={report.data ?? report.error ?? persistedReportResult?.payload}
+ />
+ </>
+ )}
+ </Page>
+ );
+}
+
+export function LivePage() {
+ const {
+ selectedCampaignId,
+ setSelectedCampaignId,
+ liveCampaignId,
+ setLiveCampaignId,
+ liveConnected,
+ setLiveConnected,
+ liveEvents,
+ clearLiveEvents
+ } = useDashboardUi();
+ const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
+ const campaignId = liveCampaignId || selectedCampaignId;
+ const [activeTab, setActiveTab] = useSessionState("ares.dashboard.live.tab", "Stream");
+ const streamEvents = liveEvents.slice(0, 10);
+
+ return (
+ <Page
+ title="Live Events"
+ actions={<span className={liveConnected ? "status-pill status-low" : "status-pill"}>{liveConnected ? "Listening" : "Offline"}</span>}
+ tabs={["Stream", "Buffer"]}
+ activeTab={activeTab}
+ onTabChange={setActiveTab}
+ >
+ {activeTab === "Stream" && (
+ <>
+ <div className="panel p-4">
+ <SectionHeader
+ title="Campaign Event Stream"
+ action={<span className="badge">{liveEvents.length} buffered</span>}
+ description="Watch selected campaign events."
+ />
+ <CampaignPicker
+ campaigns={campaigns.data ?? []}
+ value={campaignId}
+ onChange={(id) => {
+ setLiveCampaignId(id);
+ setSelectedCampaignId(id);
+ }}
+ />
+ <div className="mt-3 flex flex-wrap items-center gap-2">
+ <button className="btn btn-primary" disabled={!campaignId || liveConnected} onClick={() => {
+ if (!liveCampaignId && campaignId) {
+ setLiveCampaignId(campaignId);
+ }
+ setLiveConnected(true);
+ }}>
+ <Radio size={16} /> {liveConnected ? "Connected" : "Connect"}
+ </button>
+ {liveConnected && (
+ <button className="btn" onClick={() => setLiveConnected(false)}>
+ Disconnect
+ </button>
+ )}
+ <span className={liveConnected ? "badge badge-low" : "badge"}>{liveConnected ? "listening" : "offline"}</span>
+ </div>
+ </div>
+ <section className="panel p-4">
+ <SectionHeader title="Current Stream" action={<span className="badge">{streamEvents.length} newest</span>} />
+ {streamEvents.length > 0 ? (
+ <div className="grid gap-2">
+ {streamEvents.map((event, index) => (
+ <LiveEventCard event={event} index={index} key={index} />
+ ))}
+ </div>
+ ) : (
+ <EmptyState text={liveConnected ? "Connected. Waiting for events." : "Select a campaign and connect."} />
+ )}
+ </section>
+ </>
+ )}
+ {activeTab === "Buffer" && (
+ <section className="panel p-4">
+ <SectionHeader
+ title="Buffered Events"
+ action={liveEvents.length > 0 ? <button className="btn" onClick={clearLiveEvents}>Clear Events</button> : <span className="badge">0 retained</span>}
+ />
+ {liveEvents.length > 0 ? (
+ <div className="grid gap-2">
+ {liveEvents.map((event, index) => (
+ <LiveEventCard event={event} index={index} key={index} />
+ ))}
+ </div>
+ ) : (
+ <EmptyState text="No events retained in the buffer." />
+ )}
+ </section>
+ )}
+ </Page>
+ );
+}
+
+function Page({
+ title,
+ actions,
+ tabs,
+ activeTab,
+ onTabChange,
+ children
+}: {
+ title: string;
+ actions?: ReactNode;
+ tabs?: string[];
+ activeTab?: string;
+ onTabChange?: (tab: string) => void;
+ children: ReactNode;
+}) {
+ const [fallbackTab, setFallbackTab] = useState(tabs?.[0] ?? "");
+ const meta = pageMeta[title] ?? {
+ icon: LayoutDashboard,
+ eyebrow: "ARES",
+ description: "Security dashboard workspace."
+ };
+ const Icon = meta.icon;
+ const selectedTab = activeTab ?? fallbackTab;
+ const setTab = onTabChange ?? setFallbackTab;
+
+ function handleTabKeyDown(event: KeyboardEvent<HTMLDivElement>) {
+ if (!tabs || tabs.length === 0 || !["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) {
+ return;
+ }
+ event.preventDefault();
+ const currentIndex = Math.max(0, tabs.indexOf(selectedTab));
+ if (event.key === "Home") {
+ setTab(tabs[0]);
+ return;
+ }
+ if (event.key === "End") {
+ setTab(tabs[tabs.length - 1]);
+ return;
+ }
+ const offset = event.key === "ArrowRight" ? 1 : -1;
+ const nextIndex = (currentIndex + offset + tabs.length) % tabs.length;
+ setTab(tabs[nextIndex]);
+ }
+
+ return (
+ <div className="page">
+ <section className="page-header">
+ <div className="page-heading">
+ <span className="page-icon">
+ <Icon size={19} />
+ </span>
+ <div>
+ <p className="page-eyebrow">{meta.eyebrow}</p>
+ <h1>{title}</h1>
+ <p>{meta.description}</p>
+ </div>
+ </div>
+ {actions ? <div className="page-actions">{actions}</div> : null}
+ </section>
+ {tabs ? (
+ <div className="page-tabs" aria-label={`${title} sections`} onKeyDown={handleTabKeyDown} role="tablist">
+ {tabs.map((tab) => (
+ <button
+ aria-selected={tab === selectedTab}
+ className={tab === selectedTab ? "active" : ""}
+ key={tab}
+ onClick={() => setTab(tab)}
+ role="tab"
+ tabIndex={tab === selectedTab ? 0 : -1}
+ type="button"
+ >
+ {tab}
+ </button>
+ ))}
+ </div>
+ ) : null}
+ <div className="page-content">{children}</div>
+ </div>
+ );
+}
+
+function SectionHeader({
+ title,
+ eyebrow,
+ description,
+ action
+}: {
+ title: string;
+ eyebrow?: string;
+ description?: string;
+ action?: ReactNode;
+}) {
+ return (
+ <div className="section-header">
+ <div>
+ {eyebrow ? <p className="section-eyebrow">{eyebrow}</p> : null}
+ <h2>{title}</h2>
+ {description ? <p>{description}</p> : null}
+ </div>
+ {action ? <div className="section-action">{action}</div> : null}
+ </div>
+ );
+}
+
+function MiniStat({ title, value, detail, icon }: { title: string; value: string; detail?: string; icon?: ReactNode }) {
+ return (
+ <div className="mini-stat">
+ <div>
+ <span>{title}</span>
+ <strong>{value}</strong>
+ {detail ? <small>{detail}</small> : null}
+ </div>
+ {icon ? <div className="mini-stat-icon">{icon}</div> : null}
+ </div>
+ );
+}
+
+function HighlightRow({
+ label,
+ value,
+ detail,
+ tone = "neutral"
+}: {
+ label: string;
+ value: string;
+ detail: string;
+ tone?: "low" | "medium" | "high" | "neutral";
+}) {
+ return (
+ <div className="highlight-row">
+ <div>
+ <strong>{label}</strong>
+ <span>{detail}</span>
+ </div>
+ <span className={`highlight-value highlight-${tone}`}>{value}</span>
+ </div>
+ );
+}
+
+function SparklineBars({ values }: { values: MonthlyFindingStats["series"] }) {
+ const max = Math.max(...values.map((value) => value.count), 1);
+ const labelDays = new Set([1, 7, 14, 21, 28, values.length]);
+ return (
+ <>
+ <div className="sparkline" aria-hidden="true">
+ {values.map((value) => (
+ <span
+ key={value.date}
+ title={`${formatMonthlyDate(value.date)} — ${value.count} ${value.count === 1 ? "security signal" : "security signals"}`}
+ style={{ height: value.count > 0 ? `${Math.max(6, (value.count / max) * 100)}%` : "0%" }}
+ />
+ ))}
+ </div>
+ <div className="sparkline-axis" aria-hidden="true">
+ {values.map((value) => {
+ const day = Number(value.date.slice(-2));
+ return <span key={value.date}>{labelDays.has(day) ? formatMonthlyDate(value.date) : null}</span>;
+ })}
+ </div>
+ </>
+ );
+}
+
+function formatMonthlyDate(date: string): string {
+ const [year, month, day] = date.split("-").map(Number);
+ return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", timeZone: "UTC" }).format(
+ new Date(Date.UTC(year, month - 1, day))
+ );
+}
+
+function metricNumber(map: TelemetryMetricMap | undefined, key: string): number {
+ return metricNumberOrNull(map, key) ?? 0;
+}
+
+function metricNumberOrNull(map: TelemetryMetricMap | undefined, key: string): number | null {
+ const value = map?.[key];
+ if (typeof value === "number" && Number.isFinite(value)) return value;
+ if (typeof value === "string" && value.trim()) {
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : null;
+ }
+ return null;
+}
+
+function formatMetric(value: number, suffix = ""): string {
+ if (!Number.isFinite(value)) return `0${suffix}`;
+ if (Number.isInteger(value)) return `${value}${suffix}`;
+ return `${value.toFixed(1)}${suffix}`;
+}
+
+function formatRate(value: unknown): string {
+ if (typeof value !== "number" || !Number.isFinite(value)) {
+ return "not enough data";
+ }
+ const normalized = value <= 1 ? value * 100 : value;
+ return `${Math.round(normalized)}%`;
+}
+
+function formatTimestamp(value: number | undefined): string {
+ if (!value) return "No runtime sample yet";
+ return new Date(value * 1000).toLocaleString();
+}
+
+function formatBytes(value: number): string {
+ if (!Number.isFinite(value)) return "n/a";
+ if (value < 1024) return `${value} B`;
+ const units = ["KB", "MB", "GB", "TB"];
+ let size = value / 1024;
+ let unitIndex = 0;
+ while (size >= 1024 && unitIndex < units.length - 1) {
+ size /= 1024;
+ unitIndex += 1;
+ }
+ return `${size >= 10 ? size.toFixed(0) : size.toFixed(1)} ${units[unitIndex]}`;
+}
+
+function formatReportDate(value: number): string {
+ if (!Number.isFinite(value)) return "n/a";
+ const timestamp = value > 10_000_000_000 ? value : value * 1000;
+ return new Date(timestamp).toLocaleString();
+}
+
+function TelemetryPanel({ snapshot, loading, confirmedFindings }: { snapshot?: TelemetrySnapshot; loading: boolean; confirmedFindings: number }) {
+ const total = metricNumber(snapshot?.modules, "total");
+ const success = metricNumber(snapshot?.modules, "success");
+ const failed = metricNumber(snapshot?.modules, "failed");
+ const findings = confirmedFindings;
+ const successRate = total > 0 ? Math.round((success / total) * 100) : null;
+ const errorRate = total > 0 ? Math.min(100, Math.round(metricNumber(snapshot?.modules, "error_rate") * 100)) : null;
+ const p95 = metricNumberOrNull(snapshot?.latency_ms, "p95");
+ const queueDepth = metricNumber(snapshot?.queue, "depth");
+ const activeWorkers = metricNumber(snapshot?.workers, "active");
+ const unhealthyWorkers = metricNumber(snapshot?.workers, "unhealthy");
+ const hostsDiscovered = metricNumber(snapshot?.hosts, "discovered");
+ const hostsOwned = metricNumberOrNull(snapshot?.hosts, "owned");
+ const tasksPerMin = metricNumberOrNull(snapshot?.throughput, "tasks_per_min");
+ const workerTotal = activeWorkers + unhealthyWorkers;
+ const workerCapacity = workerTotal > 0 ? Math.round((activeWorkers / workerTotal) * 100) : null;
+ const hostsAvailable = snapshot?.hosts?.available === true;
+ const hostOwnership = hostsAvailable && hostsDiscovered > 0 && hostsOwned !== null
+ ? Math.round((hostsOwned / hostsDiscovered) * 100)
+ : null;
+ const throughputValue = tasksPerMin === null ? "n/a" : `${formatMetric(tasksPerMin)}/min`;
+ const latencyDetail = p95 === null ? "no run timing data" : `${formatMetric(p95, " ms")} p95`;
+
+ return (
+ <section className="panel telemetry-panel">
+ <SectionHeader
+ title="Telemetry Report"
+ description={loading ? "Waiting for metrics." : `Last sample: ${formatTimestamp(snapshot?.timestamp)}`}
+ action={<span className={snapshot ? "badge badge-low" : "badge badge-medium"}>{snapshot ? "online" : "pending"}</span>}
+ />
+
+ <div className="telemetry-chart" aria-label="Runtime telemetry chart">
+ <TelemetryBar label="Success rate" value={successRate} />
+ <TelemetryBar label="Error rate" value={errorRate} tone="danger" />
+ <TelemetryBar label="Worker capacity" value={workerCapacity} />
+ <TelemetryBar label="Host ownership" value={hostOwnership} tone={hostsOwned !== null && hostsOwned > 0 ? "danger" : "ok"} />
+ </div>
+
+ <div className="mini-stat-grid mt-4">
+ <MiniStat title="Module runs" value={formatMetric(total)} detail={`${success} success / ${failed} failed`} icon={<Database size={16} />} />
+ <MiniStat title="Findings" value={formatMetric(findings)} icon={<ShieldAlert size={16} />} />
+ <MiniStat title="Queue" value={formatMetric(queueDepth)} detail={`${activeWorkers} active workers`} icon={<Layers size={16} />} />
+ <MiniStat title="Throughput" value={throughputValue} detail={latencyDetail} icon={<TrendingUp size={16} />} />
+ </div>
+
+ <div className="telemetry-footer">
+ <span><Target size={14} /> Scope: {snapshot?.campaign_id ? `campaign ${snapshot.campaign_id}` : "global"}</span>
+ <span>{hostsAvailable ? `${hostsDiscovered} discovered / ${hostsOwned ?? 0} owned hosts` : "Host ownership unavailable"}</span>
+ <span>{workerTotal === 0 ? "no worker sample" : unhealthyWorkers === 0 ? "workers healthy" : `${unhealthyWorkers} unhealthy workers`}</span>
+ </div>
+
+ <details className="advanced-details">
+ <summary>Details</summary>
+ <pre className="json-box">{JSON.stringify(snapshot ?? {}, null, 2)}</pre>
+ </details>
+ </section>
+ );
+}
+
+function TelemetryBar({ label, value, tone = "ok" }: { label: string; value: number | null; tone?: "ok" | "danger" }) {
+ const clamped = value === null ? 0 : Math.max(0, Math.min(100, value));
+ return (
+ <div className="telemetry-bar" title={value === null ? "Not enough telemetry data" : undefined}>
+ <span>{label}</span>
+ <div className="telemetry-bar-track">
+ <div className={tone === "danger" ? "telemetry-bar-fill danger" : "telemetry-bar-fill"} style={{ width: `${clamped}%` }} />
+ </div>
+ <strong>{value === null ? "n/a" : `${clamped}%`}</strong>
+ </div>
+ );
+}
+
+function DataPanel({ title, data }: { title: string; data: unknown }) {
+ if (!data) {
+ return null;
+ }
+ const isError = data instanceof Error || data instanceof ApiError;
+ return (
+ <section className="panel detail-panel">
+ <SectionHeader
+ title={title}
+ eyebrow={isError ? "Needs attention" : undefined}
+ action={isError ? <span className="badge badge-high">error</span> : <span className="badge">details</span>}
+ />
+ {isError ? (
+ <p className="notice notice-danger">
+ <AlertTriangle size={16} />
+ {data instanceof ApiError ? String(data.detail) : data instanceof Error ? data.message : "The request failed."}
+ </p>
+ ) : null}
+ <details className="advanced-details">
+ <summary>Details</summary>
+ <pre className="json-box">{JSON.stringify(serializeError(data), null, 2)}</pre>
+ </details>
+ </section>
+ );
+}
+
+function ModuleRunSummary({ result, error }: { result?: Record<string, unknown>; error?: unknown }) {
+ if (!result && !error) {
+ return null;
+ }
+ if (error) {
+ return (
+ <section className="inline-summary mt-4">
+ <SectionHeader title="Execution Summary" action={<span className="badge badge-high">failed</span>} />
+ <p className="notice notice-danger">
+ <AlertTriangle size={16} />
+ {error instanceof ApiError ? String(error.detail) : error instanceof Error ? error.message : "Module run failed."}
+ </p>
+ </section>
+ );
+ }
+
+ const findings = Array.isArray(result?.findings) ? result.findings as Finding[] : [];
+ const validationCount = Array.isArray(result?.validation_results) ? result.validation_results.length : 0;
+ const duration = typeof result?.duration_ms === "number" ? formatMetric(result.duration_ms, " ms") : "n/a";
+ const status = String(result?.status ?? "unknown");
+ const moduleId = String(result?.module_id ?? "module");
+ const runError = typeof result?.error === "string" ? result.error : "";
+ const outcome = String(result?.outcome ?? "");
+ const outcomeMessage = String(result?.outcome_message ?? "");
+ const displayOutcome = outcome || status;
+ const dryRun = result?.dry_run === true || status.startsWith("dry_run_");
+ const warnings = Array.isArray(result?.warnings) ? result.warnings.map(String) : [];
+ const nextSteps = Array.isArray(result?.operator_next_steps) ? result.operator_next_steps.map(String) : [];
+ const hasOutcomeError = ["operator_error", "dependency_error", "network_error", "unsupported", "module_error", "failed", "timeout"].includes(displayOutcome);
+ const emptyText = dryRun
+ ? "No live execution was performed."
+ : outcome === "completed_no_findings"
+ ? "No confirmed findings. The module completed without observing an exploitable condition."
+ : runError
+ ? "No findings recorded because execution failed."
+ : "No findings returned.";
+
+ return (
+ <section className="inline-summary mt-4">
+ <SectionHeader
+ title="Execution Summary"
+ action={(
+ <div className="flex flex-wrap gap-2">
+ <span className="badge">{moduleId}</span>
+ <span className={hasOutcomeError ? "badge badge-high" : displayOutcome === "confirmed_findings" || displayOutcome === "completed_no_findings" || displayOutcome === "dry_run_ok" || displayOutcome === "done" ? "badge badge-low" : "badge badge-medium"}>{displayOutcome}</span>
+ <span className="badge">{duration}</span>
+ </div>
+ )}
+ />
+ {(outcomeMessage || runError) && (
+ <p className={`notice mb-3 ${hasOutcomeError || runError ? "notice-danger" : ""}`}>
+ {hasOutcomeError || runError ? <AlertTriangle size={16} /> : null}
+ {outcomeMessage || runError}
+ </p>
+ )}
+ {warnings.length > 0 && (
+ <div className="notice mb-3">
+ <strong>{dryRun ? "Dry-run notes" : "Notes"}</strong>
+ <ul className="mt-1 list-disc pl-5">{warnings.map((warning) => <li key={warning}>{warning}</li>)}</ul>
+ </div>
+ )}
+ {nextSteps.length > 0 && (
+ <div className="notice mb-3">
+ <strong>Next steps</strong>
+ <ul className="mt-1 list-disc pl-5">{nextSteps.map((step) => <li key={step}>{step}</li>)}</ul>
+ </div>
+ )}
+ <div className="mini-stat-grid mb-3">
+ <MiniStat title="Findings" value={String(findings.length)} detail="returned observations" />
+ <MiniStat title="Validation" value={String(validationCount)} detail="post-run checks" />
+ <MiniStat title="Duration" value={duration} detail="server execution" />
+ </div>
+ {findings.length > 0 ? (
+ <div className="compact-list">
+ {findings.map((finding, index) => (
+ <div className="compact-row" key={finding.id ?? index}>
+ <div className="flex flex-wrap items-start justify-between gap-2">
+ <div>
+ <div className="font-bold">{finding.title ?? `Finding ${index + 1}`}</div>
+ <div className="mt-1 text-sm text-slate-600">{String(finding.description ?? "")}</div>
+ </div>
+ <span className={opsecBadge(finding.severity)}>{finding.severity ?? "info"}</span>
+ </div>
+ <div className="mt-2 flex flex-wrap gap-2">
+ {finding.host && <span className="badge">Host: {finding.host}</span>}
+ {finding.mitre_technique && <span className="badge">{finding.mitre_technique}</span>}
+ {typeof finding.confidence === "number" && <span className="badge">Confidence: {formatRate(finding.confidence)}</span>}
+ </div>
+ {finding.remediation ? (
+ <p className="mt-2 text-sm text-slate-700">
+ <strong>Remediation:</strong> {String(finding.remediation)}
+ </p>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ ) : (
+ <EmptyState text={emptyText} />
+ )}
+ </section>
+ );
+}
+
+function TemplatePlanSummary({ plan }: { plan?: TemplatePlanResponse }) {
+ const stages = plan?.plan?.stages ?? [];
+ if (!plan || stages.length === 0) {
+ return null;
+ }
+ const moduleCount = stages.reduce((total, stage) => total + (stage.modules?.length ?? 0), 0);
+ return (
+ <section className="inline-summary mt-4">
+ <SectionHeader
+ title={plan.template ?? "Generated Plan"}
+ description={plan.description}
+ action={(
+ <div className="flex flex-wrap gap-2">
+ <span className="badge">{stages.length} stages</span>
+ <span className="badge">{moduleCount} modules</span>
+ </div>
+ )}
+ />
+ <div className="compact-list">
+ {stages.map((stage, index) => (
+ <div className="compact-row" key={`${stage.name ?? "stage"}-${index}`}>
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span className="font-bold">{index + 1}. {stage.name ?? "stage"}</span>
+ <span className="text-xs font-semibold text-slate-500">{stage.modules?.length ?? 0} modules</span>
+ </div>
+ <div className="mt-2 flex flex-wrap gap-1">
+ {(stage.modules ?? []).map((moduleId) => <span className="badge" key={moduleId}>{moduleId}</span>)}
+ </div>
+ </div>
+ ))}
+ </div>
+ <p className="mt-3 text-sm text-slate-500">Ready for campaign dry-run structure.</p>
+ </section>
+ );
+}
+
+function CampaignScopeSummary({ campaign, loading }: { campaign?: Campaign; loading?: boolean }) {
+ if (loading) {
+ return (
+ <div className="detail-summary mt-3">
+ <div className="loading-row">
+ <Loader2 className="spin" size={16} /> Loading campaign...
+ </div>
+ </div>
+ );
+ }
+ if (!campaign) {
+ return <EmptyState text="Select a campaign to review scope and findings." />;
+ }
+ const targets = campaignTargets(campaign);
+ const scope = campaignScopeEntries(campaign);
+ return (
+ <div className="detail-summary mt-3">
+ <div className="mb-3 flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <h3 className="text-base font-bold">{campaign.name}</h3>
+ <p className="text-sm text-slate-600">{campaign.client ?? "No client"} &middot; {campaign.status ?? "created"}</p>
+ </div>
+ <span className="badge">{campaign.operator ?? "operator"}</span>
+ </div>
+ <div className="mini-stat-grid">
+ <MiniStat title="Targets" value={String(targets.length)} detail={targets.slice(0, 3).join(", ") || "none declared"} />
+ <MiniStat title="Scope CIDRs" value={String(scope.length)} detail={scope.slice(0, 3).join(", ") || "none declared"} />
+ <MiniStat title="Noise Profile" value={String(campaign.noise_profile ?? "stealth")} detail="OPSEC guardrail" />
+ <MiniStat title="Campaign ID" value={campaign.id.slice(0, 8)} detail="API/report key" />
+ </div>
+ </div>
+ );
+}
+
+function CampaignPicker({
+ campaigns,
+ value,
+ onChange
+}: {
+ campaigns: Campaign[];
+ value: string;
+ onChange: (id: string) => void;
+}) {
+ return (
+ <select className="field" value={value} onChange={(event) => onChange(event.target.value)}>
+ <option value="">Select campaign</option>
+ {campaigns.map((campaign) => (
+ <option key={campaign.id} value={campaign.id}>
+ {campaign.name || campaign.id}
+ </option>
+ ))}
+ </select>
+ );
+}
+
+function CampaignTable({ campaigns }: { campaigns: Campaign[] }) {
+ return (
+ <section className="panel table-panel">
+ <SectionHeader
+ title="Campaign Activity"
+ action={<span className="badge">{campaigns.length} records</span>}
+ />
+ {campaigns.length > 0 ? (
+ <div className="table-scroll">
+ <table className="table">
+ <thead><tr><th>#</th><th>Name</th><th>Client</th><th>Status</th><th>Noise</th><th>Operator</th></tr></thead>
+ <tbody>
+ {campaigns.map((campaign, index) => (
+ <tr key={campaign.id}>
+ <td className="muted-cell">#{String(index + 1).padStart(2, "0")}</td>
+ <td>
+ <div className="font-medium text-slate-950">{campaign.name}</div>
+ <div className="mt-1 flex items-center gap-1 text-xs text-slate-500"><Eye size={13} /> {campaign.id.slice(0, 12)}</div>
+ </td>
+ <td>{campaign.client || "Internal"}</td>
+ <td><span className={statusBadge(campaign.status)}>{campaign.status ?? "created"}</span></td>
+ <td><span className={opsecBadge(campaign.noise_profile)}>{campaign.noise_profile ?? "stealth"}</span></td>
+ <td>{campaign.operator || "operator"}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ ) : (
+ <EmptyState text="No campaigns yet. Create one from the Campaigns page to unlock modules, reports, and graph views." />
+ )}
+ </section>
+ );
+}
+
+function FindingsTable({ findings }: { findings: any[] }) {
+ return (
+ <section className="panel table-panel">
+ <SectionHeader
+ title="Findings"
+ action={<span className="badge">{findings.length} records</span>}
+ />
+ {findings.length > 0 ? (
+ <div className="table-scroll">
+ <table className="table">
+ <thead><tr><th>Severity</th><th>Title</th><th>Module</th><th>MITRE</th><th>Host</th></tr></thead>
+ <tbody>
+ {findings.map((finding, index) => (
+ <tr key={finding.id ?? index}>
+ <td><span className={opsecBadge(finding.severity)}>{finding.severity ?? "info"}</span></td>
+ <td className="font-medium text-slate-950">{finding.title ?? `Finding ${index + 1}`}</td>
+ <td>{finding.module_id ?? "n/a"}</td>
+ <td>{finding.mitre_technique ?? "n/a"}</td>
+ <td>{finding.host ?? "n/a"}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ ) : (
+ <EmptyState text="No findings recorded for this campaign." />
+ )}
+ </section>
+ );
+}
+
+function LiveEventCard({ event, index }: { event: unknown; index: number }) {
+ const record = event && typeof event === "object" && !Array.isArray(event) ? event as Record<string, unknown> : null;
+ const type = String(record?.type ?? record?.event ?? record?.name ?? `event.${index + 1}`);
+ const message = String(record?.message ?? record?.status ?? record?.detail ?? "Campaign event received.");
+ const campaign = typeof record?.campaign_id === "string" ? record.campaign_id : "";
+ const moduleId = typeof record?.module_id === "string" ? record.module_id : "";
+ const created = typeof record?.timestamp === "number"
+ ? formatTimestamp(record.timestamp)
+ : typeof record?.created_at === "string"
+ ? formatDateTime(record.created_at)
+ : "";
+
+ return (
+ <article className="event-card">
+ <div className="event-marker" aria-hidden="true" />
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-2">
+ <strong>{type}</strong>
+ {campaign ? <span className="badge">Campaign {campaign.slice(0, 8)}</span> : null}
+ {moduleId ? <span className="badge">{moduleId}</span> : null}
+ </div>
+ <p>{message}</p>
+ {created ? <small>{created}</small> : null}
+ <details className="advanced-details compact">
+ <summary>Details</summary>
+ <pre className="json-box">{JSON.stringify(serializeError(event), null, 2)}</pre>
+ </details>
+ </div>
+ </article>
+ );
+}
+
+function ParamForm({
+ schema,
+ values,
+ onChange,
+ requiredOverrides
+}: {
+ schema: ModuleMeta["param_schema"];
+ values: Record<string, unknown>;
+ onChange: (values: Record<string, unknown>) => void;
+ requiredOverrides?: Record<string, boolean>;
+}) {
+ const entries = Object.entries(schema ?? {});
+ if (entries.length === 0) {
+ return <EmptyState text="No parameters" />;
+ }
+ return (
+ <div className="grid gap-3">
+ {entries.map(([name, field]) => {
+ const required = requiredOverrides?.[name] ?? field.required;
+ const inputField = required === field.required ? field : { ...field, required };
+ const description = fieldDescription(name, field);
+ return (
+ <label className="block text-sm font-semibold" key={name}>
+ <span className="flex items-center gap-2">
+ <span>
+ {name}
+ {required && <span className="text-red-700"> *</span>}
+ </span>
+ {!required && <span className="badge">optional</span>}
+ </span>
+ <ParamInput
+ name={name}
+ field={inputField}
+ value={values[name]}
+ onChange={(value) => {
+ const next = { ...values };
+ if (!required && isEmptyParamValue(value)) {
+ delete next[name];
+ } else {
+ next[name] = value;
+ }
+ onChange(next);
+ }}
+ />
+ {description && <span className="mt-1 block text-xs text-slate-600">{description}</span>}
+ {fieldDefaultHint(field) && (
+ <span className="mt-1 block text-xs font-medium text-slate-500">{fieldDefaultHint(field)}</span>
+ )}
+ </label>
+ );
+ })}
+ </div>
+ );
+}
+
+function ParamInput({
+ name,
+ field,
+ value,
+ onChange
+}: {
+ name: string;
+ field: ParamField;
+ value: unknown;
+ onChange: (value: unknown) => void;
+}) {
+ if (field.type === "boolean") {
+ return (
+ <input
+ className="ml-2"
+ type="checkbox"
+ checked={Boolean(value)}
+ required={field.required}
+ onChange={(event) => onChange(event.target.checked)}
+ />
+ );
+ }
+ if (field.type === "array") {
+ return (
+ <textarea
+ className="field mt-1 min-h-20"
+ value={Array.isArray(value) ? value.join(", ") : String(value ?? "")}
+ placeholder={paramPlaceholder(name, field)}
+ required={field.required}
+ onInvalid={setRequiredMessage}
+ onChange={(event) => {
+ clearValidationMessage(event);
+ onChange(parseArrayParam(event.target.value, field));
+ }}
+ />
+ );
+ }
+ const type = field.secret ? "password" : field.type === "integer" || field.type === "number" ? "number" : "text";
+ return (
+ <input
+ className="field mt-1"
+ type={type}
+ value={String(value ?? "")}
+ min={field.min}
+ max={field.max}
+ placeholder={paramPlaceholder(name, field)}
+ required={field.required}
+ onInvalid={setRequiredMessage}
+ onChange={(event) => {
+ clearValidationMessage(event);
+ if (type === "number") {
+ onChange(event.target.value === "" ? undefined : Number(event.target.value));
+ return;
+ }
+ onChange(event.target.value === "" ? undefined : event.target.value);
+ }}
+ />
+ );
+}
+
+function fieldDefaultHint(field: ParamField): string {
+ if (field.secret || field.default === undefined) {
+ return "";
+ }
+ const value = formatDefaultValue(field.default);
+ return value ? `Default: ${value}` : "";
+}
+
+function paramPlaceholder(name: string, field: ParamField): string {
+ if (!field.secret) {
+ const value = formatDefaultValue(field.default);
+ if (value) {
+ return value;
+ }
+ }
+ const lower = name.toLowerCase();
+ if (lower === "target_user" && field.description === "Required target user or SPN; run ad.enum_spn first") {
+ return "svc-sql or MSSQLSvc/sql01.lab.local:1433";
+ }
+ if (lower.includes("target")) {
+ return "127.0.0.1";
+ }
+ if (lower.includes("port")) {
+ return "80, 443, 8080, 8443, 8888";
+ }
+ if (lower.includes("domain")) {
+ return "corp.local";
+ }
+ return field.required ? "" : "Leave blank to use the module default";
+}
+
+function fieldDescription(name: string, field: ParamField): string | undefined {
+ if (name === "target_user" && field.description === "Required target user or SPN; run ad.enum_spn first") {
+ return "Required target user or SPN; run ad.enum_spn first.";
+ }
+ return field.description;
+}
+
+function formatDefaultValue(value: unknown): string {
+ if (value === undefined || value === null || value === "") {
+ return "";
+ }
+ if (Array.isArray(value)) {
+ return value.join(", ");
+ }
+ if (typeof value === "boolean") {
+ return value ? "true" : "false";
+ }
+ if (typeof value === "object") {
+ return JSON.stringify(value);
+ }
+ return String(value);
+}
+
+function ScreenMessage({ title, body }: { title: string; body: string }) {
+ return (
+ <div className="grid min-h-screen place-items-center bg-slate-100 p-4">
+ <div className="panel p-5 text-center">
+ <h1 className="text-xl font-bold">{title}</h1>
+ <p className="mt-1 text-sm text-slate-600">{body}</p>
+ </div>
+ </div>
+ );
+}
+
+function EmptyState({ text }: { text: string }) {
+ return <div className="empty-state">{text}</div>;
+}
+
+function strategyBackendHint(backend: string): string {
+ if (backend === "openai") {
+ return "OpenAI planning requires OPENAI_API_KEY in the ARES server environment. Security-page API keys do not count as LLM provider keys.";
+ }
+ if (backend === "local") {
+ return "Local planning uses Ollama from the ARES server host, usually http://localhost:11434. No cloud LLM key is required.";
+ }
+ return "Claude planning requires ANTHROPIC_API_KEY in the ARES server environment. Security-page API keys only authenticate callers to ARES.";
+}
+
+function moduleRunHint(
+ campaignId: string,
+ module: ModuleMeta | undefined,
+ campaign: Campaign | undefined,
+ sensitive: boolean,
+ confirmed: boolean,
+ dryRun: boolean
+): string {
+ if (!campaignId) {
+ return "Select a campaign before running a module.";
+ }
+ if (!module) {
+ return "Select a module from the catalog.";
+ }
+ if (!campaign) {
+ return "Campaign details are still loading.";
+ }
+ if (sensitive && !confirmed) {
+ return "Confirm authorization before running high-noise or sensitive modules.";
+ }
+ if (!dryRun && "target" in (module.param_schema ?? {}) && campaignScopeEntries(campaign).length === 0) {
+ return "Live target modules require campaign scope CIDRs. Add a scope such as 127.0.0.1/32 before running.";
+ }
+ return "";
+}
+
+function splitLines(value: string): string[] {
+ return value
+ .split(/\r?\n|,/)
+ .map((item) => item.trim())
+ .filter(Boolean);
+}
+
+function findInvalidScopeEntries(value: string): string[] {
+ return splitLines(value).filter((entry) => !looksLikeScopeEntry(entry));
+}
+
+function looksLikeScopeEntry(entry: string): boolean {
+ if (entry.includes(":")) {
+ return true;
+ }
+ const [address, prefix] = entry.split("/");
+ if (!isIpv4Address(address)) {
+ return false;
+ }
+ if (prefix === undefined) {
+ return true;
+ }
+ if (!/^\d{1,2}$/.test(prefix)) {
+ return false;
+ }
+ const value = Number(prefix);
+ return value >= 0 && value <= 32;
+}
+
+function parseArrayParam(value: string, field: ParamField): unknown[] | undefined {
+ const entries = splitLines(value);
+ if (entries.length === 0) {
+ return undefined;
+ }
+ const itemType = field.items?.type ?? "string";
+ if (itemType === "integer" || itemType === "number") {
+ const numericEntries = entries.map((entry) => Number(entry));
+ return numericEntries.every((entry) => Number.isFinite(entry)) ? numericEntries : entries;
+ }
+ return entries;
+}
+
+function isEmptyParamValue(value: unknown): boolean {
+ return value === undefined || value === "" || (Array.isArray(value) && value.length === 0);
+}
+
+function moduleScopeWarning(
+ module: ModuleMeta | undefined,
+ campaign: Campaign | undefined,
+ values: Record<string, unknown>,
+ dryRun: boolean
+): string {
+ if (!module || !campaign || dryRun || !("target" in (module.param_schema ?? {}))) {
+ return "";
+ }
+ const target = typeof values.target === "string" ? values.target.trim() : "";
+ if (!target) {
+ return "";
+ }
+ const scope = campaignScopeEntries(campaign);
+ if (scope.length === 0) {
+ return "Selected campaign has no scope CIDRs. Add a scoped campaign such as 127.0.0.1/32 before running target modules.";
+ }
+ if (isIpv4Address(target) && scope.every(looksLikeScopeEntry) && !scope.some((entry) => ipv4InScope(target, entry))) {
+ return `Target ${target} is outside the selected campaign scope (${scope.join(", ")}).`;
+ }
+ return "";
+}
+
+function campaignScopeEntries(campaign: Campaign): string[] {
+ if (Array.isArray(campaign.scope_cidrs)) {
+ return campaign.scope_cidrs.filter((entry): entry is string => typeof entry === "string" && entry.trim() !== "");
+ }
+ const rawScope = campaign.scope;
+ if (Array.isArray(rawScope)) {
+ return rawScope
+ .map((entry) => {
+ if (typeof entry === "string") {
+ return entry;
+ }
+ if (entry && typeof entry === "object" && "cidr" in entry && typeof entry.cidr === "string") {
+ return entry.cidr;
+ }
+ return "";
+ })
+ .filter(Boolean);
+ }
+ if (typeof campaign.scope_json === "string" && campaign.scope_json.trim()) {
+ try {
+ const parsed = JSON.parse(campaign.scope_json) as unknown;
+ if (Array.isArray(parsed)) {
+ return parsed
+ .map((entry) => {
+ if (typeof entry === "string") {
+ return entry;
+ }
+ if (entry && typeof entry === "object" && "cidr" in entry && typeof entry.cidr === "string") {
+ return entry.cidr;
+ }
+ return "";
+ })
+ .filter(Boolean);
+ }
+ } catch {
+ return [];
+ }
+ }
+ return [];
+}
+
+function campaignTargets(campaign: Campaign): string[] {
+ if (Array.isArray(campaign.targets)) {
+ return campaign.targets.filter((entry): entry is string => typeof entry === "string" && entry.trim() !== "");
+ }
+ if (typeof campaign.targets_json === "string" && campaign.targets_json.trim()) {
+ try {
+ const parsed = JSON.parse(campaign.targets_json) as unknown;
+ if (Array.isArray(parsed)) {
+ return parsed.filter((entry): entry is string => typeof entry === "string" && entry.trim() !== "");
+ }
+ } catch {
+ return [];
+ }
+ }
+ return [];
+}
+
+function ipv4InScope(ip: string, cidr: string): boolean {
+ const [network, prefixText = "32"] = cidr.split("/");
+ if (!isIpv4Address(network) || !/^\d{1,2}$/.test(prefixText)) {
+ return false;
+ }
+ const prefix = Number(prefixText);
+ if (prefix < 0 || prefix > 32) {
+ return false;
+ }
+ const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;
+ return (ipv4ToNumber(ip) & mask) === (ipv4ToNumber(network) & mask);
+}
+
+function ipv4ToNumber(ip: string): number {
+ return ip.split(".").reduce((acc, part) => ((acc << 8) + Number(part)) >>> 0, 0);
+}
+
+function isIpv4Address(value: string): boolean {
+ const parts = value.split(".");
+ return parts.length === 4 && parts.every((part) => {
+ if (!/^\d{1,3}$/.test(part)) {
+ return false;
+ }
+ const number = Number(part);
+ return number >= 0 && number <= 255;
+ });
+}
+
+function unique(values: string[]): string[] {
+ return [...new Set(values.filter(Boolean))].sort();
+}
+
+function safeJson(value: string): Record<string, unknown> {
+ try {
+ const parsed = JSON.parse(value) as unknown;
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : {};
+ } catch {
+ return {};
+ }
+}
+
+function isJsonObject(value: string): boolean {
+ try {
+ const parsed = JSON.parse(value) as unknown;
+ return Boolean(parsed && typeof parsed === "object" && !Array.isArray(parsed));
+ } catch {
+ return false;
+ }
+}
+
+function isSensitiveModule(module?: ModuleMeta): boolean {
+ if (!module) {
+ return false;
+ }
+ const text = `${module.id} ${module.category ?? ""} ${module.opsec_level ?? ""}`.toLowerCase();
+ return (
+ text.includes("high_noise") ||
+ text.includes("credential") ||
+ text.includes("persistence") ||
+ text.includes("edr") ||
+ text.includes("dcsync")
+ );
+}
+
+function statusBadge(status?: string): string {
+ const normalized = String(status ?? "").toLowerCase();
+ if (["active", "running", "ready", "restored", "complete", "completed"].some((item) => normalized.includes(item))) {
+ return "badge badge-low";
+ }
+ if (["failed", "deleted", "blocked", "error"].some((item) => normalized.includes(item))) {
+ return "badge badge-high";
+ }
+ if (["paused", "pending", "draft", "created"].some((item) => normalized.includes(item))) {
+ return "badge badge-medium";
+ }
+ return "badge";
+}
+
+function opsecBadge(level?: string): string {
+ const normalized = String(level ?? "").toLowerCase();
+ if (normalized.includes("high") || normalized.includes("critical")) {
+ return "badge badge-high";
+ }
+ if (normalized.includes("medium") || normalized.includes("moderate")) {
+ return "badge badge-medium";
+ }
+ return "badge badge-low";
+}
+
+function serializeError(value: unknown): unknown {
+ if (value instanceof ApiError) {
+ return { name: value.name, status: value.status, detail: value.detail };
+ }
+ if (value instanceof Error) {
+ return { name: value.name, message: value.message };
+ }
+ return value;
+}
+
+function readableError(value: unknown, fallback: string): string {
+ if (value instanceof ApiError) {
+ if (typeof value.detail === "string") {
+ return value.detail;
+ }
+ return value.message || fallback;
+ }
+ if (value instanceof Error) {
+ return value.message || fallback;
+ }
+ if (typeof value === "string") {
+ return value;
+ }
+ return fallback;
+}
+
+function pdfFailureHint(value: unknown): string {
+ if (!value) return "";
+ const serialized = serializeError(value);
+ const text = typeof serialized === "string"
+ ? serialized
+ : JSON.stringify(serialized);
+ const normalized = text.toLowerCase();
+ if (normalized.includes("elevated windows") || normalized.includes("administrator powershell")) {
+ return "PDF export is blocked from this elevated Windows session. Run PowerShell normally, or set ARES_PDF_BROWSER to a working non-Edge browser.";
+ }
+ if (
+ normalized.includes("gtk")
+ || normalized.includes("pango")
+ || normalized.includes("libgobject")
+ ) {
+ return "WeasyPrint needs native GTK/Pango libraries on Windows. Use the browser fallback from normal PowerShell or install those native libraries.";
+ }
+ if (normalized.includes("no downloadable pdf") || normalized.includes("pdf smoke")) {
+ return "PDF export did not create a valid artifact. Run ares doctor --pdf-smoke to verify the local PDF backend and browser fallback.";
+ }
+ return "";
+}
diff --git a/frontend/src/features/dashboard/DashboardRouter.tsx b/frontend/src/features/dashboard/DashboardRouter.tsx
new file mode 100644
index 0000000..8c55e06
--- /dev/null
+++ b/frontend/src/features/dashboard/DashboardRouter.tsx
@@ -0,0 +1,55 @@
+import { Loader2 } from "lucide-react";
+import { lazy, Suspense } from "react";
+import { Navigate, Route, Routes } from "react-router-dom";
+import {
+ CampaignsPage,
+ DashboardShell,
+ EdrPage,
+ LivePage,
+ ModulesPage,
+ OverviewPage,
+ ReportsPage,
+ SecurityPage,
+ StrategyPage,
+ TemplatesPage
+} from "./DashboardPages";
+import { LoginPage } from "../auth/LoginPage";
+import { useDashboardUi } from "./dashboardUiState";
+
+const GraphPage = lazy(() => import("../graph/GraphPage"));
+
+function DashboardRoutes() {
+ const { selectedCampaignId, setSelectedCampaignId } = useDashboardUi();
+
+ return (
+ <Routes>
+ <Route path="/" element={<OverviewPage />} />
+ <Route path="/playbooks" element={<Navigate to="/modules" replace />} />
+ <Route path="/campaigns" element={<CampaignsPage />} />
+ <Route path="/modules" element={<ModulesPage />} />
+ <Route path="/reports" element={<ReportsPage />} />
+ <Route
+ path="/graph"
+ element={(
+ <Suspense fallback={<div className="panel p-4 loading-row"><Loader2 className="spin" size={18} /> Loading graph renderer…</div>}>
+ <GraphPage campaignId={selectedCampaignId} onCampaignIdChange={setSelectedCampaignId} />
+ </Suspense>
+ )}
+ />
+ <Route path="/templates" element={<TemplatesPage />} />
+ <Route path="/strategy" element={<StrategyPage />} />
+ <Route path="/security" element={<SecurityPage />} />
+ <Route path="/edr" element={<EdrPage />} />
+ <Route path="/live" element={<LivePage />} />
+ </Routes>
+ );
+}
+
+export function DashboardRouter() {
+ return (
+ <Routes>
+ <Route path="/login" element={<LoginPage />} />
+ <Route path="/*" element={<DashboardShell><DashboardRoutes /></DashboardShell>} />
+ </Routes>
+ );
+}
diff --git a/frontend/src/features/dashboard/dashboardUi.test.tsx b/frontend/src/features/dashboard/dashboardUi.test.tsx
new file mode 100644
index 0000000..deda035
--- /dev/null
+++ b/frontend/src/features/dashboard/dashboardUi.test.tsx
@@ -0,0 +1,16 @@
+import { act, renderHook } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { useSessionState } from "./dashboardUiState";
+
+describe("dashboard session state", () => {
+ it("rehydrates and persists a campaign selection without changing the storage key", () => {
+ const key = "ares.dashboard.selectedCampaignId";
+ sessionStorage.setItem(key, JSON.stringify("campaign-before"));
+
+ const { result } = renderHook(() => useSessionState(key, ""));
+ expect(result.current[0]).toBe("campaign-before");
+
+ act(() => result.current[1]("campaign-after"));
+ expect(sessionStorage.getItem(key)).toBe(JSON.stringify("campaign-after"));
+ });
+});
diff --git a/frontend/src/features/dashboard/dashboardUi.tsx b/frontend/src/features/dashboard/dashboardUi.tsx
new file mode 100644
index 0000000..2aeb8cd
--- /dev/null
+++ b/frontend/src/features/dashboard/dashboardUi.tsx
@@ -0,0 +1,6 @@
+import { ReactNode } from "react";
+import { DashboardUiContext, type DashboardUiState } from "./dashboardUiState";
+
+export function DashboardUiProvider({ children, value }: { children: ReactNode; value: DashboardUiState }) {
+ return <DashboardUiContext.Provider value={value}>{children}</DashboardUiContext.Provider>;
+}
diff --git a/frontend/src/features/dashboard/dashboardUiState.ts b/frontend/src/features/dashboard/dashboardUiState.ts
new file mode 100644
index 0000000..0510c02
--- /dev/null
+++ b/frontend/src/features/dashboard/dashboardUiState.ts
@@ -0,0 +1,50 @@
+import { createContext, Dispatch, SetStateAction, useContext, useEffect, useState } from "react";
+
+export interface DashboardUiState {
+ selectedCampaignId: string;
+ setSelectedCampaignId: Dispatch<SetStateAction<string>>;
+ liveCampaignId: string;
+ setLiveCampaignId: Dispatch<SetStateAction<string>>;
+ liveConnected: boolean;
+ setLiveConnected: Dispatch<SetStateAction<boolean>>;
+ liveEvents: unknown[];
+ clearLiveEvents: () => void;
+}
+
+export const DashboardUiContext = createContext<DashboardUiState | null>(null);
+
+export function useDashboardUi(): DashboardUiState {
+ const value = useContext(DashboardUiContext);
+ if (!value) {
+ throw new Error("DashboardUiContext missing");
+ }
+ return value;
+}
+
+function readSessionState<T>(key: string, initialValue: T): T {
+ try {
+ const stored = window.sessionStorage.getItem(key);
+ return stored ? JSON.parse(stored) as T : initialValue;
+ } catch {
+ return initialValue;
+ }
+}
+
+export function useSessionState<T>(key: string, initialValue: T): readonly [T, Dispatch<SetStateAction<T>>] {
+ const [value, setValue] = useState<T>(() => readSessionState(key, initialValue));
+
+ useEffect(() => {
+ try {
+ const serialized = JSON.stringify(value);
+ if (serialized === undefined) {
+ window.sessionStorage.removeItem(key);
+ } else {
+ window.sessionStorage.setItem(key, serialized);
+ }
+ } catch {
+ // Session persistence is a UX aid; storage failures should never block the dashboard.
+ }
+ }, [key, value]);
+
+ return [value, setValue] as const;
+}
diff --git a/frontend/src/features/graph/GraphPage.tsx b/frontend/src/features/graph/GraphPage.tsx
new file mode 100644
index 0000000..9f656aa
--- /dev/null
+++ b/frontend/src/features/graph/GraphPage.tsx
@@ -0,0 +1,465 @@
+import {
+ Background,
+ Controls,
+ Handle,
+ MarkerType,
+ MiniMap,
+ Position,
+ ReactFlow,
+ type Edge,
+ type Node,
+ type NodeProps,
+ type NodeTypes
+} from "@xyflow/react";
+import "@xyflow/react/dist/style.css";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { AlertTriangle, GitGraph, Loader2, RotateCcw, Route, X } from "lucide-react";
+import { useMemo, useState, type CSSProperties } from "react";
+import { api } from "../../api/client";
+import type { AttackPath, Campaign, SafeGraphValue } from "../../api/types";
+import {
+ attackPathSummary,
+ filterGraph,
+ getPathHighlight,
+ graphNodeTypes,
+ isGraphEmpty,
+ type GraphFilters,
+ type SafeGraph,
+ type SafeGraphEdge,
+ type SafeGraphNode,
+ toSafeGraph
+} from "./graphModel";
+
+interface CanvasNodeData extends Record<string, unknown> {
+ label: string;
+ type: string;
+ color: string;
+ severity?: string;
+ dimmed: boolean;
+}
+
+type CanvasNode = Node<CanvasNodeData, "ares">;
+type CanvasEdge = Edge;
+
+type GraphSelection =
+ | { kind: "node"; value: SafeGraphNode }
+ | { kind: "edge"; value: SafeGraphEdge }
+ | null;
+
+const nodeTypes: NodeTypes = { ares: AresGraphNode };
+
+function AresGraphNode({ data, selected }: NodeProps<CanvasNode>) {
+ return (
+ <div
+ className={`ares-flow-node${selected ? " selected" : ""}${data.dimmed ? " dimmed" : ""}`}
+ style={{ "--node-color": data.color } as CSSProperties}
+ >
+ <Handle type="target" position={Position.Left} />
+ <span className="ares-flow-node-type">{data.type}</span>
+ <strong>{data.label}</strong>
+ {data.severity && <small className={`status-${data.severity}`}>{data.severity}</small>}
+ <Handle type="source" position={Position.Right} />
+ </div>
+ );
+}
+
+function graphLayout(graph: SafeGraph, highlightedNodeIds: Set<string>, highlightedEdgeIds: Set<string>) {
+ const ordered = [...graph.nodes].sort((left, right) => (
+ left.type.localeCompare(right.type) || left.label.localeCompare(right.label)
+ ));
+ const rowsByType = new Map<string, number>();
+ const columnByType = new Map<string, number>();
+ [...new Set(ordered.map((node) => node.type))].forEach((type, index) => columnByType.set(type, index));
+ const shouldDim = highlightedNodeIds.size > 0;
+ const nodes: CanvasNode[] = ordered.map((node) => {
+ const row = rowsByType.get(node.type) ?? 0;
+ rowsByType.set(node.type, row + 1);
+ return {
+ id: node.id,
+ type: "ares",
+ position: {
+ x: (columnByType.get(node.type) ?? 0) * 255,
+ y: (row % 8) * 118 + Math.floor(row / 8) * 36
+ },
+ data: {
+ label: node.label,
+ type: node.type,
+ color: node.color,
+ severity: node.severity,
+ dimmed: shouldDim && !highlightedNodeIds.has(node.id)
+ }
+ };
+ });
+ const edges: CanvasEdge[] = graph.edges.map((edge) => ({
+ id: edge.id,
+ source: edge.source,
+ target: edge.target,
+ label: edge.label || edge.type,
+ animated: highlightedEdgeIds.has(edge.id),
+ markerEnd: { type: MarkerType.ArrowClosed },
+ style: {
+ stroke: edge.color || "#94a3b8",
+ strokeWidth: highlightedEdgeIds.has(edge.id) ? 3 : 1.5,
+ opacity: highlightedEdgeIds.size > 0 && !highlightedEdgeIds.has(edge.id) ? 0.18 : 1,
+ strokeDasharray: edge.dashed ? "5 4" : undefined
+ },
+ labelStyle: { fill: "#475569", fontSize: 11, fontWeight: 600 },
+ labelBgStyle: { fill: "#ffffff", fillOpacity: 0.9 },
+ labelBgPadding: [4, 3]
+ }));
+ return { nodes, edges };
+}
+
+function safeValueText(value: SafeGraphValue): string {
+ if (value === null) return "—";
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return String(value);
+ if (Array.isArray(value)) return value.map(safeValueText).join(", ");
+ return Object.entries(value).map(([key, item]) => `${key}: ${safeValueText(item)}`).join(" · ");
+}
+
+function CampaignSelect({ campaigns, value, onChange }: {
+ campaigns: Campaign[];
+ value: string;
+ onChange: (campaignId: string) => void;
+}) {
+ return (
+ <label className="graph-campaign-select">
+ <span>Campaign</span>
+ <select className="field" value={value} onChange={(event) => onChange(event.target.value)}>
+ <option value="">Select campaign</option>
+ {campaigns.map((campaign) => (
+ <option key={campaign.id} value={campaign.id}>{campaign.name || campaign.id}</option>
+ ))}
+ </select>
+ </label>
+ );
+}
+
+function GraphFiltersPanel({ graph, filters, onChange }: {
+ graph: SafeGraph;
+ filters: GraphFilters;
+ onChange: (filters: GraphFilters) => void;
+}) {
+ const types = graphNodeTypes(graph);
+ return (
+ <div className="graph-filters" aria-label="Graph filters">
+ <span className="graph-filter-title">Filters</span>
+ <div className="graph-filter-group">
+ <span>Node type</span>
+ <div className="graph-filter-options">
+ {types.map((type) => {
+ const active = filters.nodeTypes.includes(type);
+ return (
+ <button
+ className={`filter-chip${active ? " active" : ""}`}
+ key={type}
+ onClick={() => onChange({
+ ...filters,
+ nodeTypes: active ? filters.nodeTypes.filter((item) => item !== type) : [...filters.nodeTypes, type]
+ })}
+ type="button"
+ >
+ {type}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ <label className="graph-filter-group">
+ <span>Finding severity</span>
+ <select
+ className="field"
+ value={filters.severity}
+ onChange={(event) => onChange({ ...filters, severity: event.target.value })}
+ >
+ <option value="all">All severities</option>
+ <option value="critical">Critical</option>
+ <option value="high">High</option>
+ <option value="medium">Medium</option>
+ <option value="low">Low</option>
+ <option value="info">Info</option>
+ </select>
+ </label>
+ <label className="toggle-row graph-path-only-toggle">
+ <input
+ checked={filters.activePathOnly}
+ disabled={false}
+ onChange={(event) => onChange({ ...filters, activePathOnly: event.target.checked })}
+ type="checkbox"
+ />
+ Only active attack path
+ </label>
+ </div>
+ );
+}
+
+function GraphDetailPanel({ selection, onClear }: { selection: GraphSelection; onClear: () => void }) {
+ if (!selection) {
+ return (
+ <div className="graph-detail-empty">
+ Select a node or edge to review its safe metadata.
+ </div>
+ );
+ }
+ const value = selection.value;
+ const edge = selection.kind === "edge" ? selection.value : null;
+ const entries = Object.entries(value.metadata);
+ return (
+ <div className="graph-detail-content">
+ <div className="graph-detail-heading">
+ <div>
+ <span>{selection.kind === "node" ? value.type : `edge · ${value.type}`}</span>
+ <strong>{selection.kind === "node" ? value.label : value.label || `${edge?.source} → ${edge?.target}`}</strong>
+ </div>
+ <button aria-label="Clear graph detail" className="icon-button icon-button-small" onClick={onClear} type="button">
+ <X size={14} />
+ </button>
+ </div>
+ {edge && (
+ <p className="graph-detail-route">{edge.source} → {edge.target}</p>
+ )}
+ {entries.length > 0 ? (
+ <dl className="graph-detail-list">
+ {entries.map(([key, item]) => (
+ <div key={key}>
+ <dt>{key.replace(/_/g, " ")}</dt>
+ <dd>{safeValueText(item)}</dd>
+ </div>
+ ))}
+ </dl>
+ ) : (
+ <p className="graph-detail-empty">No additional safe metadata is available.</p>
+ )}
+ </div>
+ );
+}
+
+function AttackPathList({ paths, selectedIndex, onSelect }: {
+ paths: AttackPath[];
+ selectedIndex: number | null;
+ onSelect: (index: number) => void;
+}) {
+ if (paths.length === 0) {
+ return <div className="graph-detail-empty">No attack paths are available yet. Run reconnaissance or ingest a graph snapshot first.</div>;
+ }
+ return (
+ <div className="attack-path-list">
+ {paths.map((path, index) => (
+ <button
+ className={`attack-path-card${selectedIndex === index ? " active" : ""}`}
+ key={`${attackPathSummary(path)}:${index}`}
+ onClick={() => onSelect(index)}
+ type="button"
+ >
+ <span>Path {index + 1}</span>
+ <strong>{attackPathSummary(path)}</strong>
+ <small>{path.path_length ?? path.steps.length + 1} nodes · score {path.total_score ?? "—"}</small>
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function GraphCanvas({ graph, highlightedNodeIds, highlightedEdgeIds, onSelect }: {
+ graph: SafeGraph;
+ highlightedNodeIds: Set<string>;
+ highlightedEdgeIds: Set<string>;
+ onSelect: (selection: GraphSelection) => void;
+}) {
+ const canvas = useMemo(
+ () => graphLayout(graph, highlightedNodeIds, highlightedEdgeIds),
+ [graph, highlightedEdgeIds, highlightedNodeIds]
+ );
+ const nodeById = useMemo(() => new Map(graph.nodes.map((node) => [node.id, node])), [graph.nodes]);
+ const edgeById = useMemo(() => new Map(graph.edges.map((edge) => [edge.id, edge])), [graph.edges]);
+ return (
+ <div className="graph-canvas" aria-label="Interactive attack graph">
+ <ReactFlow
+ edges={canvas.edges}
+ fitView
+ maxZoom={1.8}
+ minZoom={0.25}
+ nodes={canvas.nodes}
+ nodeTypes={nodeTypes}
+ onEdgeClick={(_event, edge) => {
+ const selectedEdge = edgeById.get(edge.id);
+ if (selectedEdge) onSelect({ kind: "edge", value: selectedEdge });
+ }}
+ onNodeClick={(_event, node) => {
+ const selectedNode = nodeById.get(node.id);
+ if (selectedNode) onSelect({ kind: "node", value: selectedNode });
+ }}
+ proOptions={{ hideAttribution: true }}
+ >
+ <Background color="#dbe5f0" gap={18} />
+ <Controls showInteractive={false} />
+ <MiniMap pannable zoomable />
+ </ReactFlow>
+ </div>
+ );
+}
+
+function GraphWorkspace({ graph, paths, view, filters, onFiltersChange, selectedPathIndex, onSelectPath, selection, onSelect }: {
+ graph: SafeGraph;
+ paths: AttackPath[];
+ view: "entities" | "paths";
+ filters: GraphFilters;
+ onFiltersChange: (filters: GraphFilters) => void;
+ selectedPathIndex: number | null;
+ onSelectPath: (index: number) => void;
+ selection: GraphSelection;
+ onSelect: (selection: GraphSelection) => void;
+}) {
+ const selectedPath = selectedPathIndex === null ? null : paths[selectedPathIndex] ?? null;
+ const highlight = useMemo(() => getPathHighlight(selectedPath, graph), [graph, selectedPath]);
+ const filteredGraph = useMemo(() => filterGraph(graph, filters, highlight), [filters, graph, highlight]);
+ return (
+ <div className="graph-workspace">
+ <GraphFiltersPanel graph={graph} filters={filters} onChange={onFiltersChange} />
+ {selectedPath && (
+ <div className="graph-active-path">
+ <Route size={16} />
+ <span>Highlighting {attackPathSummary(selectedPath)}</span>
+ <button className="btn btn-compact" onClick={() => onSelectPath(-1)} type="button">
+ <X size={14} /> Clear selection
+ </button>
+ </div>
+ )}
+ {filteredGraph.nodes.length > 0 ? (
+ <div className="graph-layout">
+ <GraphCanvas
+ graph={filteredGraph}
+ highlightedEdgeIds={highlight.edgeIds}
+ highlightedNodeIds={highlight.nodeIds}
+ onSelect={onSelect}
+ />
+ <aside className="panel graph-side-panel">
+ <div className="graph-side-heading">
+ <GitGraph size={16} />
+ <strong>{view === "paths" ? "Top attack paths" : "Safe detail"}</strong>
+ </div>
+ {view === "paths"
+ ? <AttackPathList paths={paths} selectedIndex={selectedPathIndex} onSelect={onSelectPath} />
+ : <GraphDetailPanel selection={selection} onClear={() => onSelect(null)} />}
+ </aside>
+ </div>
+ ) : (
+ <div className="empty-state">No graph elements match the active filters or selected attack path.</div>
+ )}
+ </div>
+ );
+}
+
+export default function GraphPage({ campaignId, onCampaignIdChange }: {
+ campaignId: string;
+ onCampaignIdChange: (campaignId: string) => void;
+}) {
+ const queryClient = useQueryClient();
+ const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
+ const graphQuery = useQuery({ queryKey: ["graph", campaignId], queryFn: () => api.graph(campaignId), enabled: Boolean(campaignId) });
+ const pathsQuery = useQuery({ queryKey: ["attack-paths", campaignId], queryFn: () => api.attackPaths(campaignId), enabled: Boolean(campaignId) });
+ const [activeTab, setActiveTab] = useState<"Entities" | "Attack Paths" | "Ingest">("Entities");
+ const [filters, setFilters] = useState<GraphFilters>({ nodeTypes: [], severity: "all", activePathOnly: false });
+ const [selection, setSelection] = useState<GraphSelection>(null);
+ const [selectedPathIndex, setSelectedPathIndex] = useState<number | null>(null);
+ const [jsonPath, setJsonPath] = useState("");
+ const [ingestNotice, setIngestNotice] = useState("");
+ const safeGraph = useMemo(() => toSafeGraph(graphQuery.data), [graphQuery.data]);
+ const paths = useMemo(() => Array.isArray(pathsQuery.data?.paths) ? pathsQuery.data.paths : [], [pathsQuery.data]);
+ const ingest = useMutation({
+ mutationFn: () => api.ingestBloodhound(campaignId, jsonPath.trim()),
+ onSuccess: async () => {
+ setIngestNotice("Import request completed. The graph will show imported data only after the API returns a durable snapshot.");
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: ["graph", campaignId] }),
+ queryClient.invalidateQueries({ queryKey: ["attack-paths", campaignId] })
+ ]);
+ }
+ });
+
+ function chooseCampaign(nextCampaignId: string): void {
+ onCampaignIdChange(nextCampaignId);
+ setSelection(null);
+ setSelectedPathIndex(null);
+ setFilters({ nodeTypes: [], severity: "all", activePathOnly: false });
+ setIngestNotice("");
+ }
+
+ function selectPath(index: number): void {
+ setSelectedPathIndex(index < 0 ? null : index);
+ if (index >= 0) setFilters((current) => ({ ...current, activePathOnly: false }));
+ }
+
+ const loading = Boolean(campaignId) && (graphQuery.isLoading || pathsQuery.isLoading);
+ const error = graphQuery.isError || pathsQuery.isError;
+ return (
+ <section className="page">
+ <header className="page-header">
+ <div className="page-heading">
+ <span className="page-icon"><GitGraph size={19} /></span>
+ <div>
+ <p className="page-eyebrow">Intelligence</p>
+ <h1>Graph</h1>
+ <p>Durable campaign entities, relationships, and API-calculated attack paths.</p>
+ </div>
+ </div>
+ <div className="page-actions">
+ <span className="status-pill">{safeGraph.nodes.length} nodes / {safeGraph.edges.length} edges</span>
+ {campaignId && <button className="btn btn-compact" onClick={() => void graphQuery.refetch()} type="button"><RotateCcw size={14} /> Retry</button>}
+ </div>
+ </header>
+ <div className="page-tabs" role="tablist" aria-label="Graph sections">
+ {(["Entities", "Attack Paths", "Ingest"] as const).map((tab) => (
+ <button className={activeTab === tab ? "active" : ""} key={tab} onClick={() => setActiveTab(tab)} role="tab" type="button">{tab}</button>
+ ))}
+ </div>
+ <section className="panel p-4 graph-panel">
+ <div className="graph-toolbar">
+ <CampaignSelect campaigns={campaigns.data ?? []} value={campaignId} onChange={chooseCampaign} />
+ {campaigns.isError && <span className="notice notice-danger"><AlertTriangle size={15} /> Campaigns could not be loaded.</span>}
+ </div>
+ {!campaignId ? (
+ <div className="empty-state">Select a campaign to load durable graph data.</div>
+ ) : loading ? (
+ <div className="loading-row"><Loader2 className="spin" size={18} /> Loading graph and attack paths…</div>
+ ) : error ? (
+ <div className="notice notice-danger graph-request-error"><AlertTriangle size={16} /> Graph data could not be loaded. Retry when the campaign API is available.</div>
+ ) : activeTab === "Ingest" ? (
+ <form className="graph-ingest-form" onSubmit={(event) => {
+ event.preventDefault();
+ setIngestNotice("");
+ if (jsonPath.trim()) ingest.mutate();
+ }}>
+ <div>
+ <h2>BloodHound ingest</h2>
+ <p>Use a server-local path. The graph only reflects imported data after a durable API snapshot is returned.</p>
+ </div>
+ <label>
+ <span>JSON path</span>
+ <input className="field" onChange={(event) => setJsonPath(event.target.value)} placeholder="C:\\labs\\bloodhound\\results.json" required value={jsonPath} />
+ </label>
+ <button className="btn btn-primary" disabled={ingest.isPending} type="submit">
+ {ingest.isPending ? <><Loader2 className="spin" size={16} /> Importing…</> : <><GitGraph size={16} /> Request import</>}
+ </button>
+ {ingestNotice && <p className="notice">{ingestNotice}</p>}
+ {ingest.isError && <p className="notice notice-danger">The import request could not be completed. Confirm the allowed server-local path and retry.</p>}
+ </form>
+ ) : isGraphEmpty(safeGraph) ? (
+ <div className="empty-state">This campaign has no durable graph data yet. Run authorized reconnaissance or ingest a BloodHound/SharpHound snapshot, then reload this page.</div>
+ ) : (
+ <GraphWorkspace
+ filters={filters}
+ graph={safeGraph}
+ onFiltersChange={setFilters}
+ onSelect={setSelection}
+ onSelectPath={selectPath}
+ paths={paths}
+ selectedPathIndex={selectedPathIndex}
+ selection={selection}
+ view={activeTab === "Attack Paths" ? "paths" : "entities"}
+ />
+ )}
+ </section>
+ </section>
+ );
+}
diff --git a/frontend/src/features/graph/graphModel.test.ts b/frontend/src/features/graph/graphModel.test.ts
new file mode 100644
index 0000000..1212311
--- /dev/null
+++ b/frontend/src/features/graph/graphModel.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from "vitest";
+import type { AttackPath, CampaignGraph } from "../../api/types";
+import { filterGraph, getPathHighlight, isGraphEmpty, toSafeGraph } from "./graphModel";
+
+const payload: CampaignGraph = {
+ nodes: [
+ {
+ id: "host:10.0.0.5",
+ type: "host",
+ label: "app01",
+ color: "#0dcaf0",
+ data: {
+ hostname: "app01",
+ access_token: "must-not-render",
+ nested: { password_hash: "nope", raw_evidence: "not-for-ui", role: "web" }
+ }
+ },
+ {
+ id: "finding:1",
+ type: "finding",
+ label: "Critical service exposure",
+ color: "#dc3545",
+ data: { severity: "critical", secret_enc: "nope", module_id: "network.safe_probe" }
+ },
+ {
+ id: "pivot:1",
+ type: "pivot",
+ label: "Approved route",
+ color: "#64748b",
+ data: { route: "10.0.0.0/24" }
+ }
+ ],
+ edges: [
+ { source: "host:10.0.0.5", target: "finding:1", type: "compromise", label: "exposed" },
+ { source: "finding:1", target: "pivot:1", type: "pivot", label: "route" }
+ ]
+};
+
+describe("graph model", () => {
+ it("never forwards secret-like metadata to a node or safe detail payload", () => {
+ const graph = toSafeGraph(payload);
+
+ expect(JSON.stringify(graph)).not.toContain("must-not-render");
+ expect(JSON.stringify(graph)).not.toContain("secret_enc");
+ expect(JSON.stringify(graph)).not.toContain("password");
+ expect(JSON.stringify(graph)).not.toContain("evidence");
+ expect(graph.nodes[0]?.metadata).toEqual({ hostname: "app01", nested: { role: "web" } });
+ });
+
+ it("represents an empty API graph as an explicit empty state", () => {
+ expect(isGraphEmpty(toSafeGraph({ nodes: [], edges: [] }))).toBe(true);
+ });
+
+ it("filters node type and finding severity without inventing graph elements", () => {
+ const graph = toSafeGraph(payload);
+ const filtered = filterGraph(
+ graph,
+ { nodeTypes: ["finding", "host"], severity: "critical", activePathOnly: false },
+ { nodeIds: new Set(), edgeIds: new Set() }
+ );
+
+ expect(filtered.nodes.map((node) => node.id)).toEqual(["host:10.0.0.5", "finding:1"]);
+ expect(filtered.edges).toHaveLength(1);
+ });
+
+ it("highlights exactly the API-selected attack path nodes and edges", () => {
+ const graph = toSafeGraph(payload);
+ const path: AttackPath = {
+ steps: [
+ { from: "app01", to: "Critical service exposure", edge: "exposed" },
+ { from: "Critical service exposure", to: "Approved route", edge: "route" }
+ ]
+ };
+ const highlight = getPathHighlight(path, graph);
+
+ expect(highlight.nodeIds).toEqual(new Set(["host:10.0.0.5", "finding:1", "pivot:1"]));
+ expect(highlight.edgeIds).toEqual(new Set(["edge:host:10.0.0.5:finding:1:0", "edge:finding:1:pivot:1:1"]));
+ });
+
+ it("drops malformed API nodes and edges instead of crashing the renderer", () => {
+ const graph = toSafeGraph({
+ nodes: [null, { id: 12 }, { id: "safe", type: "host", label: "safe" }],
+ edges: [{ source: "safe" }, { source: "safe", target: "missing" }, { source: "safe", target: "safe" }]
+ });
+
+ expect(graph.nodes).toHaveLength(1);
+ expect(graph.edges).toHaveLength(1);
+ });
+});
diff --git a/frontend/src/features/graph/graphModel.ts b/frontend/src/features/graph/graphModel.ts
new file mode 100644
index 0000000..0825b03
--- /dev/null
+++ b/frontend/src/features/graph/graphModel.ts
@@ -0,0 +1,229 @@
+import type { AttackPath, AttackPathStep, CampaignGraph, SafeGraphValue } from "../../api/types";
+
+export const SENSITIVE_GRAPH_FIELDS = new Set([
+ "secret",
+ "secret_enc",
+ "password",
+ "passwd",
+ "token",
+ "api_key",
+ "private_key",
+ "hash",
+ "hash_value",
+ "nt_hash",
+ "lm_hash",
+ "cracked_value",
+ "evidence",
+ "raw_evidence"
+]);
+
+type UnknownRecord = Record<string, unknown>;
+
+export interface SafeGraphNode {
+ id: string;
+ type: string;
+ label: string;
+ color: string;
+ severity?: string;
+ metadata: Record<string, SafeGraphValue>;
+}
+
+export interface SafeGraphEdge {
+ id: string;
+ source: string;
+ target: string;
+ type: string;
+ label: string;
+ weight: number;
+ color?: string;
+ dashed: boolean;
+ metadata: Record<string, SafeGraphValue>;
+}
+
+export interface SafeGraph {
+ nodes: SafeGraphNode[];
+ edges: SafeGraphEdge[];
+}
+
+export interface GraphFilters {
+ nodeTypes: string[];
+ severity: string;
+ activePathOnly: boolean;
+}
+
+export interface GraphHighlight {
+ nodeIds: Set<string>;
+ edgeIds: Set<string>;
+}
+
+function isRecord(value: unknown): value is UnknownRecord {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+function safeString(value: unknown, fallback = ""): string {
+ return typeof value === "string" ? value : fallback;
+}
+
+function safeNumber(value: unknown, fallback = 0): number {
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
+}
+
+function safeBoolean(value: unknown, fallback = false): boolean {
+ return typeof value === "boolean" ? value : fallback;
+}
+
+function isSensitiveGraphField(key: string): boolean {
+ const normalized = key.toLowerCase();
+ return SENSITIVE_GRAPH_FIELDS.has(normalized)
+ || /(?:secret|password|passwd|token|api[_-]?key|private[_-]?key|hash|cracked|evidence)/.test(normalized);
+}
+
+export function sanitizeGraphValue(value: unknown): SafeGraphValue | undefined {
+ if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
+ return value;
+ }
+ if (Array.isArray(value)) {
+ return value.flatMap((item) => {
+ const sanitized = sanitizeGraphValue(item);
+ return sanitized === undefined ? [] : [sanitized];
+ });
+ }
+ if (isRecord(value)) {
+ const sanitized: Record<string, SafeGraphValue> = {};
+ Object.entries(value).forEach(([key, item]) => {
+ if (isSensitiveGraphField(key)) return;
+ const safeValue = sanitizeGraphValue(item);
+ if (safeValue !== undefined) {
+ sanitized[key] = safeValue;
+ }
+ });
+ return sanitized;
+ }
+ return undefined;
+}
+
+export function sanitizeGraphMetadata(value: unknown): Record<string, SafeGraphValue> {
+ const sanitized = sanitizeGraphValue(value);
+ return isRecord(sanitized) ? sanitized as Record<string, SafeGraphValue> : {};
+}
+
+function toSafeNode(raw: unknown): SafeGraphNode | null {
+ if (!isRecord(raw)) return null;
+ const id = safeString(raw.id);
+ if (!id) return null;
+ const data = sanitizeGraphMetadata(raw.data);
+ const style = isRecord(raw.style) ? raw.style : {};
+ const rawType = safeString(raw.type, "artifact");
+ const severity = safeString(data.severity).toLowerCase() || undefined;
+ return {
+ id,
+ type: rawType,
+ label: safeString(raw.label, id),
+ color: safeString(raw.color, safeString(style.color, "#64748b")),
+ severity,
+ metadata: data
+ };
+}
+
+function toSafeEdge(raw: unknown, index: number): SafeGraphEdge | null {
+ if (!isRecord(raw)) return null;
+ const source = safeString(raw.source);
+ const target = safeString(raw.target);
+ if (!source || !target) return null;
+ const data = sanitizeGraphMetadata(raw.data);
+ const style = isRecord(raw.style) ? raw.style : {};
+ return {
+ id: graphEdgeId(source, target, index),
+ source,
+ target,
+ type: safeString(raw.type, "related"),
+ label: safeString(raw.label),
+ weight: safeNumber(raw.weight, 1),
+ color: safeString(style.color) || undefined,
+ dashed: safeBoolean(style.dashed),
+ metadata: data
+ };
+}
+
+export function graphEdgeId(source: string, target: string, index: number): string {
+ return `edge:${source}:${target}:${index}`;
+}
+
+export function toSafeGraph(payload: CampaignGraph | unknown): SafeGraph {
+ const source = isRecord(payload) ? payload : {};
+ const rawNodes = Array.isArray(source.nodes) ? source.nodes : [];
+ const rawEdges = Array.isArray(source.edges) ? source.edges : [];
+ const nodeIds = new Set<string>();
+ const nodes = rawNodes.flatMap((node) => {
+ const safeNode = toSafeNode(node);
+ if (!safeNode || nodeIds.has(safeNode.id)) return [];
+ nodeIds.add(safeNode.id);
+ return [safeNode];
+ });
+ const edges = rawEdges.flatMap((edge, index) => {
+ const safeEdge = toSafeEdge(edge, index);
+ if (!safeEdge || !nodeIds.has(safeEdge.source) || !nodeIds.has(safeEdge.target)) return [];
+ return [safeEdge];
+ });
+ return { nodes, edges };
+}
+
+function samePathEndpoint(value: string, node: SafeGraphNode): boolean {
+ return value === node.id || value === node.label;
+}
+
+function pathNodeId(value: string, nodes: SafeGraphNode[]): string | undefined {
+ return nodes.find((node) => samePathEndpoint(value, node))?.id;
+}
+
+function pathEdgeIds(step: AttackPathStep, nodes: SafeGraphNode[], edges: SafeGraphEdge[]): string[] {
+ const source = pathNodeId(step.from, nodes);
+ const target = pathNodeId(step.to, nodes);
+ if (!source || !target) return [];
+ return edges.filter((edge) => edge.source === source && edge.target === target).map((edge) => edge.id);
+}
+
+export function getPathHighlight(path: AttackPath | null | undefined, graph: SafeGraph): GraphHighlight {
+ const nodeIds = new Set<string>();
+ const edgeIds = new Set<string>();
+ if (!path) return { nodeIds, edgeIds };
+ path.steps.forEach((step) => {
+ const source = pathNodeId(step.from, graph.nodes);
+ const target = pathNodeId(step.to, graph.nodes);
+ if (source) nodeIds.add(source);
+ if (target) nodeIds.add(target);
+ pathEdgeIds(step, graph.nodes, graph.edges).forEach((edgeId) => edgeIds.add(edgeId));
+ });
+ return { nodeIds, edgeIds };
+}
+
+export function filterGraph(graph: SafeGraph, filters: GraphFilters, highlight: GraphHighlight): SafeGraph {
+ const selectedTypes = new Set(filters.nodeTypes);
+ const hasTypeFilter = selectedTypes.size > 0;
+ const nodes = graph.nodes.filter((node) => {
+ if (hasTypeFilter && !selectedTypes.has(node.type)) return false;
+ if (filters.severity !== "all" && node.type === "finding" && node.severity !== filters.severity) return false;
+ if (filters.activePathOnly && !highlight.nodeIds.has(node.id)) return false;
+ return true;
+ });
+ const nodeIds = new Set(nodes.map((node) => node.id));
+ const edges = graph.edges.filter((edge) => {
+ if (!nodeIds.has(edge.source) || !nodeIds.has(edge.target)) return false;
+ return !filters.activePathOnly || highlight.edgeIds.has(edge.id);
+ });
+ return { nodes, edges };
+}
+
+export function graphNodeTypes(graph: SafeGraph): string[] {
+ return [...new Set(graph.nodes.map((node) => node.type))].sort();
+}
+
+export function isGraphEmpty(graph: SafeGraph): boolean {
+ return graph.nodes.length === 0;
+}
+
+export function attackPathSummary(path: AttackPath): string {
+ const start = path.start || path.steps[0]?.from || "Unknown source";
+ const end = path.end || path.steps[path.steps.length - 1]?.to || "Unknown target";
+ return `${start} → ${end}`;
+}
diff --git a/frontend/src/styles.css b/frontend/src/styles.css
index c8cd54f..4fb7475 100644
--- a/frontend/src/styles.css
+++ b/frontend/src/styles.css
@@ -1232,6 +1232,299 @@ textarea.field {
color: #c2410c;
}
+.graph-panel {
+ min-height: 580px;
+}
+
+.graph-toolbar {
+ display: flex;
+ align-items: end;
+ justify-content: space-between;
+ gap: 0.75rem;
+ margin-bottom: 0.85rem;
+}
+
+.graph-campaign-select,
+.graph-ingest-form label,
+.graph-filter-group {
+ display: grid;
+ gap: 0.34rem;
+ color: #475569;
+ font-size: 0.76rem;
+ font-weight: 650;
+}
+
+.graph-campaign-select {
+ width: min(100%, 360px);
+}
+
+.graph-workspace {
+ display: grid;
+ gap: 0.85rem;
+}
+
+.graph-filters,
+.graph-active-path {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 0.65rem;
+ border: 1px solid #e2e8f0;
+ border-radius: 6px;
+ background: #fbfdff;
+ padding: 0.62rem;
+}
+
+.graph-filter-title {
+ color: #334155;
+ font-size: 0.8rem;
+ font-weight: 700;
+}
+
+.graph-filter-group {
+ min-width: 132px;
+}
+
+.graph-filter-group .field {
+ min-height: 31px;
+ font-size: 0.78rem;
+}
+
+.graph-filter-options {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.32rem;
+}
+
+.filter-chip {
+ border: 1px solid #cbd5e1;
+ border-radius: 999px;
+ background: #ffffff;
+ padding: 0.22rem 0.48rem;
+ color: #475569;
+ font-size: 0.72rem;
+ font-weight: 650;
+}
+
+.filter-chip.active {
+ border-color: #c2410c;
+ background: #fff8f1;
+ color: #9a3412;
+}
+
+.graph-path-only-toggle {
+ margin-left: auto;
+ font-size: 0.78rem;
+}
+
+.graph-active-path {
+ border-color: #fed7aa;
+ background: #fff8f1;
+ color: #9a3412;
+ font-size: 0.82rem;
+ font-weight: 600;
+}
+
+.graph-active-path .btn {
+ margin-left: auto;
+}
+
+.graph-canvas {
+ min-height: 520px;
+ overflow: hidden;
+ border: 1px solid #d5dce7;
+ border-radius: 6px;
+ background: #f8fafc;
+}
+
+.graph-canvas .react-flow__controls,
+.graph-canvas .react-flow__minimap {
+ border: 1px solid #cbd5e1;
+ border-radius: 5px;
+ box-shadow: 0 4px 10px rgba(15, 23, 42, 0.1);
+}
+
+.ares-flow-node {
+ min-width: 148px;
+ max-width: 210px;
+ border: 1px solid color-mix(in srgb, var(--node-color) 62%, #64748b);
+ border-left: 4px solid var(--node-color);
+ border-radius: 6px;
+ background: #ffffff;
+ padding: 0.45rem 0.55rem;
+ color: #1f2937;
+ box-shadow: 0 5px 12px rgba(15, 23, 42, 0.09);
+ transition: opacity 120ms ease, box-shadow 120ms ease;
+}
+
+.ares-flow-node.selected {
+ box-shadow: 0 0 0 3px rgba(249, 115, 22, 0.28), 0 5px 12px rgba(15, 23, 42, 0.1);
+}
+
+.ares-flow-node.dimmed {
+ opacity: 0.28;
+}
+
+.ares-flow-node-type,
+.ares-flow-node small {
+ display: block;
+ color: #64748b;
+ font-size: 0.65rem;
+ font-weight: 650;
+ text-transform: uppercase;
+}
+
+.ares-flow-node strong {
+ display: block;
+ margin: 0.16rem 0;
+ overflow: hidden;
+ color: #1f2937;
+ font-size: 0.78rem;
+ font-weight: 700;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.ares-flow-node small {
+ width: fit-content;
+ border-radius: 999px;
+ padding: 0.08rem 0.3rem;
+}
+
+.graph-side-panel {
+ align-self: stretch;
+ min-height: 300px;
+ padding: 0.78rem;
+}
+
+.graph-side-heading,
+.graph-detail-heading {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 0.55rem;
+ color: #334155;
+}
+
+.graph-side-heading {
+ align-items: center;
+ margin-bottom: 0.75rem;
+ font-size: 0.84rem;
+}
+
+.graph-detail-heading span,
+.graph-detail-heading strong {
+ display: block;
+}
+
+.graph-detail-heading span,
+.graph-detail-route {
+ color: #64748b;
+ font-size: 0.72rem;
+ font-weight: 600;
+}
+
+.graph-detail-heading strong {
+ margin-top: 0.14rem;
+ color: #1f2937;
+ font-size: 0.88rem;
+ overflow-wrap: anywhere;
+}
+
+.graph-detail-route {
+ overflow-wrap: anywhere;
+}
+
+.graph-detail-empty {
+ color: #64748b;
+ font-size: 0.82rem;
+ line-height: 1.45;
+}
+
+.graph-detail-list {
+ display: grid;
+ gap: 0.52rem;
+ margin: 0.8rem 0 0;
+}
+
+.graph-detail-list div {
+ border-top: 1px solid #eef2f7;
+ padding-top: 0.48rem;
+}
+
+.graph-detail-list dt {
+ color: #64748b;
+ font-size: 0.69rem;
+ font-weight: 700;
+ text-transform: capitalize;
+}
+
+.graph-detail-list dd {
+ margin: 0.14rem 0 0;
+ overflow-wrap: anywhere;
+ color: #334155;
+ font-size: 0.78rem;
+ line-height: 1.4;
+}
+
+.attack-path-list {
+ display: grid;
+ gap: 0.5rem;
+}
+
+.attack-path-card {
+ display: grid;
+ gap: 0.2rem;
+ width: 100%;
+ border: 1px solid #e2e8f0;
+ border-radius: 6px;
+ background: #fbfdff;
+ padding: 0.62rem;
+ text-align: left;
+}
+
+.attack-path-card:hover,
+.attack-path-card.active {
+ border-color: #f97316;
+ background: #fff8f1;
+}
+
+.attack-path-card span,
+.attack-path-card small {
+ color: #64748b;
+ font-size: 0.7rem;
+ font-weight: 600;
+}
+
+.attack-path-card strong {
+ overflow-wrap: anywhere;
+ color: #334155;
+ font-size: 0.8rem;
+}
+
+.graph-ingest-form {
+ display: grid;
+ max-width: 620px;
+ gap: 0.75rem;
+}
+
+.graph-ingest-form h2,
+.graph-ingest-form p {
+ margin: 0;
+}
+
+.graph-ingest-form h2 {
+ color: #1f2937;
+ font-size: 0.95rem;
+}
+
+.graph-ingest-form p:not(.notice) {
+ margin-top: 0.2rem;
+ color: #64748b;
+ font-size: 0.82rem;
+ line-height: 1.4;
+}
+
.key-row {
display: flex;
align-items: center;
@@ -1391,4 +1684,21 @@ textarea.field {
align-items: flex-start;
flex-direction: column;
}
+
+ .graph-toolbar {
+ align-items: stretch;
+ flex-direction: column;
+ }
+
+ .graph-campaign-select {
+ width: 100%;
+ }
+
+ .graph-path-only-toggle {
+ margin-left: 0;
+ }
+
+ .graph-canvas {
+ min-height: 390px;
+ }
}
diff --git a/pyproject.toml b/pyproject.toml
index f70b1d1..d9345a2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -154,7 +154,7 @@ asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "session"
timeout = 15
testpaths = ["tests"]
-addopts = "-v --tb=short"
+addopts = "-v --tb=short --basetemp=.pytest-tmp"
markers = [
"live: marks tests that require real network access (deselect with '-m not live')",
"slow: marks tests that are slow (deselect with '-m not slow')",
diff --git a/tests/integration/test_api_post.py b/tests/integration/test_api_post.py
index aec7c21..7a7ebde 100644
--- a/tests/integration/test_api_post.py
+++ b/tests/integration/test_api_post.py
@@ -31,15 +31,33 @@ _ENCKEY = "integration-enc-key-min32-chars!!"
_ADMIN = "IntegrationAdmin1!"
_DBURL = "sqlite+aiosqlite:///file:int_post_test?mode=memory&cache=shared&uri=true"
-os.environ["ARES_SECRET_KEY"] = _SECRET
-os.environ["ARES_ENCRYPTION_KEY"] = _ENCKEY
-os.environ["ARES_DEFAULT_ADMIN_PASSWORD"]= _ADMIN
-os.environ["ARES_DATABASE_URL"] = _DBURL
-
import pytest
from fastapi.testclient import TestClient
[email protected](scope="module", autouse=True)
+def isolated_api_post_environment():
+ """Keep this integration database URL from leaking into the full suite."""
+ updates = {
+ "ARES_SECRET_KEY": _SECRET,
+ "ARES_ENCRYPTION_KEY": _ENCKEY,
+ "ARES_DEFAULT_ADMIN_PASSWORD": _ADMIN,
+ "ARES_DATABASE_URL": _DBURL,
+ }
+ original = {key: os.environ.get(key) for key in updates}
+ os.environ.update(updates)
+ from ares.core.config import get_settings
+
+ get_settings.cache_clear()
+ yield
+ for key, value in original.items():
+ if value is None:
+ os.environ.pop(key, None)
+ else:
+ os.environ[key] = value
+ get_settings.cache_clear()
+
+
def _fresh_client() -> TestClient:
"""
Return a TestClient with a fresh settings cache.
diff --git a/tests/unit/db/test_database.py b/tests/unit/db/test_database.py
index d49624c..a038706 100644
--- a/tests/unit/db/test_database.py
+++ b/tests/unit/db/test_database.py
@@ -99,7 +99,7 @@ class TestPluginLoader:
assert len(ad_mods) >= 4
def test_external_dir_empty_is_ok(self, tmp_path: Path) -> None:
- loader = PluginLoader()
+ loader = PluginLoader(trusted_external_roots=[tmp_path])
loader._load_external(str(tmp_path)) # Should not raise
assert loader.errors == []
@@ -135,14 +135,14 @@ class ExternalTestModule(BaseModule):
return [], {}
'''
(tmp_path / "external_test_module.py").write_text(plugin_code)
- loader = PluginLoader()
+ loader = PluginLoader(trusted_external_roots=[tmp_path])
registry = loader.load_all(external_dir=str(tmp_path))
assert "external.test" in registry
def test_invalid_plugin_does_not_crash_loader(self, tmp_path: Path) -> None:
"""Broken plugin should not crash the loader."""
(tmp_path / "broken.py").write_text("this is not valid python }{}{")
- loader = PluginLoader()
+ loader = PluginLoader(trusted_external_roots=[tmp_path])
loader.load_all(external_dir=str(tmp_path))
assert len(loader.errors) >= 1
diff --git a/tests/unit/test_api_endpoints.py b/tests/unit/test_api_endpoints.py
index e25b18a..f0f9481 100644
--- a/tests/unit/test_api_endpoints.py
+++ b/tests/unit/test_api_endpoints.py
@@ -1318,9 +1318,10 @@ class TestModuleRunEndpoint:
assert snapshot["modules"]["success"] == 1
assert snapshot["findings"] == 1
assert snapshot["latency_ms"]["p50"] == 42.5
- db.record_module_run.assert_awaited_once()
- assert db.record_module_run.await_args.kwargs["outcome"] == "confirmed_findings"
- assert db.record_module_run.await_args.kwargs["success"] is True
+ # Persistence belongs to the DB-bound engine. A lightweight route
+ # double must not cause the API layer to write a second record.
+ db.record_module_run.assert_not_awaited()
+ db.save_finding.assert_not_awaited()
class TestReportEndpoints:
@@ -1471,6 +1472,9 @@ class TestReportEndpoints:
class FakeEngine:
registry = FakeRegistry()
+ def __init__(self, db: AresDatabase) -> None:
+ self.db = db
+
async def run_module(
self,
module_id: str,
@@ -1511,20 +1515,29 @@ class TestReportEndpoints:
remediation="Rotate service account credentials.",
host="10.10.10.20",
)
- return EngineModuleResult(
+ result = EngineModuleResult(
module_id=module_id,
status=ModuleStatus.DONE,
findings=[finding],
raw_output={"confirmed": 1},
duration_ms=12.0,
)
+ await self.db.save_finding(campaign.id, finding, module_id)
+ await self.db.record_module_run(
+ campaign.id,
+ module_id,
+ result.outcome,
+ True,
+ result.duration_ms,
+ )
+ return result
def generator_factory(*args: Any, **kwargs: Any) -> Any:
return real_report_generator(output_dir=str(tmp_path / "reports"), **kwargs)
app.state.db = real_db
app.dependency_overrides[get_db] = lambda: real_db
- app.dependency_overrides[get_engine] = lambda: FakeEngine()
+ app.dependency_overrides[get_engine] = lambda: FakeEngine(real_db)
monkeypatch.setattr(report_gen, "ReportGenerator", generator_factory)
try:
common_params = {
diff --git a/tests/unit/test_phase1_runtime_durability.py b/tests/unit/test_phase1_runtime_durability.py
new file mode 100644
index 0000000..060d6f4
--- /dev/null
+++ b/tests/unit/test_phase1_runtime_durability.py
@@ -0,0 +1,265 @@
+"""Phase 1 regressions for the durable API -> engine -> DB -> graph path."""
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock
+
+import pytest
+
+from ares.api import server
+from ares.core.campaign import Campaign, Finding, NoiseProfile, ScopeEntry, Severity
+from ares.core.config import AresSettings
+from ares.core.engine import AresEngine, ExecutionPlan, ModuleStatus
+from ares.core.plugin.loader import ModuleRegistry
+from ares.credential.vault import Credential, CredentialType, CredentialVault
+from ares.db.database import AresDatabase, DBCredential, Host
+from ares.modules.base import BaseModule, ModuleResult
+from ares.strategy.engine import StrategyEngine
+
+
+class PhaseOneProbeModule(BaseModule):
+ """A no-network module used only to exercise engine persistence."""
+
+ MODULE_ID = "ad.phase1_probe"
+ MODULE_NAME = "Phase 1 probe"
+ MODULE_CATEGORY = "ad"
+ MODULE_DESCRIPTION = "Test-only durable runtime probe"
+ contexts: list[Any] = []
+
+ async def validate(self, ctx: Any) -> None:
+ return None
+
+ async def execute(self, ctx: Any) -> ModuleResult:
+ type(self).contexts.append(ctx)
+ ctx.session.add_host("10.10.10.5", hostname="dc01", is_dc=True)
+ finding = Finding(
+ title="Persisted probe finding",
+ description="A safe test finding created without contacting a target.",
+ severity=Severity.HIGH,
+ host="10.10.10.5",
+ module_id=self.MODULE_ID,
+ )
+ return ModuleResult(
+ status="success",
+ module_id=self.MODULE_ID,
+ findings=[finding],
+ raw={"source": "phase1-test"},
+ )
+
+
+def _settings() -> AresSettings:
+ return AresSettings(
+ ares_secret_key="phase1-test-secret-key-min-32-chars!!",
+ ares_encryption_key="phase1-test-encryption-key-min-32chars!!",
+ ares_default_admin_password="Phase1TestPassword!",
+ )
+
+
+def _campaign(campaign_id: str = "phase1-campaign") -> Campaign:
+ return Campaign(
+ id=campaign_id,
+ name="Phase 1 durable test",
+ client="ARES",
+ operator="owner",
+ scope=[ScopeEntry(cidr="10.10.10.0/24")],
+ noise_profile=NoiseProfile.NORMAL,
+ )
+
+
+def _engine(settings: AresSettings, db: AresDatabase) -> AresEngine:
+ engine = AresEngine(settings=settings, db=db)
+ registry = ModuleRegistry()
+ registry.register(PhaseOneProbeModule)
+ engine._registry = registry
+ return engine
+
+
+async def test_db_bound_engine_persists_each_execution_once(tmp_path: Any) -> None:
+ settings = _settings()
+ db = await AresDatabase.create(tmp_path / "phase1.db", settings.encryption_key_value)
+ campaign = _campaign()
+ await db.save_campaign(campaign)
+ engine = _engine(settings, db)
+ PhaseOneProbeModule.contexts.clear()
+ try:
+ result = await engine.run_module(
+ PhaseOneProbeModule.MODULE_ID,
+ campaign,
+ {"target": "10.10.10.5"},
+ actor_role="team_lead",
+ )
+ findings, total = await db.list_findings(campaign.id, per_page=20)
+ async with db.conn.execute(
+ "SELECT COUNT(*) AS n FROM module_runs WHERE campaign_id=?", (campaign.id,)
+ ) as cursor:
+ module_runs = int((await cursor.fetchone())["n"])
+
+ assert result.status is ModuleStatus.DONE
+ assert total == len(findings) == 1
+ assert module_runs == 1
+ assert PhaseOneProbeModule.contexts[-1].artifact_store is campaign._runtime_state.artifact_store
+ assert PhaseOneProbeModule.contexts[-1].vault is campaign._runtime_state.vault
+ finally:
+ await db.close()
+
+
+async def test_restored_vault_is_reused_by_the_next_campaign_run(tmp_path: Any) -> None:
+ settings = _settings()
+ db = await AresDatabase.create(tmp_path / "phase1-vault.db", settings.encryption_key_value)
+ campaign = _campaign("phase1-vault")
+ await db.save_campaign(campaign)
+ source_vault = CredentialVault(settings.encryption_key_value)
+ credential = Credential(
+ campaign_id=campaign.id,
+ username="svc_phase1",
+ domain="LAB.LOCAL",
+ cred_type=CredentialType.CLEARTEXT,
+ )
+ source_vault.store(credential, "never-return-this-secret")
+ await db.save_credential_preencrypted(DBCredential(
+ id=credential.id,
+ campaign_id=campaign.id,
+ username=credential.username,
+ cred_type=credential.cred_type.value,
+ secret=credential.secret_enc.decode(),
+ domain=credential.domain,
+ source_module="phase1.fixture",
+ ))
+ engine = _engine(settings, db)
+ PhaseOneProbeModule.contexts.clear()
+ try:
+ restored = await engine.restore_campaign_vault(campaign)
+ result = await engine.run_module(
+ PhaseOneProbeModule.MODULE_ID,
+ campaign,
+ {"target": "10.10.10.5"},
+ actor_role="team_lead",
+ )
+
+ assert restored == 1
+ assert result.status is ModuleStatus.DONE
+ assert PhaseOneProbeModule.contexts[-1].vault is campaign._runtime_state.vault
+ assert campaign._runtime_state.vault.get(credential.id) is not None
+ assert "never-return-this-secret" not in json.dumps(result.model_dump(mode="json"))
+ finally:
+ await db.close()
+
+
+async def test_plan_and_strategy_rehydrate_durable_state_and_done_is_success(tmp_path: Any) -> None:
+ settings = _settings()
+ db = await AresDatabase.create(tmp_path / "phase1-plan.db", settings.encryption_key_value)
+ campaign = _campaign("phase1-plan")
+ await db.save_campaign(campaign)
+ engine = _engine(settings, db)
+ try:
+ plan = ExecutionPlan().add_stage(
+ "probe", [PhaseOneProbeModule.MODULE_ID],
+ {PhaseOneProbeModule.MODULE_ID: {"target": "10.10.10.5"}},
+ )
+ plan_results = await engine.run_plan(plan, campaign, actor_role="team_lead")
+ assert plan_results[PhaseOneProbeModule.MODULE_ID].status is ModuleStatus.DONE
+
+ strategy = StrategyEngine(ares_engine=engine, settings=settings)
+ strategy._run_coverage_predictor = AsyncMock(return_value={
+ "detection_score": 0.0,
+ "wait_recommendation": {"hours": 0},
+ })
+ strategy._get_edr_context = AsyncMock(return_value={
+ "edr_vendor": "test", "viable_techniques": [], "recommended_approach": None,
+ })
+ strategy._run_ai_planner = AsyncMock(return_value={
+ "confidence_score": 1.0,
+ "execution_plan": [{
+ "name": "probe",
+ "modules": [PhaseOneProbeModule.MODULE_ID],
+ "params": {PhaseOneProbeModule.MODULE_ID: {"target": "10.10.10.5"}},
+ }],
+ "warnings": [],
+ })
+ strategy_result = await strategy.run_autonomous_engagement(
+ campaign=campaign,
+ max_rounds=1,
+ llm_backend="local",
+ actor_role="team_lead",
+ )
+ assert PhaseOneProbeModule.MODULE_ID in strategy_result.modules_succeeded
+
+ engine.discard_campaign_runtime(campaign.id)
+ rehydrated_campaign = _campaign(campaign.id)
+ restarted_engine = _engine(settings, db)
+ restarted_state = await restarted_engine.ensure_campaign_runtime(rehydrated_campaign)
+ findings, total = await db.list_findings(campaign.id, per_page=20)
+
+ assert total == len(findings) >= 2
+ assert restarted_state.session.get_host("10.10.10.5") is not None
+ assert (await db.get_campaign_graph(campaign.id)) is not None
+ finally:
+ await db.close()
+
+
+async def test_strategy_preflight_does_not_reserve_a_slot_for_unknown_campaign(monkeypatch: Any) -> None:
+ original_db, original_engine = server._db, server._engine
+ server._active_engagements.clear()
+ try:
+ server._db = SimpleNamespace(get_campaign=AsyncMock(return_value=None))
+ server._engine = object() # preflight exits before engine use
+ body = server.AutonomousEngagementRequest(campaign_id="missing", llm_backend="local")
+ with pytest.raises(server.HTTPException) as exc_info:
+ await server.start_autonomous_engagement(
+ body,
+ actor=SimpleNamespace(username="owner", role="team_lead"),
+ )
+ assert exc_info.value.status_code == 404
+ assert server._active_engagements == {}
+ finally:
+ server._db, server._engine = original_db, original_engine
+ server._active_engagements.clear()
+
+
+async def test_persisted_graph_and_attack_paths_use_safe_durable_rows(tmp_path: Any) -> None:
+ settings = _settings()
+ db = await AresDatabase.create(tmp_path / "phase1-graph.db", settings.encryption_key_value)
+ campaign = _campaign("phase1-graph")
+ await db.save_campaign(campaign)
+ await db.upsert_host(Host(
+ campaign_id=campaign.id,
+ ip_address="10.10.10.5",
+ hostname="dc01",
+ is_dc=True,
+ ))
+ await db.save_finding(campaign.id, Finding(
+ title="Persisted graph finding",
+ description="Verified durable graph fixture.",
+ severity=Severity.CRITICAL,
+ host="10.10.10.5",
+ module_id="ad.phase1_probe",
+ validated=True,
+ ))
+ await db.save_credential(DBCredential(
+ campaign_id=campaign.id,
+ username="svc_graph",
+ cred_type="cleartext",
+ secret="graph-secret-must-not-leak",
+ domain="LAB.LOCAL",
+ ))
+ engine = _engine(settings, db)
+ actor = SimpleNamespace(username="owner", role="team_lead")
+ try:
+ graph_payload = await server.campaign_graph(campaign.id, actor=actor, engine=engine, db=db)
+ path_payload = await server.campaign_attack_paths(
+ campaign.id, actor=actor, engine=engine, db=db
+ )
+
+ assert graph_payload["stats"]["hosts"] == 1
+ assert graph_payload["stats"]["findings"] == 1
+ assert "graph-secret-must-not-leak" not in json.dumps(graph_payload)
+ assert path_payload["stats"]["nodes"] >= 3
+ finally:
+ await db.close()