# scoping-bee

Perform structured pre-audit scoping for smart contract security audits (Solidity and Solana/Anchor). Analyzes a codebase to produce flow diagrams, complexity scoring, prioritized hitlists, and a bee-themed scope report with configurable auditor pace. Includes pre-scoping threat intelligence scan. Use when starting a new audit, scoping a contract, evaluating audit complexity, or preparing a scope document for a security engagement.

- **Kind:** skill
- **Source:** https://github.com/0xRayaa/scoping-bee
- **Page:** https://forefy.com/skills/f357ca11-7760-4d3e-8bac-18144943ee68
- **API (JSON + files):** https://forefy.com/api/skills/f357ca11-7760-4d3e-8bac-18144943ee68

---

## CLAUDE.md

# 🐝 Scoping Bee

**`━━━━⬡⬡⬡━━━━`** Smart contract security audit scoping tool **`━━━━⬡⬡⬡━━━━`**

When the user provides a **GitHub URL**, **ZIP file**, or **contract address**, automatically run the full scoping pipeline.

## ⬡ Quick Start

The user will give you one of these inputs:
- A GitHub link (e.g., `https://github.com/org/repo`)
- A ZIP file path (e.g., `./contracts.zip`)
- A block explorer URL (e.g., `https://etherscan.io/address/0x...`)
- A contract address with chain (e.g., `0x... --chain bsc`)
- A local directory path

**When any of these is provided, immediately run the full scoping pipeline without asking questions.**

## ⬡ Pipeline (run in order)

### Step 1: 📥 Fetch Source
```bash
bash <project_root>/scripts/source_fetcher.sh <input> --output ./audit-target [OPTIONS]
```

### Step 2: 🛡️ Threat Intel Scan (MANDATORY)

Two methods are available — **prefer Method A (Docker)** when Docker is installed.

#### Method A — Isolated Docker scan (preferred)

> **⚠️ Runs inside a Docker container with `--network none` and a read-only mount. The untrusted code never executes on your machine.**

```bash
bash <project_root>/scripts/run_threat_scan.sh ./audit-target
```

Wraps `scripts/threat_intel_scan.sh` (16-phase scanner) inside the image built from `scanner/Dockerfile`. On first run with no cached image, the script builds it locally; subsequent runs reuse the cache and start instantly.

Interpret the exit code:
- `0` → CLEAN — continue
- `10` → MEDIUM findings — warn user, ask to confirm before continuing
- `20` → HIGH findings — BLOCK. Do NOT proceed under any circumstances
- `1` → Docker unavailable — fall back to Method B
- `3` → Scan timeout — investigate before proceeding

#### Method B — LLM-driven manual scan (fallback)

When Docker is not available, follow the 16-phase methodology in [THREAT_INTEL_SKILL.md](THREAT_INTEL_SKILL.md) and run the grep/find checks directly against `./audit-target`.

> **⚠️ Method B executes scan commands on the host. Do NOT run `npm install`, `forge build`, or any build/test commands until the scan reports CLEAN.**

Apply the same severity-based decision logic as Method A (BLOCK on HIGH/CRITICAL, WARN on MEDIUM, proceed on LOW/INFO only).

### Step 3: 📊 Count nSLOC
```bash
bash <project_root>/scripts/sloc_counter.sh ./audit-target [--lang solidity|rust]
```
Mock files are automatically excluded from the count.

### Step 4: 🗺️ Visualize Codebase
```bash
bash <project_root>/scripts/codebase_visualizer.sh ./audit-target
```

### Step 5: 🔍 Full Analysis (Phases 1-4)
Follow the complete methodology in [SKILL.md](SKILL.md):
1. **Codebase Ingestion** — detect language, discover files, count nSLOC, detect deps
2. **Flow Diagram & Dependencies** — Mermaid diagrams for value flow and cross-contract calls
3. **Complexity & Risk** — use [complexity-rubric.md](references/complexity-rubric.md)
4. **Scope Report** — output using [scope-report-template.md](references/scope-report-template.md)

### Step 6: 🐝 Output Report
Save as `<protocol_name>_scope_report.md` in the current working directory.
Use the bee-themed template — honeycomb sections (`⬡ HIVE SECTION N ⬡`),
contract roles (👑 Queen / 🏗️ Builder / 🔧 Worker / 🐝 Guard / 🍯 Honeypot),
ASCII boxes for summaries, amber Mermaid diagrams (`#f0a500`, `#ffd966`),
and the honeycomb footer (`🐝 Generated by Scoping Bee 🍯`).

## ⬡ Key Rules

- `<project_root>` = the directory containing this CLAUDE.md file
- Default audit pace: **350 nSLOC/day** (user can override)
- Always exclude mock/test/script files from nSLOC calculation
- Always run threat intel scan before analysis
- Always state the audit pace used in the final report
- **Threat scan**: Do NOT show false positive counts — only show category check status
- **Estimated Effort**: Place right after Executive Summary (not at the bottom)
- **No Architectural Context JSON**: Use Mermaid flow diagrams instead
- **No System Maps section**: Contract Inventory + Flow Diagram covers this
- **No Attack Surface Matrix**: Use internally for analysis, omit from report
- **Bee theme**: Every report must use the honeycomb theme from the template

## ⬡ Setup for New Scoping Projects

To use this in any directory, copy or symlink the `.claude/` folder and point it to this repo:
```bash
# From your new scoping directory:
mkdir -p .claude
cat > CLAUDE.md << 'EOF'
# 🐝 Scoping Project
Use the scoping-bee skill at /path/to/scoping-bee for all audit scoping tasks.
When given a GitHub URL, ZIP, or contract address, run the full scoping pipeline from SKILL.md.
EOF
```

## LICENSE

```

```

## README.md

<div align="center">

# 🐝 Scoping Bee

**`━━━━⬡⬡⬡━━━━ AI-POWERED AUDIT SCOPING ━━━━⬡⬡⬡━━━━`**

*Point it at a codebase. Get a structured scope report.*

**Solidity** (Foundry/Hardhat) · **Solana/Anchor** (Rust)

</div>

---

<div align="center">

### ⬡ THE HIVE ⬡

</div>

Scoping Bee automates the most critical (and most tedious) phase of a security audit — the initial scoping. Give it a codebase and receive a bee-themed scope report with flow diagrams, complexity scoring, prioritized hitlists, and time estimates.

```
  ⬡─────────────────────────────────────────────────────────────⬡
  │                                                              │
  │  📥 Source Fetch  →  🛡️ Threat Scan  →  📊 Analysis  →  🐝 Report │
  │                                                              │
  ⬡─────────────────────────────────────────────────────────────⬡
```

---

<div align="center">

### ⬡ INSTALLATION ⬡

</div>

## 🔧 Install

Scoping Bee is a set of bash scripts plus an AI-skill definition — no compile step, no package install. Clone it and point your AI assistant at it, or run the scripts directly.

### 1. Clone the repo

```bash
git clone https://github.com/<owner>/scoping-bee.git ~/.scoping-bee
```

(Or clone anywhere you prefer; the path is referenced from your project via `CLAUDE.md` or the skill loader.)

### 2. Prerequisites

| Tool | Why | Install |
|:-----|:----|:--------|
| `bash` 4+ | Runs the scripts | macOS: `brew install bash`; Linux: pre-installed |
| `perl` | Comment-stripping / nSLOC counting | macOS/Linux: pre-installed |
| `find`, `wc`, `grep`, `sed`, `awk`, `od` | Core shell utilities | Pre-installed |
| `git` | GitHub clone input | `brew install git` / apt / dnf |
| `curl`, `jq` | Block-explorer API fetch (only for address / explorer-URL inputs) | `brew install curl jq` |
| `unzip` | ZIP archive input | Pre-installed |

The threat-intel scan and the analysis phases use only the tools above — no pip/npm installs required.

### 3. Wire it into an AI assistant (optional)

**Claude Code (per-project):**

```bash
cd /path/to/your/scoping-project
mkdir -p .claude
cat > CLAUDE.md << 'EOF'
# 🐝 Scoping Project
Use the scoping-bee skill at ~/.scoping-bee for all audit scoping tasks.
When given a GitHub URL, ZIP, or contract address, run the full scoping pipeline from SKILL.md.
EOF
```

**Cursor / other assistants:** reference `SKILL.md` directly and pass the skill folder path in your prompt.

### 4. Environment variables (optional)

Only needed for explorer / contract-address inputs:

```bash
export EXPLORER_API_KEY=<your_etherscan_or_chain_api_key>
```

### 5. Smoke test

```bash
bash ~/.scoping-bee/scripts/sloc_counter.sh ~/.scoping-bee --lang solidity
# Expect: "No source files found" (scoping-bee itself has no .sol files)

bash ~/.scoping-bee/scripts/sloc_counter.sh /path/to/some/contracts
```

If nSLOC prints, you're ready.

---

<div align="center">

### ⬡ RENDERING THE REPORT ⬡

</div>

## 🖼️ How to view Mermaid diagrams in the report

The generated `<protocol>_scope_report.md` embeds Mermaid flow diagrams. They render **natively** in some viewers and need a plugin in others.

| Viewer | Works out of the box? | Notes |
|:-------|:---------------------|:------|
| GitHub web UI | ✅ Yes | Native rendering in any `.md` file since 2022 |
| GitLab web UI | ✅ Yes | Native |
| VS Code (default preview) | ❌ No | Needs an extension (see below) |
| Cursor | ❌ No | Same extension as VS Code |
| Obsidian | ✅ Yes | Native |
| Typora | ✅ Yes | Native |
| Any plain editor | ❌ No | Paste the fenced ` ```mermaid ` block into a Mermaid-aware viewer |

### ✅ Recommended: VS Code / Cursor extension

Install **Markdown Preview Mermaid Support** (free, no subscription, no sign-in):

```bash
# VS Code
code --install-extension bierner.markdown-mermaid

# Cursor
cursor --install-extension bierner.markdown-mermaid
```

Then open the report and press `Cmd/Ctrl+Shift+V` to preview — diagrams render inline.

### ✅ Alternative: push to GitHub

Commit the report to any GitHub repo (public or private) and open it in the web UI — Mermaid blocks render without any configuration.

### ⚠️ Note on mermaid.live

`mermaid.live` works in the browser without an account for quick one-off rendering. It prompts for sign-in only if you try to save or share diagrams to their cloud. For viewing reports you don't need to sign up — prefer the VS Code extension or GitHub for a smoother local workflow.

---

<div align="center">

### ⬡ As an AI Skill ⬡

When integrated with an AI coding assistant, simply ask:

> "Scope the audit for https://github.com/org/repo" 
> "Scope this contract: 0x1234... on BSC" 
> "Scope the audit for ./src" 


### ⬡ FEATURES ⬡

</div>

## 📥 Multi-Source Input

Accepts audit targets from multiple sources — no manual setup needed:

```bash
# GitHub repo
bash scripts/source_fetcher.sh https://github.com/org/repo

# Verified contract on any block explorer
bash scripts/source_fetcher.sh https://bscscan.com/address/0x1234...

# Raw address + chain
bash scripts/source_fetcher.sh 0x1234...abcd --chain bsc

# ZIP file from client
bash scripts/source_fetcher.sh ./contracts.zip

# Local directory
bash scripts/source_fetcher.sh ./src
```

**Supported explorers:** Etherscan, BSCScan, Polygonscan, Arbiscan, Optimism, Fantom, Avalanche, Base (+ testnets)

---

## 🛡️ Pre-Audit Threat Intelligence Scan

Every scoping session starts with a mandatory **10-phase** hive security sweep. Untrusted audit codebases can contain shell injection, network exfiltration, phishing kits, supply chain attacks, and obfuscated payloads targeting auditor machines.

> **⚠️ IMPORTANT: Always run the threat scan in a sandbox first (VM, Docker container, or isolated environment). Only after the scan returns CLEAN should you proceed to analyze the codebase on your local machine. This protects your host from malicious code that the scan is designed to detect.**

```
  Recommended workflow:
  1. Fetch source → sandbox environment (VM / Docker / cloud instance)
  2. Run threat_intel_scan.sh inside the sandbox
  3. If CLEAN ✅ → clone/copy to local machine and proceed with scoping
  4. If BLOCKED 🛑 → do NOT move to local. Review findings in sandbox first.
```

```bash
# Step 1: Run in sandbox first
bash scripts/threat_intel_scan.sh ./target-repo

# Step 2: Only after CLEAN verdict, proceed on local
bash scripts/sloc_counter.sh ./target-repo
```

```
┌─────────────────────────────────────────────────────────┐
│  🐝 HIVE SECURITY SWEEP — 10 PHASES                     │
├─────────────────────────────────────────────────────────┤
│  ⬡ Phase 1   Code Behavior Analysis          (HIGH)    │
│  ⬡ Phase 2   HTML Fingerprint Matching        (MED-HI) │
│  ⬡ Phase 3   Banner & Favicon Analysis        (HIGH)   │
│  ⬡ Phase 4   Client-Side JS Inspection        (MED-HI) │
│  ⬡ Phase 5   Post-Signature Distributor Check  (HIGH)   │
│  ⬡ Phase 6   Codebase Profile Analysis        (MED)    │
│  ⬡ Phase 7   Function Purpose Analysis        (MED-HI) │
│  ⬡ Phase 8   Dependency Audit                 (HIGH)   │
│  ⬡ Phase 9   Reachability Analysis            (MED)    │
│  ⬡ Phase 10  OSS Feed & Vuln Check            (MED-HI) │
├─────────────────────────────────────────────────────────┤
│  Verdict: CLEAN ✅ / WARNING ⚠️ / BLOCKED 🛑            │
└─────────────────────────────────────────────────────────┘
```

---

## 🗺️ Codebase Complexity Visualizer

Generate Mermaid diagrams to visually map code complexity, contract relationships, and attack surfaces:

```bash
# Generate all diagrams to a markdown file
bash scripts/codebase_visualizer.sh ./src --output complexity_map.md

# Generate only inheritance diagram
bash scripts/codebase_visualizer.sh ./src --diagram inheritance

# Include test files
bash scripts/codebase_visualizer.sh ./src --include-tests --output full_map.md
```

**8 Diagram Types:**

| # | Diagram | What it shows |
|--:|:--------|:-------------|
| 1 | Inheritance Hierarchy | Contract `is` chains and trait implementations |
| 2 | Inter-Contract Call Graph | Which contracts call which |
| 3 | State Variable Map | Class diagram of state vars and functions |
| 4 | Access Control Flow | Roles, modifiers, and protected functions |
| 5 | External Dependency Graph | OpenZeppelin, Solmate, custom imports |
| 6 | Function Flow | Entry points → internal → external calls |
| 7 | Complexity Heatmap | Per-file metrics table |
| 8 | Value Flow | Token deposit, withdraw, transfer paths |

---

## 📊 Configurable Audit Pace

Effort estimation uses a configurable **lines-of-code per day** rate:

```bash
# Default: 350 nSLOC/day
bash scripts/sloc_counter.sh ./src

