![DARKSOL](./assets/darksol-banner.png)
Built by DARKSOL 🌑

# 🔬 Threat Lab

[![Threat Assessment](https://img.shields.io/badge/threat%20analysis-4%20layers-ff4444?style=flat-square&logo=shield)](https://github.com/darks0l/threat-lab)
[![npm version](https://img.shields.io/badge/npm-0.4.0-orange?style=flat-square)](https://www.npmjs.com/package/threat-lab)
[![tests](https://img.shields.io/badge/tests-99%20passing-brightgreen?style=flat-square)](https://github.com/darks0l/threat-lab)
[![Solidity](https://img.shields.io/badge/solidity-0.8-blue?style=flat-square&logo=solidity)](https://docs.soliditylang.org/)
[![Foundry](https://img.shields.io/badge/foundry-deployed-ff1111?style=flat-square&logo=foundry)](https://book.getfoundry.sh/)
[![License: MIT](https://img.shields.io/badge/license-MIT-yellow?style=flat-square)](./LICENSE)
[![Built with teeth](https://img.shields.io/badge/built%20with-teeth%20🌑-black?style=flat-square)](https://darksol.net)

![Threat Lab Banner](assets/darksol-banner.png)

> Unified Solidity security scanner and threat research CLI — static analysis, dependency audit, live threat intel, exploit simulation, and watch-mode monitoring.

**The threat landscape is a moving target.** MEV bots, flash loan attacks, oracle manipulation — by the time a new exploit pattern is understood well enough to defend against, dozens of protocols have already been hit. The window between "detected" and "exploited" is milliseconds. The window between "exploited" and "patched" is weeks.

Threat Lab is the research infrastructure for that gap. Instead of waiting for the next attack to happen on mainnet, security researchers deploy realistic exploit scenarios in a sandboxed environment, get AI-powered analysis of the attack mechanics, and submit findings to a growing pattern library. The platform gets smarter with every submission.

---

## How it works

```
┌─────────────┐     ┌──────────────┐     ┌────────────┐     ┌──────────────┐
│  Scenario   │────▶│   Execute    │────▶│  Analyze   │────▶│   Library    │
│  Library    │     │ (Anvil/Sepolia)│     │(multi-model)│     │  (grows)     │
└─────────────┘     └──────────────┘     └──────────────┘     └──────────────┘
                           │                    │
                           ▼                    ▼
                    Real tx traces       Threat Report
                    + gas analysis      + recommendations
```

1. **Choose a scenario** — pre-built exploit templates or your own
2. **Execute it** — deploy contracts to Anvil or Base Sepolia, run exploit steps, capture real tx traces
3. **Get AI analysis** — multi-model analysis via Bankr LLM gateway produces structured threat reports
4. **Submit to library** — findings are stored permanently, searchable, citable
5. **Pattern library compounds** — every submission makes future analysis smarter

---

## Quick start

## Install

```bash
npm install threat-lab
```

## Quick Start

```bash
# Check status
npx threat-lab status

# List scenarios + library
npx threat-lab list

# Unified scan — all 4 layers in one pass (recommended)
npx threat-lab scan .                   # full: static + deps + intel + exploit sim
npx threat-lab scan . --quick           # fast: static + deps (no Anvil)
npx threat-lab scan . --no-intel        # skip live threat intel
npx threat-lab scan . --deep            # full + modelab deep research + patch generation
npx threat-lab scan . --output report.md # save a reusable markdown report
npx threat-lab scan . --output .reports/security/threat-lab.sarif # nested dirs auto-create
npx threat-lab scan . --compare baseline.json # see what changed vs a prior scan
npx threat-lab scan . --fail-on high    # fail CI/builds on high+ findings

# Continuous monitoring / watch mode
npx threat-lab watch . --interval 60              # rescan every minute
npx threat-lab watch . --interval 30 --iterations 5 # run 5 monitor cycles then exit
npx threat-lab watch . --out-dir .threat-lab/watch # save per-cycle snapshots

# Fleet monitor / multi-repo monitoring
npx threat-lab monitor add ../repo-a ../repo-b
npx threat-lab monitor list
npx threat-lab monitor scan --output .reports/security/fleet.json

# Analyze a Solidity file directly (static analysis only)
npx threat-lab analyze ./contracts/MyVault.sol

# Dependency audit only (npm + OSV + Socket.dev)
npx threat-lab audit .
npx threat-lab audit ./ --no-socket   # skip Socket.dev (no API key)

# Execute a scenario (requires Anvil running)
npx threat-lab run reentrancy-101 --network anvil

# Search the pattern library
npx threat-lab library search reentrancy

# View library stats
npx threat-lab library

# Export library (IPFS-ready)
npx threat-lab export
```

---

## Scenarios

| ID | Pattern | Severity | Difficulty |
|----|----------|----------|------------|
| `reentrancy-101` | Reentrancy vault drain | Critical | Beginner |
| `oracle-manipulation-101` | Uniswap V2 oracle manipulation | High | Intermediate |
| `flash-loan-101` | Flash loan arbitrage | Medium | Beginner |
| `sandwich-attack-101` | AMM sandwich attack | High | Intermediate |
| `governance-attack-101` | DAO governance flash loan takeover | Critical | Advanced |
| `liquidation-attack-101` | Aave V2 oracle liquidation attack | High | Advanced |

---

## Architecture

```
threat-lab/
├── src/
│   ├── schemas.ts           # Zod schemas for all entities
│   ├── scenarios.ts         # Built-in attack scenario library
│   ├── executor.ts          # Deploy contracts + run exploit steps
│   ├── runner.ts            # Full orchestrator: execute → analyze → library
│   ├── modelabIntegration.ts # Multi-model AI analysis via Bankr gateway
│   ├── analyzer.ts          # AI analysis engine (signature + LLM)
│   ├── patternDetector.ts    # Pattern matching against known signatures
│   ├── library.ts           # Persistent pattern library (IPFS-ready)
│   ├── scanner.ts           # Unified scan orchestrator (static + deps + sim)
│   ├── audit.ts             # Dependency audit (OSV + npm + Socket.dev)
│   ├── auditSchemas.ts      # Zod schemas for audit result types
│   ├── api.ts               # Submission endpoint handler
│   └── cli.ts               # Full CLI (scan/audit/run/analyze/library/export)
├── contracts/              # Exploitable Solidity contract templates
│   ├── ReentrancyVault.sol
│   ├── OracleManipulation.sol
│   ├── FlashLoanAttacker.sol
│   └── *.sol                # Additional scenario contracts
├── library/                # Pattern library storage (created at runtime)
│   ├── index.json           # Library index
│   └── reports/             # Individual threat reports
├── scripts/
│   └── deploy.ts            # Deploy scenarios to Anvil / Base Sepolia
├── test/                   # Foundry/Forge tests
└── foundry.toml            # Forge configuration
```

---

## The execution loop

```
threat-lab run reentrancy-101

⚡ Executing: Reentrancy Vault Drain
   Network: anvil | RPC: http://127.0.0.1:8545

  [0] Deployed ReentrancyVault at 0x5FbDB2315678afecb367f032d93F642f54180a3E
  [1] Funded vault with 10 ETH
  [2] Deployed Attacker contract
  [3] Executed attack(10 ETH) -> recursive withdrawal confirmed

📋 Captured 4 transactions

🧠 Running modelab analysis for: Reentrancy Vault Drain
   Models: claude-sonnet-4-6
  ✅ claude-sonnet-4-6: reentrancy (80% confidence) — 1420ms

🏆 Best analysis: claude-sonnet-4-6 — reentrancy (80% conf)

📚 Added to pattern library:
   ID: a1b2c3d4-...
   Pattern: reentrancy | Severity: critical
   Library size: 7 entries

────────────────────────────────────────────────────────────
📋 THREAT REPORT — Reentrancy Vault Drain
   Pattern:   reentrancy
   Severity:   critical
   Confidence: 80%
   AI Model:  claude-sonnet-4-6

   Recommendations:
   - Implement CEI pattern (Checks-Effects-Interactions)
   - Add ReentrancyGuard from OpenZeppelin
   - Use pull-based withdrawal pattern instead of push
────────────────────────────────────────────────────────────
```

---

## Pattern library

The library currently recognizes:

- `reentrancy` — external calls before state updates
- `oracle-manipulation` — spot price oracle attacks
- `flash-loan-attack` — uncollateralized borrow + arbitrage
- `access-control` — missing permission checks
- `front-running` — MEV transaction order exploitation
- `sandwich-attack` — front-run + back-run combo
- `integer-overflow` — unchecked arithmetic
- `delegatecall-injection` — storage corruption via delegatecall
- `permit-front-run` — EIP712 signature replay
- `liquidation-attack` — oracle-manipulated liquidation exploit

Every submission expands the library. New patterns can be added by submitting a new scenario.

**Community submissions are reviewed manually.** See [library/SUBMISSION_GUIDE.md](library/SUBMISSION_GUIDE.md) for the full workflow, JSON format, and review criteria.

---

## Environment variables

```bash
# Bankr LLM gateway (required for AI analysis + modelab deep research)
BANKR_API_KEY=your_bankr_api_key

# Brave Search API (optional — enables Layer 2b live threat intel)
# Get free key at: https://brave.com/search/api/
BRAVE_SEARCH_API_KEY=your_brave_api_key

# Anvil (defaults to http://127.0.0.1:8545)
ANVIL_RPC=http://127.0.0.1:8545

# Base Sepolia deployment
BASE_SEPOLIA_RPC=https://sepolia.base.org
DEPLOYER_PRIVATE_KEY=0x...
```

---

## The unified scan — all 4 layers in one command

```
npx threat-lab scan .

🔬 Threat Lab — Scanning .
   Static analysis:   always on (signature patterns + AI deep-read)
   Dependency audit: ON (npm + OSV.dev + Socket.dev)
   Exploit sim:      ON (Anvil)

  🟠 contracts/MyVault.sol [score: 72] [exploit sim: liquidation-attack]
  🔴 contracts/GovToken.sol [score: 89] [exploit sim: governance-attack]
  🟢 contracts/SafeMath.sol [score: 3]

   Overall Threat: HIGH | Score: 80/100 | 3 files
```

The unified `scan` command runs four independent passes, then can stay live in `watch` mode for rescans and diffs:

### SARIF output for CI / code scanning

Threat Lab can export scan findings as **SARIF 2.1.0** for GitHub code scanning and other security tooling.

```bash
npx threat-lab scan . --output .reports/security/threat-lab.sarif
```

Custom output directories are created automatically, so nested paths are safe.

### Fleet state files

Threat Lab stores fleet-monitor state locally under `.threat-lab/`:

- `fleet.json` - registered repos in the monitoring fleet
- `fleet-last.json` - most recent fleet scan output
- `threat-state.json` - persistent deduped threat memory across scans

`threat-state.json` is where active package-level threat intel starts becoming durable instead of one-shot search noise.

### GitHub Action wrapper

Threat Lab now ships a reusable composite action, so repos can use it directly:

```yaml
name: threat-lab

on:
  push:
    branches: [main]
  pull_request:

jobs:
  scan:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Threat Lab scan
        uses: darks0l/threat-lab@v0
        with:
          path: .
          scan-args: --quick --no-intel --fail-on high
          output: .reports/security/threat-lab.sarif
```

### Action inputs

- `path` — path to scan (default: `.`)
- `node-version` — Node version for the run (default: `20`)
- `install-command` — dependency install command (default: `npm ci`)
- `build-command` — build command (default: `npm run build`)
- `scan-args` — extra args passed to `threat-lab scan` (default: `--quick --no-intel`)
- `output` — SARIF output path (default: `.reports/security/threat-lab.sarif`)
- `upload-sarif` — whether to upload SARIF automatically (default: `true`)

### Manual GitHub Actions example

If you want the lower-level version instead of the wrapper:

```yaml
name: threat-lab

on:
  push:
    branches: [main]
  pull_request:

jobs:
  scan:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install deps
        run: npm ci

      - name: Build Threat Lab
        run: npm run build

      - name: Run Threat Lab SARIF scan
        run: node dist/cli.js scan . --quick --no-intel --output .reports/security/threat-lab.sarif

      - name: Upload SARIF
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: .reports/security/threat-lab.sarif
```

If you want CI to fail on serious findings too, add `--fail-on high` to the scan command or to `scan-args` in the wrapper.

**Layer 1 — Static Analysis** *(always on)*
Signature pattern matching against all known attack patterns + Bankr AI deep-read of contract code. Scans every `.sol` file in the target path recursively.

**Layer 2 — Dependency Audit** *(if `node_modules` present)*
Queries OSV.dev, npm Security Advisories, and Socket.dev for known vulnerabilities and malicious packages. Active exploits (CVEs described as "actively exploited") are flagged at highest priority.

**Layer 2b — Live Threat Intelligence** *(always on, requires internet)*
After static vuln DB checks, searches the live web for package mentions in the last 14 days and correlates them against declared project dependencies before escalating:
- GitHub Security Advisories API (free, no key needed)
- Brave Search API for X/Twitter and security blog discussions
- Catches 0-days and active discussions NOT yet in CVE/OSV databases
- Keywords: "actively exploited", "weaponized", "poc available", "zero-day"
- Requires: `BRAVE_SEARCH_API_KEY` (get at brave.com/search/api)

**Layer 3 — Exploit Simulation** *(if Anvil running + contract matched to scenario)*
Matches your contract to a built-in scenario by code signature, deploys it to Anvil, executes the attack, and runs the transaction trace through AI for a verdict.

**Watch Mode** *(optional, `watch <path>`)*
Build a baseline scan, re-run on an interval, diff each cycle, emit only new/escalated high-signal findings, and optionally save JSON snapshots for later review.

**Fleet Monitor** *(new, `monitor ...`)*
Threat Lab can now track multiple repos as a fleet:
- `threat-lab monitor add ../repo-a ../repo-b` registers repos in `.threat-lab/fleet.json`
- `threat-lab monitor list` shows the current fleet + last scan timestamps
- `threat-lab monitor scan` runs repo-by-repo scans, builds shared dependency exposure maps, and persists threat memory to `.threat-lab/threat-state.json`
- threat memory dedupes findings by package + source URL/title, tracks first seen / last seen / sightings, and records which repos are exposed

This is the first step toward org-scale autonomous monitoring: shared package blast radius, new threat detection, and persistent cross-repo intel state.

**Deep Research** *(optional, `--deep` flag)*
Runs flagged findings through modelab's multi-model research pipeline:
- Parallel research across multiple AI models (Sonnet, Opus, GLM)
- Root cause analysis + impact assessment
- Concrete exploit scenarios with parameters

**Report Export**
- `--output report.json` saves the full machine-readable scan payload where you want it
- `--output report.md` saves a readable markdown summary for sharing, review, or diffing between runs

**Baseline Diffing**
- `--compare baseline.json` compares the current scan to a previous JSON export
- highlights new findings, resolved files, and files whose severity/score changed
- best used with saved `--output report.json` artifacts between commits or releases

**Security Gates**
- `--fail-on high` exits non-zero when the worst scan severity is `high` or `critical`
- supports: `critical`, `high`, `medium`, `low`, `informational`
- useful for CI, release checks, and protected deployment workflows
- Patch/remediation code generation in Solidity
- Validated fix output with confidence scores
- Requires: `BANKR_API_KEY`

Reports are saved to `threat-reports/<file>.<pattern>.md` and `threat-reports/simulation/<scenario>.json`.

## Building

```bash
npm install
npm run build        # TypeScript compilation
forge build          # Solidity contracts (requires Foundry)
npm test             # Run SDK tests
```

---

## Deploying scenarios

```bash
# Local Anvil (recommended for testing)
forge build && npx threat-lab run reentrancy-101 --network anvil

# Base Sepolia (requires DEPLOYER_PRIVATE_KEY)
npx threat-lab run reentrancy-101 --network base-sepolia
```

---

Built with teeth. 🌑