# High-complexity code: 300 nSLOC/day
bash scripts/sloc_counter.sh ./src --pace 300

# Simple patterns: 400 nSLOC/day
bash scripts/sloc_counter.sh ./src --pace 400
```

---

## 🔍 Dual Language Support

Auto-detects Solidity or Rust/Anchor and applies the correct analysis:

| Feature | Solidity | Rust/Anchor |
|:--------|:---------|:------------|
| nSLOC counting | Strips pragma, imports, SPDX | Strips use, mod, attributes |
| Attack surfaces | 24 EVM-specific checks | 18 Solana-specific checks |
| System mapping | Functions, modifiers, events | Instructions, PDAs, CPIs |
| Framework detection | Foundry / Hardhat | Anchor / Native Solana |

---

## 🎯 42 Attack Surface Checks

| EVM (24) | Solana (18) |
|:---------|:------------|
| Reentrancy, proxy patterns, auth bypass | Missing signer, PDA seed confusion |
| Oracle manipulation, share inflation | CPI exploits, type cosplay |
| Flash loans, precision loss, MEV | Account closure, reinitialization |
| Signature replay, gas griefing | Remaining accounts, lamport manipulation |

---

<div align="center">

### ⬡ HIVE STRUCTURE ⬡

</div>

```
  scoping-bee/
  ├── 📋 CLAUDE.md                          # Pipeline instructions
  ├── 📖 SKILL.md                           # Core methodology
  ├── 📄 README.md                          # This file
  │
  ├── 🍯 references/
  │   ├── scope-report-template.md          # Bee-themed output template
  │   ├── attack-surfaces.md                # 42 attack surface checklists
  │   └── complexity-rubric.md              # 5-metric scoring rubric
  │
  └── 🔧 scripts/
      ├── source_fetcher.sh                 # Multi-source input fetcher
      ├── threat_intel_scan.sh              # 10-phase threat scanner
      ├── codebase_visualizer.sh            # Mermaid diagram generator
      └── sloc_counter.sh                   # Dual-language nSLOC counter
```

---

<div align="center">

### ⬡ SCOPING WORKFLOW ⬡

</div>

```
  ⬡─────────────────────────────────────────────────────────────⬡
  │                                                              │
  │  1. 📥 Source Acquisition                                   │
  │         │   GitHub / Explorer / ZIP / Local                  │
  │         │                                                    │
  │  2. 🛡️ Threat Intel Scan (MANDATORY)                       │
  │         │   CLEAN → proceed / BLOCKED → stop                 │
  │         │                                                    │
  │  3. 🔍 Codebase Ingestion                                  │
  │         │   Contract inventory, nSLOC, dependencies          │
  │         │                                                    │
  │  4. 🔀 Flow Diagram & Dependencies                         │
  │         │   Value flow, cross-contract calls, trust map      │
  │         │                                                    │
  │  5. 🔬 Complexity & Risk Scoring                            │
  │         │   5-metric weighted score per contract              │
  │         │                                                    │
  │  6. 🐝 Report Assembly                                     │
  │         │   Bee-themed scope document                        │
  │                                                              │
  ⬡─────────────────────────────────────────────────────────────⬡
```

**Output:** A structured `<protocol>_scope_report.md` with:

| Section | Content |
|:--------|:--------|
| 🛡️ Threat Scan | Hive security sweep results |
| 📋 Executive Summary | Protocol at a glance |
| ⏱️ Estimated Effort | Days breakdown with complexity multipliers |
| 📦 Contract Inventory | The Honeycomb — contracts with bee roles |
| 🔀 Flow Diagram | The Waggle Dance — value flow + dependencies |
| 🔬 Complexity Scores | Per-contract weighted scoring |
| 🎯 Audit Hitlist | Sting Zone / Watch Zone / Low Pollen |
| 🛠️ Methodology | Recommended approach per contract |
| ❓ Open Questions | Items for protocol team |

---

<div align="center">

### ⬡ COMPLEXITY SCORING ⬡

</div>

Each contract is scored on 5 weighted metrics:

| Metric | Weight |
|:-------|-------:|
| nSLOC | 25% |
| External Integration Risk | 25% |
| State Coupling | 20% |
| Access Control Complexity | 15% |
| Upgradeability Risk | 15% |

**Risk Tiers:**

```
  🟢 LOW      (1.0–1.5)  →  Checklist review         — Low Pollen
  🟡 MEDIUM   (1.6–2.5)  →  Vector scan               — Watch Zone
  🟠 HIGH     (2.6–3.5)  →  Deep interrogation         — Sting Zone
  🔴 CRITICAL (3.6–4.0)  →  Full methodology + PoC     — Critical Sting Zone
```

---

<div align="center">

### ⬡ QUICK START ⬡

</div>

### 🔧 Standalone Scripts

```bash
# Fetch from GitHub
bash scripts/source_fetcher.sh https://github.com/org/repo

# Fetch verified contract from BSCScan
bash scripts/source_fetcher.sh https://bscscan.com/address/0x1234... --api-key YOUR_KEY

# Fetch by address + chain
bash scripts/source_fetcher.sh 0xAbCd...1234 --chain polygon

# Extract a ZIP
bash scripts/source_fetcher.sh ./client-contracts.zip --output ./audit-target

# Threat intel scan a repo before opening it
bash scripts/threat_intel_scan.sh /path/to/audit/repo

# Generate Mermaid complexity diagrams
bash scripts/codebase_visualizer.sh /path/to/src --output complexity_map.md

# Count nSLOC with effort estimate
bash scripts/sloc_counter.sh /path/to/src --pace 350

# Count Rust/Solana nSLOC
bash scripts/sloc_counter.sh /path/to/programs --lang rust --pace 300
```
---

## License

MIT

---

<div align="center">

```
  ⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡
  🐝  Built for auditors, by auditors.                     🍯
      Stop wasting time on manual scoping.
  ⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡
```

</div>

## SKILL.md

---
name: scoping-bee
description: >-
  Perform structured pre-audit scoping for smart contract security audits
  (Solidity and Solana/Anchor). Analyzes a codebase to produce flow diagrams,
  complexity scoring, prioritized hitlists, and a bee-themed scope report with
  configurable auditor pace. Includes pre-scoping threat intelligence scan.
  Use when starting a new audit, scoping a contract, evaluating audit complexity,
  or preparing a scope document for a security engagement.
---

# 🐝 Scoping Bee

**`━━━━⬡⬡⬡━━━━ SKILL METHODOLOGY ━━━━⬡⬡⬡━━━━`**

Systematic pre-audit scoping for smart contract security engagements.
Supports **Solidity** (Foundry/Hardhat) and **Solana/Anchor** (Rust) codebases.

Produces a bee-themed scope report with configurable effort estimation that
feeds directly into deep audit methodologies (vector scanning,
threat interrogation, invariant extraction).

---

<div align="center">

### ⬡ CONFIGURATION ⬡

</div>

## Auditor Pace (Lines of Code per Day)

The default audit pace is **350 nSLOC/day**. Adjust this based on:
- Auditor experience level
- Code complexity (drop to ~300 for high-complexity code)
- Familiarity with the protocol pattern

When the user specifies a custom pace, use their value throughout.
If unspecified, use 350.

```
AUDIT_PACE=350  # nSLOC per day (default)
```

**Examples:**
- "Scope this at 300 lines/day" → `AUDIT_PACE=300`
- "Use my normal pace" → `AUDIT_PACE=350` (default)
- "I can do 400/day for simple ERC20s" → `AUDIT_PACE=400`

When presenting the final effort estimate, always state the pace used so
the user can re-calculate if they adjust later.

---

<div align="center">

### ⬡ INVOCATION ⬡

</div>

## Invocation

When the user provides a **GitHub URL**, **ZIP file**, **contract address**, **explorer URL**,
or **local directory path**, immediately start the scoping pipeline — no questions asked.

### Auto-Trigger Inputs

Any of these inputs should trigger the full pipeline automatically:
- `https://github.com/org/repo` — GitHub URL
- `./contracts.zip` — ZIP archive
- `https://etherscan.io/address/0x...` — Block explorer URL
- `0x1234...abcd --chain bsc` — Raw contract address
- `./src` or `./contracts` — Local directory

### Pipeline Steps

1. **Fetch source** — run `source_fetcher.sh` to normalize input into `./audit-target`
2. **Threat scan** — follow [THREAT_INTEL_SKILL.md](THREAT_INTEL_SKILL.md) methodology on the fetched source (MANDATORY). Do NOT use `threat_intel_scan.sh`.
3. **Proceed if clean** — run Phases 1–6 on the normalized source
4. **Output report** — save as `<protocol_name>_scope_report.md` using the template
   in [scope-report-template.md](references/scope-report-template.md)

### Decision Logic After Threat Scan

```
If CRITICAL findings → BLOCK immediately. Do NOT proceed under any circumstances.
If HIGH severity findings → STOP. Report findings. Ask user to review.
If MEDIUM severity findings → WARN. Show findings. Ask user to confirm proceed.
If only LOW/NONE → Proceed automatically to Phase 1.
```

---

<div align="center">

### ⬡ SOURCE ACQUISITION ⬡

</div>

## Source Acquisition

The skill accepts **4 input types**, auto-detected:

| Input | Example | What Happens |
|-------|---------|-------------|
| **GitHub URL** | `https://github.com/org/repo` | Shallow clone (`--depth 1`) |
| **Explorer URL** | `https://bscscan.com/address/0x1234...` | Fetch verified source via API |
| **Contract address** | `0x1234...abcd` (+ `--chain bsc`) | Fetch verified source via API |
| **ZIP file** | `./contracts.zip` | Extract and flatten |
| **Local directory** | `./src` | Use as-is |

### Source Fetcher Script

```bash
bash <skill_dir>/scripts/source_fetcher.sh <input> [OPTIONS]
```

**Options:**
- `--output <dir>` — Output directory (default: `./audit-target`)
- `--chain <chain>` — Chain for address input (eth, bsc, polygon, arbitrum, etc.)
- `--api-key <key>` — Block explorer API key (or set `EXPLORER_API_KEY` env var)
- `--branch <branch>` — Git branch to clone (default: main)

### Supported Block Explorers

| Chain | Explorer | API |
|-------|----------|-----|
| Ethereum | etherscan.io | ✅ |
| Goerli | goerli.etherscan.io | ✅ |
| Sepolia | sepolia.etherscan.io | ✅ |
| BSC | bscscan.com | ✅ |
| BSC Testnet | testnet.bscscan.com | ✅ |
| Polygon | polygonscan.com | ✅ |
| Arbitrum | arbiscan.io | ✅ |
| Optimism | optimistic.etherscan.io | ✅ |
| Fantom | ftmscan.com | ✅ |
| Avalanche | snowtrace.io | ✅ |
| Base | basescan.org | ✅ |

### Decision Logic

```
If input is a GitHub URL      → clone repo → proceed to Phase 0
If input is an explorer URL   → extract address + chain from URL → fetch via API → proceed
If input is a raw 0x address  → require --chain flag → fetch via API → proceed
If input is a .zip file       → extract → flatten single root dir → proceed
If input is a local directory → use directly → proceed
```

**For block explorer inputs:**
- The script writes a `.explorer_metadata.json` with contract name, compiler
  version, optimization settings, and proxy status
- ABI is saved alongside source files
- If the contract is a **proxy**, the script warns — you should also fetch the
  implementation contract

---

<div align="center">

### ⬡ PHASE 0 — THREAT SCAN ⬡

</div>

## Phase 0: Threat Intelligence Scan ⚠️ MANDATORY

**Run this BEFORE any other analysis.** Untrusted audit codebases can contain
malware, phishing kits, supply chain attacks, and backdoors targeting auditor machines.

> **⚠️ SANDBOX FIRST: Always run the threat scan in an isolated environment (VM, Docker container, or cloud instance) before analyzing the codebase on your local machine. Only move the code to your local environment after a CLEAN verdict. If BLOCKED, review findings inside the sandbox — do NOT copy to local.**

> **⚠️ DO NOT use `threat_intel_scan.sh`.** Follow the comprehensive methodology in [THREAT_INTEL_SKILL.md](THREAT_INTEL_SKILL.md) instead. It covers 16 phases of deep threat analysis across all languages and attack classes.

The scan performs **16 phases** of deep threat analysis (see [THREAT_INTEL_SKILL.md](THREAT_INTEL_SKILL.md) for full details):

| Phase | Name | Severity |
|-------|------|----------|
| 1 | Code Execution & Persistence | HIGH |
| 2 | Network Exfiltration & C2 | HIGH |
| 3 | Obfuscation & Encoding | HIGH |
| 4 | Credential & Secret Theft | HIGH |
| 5 | Filesystem & System Access | HIGH |
| 6 | HTML/Phishing & Web Attacks | HIGH |
| 7 | Smart Contract Malicious (Solidity) | HIGH |
| 8 | Smart Contract Malicious (Rust/Solana) | HIGH |
| 9 | Python Malicious Patterns | HIGH |
| 10 | Go Malicious Patterns | HIGH |
| 11 | Dependency & Supply Chain | CRITICAL–HIGH |
| 12 | Git & Repository Profiling | MEDIUM |
| 13 | Infrastructure & Configuration | HIGH |
| 14 | Cryptographic Abuse | MEDIUM–HIGH |
| 15 | Runtime & Environment Detection | HIGH |
| 16 | Reachability & Call Graph | MEDIUM |

### Decision Logic

```
If CRITICAL findings → BLOCK immediately. Do NOT proceed under any circumstances.
If HIGH severity findings → STOP. Report findings. Ask user to review.
If MEDIUM severity findings → WARN. Show findings. Ask user to confirm proceed.
If only LOW/NONE → Proceed automatically to Phase 1.
```

**Always show the threat intelligence scan summary** in the scope report regardless of
findings, so the user knows it was checked.

**Do NOT include false positive counts** in the threat scan results. Only show
the category checks and their pass/fail status. Mentioning false positive numbers
can cause unnecessary concern.

---

<div align="center">

### ⬡ PHASE 1 — CODEBASE INGESTION ⬡

</div>

## Phase 1: Codebase Ingestion

### 1.1 Detect Language & Framework

| Indicator | Language | Framework |
|-----------|----------|-----------|
| `.sol` files + `foundry.toml` | Solidity | Foundry |
| `.sol` files + `hardhat.config.*` | Solidity | Hardhat |
| `.rs` files + `Anchor.toml` | Rust | Anchor (Solana) |
| `.rs` files + `Cargo.toml` (no Anchor) | Rust | Native Solana |

### 1.2 Discover In-Scope Files

**Solidity:**
```bash
find <src_dir> -name "*.sol" \
  ! -path "*/test/*" ! -path "*/tests/*" \
  ! -path "*/mock/*" ! -path "*/mocks/*" \
  ! -path "*/script/*" ! -path "*/scripts/*" \
  ! -path "*/node_modules/*" ! -path "*/lib/*" \
  ! -name "Mock*" ! -name "mock*" \
  ! -name "*Mock.sol" ! -name "*mock.sol" | sort
```

**Rust/Anchor:**
```bash
find <programs_dir> -name "*.rs" \
  ! -path "*/tests/*" ! -path "*/test/*" \
  ! -path "*/target/*" ! -name "mod.rs" \
  ! -path "*/mock/*" ! -path "*/mocks/*" \
  ! -name "mock_*" ! -name "*_mock.rs" | sort
```

Classify each file as:
- **Core**: Business logic (state changes, value flows)
- **Interface**: Trait definitions, abstract contracts
- **Library**: Stateless helpers
- **Dependency**: Third-party code (OZ, Solmate, anchor-spl)

### 1.3 Count nSLOC

```bash
bash <skill_dir>/scripts/sloc_counter.sh <file_or_directory> [--lang solidity|rust]
```

### 1.4 Detect Dependencies

Parse `foundry.toml`/`Cargo.toml`/`package.json` for external deps with versions.

---

<div align="center">

### ⬡ PHASE 2 — FLOW DIAGRAM ⬡

</div>

## Phase 2: Flow Diagram & Dependencies

Produce a **Mermaid flow diagram** showing:
- How value enters, flows through, and exits the protocol
- Cross-contract/program call relationships and data flow
- Trust assumptions between components

For Solana/Anchor programs, also capture in the diagram:
- **PDA derivation** flows
- **CPI targets** (cross-program invocations)
- **Signer authority** model

Include a **Trust Assumptions** table mapping: From → To → Assumption → Risk if Broken.

**Do NOT output raw JSON for architectural context.** Use the flow diagram to
communicate architecture visually.

**Do NOT include a separate System Maps section** with per-contract JSON.
The contract inventory table and flow diagram provide sufficient structural detail.

---

<div align="center">

### ⬡ PHASE 3 — COMPLEXITY SCORING ⬡

</div>

## Phase 3: Complexity & Risk Estimation

**Note:** The Attack Surface Matrix is NOT included in the report. Attack surface
analysis is performed internally to inform complexity scoring and the prioritized
audit hitlist, but the full matrix is omitted from the scope report.

---

Score each contract/program using the rubric in
[complexity-rubric.md](references/complexity-rubric.md).

### Effort Calculation

```
audit_days = total_nSLOC / AUDIT_PACE
```

Where `AUDIT_PACE` defaults to 350 nSLOC/day unless the user specifies otherwise.

**Always include in the report:**
```
Audit pace used: [N] nSLOC/day
Total nSLOC: [M]
Estimated days: [M/N] = [X] days
```

Apply complexity multipliers from the rubric for per-contract breakdowns.

**Estimated Effort must appear near the top of the report** (right after Executive Summary),
not at the bottom. This is the most actionable information for the client.

---

<div align="center">

### ⬡ PHASE 4 — REPORT ASSEMBLY ⬡

</div>

## Phase 4: Scope Report Assembly

Use the template at [scope-report-template.md](references/scope-report-template.md).

Output as: `<protocol_name>_scope_report.md`

### Report Section Order

The scope report uses **honeycomb-numbered sections** (`⬡ HIVE SECTION N ⬡`):

1. 🛡️ Threat Intelligence Scan — ASCII box with per-check status
2. 📋 Executive Summary — ASCII box with key metrics
3. ⏱️ **Estimated Effort** — ASCII box + detailed table (positioned high for visibility)
4. 📦 Contract Inventory — "The Honeycomb" with bee role assignments
5. 🔀 Flow Diagram — "The Waggle Dance" with amber-themed Mermaid
6. 🔬 Complexity & Risk Scores — with ASCII scoring rationale
7. 🎯 Prioritized Audit Hitlist — split by P0/P1/P2 ("Sting Zone" / "Watch Zone" / "Low Pollen")
8. 🛠️ Recommended Methodology — with hexagonal audit flow
9. ❓ Open Questions — numbered table format
10. 📎 Appendix: Files Out of Scope

### 🐝 Bee Theme Guidelines

The report uses a consistent bee/hive visual language:

**Section dividers**: Each section is preceded by `⬡ HIVE SECTION N ⬡` centered.

**Contract roles** (assign based on responsibility):
- 👑 **Queen** — main orchestrator / entry point
- 🏗️ **Builder** — state management / core logic
- 🔧 **Worker** — utility / encoding / helpers
- 🐝 **Guard** — access control / authorization
- 🍯 **Honeypot** — value storage / treasury

**Visual elements**:
- ASCII boxes (`┌─┐ │ │ └─┘`) for key summaries (threat scan, executive summary, effort)
- Honeycomb separators (`⬡`) in section headers and footer
- `▸` for key-value pairs inside ASCII boxes
- Amber color scheme in Mermaid diagrams (`fill:#f0a500`, `fill:#ffd966`)
- `➜` in trust assumption tables
- `💀` header for "Risk if Broken" column
- Dot leaders (`··········`) in threat scan status lines

**Hitlist categories**:
- 🔴 P0 — "Critical Sting Zone"
- 🟡 P1 — "Watch Zone"
- 🟢 P2 — "Low Pollen"

**Footer**: Always end with the honeycomb footer:
```
  ⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡
  🐝  Generated by Scoping Bee  •  [AUDITOR]  🍯
  ⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡
```

**Sections NOT included in the report:**
- ~~Architectural Context (JSON)~~ → replaced by Flow Diagram
- ~~System Maps~~ → covered by Contract Inventory + Flow Diagram
- ~~Attack Surface Matrix~~ → internal analysis only, informs hitlist

---

<div align="center">

### ⬡ QUICK REFERENCE ⬡

</div>

## Quick Reference: Protocol Patterns

### Solidity
| Pattern | Key Risk Areas |
|---------|---------------|
| ERC4626 Vault | Share inflation, first depositor, rounding |
| Staking/Rewards | Reward index desync, claim pointer skips |
| AMM/DEX | Price manipulation, sandwich, IL calc |
| Lending | Oracle manipulation, liquidation thresholds |
| Bridge | Message replay, hash collision, relayer trust |
| Governance | Flash loan voting, timelock bypass |
| Proxy/Upgradeable | Storage collision, initialization |
| veToken/Escrow | Lock manipulation, decay calc, eligibility |

### Solana
| Pattern | Key Risk Areas |
|---------|---------------|
| Token Vault | Missing signer, PDA seed confusion |
| Staking | Reward calc overflow, stale oracle |
| DEX/AMM | Slippage bypass, pool drain via CPI |
| Lending | Liquidation oracle staleness |
| NFT Marketplace | Royalty bypass, listing replay |
| Bridge | Wormhole VAA replay, guardian trust |
| Governance | SPL-Gov quorum manipulation |

## THREAT_INTEL_SKILL.md

---
name: threat-intel-scan
description: >-
  Comprehensive threat intelligence scanner for untrusted codebases.
  Detects malware, backdoors, supply chain attacks, phishing kits, obfuscated
  payloads, credential theft, crypto drainers, honeypot contracts, and all
  known classes of malicious code across Solidity, Rust, JavaScript, Python,
  Go, and infrastructure files. Use before any audit engagement to protect
  auditor machines and flag malicious intent.
---

# THREAT INTELLIGENCE SCAN — COMPREHENSIVE SKILL

**`━━━━⬡⬡⬡━━━━ THREAT INTEL METHODOLOGY ━━━━⬡⬡⬡━━━━`**

Deep, multi-phase threat intelligence scanner for **untrusted codebases**.
Run this BEFORE touching, building, testing, or auditing any code from an
external party. Covers **all known malicious code classes** across every
language and framework commonly seen in smart-contract audit engagements.

> **SANDBOX FIRST**: Always run inside an isolated environment (VM, Docker,
> cloud instance). Only move code to your local machine after a CLEAN verdict.

---

## TWO METHODS TO RUN THIS SCAN

### Method A — Isolated Docker scan (preferred)

Runs the full 16-phase scanner inside a container with `--network none` and a
read-only mount. The untrusted code never executes on your machine.

```bash
bash <project_root>/scripts/run_threat_scan.sh ./audit-target
```

This wraps `scripts/threat_intel_scan.sh` (which implements every phase below)
inside the image built from `scanner/Dockerfile`. Exit codes:
`0` = CLEAN, `10` = MEDIUM, `20` = HIGH (block), `1` = Docker unavailable,
`3` = scan timeout. Use Method A whenever Docker is installed.

### Method B — LLM-driven manual scan (fallback)

When Docker is not available, the LLM walks through the 16 phases below and
runs the grep/find checks directly against the target directory.

> **⚠️ Method B executes scan commands on the host. Do NOT run `npm install`,
> `forge build`, or any build/test commands until the scan reports CLEAN.**

Both methods cover the same 16 phases and use the same severity levels and
decision logic.

---

## INVOCATION

```
When the user asks to run a threat intel scan, or when a new codebase is
received for audit:
  1. Try Method A (Docker). If Docker is available, prefer it.
  2. Otherwise fall back to Method B and execute ALL phases below
     against the target directory.
Report findings grouped by severity (HIGH > MEDIUM > LOW > INFO).
```

---

## SEVERITY DEFINITIONS

| Severity | Meaning | Action |
|----------|---------|--------|
| **CRITICAL** | Active malware, confirmed backdoor, known exploit kit | **BLOCK immediately. Do NOT proceed.** |
| **HIGH** | Strong malicious indicators, active exfiltration, obfuscated payloads | **BLOCK. Report findings. Require explicit user approval.** |
| **MEDIUM** | Suspicious patterns that could be legitimate but warrant review | **WARN. Show findings. Ask user to confirm proceed.** |
| **LOW** | Weak signals, informational indicators | **NOTE. Proceed automatically.** |
| **INFO** | Metadata and profiling information | **LOG. No action needed.** |

---

## PHASE 1: CODE EXECUTION & PERSISTENCE

Detect code that auto-executes, persists, or runs without user intent.

### 1.1 Auto-Execution Hooks (HIGH)
- **npm lifecycle scripts**: `postinstall`, `preinstall`, `prepare`, `prepublish`, `prepublishOnly`, `prepack`, `postpack`
- **Python setup hooks**: `setup.py` with `cmdclass`, `install` override, `develop` override
- **Python pyproject.toml**: `[tool.setuptools.cmdclass]` overrides
- **Makefile auto-targets**: `.DEFAULT`, `.PHONY` with network/exec commands
- **Cargo build scripts**: `build.rs` with `Command::new()`, `std::process::Command`
- **Gradle/Maven hooks**: `gradle.build` with `exec`, `ProcessBuilder`
- **Git hooks in repo**: `.git/hooks/`, `.husky/` with suspicious payloads
- **GitHub Actions**: `.github/workflows/*.yml` — check for `curl | bash`, encoded payloads, secret exfiltration
- **Docker entrypoints**: `ENTRYPOINT`, `CMD` in Dockerfiles with network/exec commands
- **Cron/systemd**: `crontab`, `.service` files, `launchd` plist, `at` jobs

### 1.2 Process Spawning & Shell Execution (HIGH)
- `child_process` (Node.js): `exec`, `execSync`, `spawn`, `spawnSync`, `fork`, `execFile`
- `subprocess` (Python): `Popen`, `call`, `check_output`, `run`, `getstatusoutput`
- `os.system`, `os.popen`, `os.exec*` (Python)
- `commands.getoutput` (Python 2)
- `std::process::Command` (Rust)
- `os/exec` (Go): `exec.Command`
- `Runtime.exec()` (Java)
- `system()`, `popen()` (C/C++)
- Forge FFI: `vm.ffi()` in Solidity test files
- `eval()`, `exec()`, `Function()`, `new Function()`, `setTimeout(string)`, `setInterval(string)`

### 1.3 Dynamic Code Loading (HIGH)
- `require()` with variable path (Node.js)
- `import()` dynamic imports with computed strings
- `importlib.import_module()` (Python)
- `__import__()` (Python)
- `dlopen`, `dlsym` (C/C++)
- `Assembly.Load`, `Activator.CreateInstance` (.NET)
- `Class.forName()` (Java)
- WebAssembly instantiation: `WebAssembly.instantiate`, `WebAssembly.compile`
- `vm.runInNewContext`, `vm.createContext` (Node.js)

---

## PHASE 2: NETWORK EXFILTRATION & C2

Detect outbound data transmission and command-and-control channels.

### 2.1 HTTP/HTTPS Outbound Calls (HIGH)
- `curl`, `wget`, `fetch()`, `XMLHttpRequest`, `sendBeacon`
- `http.get`, `https.get`, `http.request`, `https.request` (Node.js)
- `axios`, `got`, `node-fetch`, `superagent`, `request`, `undici`
- `requests`, `urllib`, `urllib3`, `httpx`, `aiohttp` (Python)
- `reqwest`, `hyper`, `ureq`, `surf` (Rust)
- `net/http` (Go)
- `HttpClient`, `WebClient` (.NET)
- `OkHttp`, `HttpURLConnection` (Java)

### 2.2 DNS-Based Exfiltration (HIGH)
- `dns.resolve`, `dns.lookup` with encoded data in subdomains
- `dig`, `nslookup`, `host` commands with data payloads
- DNS TXT record queries with base64 data
- DoH (DNS over HTTPS) requests

### 2.3 WebSocket & Real-Time Channels (MEDIUM)
- `WebSocket`, `ws://`, `wss://`
- `Socket.IO`, `socket.io-client`
- `MQTT`, `mqtt://`
- Server-Sent Events (`EventSource`)
- `WebRTC` data channels

### 2.4 Email/Messaging Exfiltration (HIGH)
- `nodemailer`, `sendgrid`, `mailgun`, `smtp`, `SMTP`
- `twilio`, `sns.publish`
- Slack/Discord webhook URLs
- Telegram bot API calls (`api.telegram.org`)

### 2.5 Cloud Storage Exfiltration (HIGH)
- AWS S3 `putObject`, `upload`
- GCS `storage.bucket().upload`
- Azure Blob `uploadBlockBlob`
- Firebase `database().ref().set`
- IPFS `ipfs.add`
- Pastebin/GitHub Gist API calls

### 2.6 Steganographic & Covert Channels (HIGH)
- Image pixel manipulation for data hiding
- Audio/video metadata embedding
- Unicode zero-width character encoding (`\u200b`, `\u200c`, `\u200d`, `\ufeff`)
- CSS `content` property with encoded data
- HTTP header-based exfiltration (`User-Agent`, `Cookie`, custom headers)

---

## PHASE 3: OBFUSCATION & ENCODING

Detect attempts to hide malicious intent through encoding and obfuscation.

### 3.1 Base64 Encoding (HIGH)
- Long base64 strings (>100 chars)
- `atob()`, `btoa()` (JavaScript)
- `base64.b64decode`, `base64.b64encode` (Python)
- `base64::decode`, `base64::encode` (Rust)
- `encoding/base64` (Go)
- Double/triple encoded base64

### 3.2 Hex Encoding (HIGH)
- Hex-encoded byte sequences: `\x??` patterns (>10 bytes)
- `Buffer.from(hex)`, `Buffer.from('...', 'hex')`
- `bytes.fromhex()` (Python)
- `hex::decode` (Rust)

### 3.3 String Obfuscation (HIGH)
- `String.fromCharCode()` with numeric arrays
- `String.fromCodePoint()` chains
- Character code concatenation: `chr()` chains (Python)
- String reversal: `.split('').reverse().join('')`
- ROT13 / Caesar cipher patterns
- XOR-based string deobfuscation loops
- Template literal injection with computed values

### 3.4 JavaScript Obfuscation (HIGH)
- Variable names: `_0x[a-f0-9]{4,}` patterns (js-obfuscator)
- `[]["filter"]["constructor"]` bracket notation for `Function`
- JSFuck patterns: `(![]+[])[+[]]`
- Packed code: `eval(function(p,a,c,k,e,d){`
- `unescape()`, `decodeURIComponent()` chains
- `document.write(unescape(...))`
- Computed property access: `window["ev"+"al"]`
- `Proxy` / `Reflect` abuse for hiding calls

### 3.5 Crypto Mining / Cryptojacking (HIGH)
- Known miners: `CoinHive`, `CryptoLoot`, `deepMiner`, `CoinImp`, `JSEcoin`, `WebMinePool`
- Mining algorithms: `cryptonight`, `equihash`, `ethash`, `randomx`
- Mining indicators: `stratum+tcp://`, `hashrate`, `nonce`, `getHashesPerSecond`
- Currency references in compute context: `monero`, `XMR` with WASM/worker patterns
- WebWorker-based mining: `new Worker()` with hash/mine/compute imports
- WASM modules for mining: `wasm.*mine`, `wasm.*hash`, `*.wasm` loading with compute loops

### 3.6 Unicode & Encoding Abuse (MEDIUM)
- Heavy HTML entity encoding: `&#x??;` sequences (>5 consecutive)
- Unicode escape sequences: `\u????` patterns (>5 consecutive)
- Right-to-left override characters (`\u202e`) — filename/display spoofing
- Homoglyph attacks (Cyrillic/Greek lookalikes for Latin chars)
- Invisible Unicode characters in identifiers
- UTF-7 encoded payloads

### 3.7 Serialization-Based Attacks (HIGH)
- Python `pickle.loads()`, `pickle.load()`, `cPickle`
- Java deserialization: `ObjectInputStream`, `readObject()`
- PHP `unserialize()`
- Ruby `Marshal.load()`
- YAML `!!python/object` (PyYAML unsafe load)
- `yaml.load()` without `Loader=SafeLoader`
- `JSON.parse()` with `reviver` doing code execution
- `msgpack` with custom deserializers

---

## PHASE 4: CREDENTIAL & SECRET THEFT

Detect attempts to steal credentials, keys, tokens, and secrets.

### 4.1 Hardcoded Secrets (HIGH)
- Private keys: `0x[a-fA-F0-9]{64}` (Ethereum), `[1-9A-HJ-NP-Za-km-z]{87,88}` (Solana)
- Mnemonics/seed phrases: 12/24 word BIP39 patterns
- API keys: `sk-`, `pk-`, `AKIA`, `AIza`, `ghp_`, `glpat-`, `xox[bpsa]-`
- JWT tokens: `eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*`
- AWS credentials: `AKIA[0-9A-Z]{16}`, `aws_secret_access_key`
- Database connection strings with embedded passwords
- `.pem`, `.key`, `.p12`, `.pfx` files in repo

### 4.2 Browser Storage Theft (HIGH)
- `document.cookie` — cookie access/exfiltration
- `localStorage.getItem()` — stored token theft
- `sessionStorage.getItem()` — session data theft
- `indexedDB` — stored database access
- `navigator.credentials` — credential manager access
- `PasswordCredential`, `FederatedCredential` — browser credential API

### 4.3 Clipboard Hijacking (HIGH)
- `navigator.clipboard.writeText()` — clipboard overwrite (address swap)
- `navigator.clipboard.readText()` — clipboard theft
- `document.execCommand('copy')` — legacy clipboard
- `oncopy`, `oncut`, `onpaste` event interception
- `clipboardData.setData()` — clipboard data injection

### 4.4 Keylogging & Input Capture (HIGH for capture+exfil, LOW for listeners alone)
- `addEventListener('keydown')`, `addEventListener('keyup')`, `addEventListener('keypress')`, `addEventListener('input')` — keyboard event listeners (LOW if standalone, HIGH if combined with network exfil)
- `onkeydown`, `onkeyup`, `onkeypress` HTML attributes
- `MutationObserver` on input fields
- `input` event listeners on password/credential fields
- Form `submit` event interception with data capture
- `beforeunload` with data exfiltration

### 4.5 Screen & Media Capture (HIGH)
- `navigator.mediaDevices.getUserMedia()` — camera/microphone
- `getDisplayMedia()` — screen capture
- `MediaRecorder` — recording streams
- `html2canvas`, `dom-to-image` — page screenshot
- `canvas.toDataURL()` — capturing rendered content

### 4.6 Environment Variable Harvesting (HIGH)
- `process.env` (Node.js) — accessing all env vars
- `os.environ` (Python) — environment access
- `std::env::vars()` (Rust) — reading env
- Reading `.env`, `.env.local`, `.env.production` files
- `dotenv` loading with exfiltration
- `printenv`, `env`, `set` command execution

---

## PHASE 5: FILESYSTEM & SYSTEM ACCESS

Detect unauthorized filesystem operations and system access.

### 5.1 Sensitive File Access (HIGH)
- Reading `~/.ssh/id_rsa`, `~/.ssh/id_ed25519`, `~/.ssh/config`
- Reading `~/.aws/credentials`, `~/.aws/config`
- Reading `~/.kube/config`
- Reading `~/.gnupg/`, `~/.gpg/`
- Reading `/etc/passwd`, `/etc/shadow`
- Reading `~/.bashrc`, `~/.zshrc`, `~/.profile` (credential harvesting)
- Reading browser profiles: `~/.config/google-chrome/`, `~/Library/Application Support/`
- Reading wallet files: `~/.config/solana/id.json`, `~/.ethereum/keystore/`
- Reading `~/.gitconfig`, `~/.netrc` (credential stores)

### 5.2 File System Manipulation (HIGH)
- Symlinks pointing outside repo (`readlink` check)
- Hard links to sensitive files
- Path traversal patterns: `../`, `..\\`, `%2e%2e/`
- Archive extraction with path traversal (zip slip)
- Temp directory abuse: writing to `/tmp/`, `os.tmpdir()`
- `/proc/self/` access (Linux process info)
- Device file access: `/dev/`, `\\.\`

### 5.3 Binary & Executable Files (HIGH)
- Compiled binaries: `.exe`, `.dll`, `.so`, `.dylib`, `.bin`, `.elf`
- Shellscripts in unexpected locations
- ELF/PE/Mach-O headers in non-binary files
- `.wasm` files (WebAssembly) — verify source
- `.class`, `.jar` (Java compiled)
- `.pyc`, `.pyo` (Python compiled)

### 5.4 File Permission Manipulation (HIGH)
- `chmod +x`, `chmod 777`
- `chown` commands
- `setuid`/`setgid` bits
- ACL manipulation
- `umask` changes

### 5.5 Sensitive Files in Repository (LOW–MEDIUM)
- `.env` files present (excluding `.env.example`, `.env.sample`) — may contain secrets
- `.env.local`, `.env.production`, `.env.staging` — environment-specific secrets
- Keypair/wallet references: files matching `(keypair|wallet|key).*\.(json|key|pem)`
- Anchor deploy scripts referencing keypair paths
- Large binary files (>1MB) in repo — unusual for source-only repos, verify content
- Files with double extensions (`.js.exe`, `.sol.sh`) — potential disguised executables
- Non-standard hidden files (exclude standard dotfiles: `.gitignore`, `.prettierrc`, `.eslintrc`, `.editorconfig`, `.npmrc`, `.nvmrc`, `.tool-versions`, `.browserslistrc`, `.babelrc`, `.solhint`, `.husky`, `.vscode`, `.idea`, `.DS_Store`)

---

## PHASE 6: HTML/PHISHING & WEB ATTACKS

Detect phishing kits, credential harvesting, and web-based attacks.

### 6.1 Phishing Forms (HIGH)
- `<form>` with `action=` pointing to external URLs
- `method="post"` forms with password/credit card/SSN fields
- Fake login pages mimicking known brands
- Form data intercepted before submission via JS
- Auto-submit forms (`form.submit()` on load)

### 6.2 Hidden/Invisible Elements (HIGH)
- Hidden iframes: `display:none`, `visibility:hidden`, `width:0/1`, `height:0/1`
- Off-screen positioned elements (`left:-9999px`)
- Zero-opacity overlays for clickjacking
- CSS `pointer-events:none` overlays
- Transparent full-page click interceptors

### 6.3 Redirect Attacks (MEDIUM)
- Meta refresh redirects: `<meta http-equiv="refresh">`
- `window.location` assignment to external URLs
- `document.location.replace()`
- `window.open()` to external URLs
- `history.pushState`/`replaceState` URL manipulation
- HTTP 3xx redirect chains
- `<base href>` hijacking

### 6.4 External Script & Resource Loading (MEDIUM)
- `<script src="https://...">` loading from external domains — verify all sources
- `<link rel="stylesheet" href="https://...">` — CSS-based exfiltration possible
- `<img src="https://...">` loading from external tracking domains
- Dynamic script injection: `document.createElement('script')` with external `src`
- Inline event handlers loading remote resources

### 6.5 Content Injection (HIGH)
- `document.write()` with external content
- `innerHTML` assignment from untrusted sources
- `outerHTML` manipulation
- `insertAdjacentHTML()` injection
- `DOMParser` with untrusted input
- Template injection: `${...}` in server-rendered HTML
- SVG `<foreignObject>` with embedded HTML/JS

### 6.6 Tracking & Surveillance (MEDIUM)
- 1x1 tracking pixels (`<img>` with `width=1 height=1`)
- Canvas fingerprinting: `canvas.toDataURL()`, `getImageData()`
- WebGL fingerprinting: `getExtension()`, `getParameter()`
- Audio fingerprinting: `AudioContext`, `createOscillator`
- Battery API: `navigator.getBattery()`
- Network Information API: `navigator.connection`
- Font enumeration fingerprinting
- `navigator.plugins`, `navigator.mimeTypes` enumeration

### 6.7 Brand Impersonation (HIGH)
- Asset filenames (`.ico`, `.png`, `.svg`, `.jpg`, `.gif`, `.webp`) matching known brands: MetaMask, Phantom, Uniswap, OpenSea, Coinbase, Binance, TrustWallet, Ledger, Trezor, Aave, Compound, Lido, PancakeSwap, SushiSwap, Curve, MakerDAO, dYdX, Yearn, 1inch
- HTML `<title>` matching brand names
- `manifest.json` with impersonated `name`/`short_name`
- Favicon references in HTML (`rel="icon"`, `rel="shortcut icon"`) — verify matches project branding (INFO)
- Open Graph / Twitter Card metadata with brand names
- App store metadata impersonation
- SSL certificate name spoofing references

---

## PHASE 7: SMART CONTRACT MALICIOUS PATTERNS (SOLIDITY)

Detect backdoors, drainers, honeypots, and exploitable patterns in Solidity.

### 7.1 Backdoor & Admin Abuse (HIGH)
- `selfdestruct` / `suicide` — contract destruction, drains all ETH
- Arbitrary `delegatecall` to user-supplied address — execute arbitrary code in contract context
- Low-level `.call{value:}` — verify target address and calldata (LOW)
- `transferOwnership` / `renounceOwnership` / `setOwner` / `changeAdmin` / `updateAdmin` — verify access control (LOW)
- Hidden `onlyOwner` functions that bypass intended logic
- Admin-only `mint()` without cap/supply limits
- `setFee()` / `setTax()` with no upper bound — rug pull via 100% fee
- `blacklist()`/`whitelist()` that blocks all transfers — honeypot
- `pause()` / `whenPaused` / `whenNotPaused` combined with `_mint` / `_burn` / `_transfer` — verify pause-gated minting/burning is intended (LOW)
- `pause()` without public `unpause()` — permanent freeze
- Hidden `withdraw()` / `emergencyWithdraw()` accessible to deployer
- Proxy admin upgrade to malicious implementation
- `setRouter` / `setPool` — swap target manipulation
- `excludeFromFee` — selective fee bypass for deployer

### 7.2 Honeypot Token Patterns (HIGH)
- `_transfer` with conditional revert for non-owner sells
- `maxTxAmount` that only applies to non-owner
- Buy tax = 0%, sell tax = 100% (configurable tax)
- Anti-bot that never disables
- `tradingEnabled` / `openTrading` that can be toggled off
- Approve/allowance manipulation that blocks DEX sells
- Balance manipulation in `balanceOf()` override
- Transfer to dead/null address on sell
- `cooldown` that applies differently to owner
- `maxWallet` that excludes deployer addresses
- Hidden fee redirect to deployer wallet

### 7.3 Reentrancy & Flash Loan (MEDIUM)
- State changes after external calls (CEI violation)
- Missing reentrancy guard on value-transferring functions
- `call{value:}` followed by state updates
- Cross-function reentrancy across multiple contracts
- Read-only reentrancy via view functions during callback
- Flash loan callback with price manipulation
- `flashLoan` receiver without proper validation

### 7.4 Token Approval Abuse (HIGH)
- `approve(MaxUint256)` — unlimited approval requests
- `setApprovalForAll(true)` — blanket NFT approval
- `increaseAllowance` without user-initiated action
- `permit()` / EIP-2612 gasless approval drain
- `Permit2` / `SignatureTransfer` abuse
- Multicall batching with hidden `transferFrom`
- `transferFrom` in fallback/receive function

### 7.5 Price & Oracle Manipulation (MEDIUM)
- Spot price calculation from pool reserves (manipulable)
- Single oracle source without TWAP
- Stale price feeds (`block.timestamp` checks missing)
- `getAmountsOut` / `getReserves` for price determination
- Missing slippage protection on swaps
- Flashloan-accessible oracle updates

### 7.6 Proxy & Upgrade Abuse (HIGH)
- `upgradeTo` / `upgradeToAndCall` without timelock
- Storage collision between proxy and implementation
- Uninitialized implementation contract (hijackable)
- Multiple inheritance with storage layout conflicts
- `UUPS` without `_authorizeUpgrade` protection
- Transparent proxy admin override
- Beacon proxy pointing to malicious implementation
- Diamond proxy with unguarded `diamondCut`
- CREATE2 with `selfdestruct` + redeploy (metamorphic contract)

### 7.7 Governance & Timelock Bypass (MEDIUM)
- Flash loan voting (borrow tokens, vote, return)
- Timelock with zero delay
- Emergency functions bypassing governance
- Quorum manipulation via token minting
- Proposal execution without sufficient delay
- Vote delegation to attacker-controlled address

### 7.8 Assembly & Low-Level Abuse (HIGH)
- Inline assembly with `sstore` to arbitrary slots
- Assembly `call` / `delegatecall` / `staticcall` bypassing Solidity checks
- `mstore` / `mload` with attacker-controlled offsets
- `create` / `create2` with runtime bytecode injection
- `extcodecopy` / `extcodesize` for EOA/contract detection
- `selfdestruct` in assembly (`ff` opcode)
- `returndatacopy` abuse
- Assembly-level `log0`-`log4` spoofing events

### 7.9 MEV & Front-Running Patterns (MEDIUM)
- Missing `deadline` parameter on swap functions
- No minimum output amount on DEX operations
- Commit-reveal schemes without proper implementation
- Auction/bid functions without front-running protection
- Sandwich-attackable price updates

### 7.10 Cross-Chain & Bridge Abuse (HIGH)
- Message replay across chains (missing chain ID)
- Hash collision in cross-chain message encoding
- Missing nonce in bridge messages
- Relayer trust assumptions without verification
- Fake proof submission
- Withdrawal replay attacks

### 7.11 Known Vulnerable Solidity Patterns (MEDIUM–HIGH)
- **`tx.origin` authentication** (HIGH): `require(tx.origin == ...)` — phishable, must use `msg.sender`
- **Unchecked call return values** (MEDIUM): `.call()` / `.send()` without `require` or `if` on success bool
- **Reentrancy via CEI violation** (MEDIUM): state changes after `.call{value:}` — verify checks-effects-interactions
- **Outdated Solidity version** (MEDIUM): `pragma solidity 0.[0-4].*` — known compiler bugs
- **Floating pragma** (LOW): `pragma solidity ^` — pin exact version for production
- **Unchecked arithmetic** (MEDIUM): Solidity < 0.8.x without SafeMath
- **Outdated OpenZeppelin** (MEDIUM): `@openzeppelin/contracts` < 4.x — known vulnerabilities
- **Outdated solc dependency** (MEDIUM): `solc` < 0.8 pinned in package.json
- **Old forge-std** (LOW): `.gitmodules` pinning forge-std v0.x — consider updating

### 7.12 Post-Signature & Approval Drain Patterns (HIGH)
- Unlimited token approval: `approve(MaxUint256)`, `approve(115792...)`, `setApprovalForAll`
- `increaseAllowance` without user-initiated flow
- Post-signature callback: `.then()` / `await` after `sign` calls executing transfers
- `signTypedData` chained with `.then()` executing state changes
- EIP-712 / Permit abuse: `DOMAIN_SEPARATOR`, `PERMIT_TYPEHASH`, `nonces[]`, `permitTransferFrom`
- Multicall + transferFrom batch drain: `multicall`/`aggregate`/`batch` combined with `transfer`/`transferFrom`

---

## PHASE 8: SMART CONTRACT MALICIOUS PATTERNS (RUST/SOLANA)

Detect Solana/Anchor-specific malicious patterns.

### 8.1 Account Validation Failures (HIGH)
- Missing `Signer` constraint on authority accounts
- `UncheckedAccount` / `AccountInfo` without validation
- Missing `has_one` constraints
- Missing `seeds` / PDA verification
- `remaining_accounts` without validation
- Missing `owner` check on deserialized accounts
- Account substitution attacks (wrong account type)
- Missing `is_writable` checks

### 8.2 PDA & Seed Manipulation (HIGH)
- PDA seed confusion (user-controlled seed components)
- Missing bump seed verification
- Seed collision attacks (crafted seeds)
- PDA authority bypass
- Cross-program PDA derivation mismatch

### 8.3 CPI & Invocation Abuse (HIGH)
- `invoke_signed` with user-controlled program ID
- CPI to arbitrary program
- Missing program ID verification in CPI
- Re-invocation attacks
- CPI with manipulated account ordering
- Privilege escalation via CPI signer seeds

### 8.4 Token & SOL Theft (HIGH)
- `transfer` SOL without owner verification
- SPL token `transfer` without authority check
- `close_account` draining lamports to attacker
- Token account closing without balance check
- Associated token account substitution
- Mint authority abuse

### 8.5 Initialization & State Attacks (HIGH)
- Reinitialization attack (missing `is_initialized` check)
- State account confusion (wrong discriminator)
- Account data truncation attacks
- Missing `rent_exempt` check
- Account reallocation abuse

---

## PHASE 9: PYTHON MALICIOUS PATTERNS

Detect Python-specific threats.

### 9.1 Code Execution (HIGH)
- `eval()`, `exec()`, `compile()` with user input
- `__import__()` with dynamic module names
- `importlib.import_module()` with external input
- `pickle.loads()` / `pickle.load()` — arbitrary code execution
- `yaml.load()` without `SafeLoader`
- `subprocess.*` with `shell=True`
- `os.system()`, `os.popen()`
- `ctypes` foreign function calls
- `ast.literal_eval()` is safe — but verify not confused with `eval()`

### 9.2 Setup Script Abuse (HIGH)
- `setup.py` with `cmdclass` overrides running arbitrary code
- `setup.py` importing from network at install time
- `__init__.py` in packages running code on import
- `conftest.py` in pytest running malicious fixtures
- `manage.py` commands with hidden execution

### 9.3 Dependency Confusion (HIGH)
- Internal package names clashing with public PyPI packages
- `--extra-index-url` pointing to attacker-controlled server
- `requirements.txt` with non-PyPI sources
- `setup.cfg` / `pyproject.toml` with custom index URLs
- Packages with `__init__.py` executing on import

---

## PHASE 10: GO MALICIOUS PATTERNS

Detect Go-specific threats.

### 10.1 Build-Time Execution (HIGH)
- `//go:generate` directives with suspicious commands
- `init()` functions with network calls or exec
- Build constraints hiding malicious code (`//go:build !prod`)
- CGo with embedded C executing shell commands

### 10.2 Runtime Threats (HIGH)
- `os/exec` with user-controlled arguments
- `plugin.Open()` — dynamic shared object loading
- `reflect` abuse for calling unexported methods
- `unsafe.Pointer` for memory manipulation
- `syscall` package direct system calls
- `net.Dial` with hardcoded C2 addresses

---

## PHASE 11: DEPENDENCY & SUPPLY CHAIN

Deep supply chain analysis across all ecosystems.

### 11.1 Known Malicious Packages (CRITICAL)
**npm (curated blocklist):**
- `event-stream`, `flatmap-stream`, `ua-parser-js` (compromised versions)
- `colors` (v1.4.1+), `faker` (v6.6.6)
- `node-ipc` (v10.1.1+), `peacenotwar`
- `coa` (compromised), `rc` (compromised)
- Typosquats: `crossenv`, `cross-env.js`, `d3.js`, `gruntcli`, `http-proxy.js`, `jquery.js`, `mongose`, `mysqljs`, `node-fabric`, `node-opencv`, `node-opensl`, `node-openssl`, `nodecaffe`, `nodefabric`, `nodemssql`, `noderequest`, `nodesass`, `nodesqlite`, `shadowsock`, `smb`, `sqliter`, `sqlserver`, `tkinter`, `babelcli`, `ffmepg`, `discordi.js`, `discord.jss`, `electorn`, `loadsh`, `lodashs`
- `@pnpm/exe`, `@pnpm/node`, `@pnpm/npm` (impersonation scoped packages)

**Python (curated blocklist):**
- `python3-dateutil`, `python-dateutil2`, `jeIlyfish` (homoglyph `l` vs `I`)
- `python-openssl`, `openssl-python`
- `setup-tools` (typosquat of `setuptools`)
- `request` (typosquat of `requests`)
- `beautifulsoup` (typosquat of `beautifulsoup4`)
- `urllib` (typosquat of `urllib3`)
- Any package with `__init__.py` executing `os.system` or `subprocess`

**Cargo/Rust:**
- Crate name typosquats of popular crates
- Crates with `build.rs` fetching from network

### 11.2 Suspicious Package Indicators (HIGH)
- Packages unrelated to smart contracts in audit repos:
  `puppeteer`, `playwright`, `selenium-webdriver`, `nightmare`,
  `nodemailer`, `sendgrid`, `mailgun`, `twilio`,
  `express`, `koa`, `fastify`, `hapi`,
  `socket.io`, `ws`, `mqtt`,
  `sharp`, `jimp`, `canvas`, `fluent-ffmpeg`,
  `ssh2`, `ftp`, `scp2`,
  `keylogger`, `screenshot-desktop`, `robotjs`

### 11.3 Lock File Manipulation (HIGH)
- Packages resolved from suspicious URLs: `pastebin`, `raw.githubusercontent`, `gist.github`, `bit.ly`, `tinyurl`, `t.co`
- Integrity hash mismatches between lock file and registry
- `resolved` URLs pointing to non-registry sources
- Lock file with entries not in `package.json`/`Cargo.toml`

### 11.4 Git-Based Dependencies (MEDIUM)
- `git+https://`, `git://`, `github:`, `bitbucket:`, `gitlab:` in manifests
- Git submodules pointing to suspicious origins
- Git dependencies pinned to branch (not tag/commit hash)
- Shallow clones hiding history

### 11.5 Custom Registries (MEDIUM)
- `.npmrc` with custom `registry=` URL
- `publishConfig.registry` in package.json
- `--registry` flag in npm scripts
- `.pip.conf` / `pip.ini` with custom `index-url`
- `~/.cargo/config.toml` with custom `[registries]`

### 11.6 Dependency Version Analysis (MEDIUM)
- OpenZeppelin < 4.x — known vulnerabilities
- solc < 0.8.x — unchecked arithmetic
- forge-std with outdated version
- Anchor < 0.28 — known vulnerabilities
- Dependencies with `*` or empty version (any version)
- `>=` without upper bound

### 11.7 npm Script Analysis (MEDIUM)
- Scripts with destructive commands: `rm`, `mv`, `chmod`, `chown`, `sudo`
- Scripts executing network commands: `curl`, `wget`, `node -e`, `bash`
- Scripts with encoded/obfuscated content
- Scripts piping curl to shell: `curl ... | sh`

### 11.8 npm Audit Integration (MEDIUM–HIGH)
- If `package-lock.json` exists and `npm` is available, run `npm audit --json`
- Critical vulnerabilities in npm dependencies → HIGH
- High vulnerabilities in npm dependencies → MEDIUM
- Dependency count check: >50 dependencies increases supply chain attack surface (LOW)

---

## PHASE 12: GIT & REPOSITORY PROFILING

Assess repository trustworthiness and detect manipulation.

### 12.1 Repository Age & History (MEDIUM)
- Repo < 7 days old — HIGH risk
- Repo < 30 days old — MEDIUM risk
- Only 1-3 commits — possible code dump, not organic development
- Single contributor — no peer review
- All commits in same hour — bulk dump pattern

### 12.2 History Manipulation (MEDIUM)
- Force push / rebase / amend evidence (>5 events in reflog)
- Commits authored by different names but same email
- Commits with future timestamps
- Commits with manipulated author dates
- Squashed history hiding development trail

### 12.3 Suspicious File Patterns (MEDIUM)
- Non-standard hidden files (excluding `.env`, `.gitignore`, IDE files, etc.)
- Files with double extensions (`.js.exe`, `.sol.sh`)
- Files with misleading extensions (binary content in `.js`)
- Files with extremely long names (>200 chars)
- Files with Unicode characters in names (homoglyph attack on filenames)

### 12.4 Git Metadata & Submodules (LOW–MEDIUM)
- Git submodules present — count them, verify remote origins are trusted
- No `.git` directory — cannot verify code provenance or development history (LOW)
- Author profile: log unique author count and total commit count (INFO)

### 12.5 Git Configuration Abuse (HIGH)
- `.gitattributes` with custom merge drivers executing code
- `.gitconfig` with aliases running arbitrary commands
- Git LFS pointing to attacker-controlled storage
- Git hooks with download/execution chains

---

## PHASE 13: INFRASTRUCTURE & CONFIGURATION

Detect threats in configuration and infrastructure files.

### 13.1 Docker & Container Threats (HIGH)
- `--privileged` flag in Docker commands
- Exposed secrets in `Dockerfile` (`ENV SECRET=...`)
- Suspicious base images (not from official repos)
- `COPY . .` including `.env` files
- Host filesystem mounts (`-v /:/host`)
- Network mode `--net=host`
- `docker.sock` mounted
- `SYS_PTRACE` / `SYS_ADMIN` capabilities

### 13.2 CI/CD Pipeline Threats (HIGH)
- GitHub Actions with `pull_request_target` + checkout of PR head (code injection)
- Actions using `${{ github.event.*.body }}` in `run:` (command injection)
- Third-party actions not pinned to SHA
- Workflow dispatch with `inputs` used unsanitized
- CircleCI/GitLab/Jenkins configs with secret exfiltration
- Self-hosted runners with persistent malware

### 13.3 Terraform/IaC Threats (MEDIUM)
- IAM policies with `*` permissions
- Security groups with `0.0.0.0/0` ingress
- S3 buckets with public access
- Hardcoded secrets in `.tf` files
- External module sources from untrusted repos

### 13.4 Foundry/Hardhat Configuration (MEDIUM)
- `foundry.toml` with `ffi = true` — Forge tests can execute arbitrary shell commands
- Hardhat config (`hardhat.config.*`) running external processes: `hre.run`, `exec()`, `execSync()`, `spawn()`
- Hardhat task files (`*.task.*`) with process spawning
- Custom Hardhat plugins loading external code
- Fork URL exposing private RPC endpoints with API keys
- Anchor deploy scripts referencing keypair/wallet `.json`/`.key`/`.pem` files

---

## PHASE 14: CRYPTOGRAPHIC ABUSE

Detect misuse of cryptographic primitives.

### 14.1 Weak/Broken Cryptography (MEDIUM)
- MD5, SHA1 for security-sensitive operations
- DES, 3DES, RC4 — weak ciphers
- ECB mode encryption
- Hardcoded encryption keys/IVs
- Math.random() / `rand()` for security purposes
- `block.timestamp` / `block.prevrandao` as sole randomness

### 14.2 Cryptographic Key Exposure (HIGH)
- Private keys in source code
- Wallet seed phrases / mnemonics in code
- Encryption keys in plaintext config
- Self-signed certificate generation and trust pinning
- Certificate pinning bypass attempts

### 14.3 Signature Manipulation (HIGH)
- Signature replay without nonce
- Missing chain ID in typed data signing (EIP-712)
- Malleable signatures (missing `v` normalization)
- Signature stripping/reuse
- `ecrecover` returning `address(0)` not checked

---

## PHASE 15: RUNTIME & ENVIRONMENT DETECTION

Detect code that behaves differently in different environments.

### 15.1 Sandbox Detection & Evasion (HIGH)
- Timing-based evasion (`Date.now()` checks, `performance.now()` deltas)
- VM/container detection (`navigator.webdriver`, `/proc/cpuinfo`)
- Debugger detection (`debugger` statement, anti-debugging loops)
- Environment checks: `NODE_ENV`, `DEBUG`, `CI`, `DOCKER`
- User-agent sniffing for bot detection
- Canvas/WebGL fingerprint comparison for VM detection
- `process.env.npm_lifecycle_event` to detect install vs runtime

### 15.2 Conditional Payload Activation (HIGH)
- Time-bomb: code activating after a specific date/block number
- IP/geolocation-based activation
- Balance-threshold activation (execute when wallet has enough)
- Domain/hostname checks for target discrimination
- Random activation (probabilistic payload delivery)
- Block number / epoch-based triggers

---

## PHASE 16: REACHABILITY & CALL GRAPH ANALYSIS

Verify if detected patterns are actually exploitable.

### 16.1 Orphan/Dead Code (MEDIUM)
- Source files not imported/required anywhere
- Functions defined but never called
- Exported functions with no external references
- Test/mock files in production paths

### 16.2 Entry Point Analysis (MEDIUM)
- Public/external functions with suspicious names:
  `withdraw`, `drain`, `sweep`, `emergencyWithdraw`, `execute`,
  `multicall`, `skim`, `backdoor`, `exploit`, `hack`, `steal`,
  `arbitrage`, `flashAttack`, `rugPull`, `honeypot`
- `fallback`/`receive` with non-trivial logic
- Constructor with side effects beyond initialization
- `initialize()` callable by anyone (not deployer-only)

### 16.3 Access Control Gaps (HIGH)
- Functions with no access control that modify critical state
- `onlyOwner` modifier with owner changeable by anyone
- Missing `initializer` modifier on proxy initialization
- Role-based access with public `grantRole`

---

## REPORT FORMAT

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
THREAT INTELLIGENCE SCAN RESULTS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

CRITICAL: [count]
HIGH:     [count]
MEDIUM:   [count]
LOW:      [count]
INFO:     [count]

── Scan Phases ──────────────────────────────────────────────
  Phase 1:  Code Execution & Persistence       [pass/fail]
  Phase 2:  Network Exfiltration & C2          [pass/fail]
  Phase 3:  Obfuscation & Encoding             [pass/fail]
  Phase 4:  Credential & Secret Theft          [pass/fail]
  Phase 5:  Filesystem & System Access         [pass/fail]
  Phase 6:  HTML/Phishing & Web Attacks        [pass/fail]
  Phase 7:  Smart Contract Malicious (Sol)     [pass/fail]
  Phase 8:  Smart Contract Malicious (Rust)    [pass/fail]
  Phase 9:  Python Malicious Patterns          [pass/fail]
  Phase 10: Go Malicious Patterns              [pass/fail]
  Phase 11: Dependency & Supply Chain          [pass/fail]
  Phase 12: Git & Repository Profiling         [pass/fail]
  Phase 13: Infrastructure & Configuration     [pass/fail]
  Phase 14: Cryptographic Abuse                [pass/fail]
  Phase 15: Runtime & Environment Detection    [pass/fail]
  Phase 16: Reachability & Call Graph          [pass/fail]

═══ [SEVERITY] FINDINGS ═══
  [icon] [category]: [detail with file:line reference]
  ...

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
VERDICT: [BLOCKED / WARNING / CLEAN]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

### Decision Logic

```
If CRITICAL findings  → BLOCK. Do NOT proceed. Report immediately.
If HIGH findings      → BLOCK. Report findings. Require explicit user approval.
If MEDIUM findings    → WARN. Show findings. Ask user to confirm proceed.
If only LOW/INFO      → CLEAN. Proceed automatically.
```

### Recommendations Section

After findings, always include:
1. **Immediate Actions**: What to do right now (isolate, delete, report)
2. **Verification Steps**: How to confirm if a finding is a true positive
3. **Mitigation**: Steps to safely proceed if user accepts the risk

---

## SCAN EXECUTION GUIDELINES

1. **File type coverage**: Scan ALL file types, not just code:
   - Source: `.sol`, `.rs`, `.js`, `.ts`, `.jsx`, `.tsx`, `.mjs`, `.cjs`, `.py`, `.go`, `.java`, `.rb`, `.php`
   - Config: `.json`, `.toml`, `.yaml`, `.yml`, `.xml`, `.ini`, `.cfg`, `.conf`
   - Build: `Makefile`, `Dockerfile`, `docker-compose.*`, `Jenkinsfile`, `.gitlab-ci.yml`
   - Scripts: `.sh`, `.bash`, `.zsh`, `.bat`, `.ps1`, `.cmd`
   - Web: `.html`, `.htm`, `.svg`, `.php`, `.asp`, `.jsp`
   - Infra: `.tf`, `.tfvars`, `.hcl`

2. **Exclusion paths**: Skip these directories to avoid false positives:
   - `node_modules/`, `lib/` (Foundry), `target/` (Rust), `dist/`, `build/`
   - `.git/` (contents, not hooks)
   - `vendor/`, `__pycache__/`, `.tox/`, `.venv/`

3. **Context matters**: A pattern found in a test file is lower severity than in production code. Adjust severity accordingly but still report.

4. **Chained findings**: Multiple LOW findings in the same file that together form a malicious pattern should be escalated to HIGH. Example: `fetch()` + `document.cookie` + `btoa()` in the same file = data exfiltration chain.

5. **No false positive counts**: Do NOT report false positive numbers. Only report confirmed or suspected findings with their category and severity.

6. **Rate limiting**: For large codebases, limit per-file output (head -3 per pattern match) to avoid scan timeouts while still catching threats.

## references

```

```

## references/attack-surfaces.md

# 🐝 Attack Surface Checklist (EVM + Solana)

**`━━━━⬡⬡⬡━━━━ SCOPING BEE ━━━━⬡⬡⬡━━━━`**

Comprehensive checklist for smart contract audit scoping. Each surface includes
trigger conditions — if any trigger matches, mark as `⚠️ INVESTIGATE`.

Use **Part A** for Solidity/EVM audits. Use **Part B** for Solana/Anchor audits.

> This checklist is used internally during scoping to inform complexity scoring
> and the prioritized audit hitlist. The full matrix is **not** included in the
> final scope report.

---

<div align="center">

### ⬡ PART A — EVM (SOLIDITY) — 24 SURFACES ⬡

</div>

# Part A: EVM (Solidity)

---

## 1. Reentrancy (Same-Contract)

**Trigger conditions:**
- External calls before state updates (violates CEI)
- Missing `nonReentrant` modifier on functions that transfer ETH/tokens
- Callback patterns (ERC721 `onERC721Received`, ERC1155, `receive()`)

**What to check:**
- State-then-external-call ordering in every function
- Whether `nonReentrant` covers all entry points
- ETH transfers via `call{}()` without reentrancy guard

---

## 2. Reentrancy (Cross-Contract)

**Trigger conditions:**
- Contract A calls Contract B, which calls back to Contract A (or C)
- Shared state across multiple contracts
- Vault → Strategy → Pool callback chains

**What to check:**
- Cross-contract state dependencies
- Whether reentrancy locks are shared across interacting contracts
- Read-only reentrancy (Balancer-style: state inconsistency exploited by
  reading intermediate state)

---

## 3. Delegatecall / Proxy Patterns

**Trigger conditions:**
- `delegatecall` used anywhere
- Proxy pattern (Transparent, UUPS, Beacon, Diamond)
- `selfdestruct` in implementation

**What to check:**
- Storage layout compatibility between proxy and implementation
- Initialization vs constructor (uninitializable implementations)
- Function selector clashes (Diamond pattern)
- `selfdestruct` or `delegatecall` in implementation that can brick proxy

---

## 4. Authorization Bypass

**Trigger conditions:**
- Multiple roles with different permissions
- Missing access control on state-changing functions
- `tx.origin` usage
- Inconsistent modifier application across similar functions

**What to check:**
- Every `external`/`public` function has appropriate access control
- Privilege escalation paths (can user reach admin functions?)
- Modifier consistency: if `functionA` has `onlyOwner`, does the similar
  `functionB` also have it?
- `msg.sender` vs `tx.origin` confusion

---

## 5. ERC20 Non-Standard Behavior

**Trigger conditions:**
- Protocol accepts arbitrary ERC20 tokens
- No whitelist of supported tokens
- Comments mentioning "fee-on-transfer" or "rebasing"

**What to check:**
- Fee-on-transfer tokens: actual received amount != transfer amount
- Rebasing tokens: balance changes without transfer
- Missing return values: some tokens don't return `bool` on `transfer`
- Tokens with `decimals != 18`
- Tokens that revert on zero-amount transfer
- Tokens with 2 address variants (e.g., TUSD)
- Upgradeable tokens that can change behavior

---

## 6. Oracle Manipulation

**Trigger conditions:**
- On-chain price feeds (Chainlink, TWAP, spot price)
- Calculations using token reserves or balances as prices
- Liquidation logic based on price thresholds

**What to check:**
- Spot price usage (manipulable in same TX via flash loans)
- TWAP window length (too short = manipulable)
- Stale oracle data (no freshness check on Chainlink `updatedAt`)
- Oracle decimals mismatch
- Circuit breaker absence (oracle returns 0 or extreme values)
- Multi-oracle inconsistency

---

## 7. Precision Loss / Rounding

**Trigger conditions:**
- Division operations (especially `a * b / c` patterns)
- Share/rate calculations
- Reward distribution math
- Tokens with different decimal counts interacting

**What to check:**
- Division before multiplication (precision loss)
- Rounding direction: does it favor protocol or user? (should favor protocol)
- Dust accumulation over many operations
- Decimal normalization when mixing tokens with different decimals
- Phantom overflow in intermediate calculations

---

## 8. Share Inflation / First Depositor

**Trigger conditions:**
- ERC4626 vault or any share-based accounting
- `totalAssets() / totalSupply()` ratio used for share price
- No minimum deposit / dead shares mechanism

**What to check:**
- First depositor can inflate share price by donating to vault
- Subsequent depositors get 0 shares due to rounding
- Presence of virtual shares/assets offset (OZ mitigation)
- Minimum initial deposit requirement

---

## 9. Flash Loan Vectors

**Trigger conditions:**
- Governance/voting based on token balance
- Price calculations using current reserves
- Any single-transaction balance check

**What to check:**
- Can balances be inflated within a single TX to manipulate protocol?
- Voting power from current balance (not time-weighted)
- Collateral value from spot price
- Lock time requirements that prevent same-TX deposit+withdraw

---

## 10. Timestamp / Block Dependency

**Trigger conditions:**
- `block.timestamp` or `block.number` used for critical logic
- Time-based rewards, vesting, or unlocking
- Epoch/period calculations

**What to check:**
- Miner manipulation window (~15 seconds)
- Off-by-one in period boundaries
- Epoch alignment assumptions (week boundaries, etc.)
- `block.timestamp` monotonicity assumptions across chains
- L2-specific timestamp behavior

---

## 11. Unchecked Low-Level Calls

**Trigger conditions:**
- `call()`, `delegatecall()`, `staticcall()` usage
- Assembly blocks with external calls
- `address.send()` or `address.transfer()`

**What to check:**
- Return value checked on all low-level calls
- Gas stipend limitations (`transfer` = 2300 gas, fails with proxy wallets)
- Calldata correctness in `abi.encodeWithSelector` / `abi.encode`

---

## 12. Storage Packing Collisions

**Trigger conditions:**
- Inline assembly that reads/writes storage
- Proxy patterns with inherited storage
- Tightly packed structs

**What to check:**
- Storage slot calculations in assembly
- Variable ordering across inherited contracts
- Struct packing assumptions (Solidity rules)

---

## 13. Gas Griefing / DoS

**Trigger conditions:**
- Loops over dynamic arrays
- External calls in loops
- User-influenced iteration counts
- `push`/`pop` on storage arrays

**What to check:**
- Unbounded loops (user can grow array to make function exceed gas limit)
- Reverting external calls in loops (one failure blocks all)
- Batch operations without gas limits
- Block gas limit constraints on critical functions

---

## 14. Reward Index Desynchronization

**Trigger conditions:**
- Reward distribution using accumulator pattern (`rewardPerToken`)
- Multiple reward tokens
- Epoch-based or streaming rewards
- Cross-contract reward sources

**What to check:**
- Checkpoint timing: is reward index updated before balance changes?
- Numerator/denominator source mismatch (global vs eligible vs snapshot)
- Reward pointer manipulation (skip/replay attack)
- Staking after reward accrual but before distribution

---

## 15. Signature Replay / EIP-712

**Trigger conditions:**
- `ecrecover` usage
- EIP-2612 permit
- Gasless transactions / meta-transactions
- Off-chain signed messages

**What to check:**
- Nonce management (prevent replay)
- Chain ID in domain separator (prevent cross-chain replay)
- `ecrecover` returns `address(0)` on invalid signature (must check)
- EIP-712 domain separator correctness
- Signature malleability (s-value range check)

---

## 16. Front-Running / MEV

**Trigger conditions:**
- Slippage-sensitive operations
- First-come-first-served mechanisms
- Commit-reveal schemes
- Admin parameter changes

**What to check:**
- Slippage protection on swaps/deposits/withdrawals
- Commit-reveal for sensitive actions
- Frontrunnable initialization
- Admin functions that change rates/params without timelock

---

## 17. Integer Overflow (Unchecked Blocks)

**Trigger conditions:**
- `unchecked { }` blocks
- Solidity < 0.8.0 (no built-in overflow checks)
- Assembly arithmetic

**What to check:**
- Every `unchecked` block: can values realistically overflow?
- Casting between types (uint256 → uint128, int → uint)
- Negation of `type(int256).min`
- Assembly arithmetic (no automatic checks)

---

## 18. Initialization / Constructor Issues

**Trigger conditions:**
- `initialize()` functions (proxy pattern)
- `constructor` in upgradeable contracts
- Missing initialization checks

**What to check:**
- Can `initialize()` be called multiple times?
- Is the implementation contract initialized? (prevent takeover)
- Are all state variables properly set during initialization?
- `initializer` modifier present and correct

---

## 19. Self-Destruct / Forced ETH

**Trigger conditions:**
- `selfdestruct` in any reachable code
- `address(this).balance` used in logic
- ETH accounting based on balance tracking

**What to check:**
- Forced ETH via `selfdestruct` breaks balance accounting
- `address(this).balance` ≠ tracked deposits
- Missing `receive()` / `fallback()` revert guard

---

## 20. Cross-Chain / Bridge Issues

**Trigger conditions:**
- Multi-chain deployment
- Bridge contracts or message passing (LayerZero, CCIP, Wormhole)
- Chain-specific behavior dependencies

**What to check:**
- Message replay across chains
- Relayer trust assumptions
- Chain-specific opcodes (`PUSH0`, `PREVRANDAO`, `SELFDESTRUCT`)
- Different gas costs / block times affecting logic
- Sequencer downtime on L2s (Chainlink sequencer uptime feed)

---

## 21. Access Control on Self-Destruct / Pause

**Trigger conditions:**
- Pausable contracts
- Emergency functions
- Kill switches

**What to check:**
- Can pause brick user funds permanently?
- Is there an unpause path if owner is compromised?
- Emergency withdrawal exists for users?
- Timelock on destructive admin functions?

---

## 22. ERC721/ERC1155 Callback Vectors

**Trigger conditions:**
- NFT minting/transferring
- `onERC721Received` / `onERC1155Received` callbacks
- `safeMint` / `safeTransferFrom`

**What to check:**
- Reentrancy via callback
- State modifications between mint and callback
- Arbitrary code execution in receiver contract

---

## 23. Governance / Voting Manipulation

**Trigger conditions:**
- On-chain governance
- Token-weighted voting
- Quorum requirements
- Proposal execution

**What to check:**
- Flash loan voting (borrow → vote → return)
- Vote buying / dark DAOs
- Quorum manipulation
- Proposal execution can be front-run
- Timelock bypass paths

---

## 24. Token Approval / Allowance Issues

**Trigger conditions:**
- `approve` / `increaseAllowance` patterns
- Infinite approvals
- Approval race conditions

**What to check:**
- Front-running `approve` (classic ERC20 race condition)
- Infinite approval to untrusted contracts
- `permit` + `transferFrom` interaction
- Dangling approvals after contract upgrade

---
---

<div align="center">

### ⬡ PART B — SOLANA (RUST / ANCHOR) — 18 SURFACES ⬡

</div>

# Part B: Solana (Rust / Anchor)

## S1. Missing Signer Check

**Trigger conditions:**
- Instruction accepts authority/admin accounts
- Account not marked `Signer` in Anchor `#[account]` struct
- Native Solana: missing `AccountInfo.is_signer` check

**What to check:**
- Can any account impersonate the authority?
- Is signer validation enforced before state mutation?
- Multi-signer scenarios: are ALL required signers checked?

---

## S2. Missing Owner / Program Check

**Trigger conditions:**
- Instruction reads data from accounts it doesn't own
- Passing arbitrary program-owned accounts
- No `owner` constraint in Anchor

**What to check:**
- Account `.owner == expected_program_id` verified
- Preventing injection of fake accounts owned by attacker's program
- SPL Token accounts validated against Token program ownership

---

## S3. Account Data Matching (Type Cosplay)

**Trigger conditions:**
- Multiple account types with same structure
- No discriminator validation
- Native Solana without Anchor's auto-discriminator

**What to check:**
- Can a Vault account be passed where a User account is expected?
- Anchor 8-byte discriminator present and checked
- Native programs: manual discriminator/tag validation

---

## S4. PDA Seed Confusion / Substitution

**Trigger conditions:**
- PDA derived from user-controlled seeds
- Multiple PDAs with overlapping seed patterns
- Missing bump seed validation

**What to check:**
- Seed uniqueness: can different inputs produce the same PDA?
- Canonical bump used (Anchor `bump` constraint)
- Variable-length seeds without delimiters (seed grinding)
- User can substitute one PDA for another

---

## S5. Missing Account Validation (has_one / constraint)

**Trigger conditions:**
- Accounts passed to instruction without relationship verification
- Missing `has_one` constraints in Anchor
- Account fields not cross-referenced

**What to check:**
- Vault.owner == signer (ownership links)
- Token account.mint == expected mint
- All relational invariants between accounts enforced

---

## S6. Arithmetic Overflow / Underflow

**Trigger conditions:**
- Rust integer arithmetic (default wraps in release builds)
- `checked_add/sub/mul/div` not used
- Large token amounts with multiplication

**What to check:**
- All arithmetic uses `checked_*` or Anchor's overflow protection
- `u64` overflow on token amounts (max ~18.4 quintillion)
- Intermediate multiplication overflow before division
- Casting between types (`u128` → `u64`, `i64` → `u64`)

---

## S7. CPI (Cross-Program Invocation) Exploits

**Trigger conditions:**
- Invoking other programs via `invoke` or `invoke_signed`
- Passing PDAs as signers to CPIs
- Calling Token program or System program

**What to check:**
- Is the target program ID hardcoded or user-supplied?
- Can attacker substitute a malicious program?
- PDA signer seeds correct for `invoke_signed`
- Account permissions (writable, signer) correct in CPI call

---

## S8. Reinitialization

**Trigger conditions:**
- `init` constraint in Anchor
- Custom initialization functions
- Account state reset patterns

**What to check:**
- Can `init` instruction be called twice? (Anchor prevents, but check `init_if_needed`)
- `init_if_needed` — attacker can front-run initialization
- Is there a `is_initialized` boolean checked and set?
- Closing and re-creating accounts to reset state

---

## S9. Closing Accounts Improperly

**Trigger conditions:**
- Account closure logic (zeroing lamports, transferring rent)
- `close` constraint in Anchor
- Manual account closing

**What to check:**
- Is account data zeroed after closing? (prevents revival attack)
- Lamports transferred to correct recipient?
- Can closed account be passed to other instructions before TX ends?
- Revival attack: refunding lamports to closed account in same TX

---

## S10. Rent Exemption Issues

**Trigger conditions:**
- Account creation with specific sizes
- Dynamic account resizing (`realloc`)
- Minimum balance assumptions

**What to check:**
- Account allocated with enough space for data + discriminator
- Rent-exempt minimum balance maintained
- `realloc` increases rent requirement appropriately
- System program invoked correctly for account creation

---

## S11. Token Account Validation

**Trigger conditions:**
- SPL Token / Token-2022 interactions
- Mint, transfer, burn operations
- Associated Token Accounts (ATAs)

**What to check:**
- Token account mint matches expected mint
- Token account authority matches expected authority
- ATA derivation is correct
- Token-2022 extensions (transfer fees, confidential transfers) handled

---

## S12. Oracle Staleness (Solana)

**Trigger conditions:**
- Pyth, Switchboard, or custom oracle usage
- Price-dependent logic (liquidation, swaps)

**What to check:**
- Oracle staleness check (`slot` or `publish_time` freshness)
- Confidence interval validation (Pyth `conf`)
- Oracle account ownership validation
- Fallback when oracle is unavailable

---

## S13. Duplicate Accounts

**Trigger conditions:**
- Instruction accepts multiple accounts of same type
- Source/destination patterns
- Multi-party instructions

**What to check:**
- Can the same account be passed as both source and destination?
- Duplicate mutable account references (Solana prevents, but logical bugs)
- Self-transfer creating/destroying tokens

---

## S14. Missing Instruction Ordering / Atomicity

**Trigger conditions:**
- Multi-instruction workflows (stake → claim → unstake)
- State flags that gate subsequent instructions
- Time/slot-dependent logic

**What to check:**
- Can instructions be reordered to bypass checks?
- Flash loan equivalents: borrow → use → repay in one TX
- State consistency between instructions within same TX

---

## S15. Remaining Accounts Exploitation

**Trigger conditions:**
- `ctx.remaining_accounts` used in Anchor
- Dynamic account lists
- Flexible multi-account patterns

**What to check:**
- Are remaining accounts validated (owner, signer, type)?
- Can attacker inject extra accounts to manipulate logic?
- Iteration over remaining accounts properly bounded

---

## S16. Program Upgrade Authority

**Trigger conditions:**
- Upgradeable BPF programs
- Authority management
- Multi-sig upgrade patterns

**What to check:**
- Who holds upgrade authority? (EOA vs multisig)
- Can authority be changed? By whom?
- Is program frozen/non-upgradeable when it should be?
- Upgrade authority = None means immutable

---

## S17. Lamport Manipulation

**Trigger conditions:**
- Logic based on account lamport balance
- Reward/fee distribution based on SOL balance
- Minimum stake requirements

**What to check:**
- Anyone can send lamports to any account (like forced ETH on EVM)
- Balance-based logic can be manipulated
- Rent-exempt balance confused with actual deposits

---

## S18. Clock / Slot Dependency

**Trigger conditions:**
- `Clock::get()` for time-based logic
- Slot-based calculations
- Epoch-dependent operations

**What to check:**
- Clock can drift on validators
- Slot times are not constant (~400ms average but variable)
- `unix_timestamp` from Clock sysvar vs slot number
- Epoch length assumptions

## references/complexity-rubric.md

# 🐝 Complexity & Risk Scoring Rubric

**`━━━━⬡⬡⬡━━━━ SCOPING BEE ━━━━⬡⬡⬡━━━━`**

Scoring system for estimating smart contract audit complexity and effort.
Applies to both **Solidity (EVM)** and **Rust/Anchor (Solana)** codebases.
Each metric is scored 1–4. Composite score = weighted average.

---

<div align="center">

### ⬡ AUDIT PACE ⬡

</div>

## Configurable Audit Pace

The effort formula uses a configurable **audit pace** (nSLOC reviewed per day):

```
Default: 350 nSLOC/day
```

| Pace | When to Use |
|------|------------|
| 400 nSLOC/day | Simple, well-documented, standard patterns |
| 350 nSLOC/day | **Default** — typical audit engagement |
| 300 nSLOC/day | High complexity, cross-contract flows, novel math |
| 250 nSLOC/day | Critical infrastructure, bridges, complex DeFi |

The user can override this at any time. When presenting estimates,
always state the pace used so they can recalculate.

---

<div align="center">

### ⬡ METRICS ⬡

</div>

## Metric 1: nSLOC (Weight: 25%)

Non-blank, non-comment source lines of code.

| Score | nSLOC Range | Description |
|-------|-------------|-------------|
| 1 | 0–100 | Small contract. Single responsibility. |
| 2 | 101–300 | Medium contract. Multiple functions, moderate state. |
| 3 | 301–600 | Large contract. Complex logic, many code paths. |
| 4 | 601+ | Very large. Likely needs decomposition or phased audit. |

---

## Metric 2: External Integration Risk (Weight: 25%)

Cross-contract calls, oracle dependencies, external protocol trust.

| Score | Criteria (Solidity) | Criteria (Solana) |
|-------|--------------------|-----------------|
| 1 | No external calls / standard transfers | No CPI, single program |
| 2 | Calls to trusted immutable libs (OZ) | CPI to SPL Token only |
| 3 | Calls to mutable contracts (strategies) | CPI to multiple programs, PDA signers |
| 4 | Untrusted addresses, multi-protocol | User-supplied program IDs, cross-chain |

### Red Flags (auto-bump to 3+)
- **Solidity**: `delegatecall`, user-supplied call targets, cross-contract reentrancy
- **Solana**: User-supplied program accounts, `invoke_signed` with complex seeds, `remaining_accounts` iteration

---

## Metric 3: State Coupling (Weight: 20%)

Number of state variables that must stay synchronized.

| Score | Criteria | Examples |
|-------|----------|---------|
| 1 | 1–3 simple state vars, independent | `owner`, `paused`, `totalSupply` |
| 2 | 4–8 state vars, some loosely coupled | Mapping + counter, balance + allowance |
| 3 | 9–15 state vars, multiple coupled invariants | Reward index + user snapshot + global counter must agree |
| 4 | 16+ state vars, complex cross-variable invariants | Epoch data + user cache + eligible supply + claim pointers |

### Red Flags (auto-bump to 3+)
- Sentinel values (0 means "unset", N+1 encoding)
- Monotonic pointer variables (claim pointers that can't go backward)
- Write-once flags that gate critical logic
- Cross-contract shared state

---

## Metric 4: Access Control Complexity (Weight: 15%)

Number and sophistication of roles and permissions.

| Score | Criteria | Examples |
|-------|----------|---------|
| 1 | Single role (owner) or no access control | Basic Ownable |
| 2 | 2 roles with clear separation | Owner + User |
| 3 | 3–4 roles with overlapping permissions | Owner + Admin + Operator + User |
| 4 | Role-based AC with delegation, timelock, multisig, governance | AccessControl + Timelock + Governor |

### Red Flags (auto-bump to 3+)
- Roles can be self-assigned
- No two-step ownership transfer
- Missing role checks on critical functions (inconsistent)
- `tx.origin` used for auth

---

## Metric 5: Upgradeability Risk (Weight: 15%)

Risk from upgrade patterns and mutability.

| Score | Criteria | Examples |
|-------|----------|---------|
| 1 | Immutable (no proxy, no admin-changeable state) | Pure contract, fixed parameters |
| 2 | Admin-mutable parameters with guardrails | Fee caps, timelocked changes |
| 3 | Proxy pattern with governance controls | UUPS + multisig + timelock |
| 4 | Proxy with EOA owner, or unconstrained mutability | TransparentProxy with single owner, unguarded setters |

### Red Flags (auto-bump to 3+)
- `selfdestruct` in implementation
- No storage gap in base contracts
- Uninitialized implementation contract
- Admin can change core protocol addresses without validation

---

<div align="center">

### ⬡ COMPOSITE SCORE ⬡

</div>

## Composite Score Calculation

```
composite = (nSLOC × 0.25) + (extIntegration × 0.25) + (stateCoupling × 0.20) 
          + (accessControl × 0.15) + (upgradeability × 0.15)
```

### Risk Tier Mapping

| Composite Range | Tier | Bee Zone | Audit Approach |
|:---------------|:-----|:---------|:---------------|
| 1.0 – 1.5 | 🟢 LOW | Low Pollen | Checklist review |
| 1.6 – 2.5 | 🟡 MEDIUM | Watch Zone | Vector scan |
| 2.6 – 3.5 | 🟠 HIGH | Sting Zone | Deep interrogation |
| 3.6 – 4.0 | 🔴 CRITICAL | Critical Sting Zone | Deep interrogation + invariant extraction + PoC |

---

<div align="center">

### ⬡ EFFORT ESTIMATION ⬡

</div>

## Effort Estimation Formula

Primary formula using configurable audit pace:

```
base_days = total_nSLOC / AUDIT_PACE
```

Default `AUDIT_PACE = 350` nSLOC/day. Users can adjust this value.

### Complexity Multipliers

Apply to base_days based on composite risk tier:

| Tier | Multiplier | Example: 1000 nSLOC @ 350/day |
|------|-----------|-------------------------------|
| LOW (1.0–1.5) | ×1.0 | 2.9 days → **3 days** |
| MEDIUM (1.6–2.5) | ×1.3 | 2.9 days → **3.7 days** |
| HIGH (2.6–3.5) | ×1.7 | 2.9 days → **4.9 days** |
| CRITICAL (3.6–4.0) | ×2.2 | 2.9 days → **6.3 days** |

### Quick Reference Table (at 350 nSLOC/day)

| nSLOC | Base Days | LOW | MEDIUM | HIGH | CRITICAL |
|-------|-----------|-----|--------|------|----------|
| 200 | 0.6 | 1 day | 1 day | 1 day | 1.5 days |
| 500 | 1.4 | 1.5 days | 2 days | 2.5 days | 3 days |
| 1000 | 2.9 | 3 days | 4 days | 5 days | 6.5 days |
| 2000 | 5.7 | 6 days | 7.5 days | 10 days | 12.5 days |
| 5000 | 14.3 | 14.5 days | 18.5 days | 24 days | 31.5 days |

### Quick Reference Table (at 300 nSLOC/day — high complexity)

| nSLOC | Base Days | LOW | MEDIUM | HIGH | CRITICAL |
|-------|-----------|-----|--------|------|----------|
| 200 | 0.7 | 1 day | 1 day | 1 day | 1.5 days |
| 500 | 1.7 | 2 days | 2 days | 3 days | 3.5 days |
| 1000 | 3.3 | 3.5 days | 4.5 days | 5.5 days | 7.5 days |
| 2000 | 6.7 | 7 days | 8.5 days | 11.5 days | 14.5 days |
| 5000 | 16.7 | 17 days | 21.5 days | 28.5 days | 36.5 days |

### Additional Effort Modifiers

Apply on top of the complexity-adjusted estimate:

| Factor | Modifier | When to Apply |
|--------|----------|---------------|
| Cross-contract/CPI interactions | +20% | Multiple contracts with shared state |
| Novel / non-standard patterns | +30% | Custom math, unusual architecture |
| Missing tests | +15% | No existing test suite |
| Missing documentation | +10% | No specs, no comments, no README |
| Multiple token types | +10% | Handles various ERC20/SPL behaviors |
| PoC requirement | +25% | Client requires exploit proofs |
| Native Solana (no Anchor) | +20% | Manual account parsing, no discriminators |

**Always show in the report:**
```
Audit pace: [N] nSLOC/day
Total nSLOC: [M]
Base days: [M ÷ N]
Complexity multiplier: [×X] (TIER)
Modifiers applied: [+Y%]
Final estimate: [Z] days
```

---

<div align="center">

### ⬡ CALIBRATION ⬡

</div>

## Calibration Examples

Scores calibrated against real audits (at 350 nSLOC/day default):

| Protocol | Chain | nSLOC | Composite | Tier | Est. Days |
|----------|-------|-------|-----------|------|-----------|
| Simple ERC20 Token | EVM | 80 | 1.1 | LOW | 0.5 |
| Basic Staking | EVM | 250 | 2.0 | MEDIUM | 1 |
| VotingEscrow + Distributor | EVM | 1182 | 3.4 | HIGH | 5.5 |
| ERC4626 Vault + Strategy | EVM | 400 | 2.7 | HIGH | 2 |
| Cross-chain Bridge | EVM | 1200 | 3.8 | CRITICAL | 7.5 |
| SPL Token Vault | Solana | 300 | 2.0 | MEDIUM | 1 |
| Anchor Staking + Rewards | Solana | 800 | 2.8 | HIGH | 4 |
| Native Solana DEX | Solana | 1500 | 3.5 | HIGH | 7.5+ |

## references/scope-report-template.md

<div align="center">

# 🐝 [PROTOCOL_NAME] — Audit Scope Report

**`━━━━⬡⬡⬡━━━━ SCOPING BEE ━━━━⬡⬡⬡━━━━`**

</div>

<table align="center">
<tr><td>🗓️ <b>Date</b></td><td>[DATE]</td></tr>
<tr><td>🔍 <b>Auditor</b></td><td>[AUDITOR]</td></tr>
<tr><td>🔗 <b>Commit</b></td><td><code>[COMMIT_HASH]</code></td></tr>
<tr><td>⛓️ <b>Chain</b></td><td>[EVM / Solana / Multi-chain]</td></tr>
<tr><td>🛠️ <b>Framework</b></td><td>[Foundry / Hardhat / Anchor]</td></tr>
</table>

---

<div align="center">

### ⬡ HIVE SECTION 1 ⬡

</div>

## 🛡️ Threat Intelligence Scan

```
┌─────────────────────────────────────────────────────────┐
│  🐝 HIVE SECURITY SWEEP                     VERDICT: ✅ │
├─────────────────────────────────────────────────────────┤
│  ⬡ Auto-exec lifecycle scripts        ··········  CLEAN │
│  ⬡ Network exfiltration patterns       ··········  CLEAN │
│  ⬡ Obfuscated payloads                ··········  CLEAN │
│  ⬡ Phishing / brand impersonation     ··········  CLEAN │
│  ⬡ Wallet draining patterns           ··········  CLEAN │
│  ⬡ Malicious dependencies             ··········  CLEAN │
│  ⬡ Backdoor functions                 ··········  CLEAN │
│  ⬡ Known vulnerabilities              ··········  CLEAN │
├─────────────────────────────────────────────────────────┤
│  🍯 All clear — safe to proceed with deep analysis.     │
└─────────────────────────────────────────────────────────┘
```

<!-- If any findings, replace CLEAN with finding status and add details below -->
<!-- - [SEVERITY] Category: detail -->

---

<div align="center">

### ⬡ HIVE SECTION 2 ⬡

</div>

## 📋 Executive Summary

```
  ╔══════════════════════════════════════════════════════╗
  ║  🐝 PROTOCOL AT A GLANCE                            ║
  ╠══════════════════════════════════════════════════════╣
  ║  Protocol Type   ▸ [e.g., Vote-escrowed staking]   ║
  ║  Chain           ▸ [EVM / Solana]                   ║
  ║  Total Contracts ▸ [N core + M supporting]          ║
  ║  Total nSLOC     ▸ [N lines]                        ║
  ║  Risk Tier       ▸ [LOW / MEDIUM / HIGH / CRITICAL] ║
  ║  Dependencies    ▸ [N packages]                     ║
  ╚══════════════════════════════════════════════════════╝
```

**One-paragraph summary**: [What this protocol does, how value flows through it, and what the primary risk surfaces are.]

---

<div align="center">

### ⬡ HIVE SECTION 3 ⬡

</div>

## ⏱️ Estimated Effort

```
  ┌──────────────────────────────────────────────┐
  │  🐝 AUDIT PACE: [N] nSLOC/day               │
  │  ─────────────────────────────────────────── │
  │  Total nSLOC      ▸  [N]                     │
  │  Base Effort       ▸  [N ÷ pace] days        │
  │  Adjusted Total    ▸  [T] days  🍯           │
  └──────────────────────────────────────────────┘
```

| ⬡ Component | nSLOC | Base Days | Complexity | Adjusted Days | Approach |
|:------------|------:|----------:|:----------:|--------------:|:---------|
| 🔴 Contract1.sol | [N] | [N÷pace] | ×[M] (TIER) | [D] | Deep interrogation |
| 🟡 Contract2.sol | [N] | [N÷pace] | ×[M] (TIER) | [D] | Vector scan |
| 🔗 Cross-contract review | — | — | +20% | [D] | Interaction audit |
| 💥 PoC construction | — | — | — | [D] | For confirmed findings |
| 📝 Report writing | — | — | — | [D] | Final deliverable |

> **To recalculate**: Change the audit pace and divide total nSLOC by your new pace, then apply the complexity multiplier for each contract's risk tier (LOW ×1.0, MEDIUM ×1.3, HIGH ×1.7, CRITICAL ×2.2).

---

<div align="center">

### ⬡ HIVE SECTION 4 ⬡

</div>

## 📦 Contract Inventory

### 🍯 Core Contracts (The Honeycomb)

<!-- Assign bee roles based on contract responsibility:
     👑 Queen  — main orchestrator / entry point
     🏗️ Builder — state management / core logic
     🔧 Worker  — utility / encoding / helpers
     🐝 Guard   — access control / authorization
     🍯 Honeypot — value storage / treasury
-->

| # | ⬡ Contract | Role | nSLOC | Score | Risk |
|--:|:-----------|:-----|------:|------:|:-----|
| 1 | `Contract1.sol` | 👑 Queen — [role description] | 350 | 2.8 | 🟠 HIGH |
| 2 | `Contract2.sol` | 🏗️ Builder — [role description] | 180 | 2.1 | 🟡 MEDIUM |
| 3 | `LibHelper.sol` | 🔧 Worker — [role description] | 60 | 1.2 | 🟢 LOW |

### 🔌 Interfaces

| # | Interface | Purpose |
|--:|:----------|:--------|
| 4 | `IContract1.sol` | [purpose] |

### 📦 External Dependencies

| Dependency | Version | Usage | Modified? |
|:-----------|:--------|:------|:---------:|
| OpenZeppelin | v4.9.3 | Access control, ERC20 | No |
| solmate | v6.2.0 | SafeTransferLib | No |

---

<div align="center">

### ⬡ HIVE SECTION 5 ⬡

</div>

## 🔀 Flow Diagram

### 🐝 The Waggle Dance — Value Flow

```mermaid
graph LR
    User -->|"deposit"| Vault
    Vault -->|"invest"| Strategy
    Strategy -->|"harvest"| RewardPool
    RewardPool -->|"claim"| User
```

### 🕸️ Cross-Contract Dependencies

```mermaid
graph TD
    A[Contract1] -->|"reads"| B[Contract2]
    A -->|"writes"| C[Contract3]
    B -->|"callback"| A

    style A fill:#f0a500,color:#000,stroke:#333
    style B fill:#ffd966,color:#000,stroke:#333
    style C fill:#ffd966,color:#000,stroke:#333
```

### 🔗 Trust Assumptions

| From | ➜ To | Assumption | 💀 Risk if Broken |
|:-----|:-----|:-----------|:-----------------|
| Vault | Strategy | Strategy returns accurate balance | Fund loss |
| Distributor | VotingEscrow | ve balances are historically accurate | Reward theft |

---

<div align="center">

### ⬡ HIVE SECTION 6 ⬡

</div>

## 🔬 Complexity & Risk Scores

| ⬡ Contract | nSLOC | Ext. | State | Access | Upgrade | Composite | Tier |
|:-----------|------:|:----:|:-----:|:------:|:-------:|----------:|:-----|
| Contract1.sol | 3 | 3 | 2 | 2 | 1 | **2.45** | 🟡 MEDIUM |
| Contract2.sol | 2 | 1 | 1 | 1 | 1 | **1.30** | 🟢 LOW |

```
  🐝 Scoring Rationale
  ─────────────────────────────────────────────────────────
  ⬡ Contract1 — [brief rationale for score]

  ⬡ Contract2 — [brief rationale for score]
  ─────────────────────────────────────────────────────────
```

---

<div align="center">

### ⬡ HIVE SECTION 7 ⬡

</div>

## 🎯 Prioritized Audit Hitlist

> 🐝 Functions ranked by sting risk — audit in this order.

### 🔴 P0 — Critical Sting Zone

| ⬡ Contract | Function / Area | Risk Factors |
|:-----------|:----------------|:-------------|
| Contract1 | `withdraw()` | Value handling, cross-contract, permissionless |
| Contract1 | `claim()` | Reward calculation, state pointer |

### 🟡 P1 — Watch Zone

| ⬡ Contract | Function / Area | Risk Factors |
|:-----------|:----------------|:-------------|
| Contract2 | `deposit()` | Share calculation, first depositor |
| Contract1 | `setConfig()` | Admin privilege, state reset |

### 🟢 P2 — Low Pollen

| ⬡ Contract | Function / Area | Risk Factors |
|:-----------|:----------------|:-------------|
| Contract2 | `view functions` | Read-only |

---

<div align="center">

### ⬡ HIVE SECTION 8 ⬡

</div>

## 🛠️ Recommended Methodology

| ⬡ Contract | Approach | Rationale |
|:-----------|:---------|:----------|
| Contract1.sol | **🔴 Deep Interrogation** | High complexity, cross-contract value flows, multiple coupled state vars |
| Contract2.sol | **🟡 Vector Scan** | Medium complexity, standard patterns with edge cases |
| LibHelper.sol | **🟢 Checklist Review** | Low complexity, stateless library |

### 🐝 Suggested Audit Flow

```
  ⬡─────────────────────────────────────────────────────────────⬡
  │                                                              │
  │  1. 📋 Scope Review (this document)         ← YOU ARE HERE  │
  │         │                                                    │
  │  2. 🔍 Invariant Extraction (all core contracts)            │
  │         │                                                    │
  │  3. 🔴 Deep Audit Pass 1 — P0 targets                      │
  │         │                                                    │
  │  4. 🟡 Deep Audit Pass 2 — P1 targets                      │
  │         │                                                    │
  │  5. 🔗 Cross-contract interaction audit                     │
  │         │                                                    │
  │  6. 💥 PoC construction for findings                        │
  │         │                                                    │
  │  7. ✅ Remediation review                                   │
  │                                                              │
  ⬡─────────────────────────────────────────────────────────────⬡
```

---

<div align="center">

### ⬡ HIVE SECTION 9 ⬡

</div>

## ❓ Open Questions

> [!IMPORTANT]
> 🐝 Items requiring clarification from the protocol team before or during audit.

| # | Topic | Question |
|--:|:------|:---------|
| 1 | **[Design intent]** | Why does function X not check Y? |
| 2 | **[Expected behavior]** | What should happen when Z is zero? |
| 3 | **[Deployment]** | What chain(s) will this deploy on? |
| 4 | **[Roles]** | Is the owner a multisig or EOA? |
| 5 | **[Known issues]** | Are there any known issues or accepted risks? |

---

<div align="center">

### ⬡ HIVE SECTION 10 ⬡

</div>

## 📎 Appendix: Files Out of Scope

| File | Reason |
|:-----|:-------|
| `test/*.sol` | Test files |
| `script/*.sol` | Deployment scripts |
| `lib/**` | Third-party dependencies (unmodified) |

---

<div align="center">

```
  ⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡
  🐝  Generated by Scoping Bee  •  [AUDITOR]  🍯
  ⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡⬡
```

</div>

## scanner

```

```

## scanner/Dockerfile

```

```

## scripts

```

```

## scripts/codebase_visualizer.sh

```bash

```

## scripts/run_threat_scan.sh

```bash

```

## scripts/sloc_counter.sh

```bash

```

## scripts/source_fetcher.sh

```bash

```

## scripts/threat_intel_scan.sh

```bash

```

